root/branches/release-34/lib/MT/CMS/Common.pm @ 1823

Revision 1823, 36.9 kB (checked in by takayama, 20 months ago)

Fixed BugId:67959
* Added check for result of object loading

  • 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_templatemaps' ) {
332            $cfg_screen = 'cfg_archives';
333        }
334        my $site_path = $obj->site_path;
335        my $fmgr      = $obj->file_mgr;
336        unless ( $fmgr->exists($site_path) ) {
337            $fmgr->mkpath($site_path);
338        }
339        $app->add_return_arg( no_writedir => 1 )
340          unless $fmgr->exists($site_path) && $fmgr->can_write($site_path);
341    }
342    elsif ( $type eq 'banlist' ) {
343        return $app->redirect(
344            $app->uri(
345                'mode' => 'list',
346                args   => {
347                    '_type' => 'banlist',
348                    blog_id => $blog_id,
349                    saved   => $obj->ip
350                }
351            )
352        );
353    }
354    elsif ( $type eq 'template' && $q->param('rebuild') ) {
355        $q->param( 'type',            'index-' . $obj->id );
356        $q->param( 'tmpl_id',         $obj->id );
357        $q->param( 'single_template', 1 );
358        require MT::CMS::Blog;
359        return MT::CMS::Blog::start_rebuild_pages($app);
360    }
361    elsif ( $type eq 'blog' ) {
362        return $app->redirect(
363            $app->uri(
364                'mode' => 'cfg_prefs',
365                args   => { blog_id => $blog_id, saved => 1 }
366            )
367        );
368    }
369    elsif ( $type eq 'author' ) {
370        # Delete the author's userpic thumb (if any); it'll be regenerated.
371        if ($original->userpic_asset_id != $obj->userpic_asset_id) {
372            my $thumb_file = $original->userpic_file();
373            my $fmgr = MT::FileMgr->new('Local');
374            if ($fmgr->exists($thumb_file)) {
375                $fmgr->delete($thumb_file);
376            }
377        }
378    }
379
380    $app->add_return_arg( 'id' => $obj->id ) if !$original->id;
381    $app->add_return_arg( 'saved' => 1 );
382    $app->call_return;
383}
384
385sub edit {
386    my $app  = shift;
387    my $q    = $app->param;
388    my $type = $q->param('_type');
389
390    return $app->errtrans("Invalid request.")
391      unless $type;
392
393    # being a general-purpose method, lets look for a mode handler
394    # that is specifically for editing this type. if we find it,
395    # reroute to it.
396
397    my $edit_mode = $app->mode . '_' . $type;
398    if ( my $hdlrs = $app->handlers_for_mode($edit_mode) ) {
399        return $app->forward($edit_mode, @_);
400    }
401
402    my %param = eval { $_[0] ? %{ $_[0] } : (); };
403    die Carp::longmess if $@;
404    my $class = $app->model($type) or return;
405    my $blog_id = $q->param('blog_id');
406
407    if ( defined($blog_id) && $blog_id ) {
408        return $app->error( $app->translate("Invalid parameter") )
409          unless ( $blog_id =~ m/\d+/ );
410    }
411
412    $app->remove_preview_file;
413
414    my $enc = $app->config->PublishCharset;
415    if ( $q->param('_recover') ) {
416        my $sess_obj = $app->autosave_session_obj;
417        if ($sess_obj) {
418            my $data = $sess_obj->thaw_data;
419            if ($data) {
420
421                # XMLHttpRequest always send text in UTF-8... right?
422                if ( 'utf-8' eq lc($enc) ) {
423                    $q->param( $_, $data->{$_} ) for keys %$data;
424                }
425                else {
426                    foreach ( keys %$data ) {
427                        my $encoded =
428                          MT::I18N::encode_text( $data->{$_}, 'utf-8', $enc );
429                        $q->param( $_, $encoded );
430                    }
431                }
432                $param{'recovered_object'} = 1;
433            }
434            else {
435                $param{'recovered_failed'} = 1;
436            }
437        }
438        else {
439            $param{'recovered_failed'} = 1;
440        }
441    }
442    elsif ( $q->param('qp') ) {
443        foreach (qw( title text )) {
444            my $data = $q->param($_);
445            my $encoded = MT::I18N::encode_text( $data, undef, $enc )
446              if $data;
447            $q->param( $_, $encoded );
448        }
449    }
450
451    $param{autosave_frequency} = $app->config->AutoSaveFrequency;
452
453    my $id     = $q->param('id');
454    my $perms  = $app->permissions;
455    my $author = $app->user;
456    my $cfg    = $app->config;
457    $param{styles} = '';
458    if ( $type eq 'author' ) {
459        if ( $perms || $blog_id ) {
460            return $app->return_to_dashboard( redirect => 1 );
461        }
462    }
463    else {
464        if ( ( !$perms || !$blog_id )
465            && ( $type eq 'entry' || $type eq 'page'
466                 || $type eq 'category' || $type eq 'folder'
467                 || $type eq 'comment'  || $type eq 'commenter'
468                 || $type eq 'ping' ) ) {
469            return $app->return_to_dashboard( redirect => 1 );
470        }
471    }
472
473    my $cols = $class->column_names;
474    require MT::Promise;
475    my $obj_promise = MT::Promise::delay(
476        sub {
477            return $class->load($id) || undef;
478        }
479    );
480
481    if ( !$author->is_superuser ) {
482        $app->run_callbacks( 'cms_view_permission_filter.' . $type,
483            $app, $id, $obj_promise )
484          || return $app->error(
485            $app->translate( "Permission denied: [_1]", $app->errstr() ) );
486    }
487    my $obj;
488    my $blog;
489    my $blog_class = $app->model('blog');
490    if ($blog_id) {
491        $blog = $blog_class->load($blog_id);
492    }
493    else {
494        $blog_id = 0;
495    }
496
497    if ($id) {    # object exists, we're just editing it.
498          # Stash the object itself so we don't have to keep forcing the promise
499        $obj = $obj_promise->force()
500          or return $app->error(
501            $app->translate(
502                "Load failed: [_1]",
503                $class->errstr || $app->translate("(no reason given)")
504            )
505          );
506
507        # Populate the param hash with the object's own values
508        for my $col (@$cols) {
509            $param{$col} =
510              defined $q->param($col) ? $q->param($col) : $obj->$col();
511        }
512
513        # Make certain any blog-specific element matches the blog we're
514        # dealing with. If not, call shenanigans.
515        if (   ( exists $param{blog_id} )
516            && ( $blog_id != ($obj->blog_id || 0) ) )
517        {
518            return $app->return_to_dashboard( redirect => 1 );
519        }
520
521        if ( $class->properties->{audit} ) {
522            my $creator = MT::Author->load(
523                {
524                    id   => $obj->created_by(),
525                    type => MT::Author::AUTHOR()
526                }
527            );
528            if ($creator) {
529                $param{created_by} = $creator->name;
530            }
531            if ( my $mod_by = $obj->modified_by() ) {
532                my $modified = MT::Author->load(
533                    {
534                        id   => $mod_by,
535                        type => MT::Author::AUTHOR()
536                    }
537                );
538                if ($modified) {
539                    $param{modified_by} = $modified->name;
540                }
541                else {
542                    $param{modified_by} = $app->translate("(user deleted)");
543                }
544
545                # Since legacy MT installs will still have a
546                # timestamp type for their modified_on fields,
547                # we cannot reliably disaply a modified on date
548                # by default; we must only show the modification
549                # date IF there is also a modified_by value.
550                if ( my $ts = $obj->modified_on ) {
551                    $param{modified_on_ts} = $ts;
552                    $param{modified_on_formatted} =
553                      format_ts( MT::App::CMS::LISTING_DATETIME_FORMAT(), $ts, undef, $app->user ? $app->user->preferred_language : undef );
554                }
555            }
556            if ( my $ts = $obj->created_on ) {
557                $param{created_on_ts} = $ts;
558                $param{created_on_formatted} =
559                  format_ts( MT::App::CMS::LISTING_DATETIME_FORMAT(), $ts, undef, $app->user ? $app->user->preferred_language : undef );
560            }
561        }
562
563        $param{new_object} = 0;
564    }
565    else {    # object is new
566        $param{new_object} = 1;
567        for my $col (@$cols) {
568            $param{$col} = $q->param($col);
569        }
570    }
571
572    my $res = $app->run_callbacks('cms_edit.' . $type, $app, $id, $obj, \%param);
573    if (!$res) {
574        return $app->error($app->callback_errstr());
575    }
576
577    if ($param{autosave_support}) {
578        # autosave support, but don't bother if we're reediting
579        if ( !$app->param('reedit') ) {
580            my $sess_obj = $app->autosave_session_obj;
581            if ($sess_obj) {
582                $param{autosaved_object_exists} = 1;
583                $param{autosaved_object_ts} =
584                  MT::Util::epoch2ts( $blog, $sess_obj->start );
585            }
586        }
587    }
588
589    if ( ( $q->param('msg') || "" ) eq 'nosuch' ) {
590        $param{nosuch} = 1;
591    }
592    for my $p ( $q->param ) {
593        $param{$p} = $q->param($p) if $p =~ /^saved/;
594    }
595    $param{page_actions} = $app->page_actions($type, $obj);
596    if ( $class->can('class_label') ) {
597        $param{object_label} = $class->class_label;
598    }
599    if ( $class->can('class_label_plural') ) {
600        $param{object_label_plural} = $class->class_label_plural;
601    }
602
603    my $tmpl_file = $param{output} || "edit_${type}.tmpl";
604    $param{object_type} ||= $type;
605    $param{screen_id} ||= "edit-$type";
606    $param{screen_class} .= " edit-$type";
607    return $app->load_tmpl( $tmpl_file, \%param );
608}
609
610sub list {
611    my $app  = shift;
612    my $q    = $app->param;
613    my $type = $q->param('_type');
614
615    return $app->errtrans("Invalid request.")
616      unless $type;
617
618    # being a general-purpose method, lets look for a mode handler
619    # that is specifically for editing this type. if we find it,
620    # reroute to it.
621
622    my $list_mode = 'list_' . $type;
623    if ( my $hdlrs = $app->handlers_for_mode($list_mode) ) {
624        return $app->forward($list_mode);
625    }
626
627    my %param = $_[0] ? %{ $_[0] } : ();
628
629    my $perms = $app->permissions;
630    return $app->return_to_dashboard( redirect => 1 )
631      unless $perms;
632    if (
633        $perms
634        && (   ( $type eq 'blog' && !$perms->can_edit_config )
635            || ( $type eq 'template'     && !$perms->can_edit_templates )
636            || ( $type eq 'notification' && !$perms->can_edit_notifications ) )
637      )
638    {
639        return $app->return_to_dashboard( permission => 1 );
640    }
641    my $id        = $q->param('id');
642    my $class     = $app->model($type) or return;
643    my $blog_id   = $q->param('blog_id');
644    my $list_pref = $app->list_pref($type);
645    my ( %terms, %args );
646    %param = ( %param, %$list_pref );
647    my $cols   = $class->column_names;
648    my $limit  = $list_pref->{rows};
649    my $offset = $app->param('offset') || 0;
650
651    for my $name (@$cols) {
652        $terms{blog_id} = $blog_id, last
653          if $name eq 'blog_id';
654    }
655    if ( $type eq 'notification' ) {
656        $args{direction} = 'descend';
657        $args{offset}    = $offset;
658        $args{limit}     = $limit + 1;
659    }
660    elsif ( $type eq 'banlist' ) {
661        $param{use_plugins} = $app->config->UsePlugins;
662        $limit = 0;
663    }
664    my $iter = $class->load_iter( \%terms, \%args );
665
666    my (
667        @data,         @index_data,  @custom_data,
668        @archive_data, @system_data, @widget_data
669    );
670    my (%authors);
671    my $blog_class = $app->model('blog');
672    my $blog       = $blog_class->load($blog_id);
673    my $set        = $blog ? $blog->template_set : undef;
674    require MT::DefaultTemplates;
675    my $dtmpl = MT::DefaultTemplates->templates($set) || [];
676    my %dtmpl = map { $_->{type} => $_ } @$dtmpl;
677
678    while ( my $obj = $iter->() ) {
679        my $row = $obj->column_values;
680        if ( my $ts = $obj->created_on ) {
681            $row->{created_on_formatted} =
682              format_ts( MT::App::CMS::LISTING_DATE_FORMAT(), $ts, $blog, $app->user ? $app->user->preferred_language : undef );
683            $row->{created_on_time_formatted} =
684              format_ts( MT::App::CMS::LISTING_DATETIME_FORMAT(), $ts, $blog, $app->user ? $app->user->preferred_language : undef );
685            $row->{created_on_relative} = relative_date( $ts, time, $blog );
686        }
687        if ( $type eq 'template' ) {
688            $row->{name} = '' if !defined $row->{name};
689            $row->{name} =~ s/^\s+|\s+$//g;
690            $row->{name} = "(" . $app->translate("No Name") . ")"
691              if $row->{name} eq '';
692
693            if ( $obj->type eq 'index' ) {
694                push @index_data, $row;
695                $row->{rebuild_me} =
696                  defined $row->{rebuild_me} ? $row->{rebuild_me} : 1;
697                my $published_url = $obj->published_url;
698                $row->{published_url} = $published_url if $published_url;
699            }
700            elsif ( $obj->type eq 'custom' ) {
701                push @custom_data, $row;
702            }
703            elsif ( $obj->type eq 'widget' ) {
704                push @widget_data, $row;
705            }
706            elsif ($obj->type eq 'archive'
707                || $obj->type eq 'category'
708                || $obj->type eq 'page'
709                || $obj->type eq 'individual' )
710            {
711
712                # FIXME: enumeration of types
713                push @archive_data, $row;
714            }
715            else {
716                if ( my $def_tmpl = $dtmpl{ $obj->type } ) {
717                    $row->{description} = $def_tmpl->{description_label};
718                }
719                else {
720
721                    # unknown system template; skip over it
722                    # or should we change it to a custom template
723                    # right now?
724                    next;
725                }
726                push @system_data, $row;
727            }
728            $param{search_label} = $app->translate('Templates');
729        }
730        else {
731            if ( $limit && ( scalar @data == $limit ) ) {
732                $param{next_offset} = 1;
733                last;
734            }
735            push @data, $row;
736        }
737        if ( $type eq 'ping' ) {
738            return $app->list_pings();
739            require MT::Trackback;
740            require MT::Entry;
741            my $tb_center = MT::Trackback->load( $obj->tb_id );
742            my $entry     = MT::Entry->load( $tb_center->entry_id )
743                or return $app->error($app->translate('Can\'t load entry #[_1].', $tb_center->entry_id));
744            if ( my $ts = $obj->created_on ) {
745                $row->{created_on_time_formatted} =
746                  format_ts( MT::App::CMS::LISTING_DATETIME_FORMAT(), $ts, $blog, $app->user ? $app->user->preferred_language : undef );
747                $row->{has_edit_access} = $perms->can_edit_all_posts
748                  || $app->user->id == $entry->author_id;
749            }
750        }
751    }    # end loop over the set of objects;
752         # NOW transform the @data array
753    if ( $type eq 'notification' ) {
754        $app->add_breadcrumb( $app->translate('Notification List') );
755        $param{nav_notifications} = 1;
756
757        #@data = sort { $a->{email} cmp $b->{email} } @data;
758        $param{object_type}        = 'notification';
759        $param{list_noncron}       = 1;
760        $param{notification_count} = scalar @data;
761        $param{search_type} = 'entry';
762    }
763    if ( $type eq 'template' ) {
764        $app->add_breadcrumb( $app->translate('Templates') );
765        $param{nav_templates} = 1;
766        for my $ref ( \@index_data, \@custom_data, \@archive_data ) {
767            @$ref = sort { $a->{name} cmp $b->{name} } @$ref;
768        }
769        my $tab = $app->param('tab') || 'index';
770        $param{template_group}      = $tab;
771        $param{"tab_$tab"}          = 1;
772        $param{object_index_loop}   = \@index_data;
773        $param{object_custom_loop}  = \@custom_data;
774        $param{object_widget_loop}  = \@widget_data;
775        $param{object_archive_loop} = \@archive_data;
776        $param{object_system_loop}  = \@system_data;
777        $param{object_type}         = 'template';
778    }
779    else {
780        $param{object_loop} = \@data;
781    }
782
783    # add any breadcrumbs
784    if ( $type eq 'banlist' ) {
785        $app->add_breadcrumb( $app->translate('IP Banning') );
786        $param{nav_config}                       = 1;
787        $param{object_type}                      = 'banlist';
788        $param{show_ip_info}                     = 1;
789        $param{list_noncron}                     = 1;
790        $param{search_type} = 'entry';
791        $param{can_edit_config_or_publish_paths} = $perms->can_edit_config
792          || $perms->can_set_publish_paths;
793    }
794    elsif ( $type eq 'ping' ) {
795        $app->add_breadcrumb( $app->translate('TrackBacks') );
796        $param{nav_trackbacks} = 1;
797        $param{object_type}    = 'ping';
798    }
799    $param{object_count} = scalar @data;
800
801    if ( $type ne 'template' ) {
802        $param{offset}     = $offset;
803        $param{list_start} = $offset + 1;
804        delete $args{limit};
805        delete $args{offset};
806        $param{list_total} = $class->count( \%terms, \%args );
807        $param{list_end}        = $offset + ( scalar @data );
808        $param{next_offset_val} = $offset + ( scalar @data );
809
810    #$param{next_offset} = $param{next_offset_val} < $param{list_total} ? 1 : 0;
811        $param{next_max} = $param{list_total} - $limit;
812        $param{next_max} = 0 if ( $param{next_max} || 0 ) < $offset + 1;
813        if ( $offset > 0 ) {
814            $param{prev_offset}     = 1;
815            $param{prev_offset_val} = $offset - $limit;
816            $param{prev_offset_val} = 0 if $param{prev_offset_val} < 0;
817        }
818    }
819
820    $app->load_list_actions( $type, \%param );
821
822    $param{saved}         = $q->param('saved');
823    $param{saved_deleted} = $q->param('saved_deleted');
824    $param{page_actions}  = $app->page_actions( 'list_' . $type );
825    unless ( $param{screen_class} ) {
826        $param{screen_class} = "list-$type";
827    }
828    $app->load_tmpl( "list_${type}.tmpl", \%param );
829}
830
831sub delete {
832    my $app  = shift;
833    my $q    = $app->param;
834    my $type = $q->param('_type');
835
836    return $app->errtrans("Invalid request.")
837      unless $type;
838
839    return $app->error( $app->translate("Invalid request.") )
840      if $app->request_method() ne 'POST';
841
842    # being a general-purpose method, lets look for a mode handler
843    # that is specifically for editing this type. if we find it,
844    # reroute to it.
845
846    my $delete_mode = 'delete_' . $type;
847    if ( my $hdlrs = $app->handlers_for_mode($delete_mode) ) {
848        return $app->forward($delete_mode);
849    }
850
851    my $parent  = $q->param('parent');
852    my $blog_id = $q->param('blog_id');
853    my $class   = $app->model($type) or return;
854    my $perms   = $app->permissions;
855    my $author  = $app->user;
856
857    $app->validate_magic() or return;
858
859    my ( $entry_id, $cat_id, $author_id ) = ( "", "", "" );
860    my %rebuild_entries;
861    my @rebuild_cats;
862    my $required_items = 0;
863    for my $id ( $q->param('id') ) {
864        next unless $id;    # avoid 'empty' ids
865        if ( ( $type eq 'association' ) && ( $id =~ /PSEUDO-/ ) ) {
866            $app->_delete_pseudo_association($id);
867            next;
868        }
869
870        my $obj = $class->load($id);
871        next unless $obj;
872        $app->run_callbacks( 'cms_delete_permission_filter.' . $type,
873            $app, $obj )
874          || return $app->error(
875            $app->translate( "Permission denied: [_1]", $app->errstr() ) );
876
877        if ( $type eq 'comment' ) {
878            $entry_id = $obj->entry_id;
879            $rebuild_entries{$entry_id} = 1 if $obj->visible;
880        }
881        elsif ( $type eq 'ping' || $type eq 'ping_cat' ) {
882            require MT::Trackback;
883            my $tb = MT::Trackback->load( $obj->tb_id );
884            if ($tb) {
885                $entry_id = $tb->entry_id;
886                $cat_id   = $tb->category_id;
887                if ( $obj->visible ) {
888                    $rebuild_entries{$entry_id} = 1 if $entry_id;
889                    push @rebuild_cats, $cat_id if $cat_id;
890                }
891            }
892        }
893        elsif ( $type eq 'tag' ) {
894
895            # if we're in a blog context, remove ONLY tags from that weblog
896            if ($blog_id) {
897                my $ot_class  = $app->model('objecttag');
898                my $obj_type  = $q->param('__type') || 'entry';
899                my $obj_class = $app->model($obj_type);
900                my $iter      = $ot_class->load_iter(
901                    {
902                        blog_id           => $blog_id,
903                        object_datasource => $obj_class->datasource,
904                        tag_id            => $id
905                    },
906                    {
907                        'join' => $obj_class->join_on(
908                            undef,
909                            {
910                                id => \'= objecttag_object_id',
911                                (
912                                    $obj_class =~ m/asset/i
913                                    ? ()
914                                    : ( class => $obj_class->class_type )
915                                )
916                            }
917                        )
918                    }
919                );
920
921                if ($iter) {
922                    my @ot;
923                    while ( my $obj = $iter->() ) {
924                        push @ot, $obj->id;
925                    }
926                    foreach (@ot) {
927                        my $obj = $ot_class->load($_);
928                        next unless $obj;
929                        $obj->remove
930                          or return $app->errtrans( 'Removing tag failed: [_1]',
931                            $obj->errstr );
932                    }
933                }
934
935                $app->run_callbacks( 'cms_post_delete.' . $type, $app, $obj );
936                next;
937
938            }
939        }
940        elsif ( $type eq 'category' ) {
941            my @kids = MT::Category->load( { parent => $id } );
942            return $app->errtrans(
943"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."
944            ) if @kids;
945            if ( $app->config('DeleteFilesAtRebuild') ) {
946                require MT::Blog;
947                require MT::Entry;
948                require MT::Placement;
949                my $blog = MT::Blog->load($blog_id)
950                    or return $app->error($app->translate('Can\'t load blog #[_1].', $blog_id));
951                my $at   = $blog->archive_type;
952                if ( $at && $at ne 'None' ) {
953                    my @at = split /,/, $at;
954                    for my $target (@at) {
955                        my $archiver = $app->publisher->archiver($target);
956                        next unless $archiver;
957                        if ( $archiver->category_based ) {
958                            if ( $archiver->date_based ) {
959                                my @entries = MT::Entry->load(
960                                    { status => MT::Entry::RELEASE() },
961                                    {
962                                        join => MT::Placement->join_on(
963                                            'entry_id',
964                                            { category_id => $id },
965                                            { unqiue      => 1 }
966                                        )
967                                    }
968                                );
969                                for (@entries) {
970                                    $app->publisher->remove_entry_archive_file(
971                                        Category    => $obj,
972                                        ArchiveType => $target,
973                                        Entry       => $_
974                                    );
975                                }
976                            }
977                            else {
978                                $app->publisher->remove_entry_archive_file(
979                                    Category    => $obj,
980                                    ArchiveType => $target
981                                );
982                            }
983                        }
984                    }
985                }
986            }
987        }
988        elsif ( $type eq 'page' ) {
989            if ( $app->config('DeleteFilesAtRebuild') ) {
990                $app->publisher->remove_entry_archive_file(
991                    Entry       => $obj,
992                    ArchiveType => 'Page'
993                );
994            }
995        }
996        elsif ( $type eq 'author' ) {
997            if ( $app->config->ExternalUserManagement ) {
998                require MT::LDAP;
999                my $ldap = MT::LDAP->new
1000                  or return $app->error(
1001                    MT->translate(
1002                        "Loading MT::LDAP failed: [_1].",
1003                        MT::LDAP->errstr
1004                    )
1005                  );
1006                my $dn = $ldap->get_dn( $obj->name );
1007                if ($dn) {
1008                    $app->add_return_arg( author_ldap_found => 1 );
1009                }
1010            }
1011        }
1012
1013        # FIXME: enumeration of types
1014        if (   $type eq 'template'
1015            && $obj->type !~
1016            /(custom|index|archive|page|individual|category|widget|backup)/o )
1017        {
1018            $required_items++;
1019        }
1020        else {
1021            $obj->remove
1022              or return $app->errtrans(
1023                'Removing [_1] failed: [_2]',
1024                $app->translate($type),
1025                $obj->errstr
1026              );
1027            $app->run_callbacks( 'cms_post_delete.' . $type, $app, $obj );
1028        }
1029    }
1030    require MT::Entry;
1031    for my $entry_id ( keys %rebuild_entries ) {
1032        my $entry = MT::Entry->load($entry_id);
1033        $app->rebuild_entry( Entry => $entry, BuildDependencies => 1 )
1034            or return $app->publish_error();
1035    }
1036    for my $cat_id (@rebuild_cats) {
1037
1038        # FIXME: What about other category-based archives?
1039        # What if user is not publishing category archives?
1040        my $cat = MT::Category->load($cat_id);
1041        $app->rebuild(
1042            Category    => $cat,
1043            BlogID      => $blog_id,
1044            ArchiveType => 'Category'
1045        ) or return $app->publish_error();
1046    }
1047    $app->run_callbacks( 'rebuild', MT::Blog->load($blog_id) );
1048    $app->add_return_arg(
1049        $type eq 'ping'
1050        ? ( saved_deleted_ping => 1 )
1051        : ( saved_deleted => 1 )
1052    );
1053    if ( $q->param('is_power_edit') ) {
1054        $app->add_return_arg( is_power_edit => 1 );
1055    }
1056    if ($required_items) {
1057        $app->add_return_arg(
1058            error => $app->translate("System templates can not be deleted.") );
1059    }
1060    $app->call_return;
1061}
1062
1063sub not_junk_test {
1064    my ( $eh, $app, $obj ) = @_;
1065    require MT::JunkFilter;
1066    MT::JunkFilter->filter($obj);
1067    $obj->is_junk ? 0 : 1;
1068}
1069
10701;
Note: See TracBrowser for help on using the browser.