root/branches/release-30/lib/MT/CMS/Common.pm @ 1369

Revision 1369, 37.9 kB (checked in by bchoate, 22 months ago)

Broke CMS into smaller parts to reduce memory footprint and group code into logical parts. BugId:58666

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