root/branches/release-38/lib/MT/CMS/Common.pm @ 2301

Revision 2301, 38.1 kB (checked in by auno, 19 months ago)

If _type parameter is set, check the handler and forward. BugzID:79706

  • Property svn:keywords set to Id Revision
Line 
1package MT::CMS::Common;
2
3use strict;
4
5use MT::Util qw( format_ts offset_time_list relative_date );
6
7sub save {
8    my $app  = shift;
9    my $q    = $app->param;
10    my $type = $q->param('_type');
11
12    return $app->errtrans("Invalid request.")
13      unless $type;
14
15    # being a general-purpose method, lets look for a mode handler
16    # that is specifically for editing this type. if we find it,
17    # reroute to it.
18
19    my $save_mode = 'save_' . $type;
20    if ( my $hdlrs = $app->handlers_for_mode($save_mode) ) {
21        return $app->forward($save_mode);
22    }
23
24    my $id = $q->param('id');
25    $q->param( 'allow_pings', 0 )
26      if ( $type eq 'category' ) && !defined( $q->param('allow_pings') );
27
28    $app->validate_magic() or return;
29    my $author = $app->user;
30
31    # Check permissions
32    my $perms = $app->permissions;
33
34    if ( !$author->is_superuser ) {
35        if ( ($type ne 'author') && ($type ne 'template') )
36        {    # for authors, blog-ctx $perms is not relevant
37            return $app->errtrans("Permisison denied.")
38              if !$perms && $id;
39        }
40
41        $app->run_callbacks( 'cms_save_permission_filter.' . $type, $app, $id )
42          || return $app->error(
43            $app->translate( "Permission denied: [_1]", $app->errstr() ) );
44    }
45
46    my $param = {};
47    if ( $type eq 'author' ) {
48        if ( my $delim = $q->param('tag_delim') ) {
49            $param->{ 'auth_pref_tag_delim_' . $delim } = 1;
50            $param->{'auth_pref_tag_delim'} = $delim;
51        }
52        $param->{languages} =
53          $app->languages_list( $q->param('preferred_language') )
54          if $q->param('preferred_language');
55        $param->{create_personal_weblog} =
56          $q->param('create_personal_weblog') ? 1 : 0;
57        require MT::Permission;
58        my $sys_perms = MT::Permission->perms('system');
59        foreach (@$sys_perms) {
60            $param->{ 'perm_can_' . $_->[0] } = 1
61              if $q->param( 'can_' . $_->[0] );
62        }
63    }
64
65    my $filter_result = $app->run_callbacks( 'cms_save_filter.' . $type, $app );
66
67    if ( !$filter_result ) {
68        my %param = (%$param);
69        $param{error}       = $app->errstr;
70        $param{return_args} = $app->param('return_args');
71
72        if ( ( $type eq 'notification' ) || ( $type eq 'banlist' ) ) {
73            return list( $app, \%param );
74        }
75        elsif ( ( $app->param('cfg_screen') || '' ) eq 'cfg_archives' ) {
76            return edit( $app, \%param );
77        }
78        else {
79            if ($type) {
80                my $mode = 'view_' . $type;
81                if ( $app->handlers_for_mode($mode) ) {
82                    return $app->forward( $mode, \%param );
83                }
84            }
85            return $app->forward( 'view', \%param );
86        }
87    }
88
89    return $app->errtrans(
90        'The Template Name and Output File fields are required.')
91      if $type eq 'template' && !$q->param('name') && !$q->param('outfile');
92
93    if ( $type eq 'template' ) {
94
95        # check for autosave
96        if ( $q->param('_autosave') ) {
97            return $app->autosave_object();
98        }
99    }
100
101    my $class = $app->model($type)
102      or return $app->errtrans( "Invalid type [_1]", $type );
103    my ($obj);
104    if ($id) {
105        $obj = $class->load($id)
106            or return $app->error($app->translate("Invalid ID [_1]", $id));
107    }
108    else {
109        $obj = $class->new;
110    }
111
112    my $original = $obj->clone();
113    my $names    = $obj->column_names;
114    my %values   = map { $_ => ( scalar $q->param($_) ) } @$names;
115
116    if ( $type eq 'blog' ) {
117        unless ( $author->is_superuser
118            || ( $perms && $perms->can_administer_blog ) )
119        {
120            if ( $id && !( $perms->can_set_publish_paths ) ) {
121                delete $values{site_url};
122                delete $values{site_path};
123                delete $values{archive_url};
124                delete $values{archive_path};
125            }
126            if ( $id && !( $perms->can_edit_config ) ) {
127                delete $values{$_} foreach grep {
128                         $_ ne 'site_path'
129                      && $_ ne 'site_url'
130                      && $_ ne 'archive_path'
131                      && $_ ne 'archive_url'
132                } @$names;
133            }
134        }
135    }
136
137    if ( $type eq 'author' ) {
138
139        #FIXME: Legacy columns - remove them
140        my @cols = qw(is_superuser can_create_blog can_view_log can_edit_templates);
141        if ( !$author->is_superuser ) {
142            delete $values{$_} for @cols;
143        }
144        else {
145            if ( !$id || ( $author->id != $id ) ) {
146                # Assign the auth_type unless it was assigned
147                # through the form.
148                $obj->auth_type($app->config->AuthenticationModule)
149                    unless $obj->auth_type;
150                if ( $values{'status'} == MT::Author::ACTIVE() ) {
151                    my $sys_perms = MT::Permission->perms('system');
152                    if ( defined($q->param('is_superuser'))
153                      && $q->param('is_superuser')) {
154                        $obj->is_superuser(1);
155                    }
156                    else {
157                        foreach (@$sys_perms) {
158                            my $name = 'can_' . $_->[0];
159                            $name = 'is_superuser' if $name eq 'can_administer';
160                            if ( defined $q->param($name) ) {
161                                $obj->$name( $q->param($name) );
162                                delete $values{$name};
163                            }
164                            else {
165                                $obj->$name(0);
166                            }
167                        }
168                    }
169                }
170            }
171        }
172        delete $values{'password'};
173    }
174
175    if ( $type eq 'blog' ) {
176        # If this is a new blog, set the preferences, archive settings
177        # and template set to the defaults.
178        if ( !$obj->id ) {
179            $obj->language( $app->user->preferred_language );
180            $obj->nofollow_urls(1);
181            $obj->follow_auth_links(1);
182            $obj->page_layout('layout-wtt');
183            my @authenticators = qw( MovableType );
184            foreach my $auth (qw( Vox LiveJournal )) {
185                my $a = MT->commenter_authenticator($auth);
186                if ( !defined $a
187                    || ( exists $a->{condition} && ( !$a->{condition}->() ) ) )
188                {
189                    next;
190                }
191                push @authenticators, $auth;
192            }
193            $obj->commenter_authenticators( join ',', @authenticators );
194            my $set = $app->param('template_set') || 'mt_blog';
195            $obj->template_set( $set );
196        }
197
198        if ( $values{file_extension} ) {
199            $values{file_extension} =~ s/^\.*//
200              if ( $q->param('file_extension') || '' ) ne '';
201        }
202
203        unless ( $values{site_url} =~ m!/$! ) {
204            my $url = $values{site_url};
205            $values{site_url} = $url;
206        }
207    }
208
209    if ( $type eq 'entry' || $type eq 'page' ) {
210
211        # This has to happen prior to callbacks since callbacks may
212        # be affected by the translation...
213
214        # translates naughty words when PublishCharset is NOT UTF-8
215        $app->_translate_naughty_words($obj);
216    }
217
218    if ( $type eq 'template' ) {
219        if (   $q->param('type') eq 'archive'
220            && $q->param('archive_type') )
221        {
222            $values{type} = $q->param('archive_type');
223        }
224    }
225
226    delete $values{'id'} if exists( $values{'id'} ) && !$values{'id'};
227    $obj->set_values( \%values );
228
229    if ( $obj->properties->{audit} ) {
230        $obj->created_by( $author->id ) unless $obj->id;
231        $obj->modified_by( $author->id ) if $obj->id;
232    }
233
234    unless (
235        $app->run_callbacks( 'cms_pre_save.' . $type, $app, $obj, $original ) )
236    {
237        if ( 'blog' eq $type ) {
238            my $meth = $q->param('cfg_screen');
239            if ( $meth && $app->handlers_for_mode($meth) ) {
240                $app->error(
241                    $app->translate( "Save failed: [_1]", $app->errstr ) );
242                return $app->$meth;
243            }
244        }
245        $param->{return_args} = $app->param('return_args');
246        return edit( $app,
247            {
248                %$param,
249                error => $app->translate( "Save failed: [_1]", $app->errstr )
250            }
251        );
252    }
253
254    # Done pre-processing the record-to-be-saved; now save it.
255
256    $obj->touch() if ( $type eq 'blog' );
257
258    $obj->save
259      or return $app->error(
260        $app->translate( "Saving object failed: [_1]", $obj->errstr ) );
261
262    # Now post-process it.
263    $app->run_callbacks( 'cms_post_save.' . $type, $app, $obj, $original )
264      or return $app->error( $app->errstr() );
265
266    # Save NWC settings
267    my $screen = $q->param('cfg_screen') || '';
268    if ( $type eq 'blog' && $screen eq 'cfg_entry' ) {
269        my @fields;
270        push( @fields, 'title' )     if $q->param('nwc_title');
271        push( @fields, 'text' )      if $q->param('nwc_text');
272        push( @fields, 'text_more' ) if $q->param('nwc_text_more');
273        push( @fields, 'keywords' )  if $q->param('nwc_keywords');
274        push( @fields, 'excerpt' )   if $q->param('nwc_excerpt');
275        push( @fields, 'tags' )      if $q->param('nwc_tags');
276        my $fields = @fields ? join( ',', @fields ) : 0;
277        $obj->smart_replace_fields( $fields );
278        $obj->smart_replace( $q->param('nwc_smart_replace') );
279        $obj->save;
280    }
281
282    # Finally, decide where to go next, depending on the object type.
283    my $blog_id = $q->param('blog_id');
284    if ( $type eq 'blog' ) {
285        $blog_id = $obj->id;
286    }
287
288    # TODO: convert this to use $app->call_return();
289    # then templates can determine the page flow.
290    if ( $type eq 'notification' ) {
291        return $app->redirect(
292            $app->uri(
293                'mode' => 'list',
294                args   => {
295                    '_type' => 'notification',
296                    blog_id => $blog_id,
297                    saved   => $obj->email
298                }
299            )
300        );
301    }
302    elsif ( my $cfg_screen = $q->param('cfg_screen') ) {
303        if ( $cfg_screen eq 'cfg_publish_profile' ) {
304            my $dcty = $obj->custom_dynamic_templates || 'none';
305            if ( ( $dcty eq 'all' ) || ( $dcty eq 'archives' ) ) {
306                require MT::CMS::Blog;
307                my %param = ();
308                MT::CMS::Blog::_create_build_order( $app, $obj, \%param );
309                $q->param( 'single_template', 1 ); # to show tmpl full-screen
310                if ( $dcty eq 'all' ) {
311                    $q->param( 'type', $param{build_order} );
312                }
313                elsif ( $dcty eq 'archives' ) {
314                    my @ats = map { $_->{archive_type} } @{ $param{archive_type_loop} };
315                    $q->param( 'type', join( ',', @ats ) );
316                }
317                return MT::CMS::Blog::start_rebuild_pages($app);
318            }
319        }
320        if ( $cfg_screen eq 'cfg_templatemaps' ) {
321            $cfg_screen = 'cfg_archives';
322        }
323        my $site_path = $obj->site_path;
324        my $fmgr      = $obj->file_mgr;
325        unless ( $fmgr->exists($site_path) ) {
326            $fmgr->mkpath($site_path);
327        }
328        $app->add_return_arg( no_writedir => 1 )
329          unless $fmgr->exists($site_path) && $fmgr->can_write($site_path);
330    }
331    elsif ( $type eq 'banlist' ) {
332        return $app->redirect(
333            $app->uri(
334                'mode' => 'list',
335                args   => {
336                    '_type' => 'banlist',
337                    blog_id => $blog_id,
338                    saved   => $obj->ip
339                }
340            )
341        );
342    }
343    elsif ( $type eq 'template' && $q->param('rebuild') ) {
344        if ( !$id ) {
345            # add return argument for newly created templates
346            $app->add_return_arg( id => $obj->id );
347        }
348        if ( $obj->build_type ) {
349            if ( $obj->type eq 'index' ) {
350                $q->param( 'type',            'index-' . $obj->id );
351                $q->param( 'tmpl_id',         $obj->id );
352                $q->param( 'single_template', 1 );
353                return $app->forward( 'start_rebuild' );
354            } else {
355                # archive rebuild support
356                $q->param( 'id', $obj->id );
357                return $app->forward( 'publish_archive_templates' );
358            }
359        }
360    }
361    elsif ( $type eq 'template' ) {
362        if (   $obj->type eq 'archive'
363            || $obj->type eq 'category'
364            || $obj->type eq 'page'
365            || $obj->type eq 'individual' )
366        {
367            require MT::TemplateMap;
368            my @maps = MT::TemplateMap->load(
369                {
370                    template_id => $obj->id,
371                    build_type  => MT::PublishOption::DYNAMIC()
372                }
373            );
374            my @ats = map { $_->archive_type } @maps;
375            if ($#ats >= 0) {
376                $q->param( 'type', join( ',', @ats ) );
377                $q->param( 'with_indexes', 1 );
378                $q->param( 'no_static', 1 );
379                $q->param( 'template_id', $obj->id );
380                $q->param( 'single_template', 1 );
381                require MT::CMS::Blog;
382                return MT::CMS::Blog::start_rebuild_pages($app);
383            }
384        }
385    }
386    elsif ( $type eq 'blog' ) {
387        return $app->redirect(
388            $app->uri(
389                'mode' => 'cfg_prefs',
390                args   => { blog_id => $blog_id, saved => 1 }
391            )
392        );
393    }
394    elsif ( $type eq 'author' ) {
395        # Delete the author's userpic thumb (if any); it'll be regenerated.
396        if ($original->userpic_asset_id != $obj->userpic_asset_id) {
397            my $thumb_file = $original->userpic_file();
398            my $fmgr = MT::FileMgr->new('Local');
399            if ($fmgr->exists($thumb_file)) {
400                $fmgr->delete($thumb_file);
401            }
402        }
403    }
404
405    $app->add_return_arg( 'id' => $obj->id ) if !$original->id;
406    $app->add_return_arg( 'saved' => 1 );
407    $app->call_return;
408}
409
410sub edit {
411    my $app  = shift;
412    my $q    = $app->param;
413    my $type = $q->param('_type');
414
415    return $app->errtrans("Invalid request.")
416      unless $type;
417
418    # being a general-purpose method, lets look for a mode handler
419    # that is specifically for editing this type. if we find it,
420    # reroute to it.
421
422    my $edit_mode = $app->mode . '_' . $type;
423    if ( my $hdlrs = $app->handlers_for_mode($edit_mode) ) {
424        return $app->forward($edit_mode, @_);
425    }
426
427    my %param = eval { $_[0] ? %{ $_[0] } : (); };
428    die Carp::longmess if $@;
429    my $class = $app->model($type) or return;
430    my $blog_id = $q->param('blog_id');
431
432    if ( defined($blog_id) && $blog_id ) {
433        return $app->error( $app->translate("Invalid parameter") )
434          unless ( $blog_id =~ m/\d+/ );
435    }
436
437    $app->remove_preview_file;
438
439    my $enc = $app->config->PublishCharset;
440    if ( $q->param('_recover') ) {
441        my $sess_obj = $app->autosave_session_obj;
442        if ($sess_obj) {
443            my $data = $sess_obj->thaw_data;
444            if ($data) {
445
446                # XMLHttpRequest always send text in UTF-8... right?
447                if ( 'utf-8' eq lc($enc) ) {
448                    $q->param( $_, $data->{$_} ) for keys %$data;
449                }
450                else {
451                    foreach ( keys %$data ) {
452                        my $encoded =
453                          MT::I18N::encode_text( $data->{$_}, 'utf-8', $enc );
454                        $q->param( $_, $encoded );
455                    }
456                }
457                $param{'recovered_object'} = 1;
458            }
459            else {
460                $param{'recovered_failed'} = 1;
461            }
462        }
463        else {
464            $param{'recovered_failed'} = 1;
465        }
466    }
467    elsif ( $q->param('qp') ) {
468        foreach (qw( title text )) {
469            my $data = $q->param($_);
470            my $encoded = MT::I18N::encode_text( $data, undef, $enc )
471              if $data;
472            $q->param( $_, $encoded );
473        }
474    }
475
476    $param{autosave_frequency} = $app->config->AutoSaveFrequency;
477
478    my $id     = $q->param('id');
479    my $perms  = $app->permissions;
480    my $author = $app->user;
481    my $cfg    = $app->config;
482    $param{styles} = '';
483    if ( $type eq 'author' ) {
484        if ( $perms || $blog_id ) {
485            return $app->return_to_dashboard( redirect => 1 );
486        }
487    }
488    else {
489        if ( ( !$perms || !$blog_id )
490            && ( $type eq 'entry' || $type eq 'page'
491                 || $type eq 'category' || $type eq 'folder'
492                 || $type eq 'comment'  || $type eq 'commenter'
493                 || $type eq 'ping' ) ) {
494            return $app->return_to_dashboard( redirect => 1 );
495        }
496    }
497
498    my $cols = $class->column_names;
499    require MT::Promise;
500    my $obj_promise = MT::Promise::delay(
501        sub {
502            return $class->load($id) || undef;
503        }
504    );
505
506    if ( !$author->is_superuser ) {
507        $app->run_callbacks( 'cms_view_permission_filter.' . $type,
508            $app, $id, $obj_promise )
509          || return $app->error(
510            $app->translate( "Permission denied: [_1]", $app->errstr() ) );
511    }
512    my $obj;
513    my $blog;
514    my $blog_class = $app->model('blog');
515    if ($blog_id) {
516        $blog = $blog_class->load($blog_id);
517    }
518    else {
519        $blog_id = 0;
520    }
521
522    if ($id) {    # object exists, we're just editing it.
523          # Stash the object itself so we don't have to keep forcing the promise
524        $obj = $obj_promise->force()
525          or return $app->error(
526            $app->translate(
527                "Load failed: [_1]",
528                $class->errstr || $app->translate("(no reason given)")
529            )
530          );
531
532        # Populate the param hash with the object's own values
533        for my $col (@$cols) {
534            $param{$col} =
535              defined $q->param($col) ? $q->param($col) : $obj->$col();
536        }
537
538        # Make certain any blog-specific element matches the blog we're
539        # dealing with. If not, call shenanigans.
540        if (   ( exists $param{blog_id} )
541            && ( $blog_id != ($obj->blog_id || 0) ) )
542        {
543            return $app->return_to_dashboard( redirect => 1 );
544        }
545
546        if ( $class->properties->{audit} ) {
547            my $creator = MT::Author->load(
548                {
549                    id   => $obj->created_by(),
550                    type => MT::Author::AUTHOR()
551                }
552            );
553            if ($creator) {
554                $param{created_by} = $creator->name;
555            }
556            if ( my $mod_by = $obj->modified_by() ) {
557                my $modified = MT::Author->load(
558                    {
559                        id   => $mod_by,
560                        type => MT::Author::AUTHOR()
561                    }
562                );
563                if ($modified) {
564                    $param{modified_by} = $modified->name;
565                }
566                else {
567                    $param{modified_by} = $app->translate("(user deleted)");
568                }
569
570                # Since legacy MT installs will still have a
571                # timestamp type for their modified_on fields,
572                # we cannot reliably disaply a modified on date
573                # by default; we must only show the modification
574                # date IF there is also a modified_by value.
575                if ( my $ts = $obj->modified_on ) {
576                    $param{modified_on_ts} = $ts;
577                    $param{modified_on_formatted} =
578                      format_ts( MT::App::CMS::LISTING_DATETIME_FORMAT(), $ts, undef, $app->user ? $app->user->preferred_language : undef );
579                }
580            }
581            if ( my $ts = $obj->created_on ) {
582                $param{created_on_ts} = $ts;
583                $param{created_on_formatted} =
584                  format_ts( MT::App::CMS::LISTING_DATETIME_FORMAT(), $ts, undef, $app->user ? $app->user->preferred_language : undef );
585            }
586        }
587
588        $param{new_object} = 0;
589    }
590    else {    # object is new
591        $param{new_object} = 1;
592        for my $col (@$cols) {
593            $param{$col} = $q->param($col);
594        }
595    }
596
597    my $res = $app->run_callbacks('cms_edit.' . $type, $app, $id, $obj, \%param);
598    if (!$res) {
599        return $app->error($app->callback_errstr());
600    }
601
602    if ($param{autosave_support}) {
603        # autosave support, but don't bother if we're reediting
604        if ( !$app->param('reedit') ) {
605            my $sess_obj = $app->autosave_session_obj;
606            if ($sess_obj) {
607                $param{autosaved_object_exists} = 1;
608                $param{autosaved_object_ts} =
609                  MT::Util::epoch2ts( $blog, $sess_obj->start );
610            }
611        }
612    }
613
614    if ( ( $q->param('msg') || "" ) eq 'nosuch' ) {
615        $param{nosuch} = 1;
616    }
617    for my $p ( $q->param ) {
618        $param{$p} = $q->param($p) if $p =~ /^saved/;
619    }
620    $param{page_actions} = $app->page_actions($type, $obj);
621    if ( $class->can('class_label') ) {
622        $param{object_label} = $class->class_label;
623    }
624    if ( $class->can('class_label_plural') ) {
625        $param{object_label_plural} = $class->class_label_plural;
626    }
627
628    my $tmpl_file = $param{output} || "edit_${type}.tmpl";
629    $param{object_type} ||= $type;
630    $param{screen_id} ||= "edit-$type";
631    $param{screen_class} .= " edit-$type";
632    return $app->load_tmpl( $tmpl_file, \%param );
633}
634
635sub list {
636    my $app  = shift;
637    my $q    = $app->param;
638    my $type = $q->param('_type');
639
640    return $app->errtrans("Invalid request.")
641      unless $type;
642
643    # being a general-purpose method, lets look for a mode handler
644    # that is specifically for editing this type. if we find it,
645    # reroute to it.
646
647    my $list_mode = 'list_' . $type;
648    if ( my $hdlrs = $app->handlers_for_mode($list_mode) ) {
649        return $app->forward($list_mode);
650    }
651
652    my %param = $_[0] ? %{ $_[0] } : ();
653
654    my $perms = $app->permissions;
655    return $app->return_to_dashboard( redirect => 1 )
656      unless $perms;
657    if (
658        $perms
659        && (   ( $type eq 'blog' && !$perms->can_edit_config )
660            || ( $type eq 'template'     && !$perms->can_edit_templates )
661            || ( $type eq 'notification' && !$perms->can_edit_notifications ) )
662      )
663    {
664        return $app->return_to_dashboard( permission => 1 );
665    }
666    my $id        = $q->param('id');
667    my $class     = $app->model($type) or return;
668    my $blog_id   = $q->param('blog_id');
669    my $list_pref = $app->list_pref($type);
670    my ( %terms, %args );
671    %param = ( %param, %$list_pref );
672    my $cols   = $class->column_names;
673    my $limit  = $list_pref->{rows};
674    my $offset = $app->param('offset') || 0;
675
676    for my $name (@$cols) {
677        $terms{blog_id} = $blog_id, last
678          if $name eq 'blog_id';
679    }
680    if ( $type eq 'notification' ) {
681        $args{direction} = 'descend';
682        $args{offset}    = $offset;
683        $args{limit}     = $limit + 1;
684    }
685    elsif ( $type eq 'banlist' ) {
686        $param{use_plugins} = $app->config->UsePlugins;
687        $limit = 0;
688    }
689    my $iter = $class->load_iter( \%terms, \%args );
690
691    my (
692        @data,         @index_data,  @custom_data,
693        @archive_data, @system_data, @widget_data
694    );
695    my (%authors);
696    my $blog_class = $app->model('blog');
697    my $blog       = $blog_class->load($blog_id);
698    my $set        = $blog ? $blog->template_set : undef;
699    require MT::DefaultTemplates;
700    my $dtmpl = MT::DefaultTemplates->templates($set) || [];
701    my %dtmpl = map { $_->{type} => $_ } @$dtmpl;
702
703    while ( my $obj = $iter->() ) {
704        my $row = $obj->column_values;
705        if ( my $ts = $obj->created_on ) {
706            $row->{created_on_formatted} =
707              format_ts( MT::App::CMS::LISTING_DATE_FORMAT(), $ts, $blog, $app->user ? $app->user->preferred_language : undef );
708            $row->{created_on_time_formatted} =
709              format_ts( MT::App::CMS::LISTING_DATETIME_FORMAT(), $ts, $blog, $app->user ? $app->user->preferred_language : undef );
710            $row->{created_on_relative} = relative_date( $ts, time, $blog );
711        }
712        if ( $type eq 'template' ) {
713            $row->{name} = '' if !defined $row->{name};
714            $row->{name} =~ s/^\s+|\s+$//g;
715            $row->{name} = "(" . $app->translate("No Name") . ")"
716              if $row->{name} eq '';
717
718            if ( $obj->type eq 'index' ) {
719                push @index_data, $row;
720                $row->{rebuild_me} =
721                  defined $row->{rebuild_me} ? $row->{rebuild_me} : 1;
722                my $published_url = $obj->published_url;
723                $row->{published_url} = $published_url if $published_url;
724            }
725            elsif ( $obj->type eq 'custom' ) {
726                push @custom_data, $row;
727            }
728            elsif ( $obj->type eq 'widget' ) {
729                push @widget_data, $row;
730            }
731            elsif ($obj->type eq 'archive'
732                || $obj->type eq 'category'
733                || $obj->type eq 'page'
734                || $obj->type eq 'individual' )
735            {
736
737                # FIXME: enumeration of types
738                push @archive_data, $row;
739            }
740            else {
741                if ( my $def_tmpl = $dtmpl{ $obj->type } ) {
742                    $row->{description} = $def_tmpl->{description_label};
743                }
744                else {
745
746                    # unknown system template; skip over it
747                    # or should we change it to a custom template
748                    # right now?
749                    next;
750                }
751                push @system_data, $row;
752            }
753            $param{search_label} = $app->translate('Templates');
754        }
755        else {
756            if ( $limit && ( scalar @data == $limit ) ) {
757                $param{next_offset} = 1;
758                last;
759            }
760            push @data, $row;
761        }
762        if ( $type eq 'ping' ) {
763            return $app->list_pings();
764            require MT::Trackback;
765            require MT::Entry;
766            my $tb_center = MT::Trackback->load( $obj->tb_id );
767            my $entry     = MT::Entry->load( $tb_center->entry_id )
768                or return $app->error($app->translate('Can\'t load entry #[_1].', $tb_center->entry_id));
769            if ( my $ts = $obj->created_on ) {
770                $row->{created_on_time_formatted} =
771                  format_ts( MT::App::CMS::LISTING_DATETIME_FORMAT(), $ts, $blog, $app->user ? $app->user->preferred_language : undef );
772                $row->{has_edit_access} = $perms->can_edit_all_posts
773                  || $app->user->id == $entry->author_id;
774            }
775        }
776    }    # end loop over the set of objects;
777         # NOW transform the @data array
778    if ( $type eq 'notification' ) {
779        $app->add_breadcrumb( $app->translate('Notification List') );
780        $param{nav_notifications} = 1;
781
782        #@data = sort { $a->{email} cmp $b->{email} } @data;
783        $param{object_type}        = 'notification';
784        $param{list_noncron}       = 1;
785        $param{notification_count} = scalar @data;
786        $param{search_type} = 'entry';
787    }
788    if ( $type eq 'template' ) {
789        $app->add_breadcrumb( $app->translate('Templates') );
790        $param{nav_templates} = 1;
791        for my $ref ( \@index_data, \@custom_data, \@archive_data ) {
792            @$ref = sort { $a->{name} cmp $b->{name} } @$ref;
793        }
794        my $tab = $app->param('tab') || 'index';
795        $param{template_group}      = $tab;
796        $param{"tab_$tab"}          = 1;
797        $param{object_index_loop}   = \@index_data;
798        $param{object_custom_loop}  = \@custom_data;
799        $param{object_widget_loop}  = \@widget_data;
800        $param{object_archive_loop} = \@archive_data;
801        $param{object_system_loop}  = \@system_data;
802        $param{object_type}         = 'template';
803    }
804    else {
805        $param{object_loop} = \@data;
806    }
807
808    # add any breadcrumbs
809    if ( $type eq 'banlist' ) {
810        $app->add_breadcrumb( $app->translate('IP Banning') );
811        $param{nav_config}                       = 1;
812        $param{object_type}                      = 'banlist';
813        $param{show_ip_info}                     = 1;
814        $param{list_noncron}                     = 1;
815        $param{search_type} = 'entry';
816        $param{can_edit_config_or_publish_paths} = $perms->can_edit_config
817          || $perms->can_set_publish_paths;
818    }
819    elsif ( $type eq 'ping' ) {
820        $app->add_breadcrumb( $app->translate('TrackBacks') );
821        $param{nav_trackbacks} = 1;
822        $param{object_type}    = 'ping';
823    }
824    $param{object_count} = scalar @data;
825
826    if ( $type ne 'template' ) {
827        $param{offset}     = $offset;
828        $param{list_start} = $offset + 1;
829        delete $args{limit};
830        delete $args{offset};
831        $param{list_total} = $class->count( \%terms, \%args );
832        $param{list_end}        = $offset + ( scalar @data );
833        $param{next_offset_val} = $offset + ( scalar @data );
834
835    #$param{next_offset} = $param{next_offset_val} < $param{list_total} ? 1 : 0;
836        $param{next_max} = $param{list_total} - $limit;
837        $param{next_max} = 0 if ( $param{next_max} || 0 ) < $offset + 1;
838        if ( $offset > 0 ) {
839            $param{prev_offset}     = 1;
840            $param{prev_offset_val} = $offset - $limit;
841            $param{prev_offset_val} = 0 if $param{prev_offset_val} < 0;
842        }
843    }
844
845    $app->load_list_actions( $type, \%param );
846
847    $param{saved}         = $q->param('saved');
848    $param{saved_deleted} = $q->param('saved_deleted');
849    $param{page_actions}  = $app->page_actions( 'list_' . $type );
850    unless ( $param{screen_class} ) {
851        $param{screen_class} = "list-$type";
852    }
853    $app->load_tmpl( "list_${type}.tmpl", \%param );
854}
855
856sub delete {
857    my $app  = shift;
858    my $q    = $app->param;
859    my $type = $q->param('_type');
860
861    return $app->errtrans("Invalid request.")
862      unless $type;
863
864    return $app->error( $app->translate("Invalid request.") )
865      if $app->request_method() ne 'POST';
866
867    # being a general-purpose method, lets look for a mode handler
868    # that is specifically for editing this type. if we find it,
869    # reroute to it.
870
871    my $delete_mode = 'delete_' . $type;
872    if ( my $hdlrs = $app->handlers_for_mode($delete_mode) ) {
873        return $app->forward($delete_mode);
874    }
875
876    my $parent  = $q->param('parent');
877    my $blog_id = $q->param('blog_id');
878    my $class   = $app->model($type) or return;
879    my $perms   = $app->permissions;
880    my $author  = $app->user;
881
882    $app->validate_magic() or return;
883
884    my ( $entry_id, $cat_id, $author_id ) = ( "", "", "" );
885    my %rebuild_entries;
886    my @rebuild_cats;
887    my $required_items = 0;
888    for my $id ( $q->param('id') ) {
889        next unless $id;    # avoid 'empty' ids
890        if ( ( $type eq 'association' ) && ( $id =~ /PSEUDO-/ ) ) {
891            require MT::CMS::User;
892            MT::CMS::User::_delete_pseudo_association($app, $id);
893            next;
894        }
895
896        my $obj = $class->load($id);
897        next unless $obj;
898        $app->run_callbacks( 'cms_delete_permission_filter.' . $type,
899            $app, $obj )
900          || return $app->error(
901            $app->translate( "Permission denied: [_1]", $app->errstr() ) );
902
903        if ( $type eq 'comment' ) {
904            $entry_id = $obj->entry_id;
905            $rebuild_entries{$entry_id} = 1 if $obj->visible;
906        }
907        elsif ( $type eq 'ping' || $type eq 'ping_cat' ) {
908            require MT::Trackback;
909            my $tb = MT::Trackback->load( $obj->tb_id );
910            if ($tb) {
911                $entry_id = $tb->entry_id;
912                $cat_id   = $tb->category_id;
913                if ( $obj->visible ) {
914                    $rebuild_entries{$entry_id} = 1 if $entry_id;
915                    push @rebuild_cats, $cat_id if $cat_id;
916                }
917            }
918        }
919        elsif ( $type eq 'tag' ) {
920
921            # if we're in a blog context, remove ONLY tags from that weblog
922            if ($blog_id) {
923                my $ot_class  = $app->model('objecttag');
924                my $obj_type  = $q->param('__type') || 'entry';
925                my $obj_class = $app->model($obj_type);
926                my $iter      = $ot_class->load_iter(
927                    {
928                        blog_id           => $blog_id,
929                        object_datasource => $obj_class->datasource,
930                        tag_id            => $id
931                    },
932                    {
933                        'join' => $obj_class->join_on(
934                            undef,
935                            {
936                                id => \'= objecttag_object_id',
937                                (
938                                    $obj_class =~ m/asset/i
939                                    ? ()
940                                    : ( class => $obj_class->class_type )
941                                )
942                            }
943                        )
944                    }
945                );
946
947                if ($iter) {
948                    my @ot;
949                    while ( my $obj = $iter->() ) {
950                        push @ot, $obj->id;
951                    }
952                    foreach (@ot) {
953                        my $obj = $ot_class->load($_);
954                        next unless $obj;
955                        $obj->remove
956                          or return $app->errtrans( 'Removing tag failed: [_1]',
957                            $obj->errstr );
958                    }
959                }
960
961                $app->run_callbacks( 'cms_post_delete.' . $type, $app, $obj );
962                next;
963
964            }
965        }
966        elsif ( $type eq 'category' ) {
967            my @kids = MT::Category->load( { parent => $id } );
968            return $app->errtrans(
969"You can't delete that category because it has sub-categories. Move or delete the sub-categories first if you want to delete this one."
970            ) if @kids;
971            if ( $app->config('DeleteFilesAtRebuild') ) {
972                require MT::Blog;
973                require MT::Entry;
974                require MT::Placement;
975                my $blog = MT::Blog->load($blog_id)
976                    or return $app->error($app->translate('Can\'t load blog #[_1].', $blog_id));
977                my $at   = $blog->archive_type;
978                if ( $at && $at ne 'None' ) {
979                    my @at = split /,/, $at;
980                    for my $target (@at) {
981                        my $archiver = $app->publisher->archiver($target);
982                        next unless $archiver;
983                        if ( $archiver->category_based ) {
984                            if ( $archiver->date_based ) {
985                                my @entries = MT::Entry->load(
986                                    { status => MT::Entry::RELEASE() },
987                                    {
988                                        join => MT::Placement->join_on(
989                                            'entry_id',
990                                            { category_id => $id },
991                                            { unqiue      => 1 }
992                                        )
993                                    }
994                                );
995                                for (@entries) {
996                                    $app->publisher->remove_entry_archive_file(
997                                        Category    => $obj,
998                                        ArchiveType => $target,
999                                        Entry       => $_
1000                                    );
1001                                }
1002                            }
1003                            else {
1004                                $app->publisher->remove_entry_archive_file(
1005                                    Category    => $obj,
1006                                    ArchiveType => $target
1007                                );
1008                            }
1009                        }
1010                    }
1011                }
1012            }
1013        }
1014        elsif ( $type eq 'page' ) {
1015            if ( $app->config('DeleteFilesAtRebuild') ) {
1016                $app->publisher->remove_entry_archive_file(
1017                    Entry       => $obj,
1018                    ArchiveType => 'Page'
1019                );
1020            }
1021        }
1022        elsif ( $type eq 'author' ) {
1023            if ( $app->config->ExternalUserManagement ) {
1024                require MT::LDAP;
1025                my $ldap = MT::LDAP->new
1026                  or return $app->error(
1027                    MT->translate(
1028                        "Loading MT::LDAP failed: [_1].",
1029                        MT::LDAP->errstr
1030                    )
1031                  );
1032                my $dn = $ldap->get_dn( $obj->name );
1033                if ($dn) {
1034                    $app->add_return_arg( author_ldap_found => 1 );
1035                }
1036            }
1037        }
1038
1039        # FIXME: enumeration of types
1040        if (   $type eq 'template'
1041            && $obj->type !~
1042            /(custom|index|archive|page|individual|category|widget|backup)/o )
1043        {
1044            $required_items++;
1045        }
1046        else {
1047            $obj->remove
1048              or return $app->errtrans(
1049                'Removing [_1] failed: [_2]',
1050                $app->translate($type),
1051                $obj->errstr
1052              );
1053            $app->run_callbacks( 'cms_post_delete.' . $type, $app, $obj );
1054        }
1055    }
1056    require MT::Entry;
1057    for my $entry_id ( keys %rebuild_entries ) {
1058        my $entry = MT::Entry->load($entry_id);
1059        $app->rebuild_entry( Entry => $entry, BuildDependencies => 1 )
1060            or return $app->publish_error();
1061    }
1062    for my $cat_id (@rebuild_cats) {
1063
1064        # FIXME: What about other category-based archives?
1065        # What if user is not publishing category archives?
1066        my $cat = MT::Category->load($cat_id);
1067        $app->rebuild(
1068            Category    => $cat,
1069            BlogID      => $blog_id,
1070            ArchiveType => 'Category'
1071        ) or return $app->publish_error();
1072    }
1073    $app->run_callbacks( 'rebuild', MT::Blog->load($blog_id) );
1074    $app->add_return_arg(
1075        $type eq 'ping'
1076        ? ( saved_deleted_ping => 1 )
1077        : ( saved_deleted => 1 )
1078    );
1079    if ( $q->param('is_power_edit') ) {
1080        $app->add_return_arg( is_power_edit => 1 );
1081    }
1082    if ($required_items) {
1083        $app->add_return_arg(
1084            error => $app->translate("System templates can not be deleted.") );
1085    }
1086    $app->call_return;
1087}
1088
1089sub not_junk_test {
1090    my ( $eh, $app, $obj ) = @_;
1091    require MT::JunkFilter;
1092    MT::JunkFilter->filter($obj);
1093    $obj->is_junk ? 0 : 1;
1094}
1095
10961;
Note: See TracBrowser for help on using the browser.