root/branches/release-36/lib/MT/CMS/Common.pm @ 2026

Revision 2026, 38.6 kB (checked in by auno, 19 months ago)

Improved perfomance of adding template maps. BugzID:69035
* do not create FileInfo during add_map
* create FileInfo when the template map is set dynamically

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