root/branches/release-36/lib/MT/CMS/Entry.pm @ 2067

Revision 2067, 78.7 kB (checked in by bsmith, 19 months ago)

bugzid:54806 - use default entry settings for status, comments, trackbacks for pages

  • Property svn:keywords set to Id Revision
Line 
1package MT::CMS::Entry;
2
3use strict;
4use MT::Util qw( format_ts relative_date remove_html encode_html encode_js
5    encode_url archive_file_for offset_time_list );
6use MT::I18N qw( substr_text const length_text wrap_text encode_text
7    break_up_text first_n_text guess_encoding );
8
9sub edit {
10    my $cb = shift;
11    my ($app, $id, $obj, $param) = @_;
12
13    my $q = $app->param;
14    my $type = $q->param('_type');
15    my $perms = $app->permissions;
16    my $blog_class = $app->model('blog');
17    my $blog = $app->blog;
18    my $blog_id = $blog->id;
19    my $author = $app->user;
20    my $class = $app->model($type);
21
22    # to trigger autosave logic in main edit routine
23    $param->{autosave_support} = 1;
24
25    if ($id) {
26        return $app->error( $app->translate("Invalid parameter") )
27          if $obj->class ne $type;
28
29        $param->{nav_entries} = 1;
30        $param->{entry_edit}  = 1;
31        if ( $type eq 'entry' ) {
32            $app->add_breadcrumb(
33                $app->translate('Entries'),
34                $app->uri(
35                    'mode' => 'list_entries',
36                    args   => { blog_id => $blog_id }
37                )
38            );
39        }
40        elsif ( $type eq 'page' ) {
41            $app->add_breadcrumb(
42                $app->translate('Pages'),
43                $app->uri(
44                    'mode' => 'list_pages',
45                    args   => { blog_id => $blog_id }
46                )
47            );
48        }
49        $app->add_breadcrumb( $obj->title
50              || $app->translate('(untitled)') );
51        ## Don't pass in author_id, because it will clash with the
52        ## author_id parameter of the author currently logged in.
53        delete $param->{'author_id'};
54        unless ( defined $q->param('category_id') ) {
55            delete $param->{'category_id'};
56            if ( my $cat = $obj->category ) {
57                $param->{category_id} = $cat->id;
58            }
59        }
60        $blog_id = $obj->blog_id;
61        my $blog = $app->model('blog')->load($blog_id);
62        my $status = $q->param('status') || $obj->status;
63        $param->{ "status_" . MT::Entry::status_text($status) } = 1;
64        $param->{ "allow_comments_"
65              . ( $q->param('allow_comments') || $obj->allow_comments || 0 )
66          } = 1;
67        $param->{'authored_on_date'} = $q->param('authored_on_date')
68          || format_ts( "%Y-%m-%d", $obj->authored_on, $blog, $app->user ? $app->user->preferred_language : undef );
69        $param->{'authored_on_time'} = $q->param('authored_on_time')
70          || format_ts( "%H:%M:%S", $obj->authored_on, $blog, $app->user ? $app->user->preferred_language : undef );
71
72        $param->{num_comments} = $id ? $obj->comment_count : 0;
73        $param->{num_pings} = $id ? $obj->ping_count : 0;
74
75        # Check permission to send notifications and if the
76        # blog has notification list subscribers
77        if (   $perms->can_send_notifications
78            && $obj->status == MT::Entry::RELEASE() )
79        {
80            my $not_class = $app->model('notification');
81            $param->{can_send_notifications} = 1;
82            $param->{has_subscribers} =
83              $not_class->exist( { blog_id => $blog_id } );
84        }
85
86        ## Load next and previous entries for next/previous links
87        if ( my $next = $obj->next ) {
88            $param->{next_entry_id} = $next->id;
89        }
90        if ( my $prev = $obj->previous ) {
91            $param->{previous_entry_id} = $prev->id;
92        }
93
94        $param->{has_any_pinged_urls} = ( $obj->pinged_urls || '' ) =~ m/\S/;
95        $param->{ping_errors}         = $q->param('ping_errors');
96        $param->{can_view_log}        = $app->user->can_view_log;
97        $param->{entry_permalink}     = $obj->permalink;
98        $param->{'mode_view_entry'}   = 1;
99        $param->{'basename_old'}      = $obj->basename;
100
101        if ( my $ts = $obj->authored_on ) {
102            $param->{authored_on_ts} = $ts;
103            $param->{authored_on_formatted} =
104              format_ts( MT::App::CMS::LISTING_DATETIME_FORMAT(), $ts, $blog, $app->user ? $app->user->preferred_language : undef );
105        }
106
107        $app->load_list_actions( $type, $param );
108    } else {
109        $param->{entry_edit} = 1;
110        if ($blog_id) {
111            if ( $type eq 'entry' ) {
112                $app->add_breadcrumb(
113                    $app->translate('Entries'),
114                    $app->uri(
115                        'mode' => 'list_entries',
116                        args   => { blog_id => $blog_id }
117                    )
118                );
119                $app->add_breadcrumb( $app->translate('New Entry') );
120                $param->{nav_new_entry} = 1;
121            }
122            elsif ( $type eq 'page' ) {
123                $app->add_breadcrumb(
124                    $app->translate('Pages'),
125                    $app->uri(
126                        'mode' => 'list_pages',
127                        args   => { blog_id => $blog_id }
128                    )
129                );
130                $app->add_breadcrumb( $app->translate('New Page') );
131                $param->{nav_new_page} = 1;
132            }
133        }
134
135        # (if there is no blog_id parameter, this is a
136        # bookmarklet post and doesn't need breadcrumbs.)
137        delete $param->{'author_id'};
138        delete $param->{'pinged_urls'};
139        my $blog_timezone = 0;
140        if ($blog_id) {
141            my $blog = $blog_class->load($blog_id)
142                or return $app->error($app->translate('Can\'t load blog #[_1].', $blog_id));
143            $blog_timezone = $blog->server_offset();
144
145            # new entry defaults used for new entries AND new pages.
146            my $def_status = $q->param('status')
147              || $blog->status_default;
148            if ($def_status) {
149                $param->{ "status_"
150                      . MT::Entry::status_text($def_status) } = 1;
151            }
152            if ( $param->{status} ) {
153                $param->{ 'allow_comments_'
154                      . $q->param('allow_comments') } = 1;
155                $param->{allow_comments} = $q->param('allow_comments');
156                $param->{allow_pings}    = $q->param('allow_pings');
157            }
158            else {
159                # new edit
160                $param->{ 'allow_comments_'
161                      . $blog->allow_comments_default } = 1;
162                $param->{allow_comments} = $blog->allow_comments_default;
163                $param->{allow_pings}    = $blog->allow_pings_default;
164            }
165        }
166
167        require POSIX;
168        my @now = offset_time_list( time, $blog );
169        $param->{authored_on_date} = $q->param('authored_on_date')
170          || POSIX::strftime( "%Y-%m-%d", @now );
171        $param->{authored_on_time} = $q->param('authored_on_time')
172          || POSIX::strftime( "%H:%M:%S", @now );
173    }
174
175    ## Load categories and process into loop for category pull-down.
176    require MT::Placement;
177    my $cat_id = $param->{category_id};
178    my $depth  = 0;
179    my %places;
180
181    # set the dirty flag in js?
182    $param->{dirty} = $q->param('dirty') ? 1 : 0;
183
184    if ($id) {
185        my @places =
186          MT::Placement->load( { entry_id => $id, is_primary => 0 } );
187        %places = map { $_->category_id => 1 } @places;
188    }
189    my $cats = $q->param('category_ids');
190    if ( defined $cats ) {
191        if ( my @cats = split /,/, $cats ) {
192            $cat_id = $cats[0];
193            %places = map { $_ => 1 } @cats;
194        }
195    }
196    if ( $q->param('reedit') ) {
197        $param->{reedit} = 1;
198        if ( !$q->param('basename_manual') ) {
199            $param->{'basename'} = '';
200        }
201    }
202    if ($blog) {
203        $param->{file_extension} = $blog->file_extension || '';
204        $param->{file_extension} = '.' . $param->{file_extension}
205          if $param->{file_extension} ne '';
206    }
207    else {
208        $param->{file_extension} = 'html';
209    }
210
211    ## Now load user's preferences and customization for new/edit
212    ## entry page.
213    if ($perms) {
214        my $pref_param = $app->load_entry_prefs( $perms->entry_prefs );
215        %$param = ( %$param, %$pref_param );
216        $param->{disp_prefs_bar_colspan} = $param->{new_object} ? 1 : 2;
217
218        # Completion for tags
219        my $auth_prefs = $author->entry_prefs;
220        if ( my $delim = chr( $auth_prefs->{tag_delim} ) ) {
221            if ( $delim eq ',' ) {
222                $param->{'auth_pref_tag_delim_comma'} = 1;
223            }
224            elsif ( $delim eq ' ' ) {
225                $param->{'auth_pref_tag_delim_space'} = 1;
226            }
227            else {
228                $param->{'auth_pref_tag_delim_other'} = 1;
229            }
230            $param->{'auth_pref_tag_delim'} = $delim;
231        }
232
233        require JSON;
234        my $json = JSON->new( autoconv => 0 ); # stringifies numbers this way
235        $param->{tags_js} =
236          $json->objToJson(
237            MT::Tag->cache( blog_id => $blog_id, class => 'MT::Entry', private => 1 )
238          );
239
240        $param->{can_edit_categories} = $perms->can_edit_categories;
241    }
242
243    my $data = $app->_build_category_list(
244        blog_id => $blog_id,
245        markers => 1,
246        type    => $class->container_type,
247    );
248    my $top_cat = $cat_id;
249    my @sel_cats;
250    my $cat_tree = [];
251    if ( $type eq 'page' ) {
252        push @$cat_tree,
253          {
254            id    => -1,
255            label => '/',
256            basename => '/',
257            path  => [],
258          };
259        $top_cat ||= -1;
260    }
261    foreach (@$data) {
262        next unless exists $_->{category_id};
263        if ( $type eq 'page' ) {
264            $_->{category_path_ids} ||= [];
265            unshift @{ $_->{category_path_ids} }, -1;
266        }
267        push @$cat_tree,
268          {
269            id => $_->{category_id},
270            label => $_->{category_label} . ( $type eq 'page' ? '/' : '' ),
271            basename => $_->{category_basename} . ( $type eq 'page' ? '/' : '' ),
272            path => $_->{category_path_ids} || [],
273          };
274        push @sel_cats, $_->{category_id}
275          if $places{ $_->{category_id} }
276          && $_->{category_id} != $cat_id;
277    }
278    $param->{category_tree} = $cat_tree;
279    unshift @sel_cats, $top_cat if defined $top_cat && $top_cat ne "";
280    $param->{selected_category_loop}   = \@sel_cats;
281    $param->{have_multiple_categories} = scalar @$data > 1;
282
283    $param->{basename_limit} = ( $blog ? $blog->basename_limit : 0 ) || 30;
284
285    if ( $q->param('tags') ) {
286        $param->{tags} = $q->param('tags');
287    }
288    else {
289        if ($obj) {
290            my $tag_delim = chr( $app->user->entry_prefs->{tag_delim} );
291            require MT::Tag;
292            my $tags = MT::Tag->join( $tag_delim, $obj->tags );
293            $param->{tags} = $tags;
294        }
295    }
296
297    ## Load text filters if user displays them
298    my %entry_filters;
299    if ( defined( my $filter = $q->param('convert_breaks') ) ) {
300        $entry_filters{$filter} = 1;
301    }
302    elsif ($obj) {
303        %entry_filters = map { $_ => 1 } @{ $obj->text_filters };
304    }
305    elsif ($blog) {
306        my $cb = $author->text_format || $blog->convert_paras;
307        $cb = '__default__' if $cb eq '1';
308        $entry_filters{$cb} = 1;
309        $param->{convert_breaks} = $cb;
310    }
311    my $filters = MT->all_text_filters;
312    $param->{text_filters} = [];
313    for my $filter ( keys %$filters ) {
314        push @{ $param->{text_filters} },
315          {
316            filter_key      => $filter,
317            filter_label    => $filters->{$filter}{label},
318            filter_selected => $entry_filters{$filter},
319            filter_docs     => $filters->{$filter}{docs},
320          };
321    }
322    $param->{text_filters} =
323      [ sort { $a->{filter_key} cmp $b->{filter_key} }
324          @{ $param->{text_filters} } ];
325    unshift @{ $param->{text_filters} },
326      {
327        filter_key      => '0',
328        filter_label    => $app->translate('None'),
329        filter_selected => ( !keys %entry_filters ),
330      };
331
332    if ($blog) {
333        if ( !defined $param->{convert_breaks} ) {
334            my $cb = $blog->convert_paras;
335            $cb = '__default__' if $cb eq '1';
336            $param->{convert_breaks} = $cb;
337        }
338        my $ext = ( $blog->file_extension || '' );
339        $ext = '.' . $ext if $ext ne '';
340        $param->{blog_file_extension} = $ext;
341    }
342
343    my $rte;
344    if ($param->{convert_breaks} eq 'richtext') {
345        ## Rich Text editor
346        $rte = lc($app->config('RichTextEditor'));
347    }
348    else {
349        $rte = 'archetype';
350    }
351    my $editors = $app->registry("richtext_editors");
352    my $edit_reg = $editors->{$rte} || $editors->{archetype};
353    my $rich_editor_tmpl;
354    if ($rich_editor_tmpl = $edit_reg->{plugin}->load_tmpl($edit_reg->{template})) {
355        $param->{rich_editor} = $rte;
356        $param->{rich_editor_tmpl} = $rich_editor_tmpl;
357    }
358
359    $param->{object_type}  = $type;
360    $param->{quickpost_js} = MT::CMS::Entry::quickpost_js($app, $type);
361    if ( 'page' eq $type ) {
362        $param->{search_label} = $app->translate('pages');
363        $param->{output}       = 'edit_entry.tmpl';
364        $param->{screen_class} = 'edit-page edit-entry';
365    }
366    $param->{sitepath_configured} = $blog && $blog->site_path ? 1 : 0;
367    1;
368}
369
370sub list {
371    my $app = shift;
372    my ($param) = @_;
373    $param ||= {};
374
375    require MT::Entry;
376    my $type = $param->{type} || MT::Entry->class_type;
377    my $pkg = $app->model($type) or return "Invalid request.";
378
379    my $q     = $app->param;
380    my $perms = $app->permissions;
381    if ( $type eq 'page' ) {
382        if ( $perms
383            && ( !$perms->can_manage_pages ) )
384        {
385            return $app->errtrans("Permission denied.");
386        }
387    }
388    else {
389        if (
390            $perms
391            && (   !$perms->can_edit_all_posts
392                && !$perms->can_create_post
393                && !$perms->can_publish_post )
394          )
395        {
396            return $app->errtrans("Permission denied.");
397        }
398    }
399
400    my $list_pref = $app->list_pref($type);
401    my %param     = %$list_pref;
402    my $blog_id   = $q->param('blog_id');
403    my %terms;
404    $terms{blog_id} = $blog_id if $blog_id;
405    $terms{class} = $type;
406    my $limit = $list_pref->{rows};
407    my $offset = $app->param('offset') || 0;
408
409    if ( !$blog_id && !$app->user->is_superuser ) {
410        require MT::Permission;
411        $terms{blog_id} = [
412            map { $_->blog_id }
413              grep { $_->can_create_post || $_->can_edit_all_posts }
414              MT::Permission->load( { author_id => $app->user->id } )
415        ];
416    }
417
418    my %arg;
419    my $filter_key = $q->param('filter_key') || '';
420    my $filter_col = $q->param('filter')     || '';
421    my $filter_val = $q->param('filter_val');
422
423    # check blog_id for deciding to apply category filter or not
424    my ( $filter_name, $filter_value );    # human-readable versions
425    if ( !exists( $terms{$filter_col} ) ) {
426        if ( $filter_col eq 'category_id' ) {
427            $filter_name = $app->translate('Category');
428            require MT::Category;
429            my $cat = MT::Category->load($filter_val);
430            return $app->errtrans( "Load failed: [_1]", MT::Category->errstr )
431              unless $cat;
432            if ( $cat->blog_id != $blog_id ) {
433                $filter_key = '';
434                $filter_col = '';
435                $filter_val = '';
436            }
437            $filter_value = $cat->label;
438        }
439        elsif ( $filter_col eq 'asset_id' ) {
440            $filter_name = $app->translate('Asset');
441            my $asset_class = MT->model('asset');
442            my $asset = $asset_class->load($filter_val);
443            return $app->errtrans( "Load failed: [_1]", $asset_class->errstr )
444              unless $asset;
445            if ($asset->blog_id != $blog_id) {
446                $filter_key = '';
447                $filter_col = '';
448                $filter_val = '';
449            }
450            $filter_value = $param{asset_label} = $asset->label;
451        }
452    }
453    if ( $filter_col && $filter_val ) {
454        if ( 'power_edit' eq $filter_col ) {
455            $filter_col = 'id';
456            unless ( 'ARRAY' eq ref($filter_val) ) {
457                my @values = $app->param('filter_val');
458                $filter_val = \@values;
459            }
460        }
461        if ( !exists( $terms{$filter_col} ) ) {
462            if ( $filter_col eq 'category_id' ) {
463                $arg{'join'} = MT::Placement->join_on(
464                    'entry_id',
465                    { category_id => $filter_val },
466                    { unique      => 1 }
467                );
468            }
469            elsif ( $filter_col eq 'asset_id' ) {
470                $arg{'join'} = MT->model('objectasset')->join_on(
471                    'object_id',
472                    { object_ds => $type,
473                      asset_id  => $filter_val },
474                    { unique    => 1 }
475                );
476            }
477            elsif (( $filter_col eq 'normalizedtag' )
478                || ( $filter_col eq 'exacttag' ) )
479            {
480                my $normalize = ( $filter_col eq 'normalizedtag' );
481                require MT::Tag;
482                require MT::ObjectTag;
483                my $tag_delim   = chr( $app->user->entry_prefs->{tag_delim} );
484                my @filter_vals = MT::Tag->split( $tag_delim, $filter_val );
485                my @filter_tags = @filter_vals;
486                if ($normalize) {
487                    push @filter_tags, MT::Tag->normalize($_)
488                      foreach @filter_vals;
489                }
490                my @tags = MT::Tag->load( { name => [@filter_tags] },
491                    { binary => { name => 1 } } );
492                my @tag_ids;
493                foreach (@tags) {
494                    push @tag_ids, $_->id;
495                    if ($normalize) {
496                        my @more = MT::Tag->load(
497                            { n8d_id => $_->n8d_id ? $_->n8d_id : $_->id } );
498                        push @tag_ids, $_->id foreach @more;
499                    }
500                }
501                @tag_ids = (0) unless @tags;
502                $arg{'join'} = MT::ObjectTag->join_on(
503                    'object_id',
504                    {
505                        tag_id            => \@tag_ids,
506                        object_datasource => $pkg->datasource
507                    },
508                    { unique => 1 }
509                );
510            }
511            else {
512                $terms{$filter_col} = $filter_val;
513            }
514            $param{filter_args} = "&filter=" . encode_url($filter_col) . "&filter_val=" . encode_url($filter_val);
515
516            if (   ( $filter_col eq 'normalizedtag' )
517                || ( $filter_col eq 'exacttag' ) )
518            {
519                $filter_name  = $app->translate('Tag');
520                $filter_value = $filter_val;
521            }
522            elsif ( $filter_col eq 'author_id' ) {
523                $filter_name = $app->translate('User');
524                my $author = MT::Author->load($filter_val);
525                return $app->errtrans( "Load failed: [_1]", MT::Author->errstr )
526                  unless $author;
527                $filter_value = $author->name;
528            }
529            elsif ( $filter_col eq 'status' ) {
530                $filter_name = $app->translate('Entry Status');
531                $filter_value =
532                  $app->translate( MT::Entry::status_text($filter_val) );
533            }
534            if ( $filter_name && $filter_value ) {
535                $param{filter}                        = $filter_col;
536                $param{ 'filter_col_' . $filter_col } = 1;
537                $param{filter_val}                    = $filter_val;
538            }
539        }
540        $param{filter_unpub} = $filter_col eq 'status';
541    }
542    elsif ($filter_key) {
543        my $filters = $app->registry("list_filters", "entry") || {};
544        if ( my $filter = $filters->{$filter_key} ) {
545            if ( my $code = $filter->{code}
546                || $app->handler_to_coderef( $filter->{handler} ) )
547            {
548                $param{filter_key}   = $filter_key;
549                $param{filter_label} = $filter->{label};
550                $code->( \%terms, \%arg );
551            }
552        }
553    }
554    require MT::Category;
555    require MT::Placement;
556
557    my $total = $pkg->count( \%terms, \%arg ) || 0;
558    $arg{'sort'} = $type eq 'page' ? 'modified_on' : 'authored_on';
559    $arg{direction} = 'descend';
560    $arg{limit}     = $limit + 1;
561    if ( $total && $offset > $total - 1 ) {
562        $arg{offset} = $offset = $total - $limit;
563    }
564    elsif ( $offset && ( ( $offset < 0 ) || ( $total - $offset < $limit ) ) ) {
565        $arg{offset} = $offset = $total - $offset;
566    }
567    else {
568        $arg{offset} = $offset if $offset;
569    }
570
571    my $iter = $pkg->load_iter( \%terms, \%arg );
572
573    my $is_power_edit = $q->param('is_power_edit');
574    if ($is_power_edit) {
575        $param{has_expanded_mode} = 0;
576        delete $param{view_expanded};
577    }
578    else {
579        $param{has_expanded_mode} = 1;
580    }
581    my $data = build_entry_table( $app,
582        iter          => $iter,
583        is_power_edit => $is_power_edit,
584        param         => \%param,
585        type          => $type
586    );
587    delete $_->{object} foreach @$data;
588    delete $param{entry_table} unless @$data;
589
590    ## We tried to load $limit + 1 entries above; if we actually got
591    ## $limit + 1 back, we know we have another page of entries.
592    my $have_next_entry = @$data > $limit;
593    pop @$data while @$data > $limit;
594    if ($offset) {
595        $param{prev_offset}     = 1;
596        $param{prev_offset_val} = $offset - $limit;
597        $param{prev_offset_val} = 0 if $param{prev_offset_val} < 0;
598    }
599    if ($have_next_entry) {
600        $param{next_offset}     = 1;
601        $param{next_offset_val} = $offset + $limit;
602    }
603
604    $iter = MT::Author->load_iter(
605        { type => MT::Author::AUTHOR() },
606        {
607            'join' => $pkg->join_on(
608                'author_id',
609                { $blog_id ? ( blog_id => $blog_id ) : () },
610                {
611                    'unique'  => 1,
612                    'sort'    => 'authored_on',
613                    direction => 'descend'
614                }
615            ),
616            limit => 51,
617        }
618    );
619    my %seen;
620    my @authors;
621    while ( my $au = $iter->() ) {
622        next if $seen{ $au->id };
623        $seen{ $au->id } = 1;
624        my $row = {
625            author_name => $au->name,
626            author_id   => $au->id
627        };
628        push @authors, $row;
629        if ( @authors == 50 ) {
630            $iter->('finish');
631            last;
632        }
633    }
634    $param{entry_author_loop} = \@authors;
635
636    # $iter = $app->model('asset')->load_iter(
637    #     { class => '*', blog_id => $blog_id },
638    #     {
639    #         'join' => MT->model('objectasset')->join_on(
640    #             'asset_id',
641    #             {},
642    #             { unique => 1 }
643    #         ),
644    #         'sort'    => 'created_on',
645    #         direction => 'descend',
646    #     }
647    # );
648    # %seen = ();
649    # my @assets;
650    # while ( my $asset = $iter->() ) {
651    #     next if $seen{ $asset->id };
652    #     $seen{ $asset->id } = 1;
653    #     my $row = {
654    #         asset_label => $asset->label,
655    #         asset_id    => $asset->id,
656    #     };
657    #     push @assets, $row;
658    #     if ( @assets == 50 ) {
659    #         $iter->('finish');
660    #         last;
661    #     }
662    # }
663    # if ($filter_col eq 'asset_id' && !$seen{$filter_val}) {
664    #     push @assets, {
665    #         asset_label => $param{asset_label},
666    #         asset_id    => $filter_val,
667    #     };
668    # }
669    # $param{entry_asset_loop} = \@assets;
670
671    $param{page_actions}        = $app->page_actions( $app->mode );
672    $param{list_filters}        = $app->list_filters('entry');
673    $param{can_power_edit}      = $blog_id && !$is_power_edit;
674    $param{can_republish}       = $blog_id ? $perms->can_rebuild : 1;
675    $param{is_power_edit}       = $is_power_edit;
676    $param{saved_deleted}       = $q->param('saved_deleted');
677    $param{no_rebuild}          = $q->param('no_rebuild');
678    $param{saved}               = $q->param('saved');
679    $param{limit}               = $limit;
680    $param{offset}              = $offset;
681    $param{object_type}         = $type;
682    $param{object_label}        = $pkg->class_label;
683    $param{object_label_plural} = $param{search_label} =
684      $pkg->class_label_plural;
685    $param{list_start}  = $offset + 1;
686    $param{list_end}    = $offset + scalar @$data;
687    $param{list_total}  = $total;
688    $param{next_max}    = $param{list_total} - $limit;
689    $param{next_max}    = 0 if ( $param{next_max} || 0 ) < $offset + 1;
690    $param{nav_entries} = 1;
691    $param{feed_label}  = $app->translate( "[_1] Feed", $pkg->class_label );
692    $param{feed_url} =
693      $app->make_feed_link( $type, $blog_id ? { blog_id => $blog_id } : undef );
694    $app->add_breadcrumb( $pkg->class_label_plural );
695    $param{listing_screen} = 1;
696
697    unless ($blog_id) {
698        $param{system_overview_nav} = 1;
699    }
700    $param{container_label} = $pkg->container_label;
701    unless ( $param{screen_class} ) {
702        $param{screen_class} = "list-$type";
703        $param{screen_class} .= " list-entry"
704          if $param{object_type} eq "page";  # to piggyback on list-entry styles
705    }
706    $param{mode}            = $app->mode;
707    if ( my $blog = MT::Blog->load($blog_id) ) {
708        $param{sitepath_unconfigured} = $blog->site_path ? 0 : 1;
709    }
710
711    $param->{return_args} ||= $app->make_return_args;
712    my @return_args = grep { $_ !~ /offset=\d/ } split /&/, $param->{return_args};
713    $param{return_args} = join '&', @return_args;
714    $param{return_args} .= "&offset=$offset" if $offset;
715    $param{screen_id} = "list-entry";
716    $param{screen_id} = "list-page"
717      if $param{object_type} eq "page";
718    if ( $param{is_power_edit} ) {
719        $param{screen_id} = "batch-edit-entry";
720        $param{screen_id} = "batch-edit-page"
721          if $param{object_type} eq "page";
722        $param{screen_class} .= " batch-edit";
723    }
724    $app->load_tmpl( "list_entry.tmpl", \%param );
725}
726
727sub preview {
728    my $app         = shift;
729    my $q           = $app->param;
730    my $type        = $q->param('_type') || 'entry';
731    my $entry_class = $app->model($type);
732    my $blog_id     = $q->param('blog_id');
733    my $blog        = $app->blog;
734    my $id          = $q->param('id');
735    my $entry;
736    my $user_id = $app->user->id;
737
738    if ($id) {
739        $entry = $entry_class->load( { id => $id, blog_id => $blog_id } )
740            or return $app->errtrans( "Invalid request." );
741        $user_id = $entry->author_id;
742    }
743    else {
744        $entry = $entry_class->new;
745        $entry->author_id($user_id);
746        $entry->id(-1); # fake out things like MT::Taggable::__load_tags
747        $entry->blog_id($blog_id);
748    }
749    my $cat;
750    my $names = $entry->column_names;
751
752    my %values = map { $_ => scalar $app->param($_) } @$names;
753    delete $values{'id'} unless $q->param('id');
754    ## Strip linefeed characters.
755    for my $col (qw( text excerpt text_more keywords )) {
756        $values{$col} =~ tr/\r//d if $values{$col};
757    }
758    $values{allow_comments} = 0
759      if !defined( $values{allow_comments} )
760      || $q->param('allow_comments') eq '';
761    $values{allow_pings} = 0
762      if !defined( $values{allow_pings} )
763      || $q->param('allow_pings') eq '';
764    $entry->set_values( \%values );
765
766    my $cat_ids = $q->param('category_ids');
767    if ($cat_ids) {
768        my @cats = split /,/, $cat_ids;
769        if (@cats) {
770            my $primary_cat = $cats[0];
771            $cat =
772              MT::Category->load( { id => $primary_cat, blog_id => $blog_id } );
773            my @categories = MT::Category->load( { id => \@cats, blog_id => $blog_id });
774            $entry->cache_property('category', undef, $cat);
775            $entry->cache_property('categories', undef, \@categories);
776        }
777    } else {
778        $entry->cache_property('category', undef, undef);
779        $entry->cache_property('categories', undef, []);
780    }
781    my $tag_delim = chr( $app->user->entry_prefs->{tag_delim} );
782    my @tag_names = MT::Tag->split( $tag_delim, $q->param('tags') );
783    if (@tag_names) {
784        my @tags;
785        foreach my $tag_name (@tag_names) {
786            my $tag = MT::Tag->new;
787            $tag->name($tag_name);
788            push @tags, $tag;
789        }
790        $entry->{__tags} = \@tag_names;
791        $entry->{__tag_objects} = \@tags;
792    }
793
794    my $date = $q->param('authored_on_date');
795    my $time = $q->param('authored_on_time');
796    my $ts   = $date . $time;
797    $ts =~ s/\D//g;
798    $entry->authored_on($ts);
799
800    my $preview_basename = $app->preview_object_basename;
801    $entry->basename($preview_basename);
802
803    require MT::TemplateMap;
804    require MT::Template;
805    my $tmpl_map = MT::TemplateMap->load(
806        {
807            archive_type => ( $type eq 'page' ? 'Page' : 'Individual' ),
808            is_preferred => 1,
809            blog_id => $blog_id,
810        }
811    );
812
813    my $tmpl;
814    my $fullscreen;
815    my $archive_file;
816    my $orig_file;
817    my $file_ext;
818    if ($tmpl_map) {
819        $tmpl         = MT::Template->load( $tmpl_map->template_id );
820        $file_ext = $blog->file_extension || '';
821        $archive_file = $entry->archive_file;
822
823        my $blog_path = $type eq 'page' ?
824            $blog->site_path :
825            ($blog->archive_path || $blog->site_path);
826        $archive_file = File::Spec->catfile( $blog_path, $archive_file );
827        require File::Basename;
828        my $path;
829        ( $orig_file, $path ) = File::Basename::fileparse( $archive_file );
830        $file_ext = '.' . $file_ext if $file_ext ne '';
831        $archive_file = File::Spec->catfile( $path, $preview_basename . $file_ext );
832    }
833    else {
834        $tmpl       = $app->load_tmpl('preview_entry_content.tmpl');
835        $fullscreen = 1;
836    }
837    return $app->error($app->translate('Can\'t load template.')) unless $tmpl;
838
839    # translates naughty words when PublishCharset is NOT UTF-8
840    $app->_translate_naughty_words($entry);
841
842    $entry->convert_breaks( scalar $q->param('convert_breaks') );
843       
844    my @data = ( { data_name => 'author_id', data_value => $user_id } );
845    $app->run_callbacks( 'cms_pre_preview', $app, $entry, \@data );
846
847    my $ctx = $tmpl->context;
848    $ctx->stash( 'entry', $entry );
849    $ctx->stash( 'blog',  $blog );
850    $ctx->stash( 'category', $cat ) if $cat;
851    $ctx->{current_timestamp} = $ts;
852    $ctx->var('entry_template',    1);
853    $ctx->var('archive_template',  1);
854    $ctx->var('entry_template',    1);
855    $ctx->var('feedback_template', 1);
856    $ctx->var('archive_class',     'entry-archive');
857    $ctx->var('preview_template',  1);
858    my $html = $tmpl->output;
859    my %param;
860    unless ( defined($html) ) {
861        my $preview_error = $app->translate( "Publish error: [_1]",
862            MT::Util::encode_html( $tmpl->errstr ) );
863        $param{preview_error} = $preview_error;
864        my $tmpl_plain = $app->load_tmpl('preview_entry_content.tmpl');
865        $tmpl->text( $tmpl_plain->text );
866        $html = $tmpl->output;
867        defined($html)
868          or return $app->error(
869            $app->translate( "Publish error: [_1]", $tmpl->errstr ) );
870        $fullscreen = 1;
871    }
872
873    # If MT is configured to do 'local' previews, convert all
874    # the normal blog URLs into the domain used by MT itself (ie,
875    # blog is published to www.example.com, which is a different
876    # server from where MT runs, mt.example.com; previews therefore
877    # should occur locally, so replace all http://www.example.com/
878    # with http://mt.example.com/).
879    my ($old_url, $new_url);
880    if ($app->config('LocalPreviews')) {
881        $old_url = $blog->site_url;
882        $old_url =~ s!^(https?://[^/]+?/)(.*)?!$1!;
883        $new_url = $app->base . '/';
884        $html =~ s!\Q$old_url\E!$new_url!g;
885    }
886
887    if ( !$fullscreen ) {
888        my $fmgr = $blog->file_mgr;
889
890        ## Determine if we need to build directory structure,
891        ## and build it if we do. DirUmask determines
892        ## directory permissions.
893        require File::Basename;
894        my $path = File::Basename::dirname($archive_file);
895        $path =~ s!/$!!
896          unless $path eq '/';    ## OS X doesn't like / at the end in mkdir().
897        unless ( $fmgr->exists($path) ) {
898            $fmgr->mkpath($path);
899        }
900
901        if ( $fmgr->exists($path) && $fmgr->can_write($path) ) {
902            $fmgr->put_data( $html, $archive_file );
903            $param{preview_file} = $preview_basename;
904            my $preview_url = $entry->archive_url;
905            $preview_url =~ s! / \Q$orig_file\E ( /? ) $!/$preview_basename$file_ext$1!x;
906
907            # We also have to translate the URL used for the
908            # published file to be on the MT app domain.
909            if (defined $new_url) {
910                $preview_url =~ s!^\Q$old_url\E!$new_url!;
911            }
912
913            $param{preview_url}  = $preview_url;
914
915            # we have to make a record of this preview just in case it
916            # isn't cleaned up by re-editing, saving or cancelling on
917            # by the user.
918            require MT::Session;
919            my $sess_obj = MT::Session->get_by_key(
920                {
921                    id   => $preview_basename,
922                    kind => 'TF',                # TF = Temporary File
923                    name => $archive_file,
924                }
925            );
926            $sess_obj->start(time);
927            $sess_obj->save;
928        }
929        else {
930            $fullscreen = 1;
931            $param{preview_error} = $app->translate(
932                "Unable to create preview file in this location: [_1]", $path );
933            my $tmpl_plain = $app->load_tmpl('preview_entry_content.tmpl');
934            $tmpl->text( $tmpl_plain->text );
935            $tmpl->reset_tokens;
936            $html = $tmpl->output;
937            $param{preview_body} = $html;
938        }
939    }
940    else {
941        $param{preview_body} = $html;
942    }
943    $param{id} = $id if $id;
944    $param{new_object} = $param{id} ? 0 : 1;
945    $param{title} = $entry->title;
946    my $cols = $entry_class->column_names;
947
948    for my $col (@$cols) {
949        next
950          if $col eq 'created_on'
951          || $col eq 'created_by'
952          || $col eq 'modified_on'
953          || $col eq 'modified_by'
954          || $col eq 'authored_on'
955          || $col eq 'author_id'
956          || $col eq 'pinged_urls'
957          || $col eq 'tangent_cache'
958          || $col eq 'template_id'
959          || $col eq 'class'
960          || $col eq 'meta';
961        if ( $col eq 'basename' ) {
962            if (   ( !defined $q->param('basename') )
963                || ( $q->param('basename') eq '' ) )
964            {
965                $q->param( 'basename', $q->param('basename_old') );
966            }
967        }
968        push @data,
969          {
970            data_name  => $col,
971            data_value => scalar $q->param($col)
972          };
973    }
974    for my $data (
975        qw( authored_on_date authored_on_time basename_manual basename_old category_ids tags )
976      )
977    {
978        push @data,
979          {
980            data_name  => $data,
981            data_value => scalar $q->param($data)
982          };
983    }
984
985    $param{entry_loop} = \@data;
986    my $list_mode;
987    my $list_title;
988    if ( $type eq 'page' ) {
989        $list_title = 'Pages';
990        $list_mode  = 'list_pages';
991    }
992    else {
993        $list_title = 'Entries';
994        $list_mode  = 'list_entries';
995    }
996    if ($id) {
997        $app->add_breadcrumb(
998            $app->translate($list_title),
999            $app->uri(
1000                'mode' => $list_mode,
1001                args   => { blog_id => $blog_id }
1002            )
1003        );
1004        $app->add_breadcrumb( $entry->title || $app->translate('(untitled)') );
1005    }
1006    else {
1007        $app->add_breadcrumb( $app->translate($list_title),
1008            $app->uri( 'mode' => $list_mode, args => { blog_id => $blog_id } )
1009        );
1010        $app->add_breadcrumb(
1011            $app->translate( 'New [_1]', $entry_class->class_label ) );
1012        $param{nav_new_entry} = 1;
1013    }
1014    $param{object_type}  = $type;
1015    $param{object_label} = $entry_class->class_label;
1016    if ($fullscreen) {
1017        return $app->load_tmpl( 'preview_entry.tmpl', \%param );
1018    }
1019    else {
1020        return $app->load_tmpl( 'preview_strip.tmpl', \%param );
1021    }
1022}
1023
1024sub cfg_entry {
1025    my $app     = shift;
1026    my $q       = $app->param;
1027    my $blog_id = scalar $q->param('blog_id');
1028    return $app->return_to_dashboard( redirect => 1 )
1029      unless $blog_id;
1030    $q->param( '_type', 'blog' );
1031    $q->param( 'id',    scalar $q->param('blog_id') );
1032    $app->forward("view",
1033        {
1034            output       => 'cfg_entry.tmpl',
1035            screen_class => 'settings-screen entry-screen'
1036        }
1037    );
1038}
1039
1040sub save {
1041    my $app = shift;
1042    $app->validate_magic or return;
1043
1044    $app->remove_preview_file;
1045
1046    if ( $app->param('is_power_edit') ) {
1047        return $app->save_entries(@_);
1048    }
1049    my $author = $app->user;
1050    my $type = $app->param('_type') || 'entry';
1051
1052    my $class = $app->model($type)
1053      or retrun $app->errtrans("Invalid parameter");
1054
1055    my $cat_class = $app->model( $class->container_type );
1056
1057    my $perms = $app->permissions
1058      or return $app->errtrans("Permission denied.");
1059
1060    if ( $type eq 'page' ) {
1061        return $app->errtrans("Permission denied.")
1062          unless $perms->can_manage_pages;
1063    }
1064
1065    my $id = $app->param('id');
1066    if ( !$id ) {
1067        return $app->errtrans("Permission denied.")
1068          unless ( ( 'entry' eq $type ) && $perms->can_create_post )
1069          || ( ( 'page' eq $type ) && $perms->can_manage_pages );
1070    }
1071
1072    $app->validate_magic() or return;
1073
1074    # check for autosave
1075    if ( $app->param('_autosave') ) {
1076        return $app->autosave_object();
1077    }
1078
1079    require MT::Blog;
1080    my $blog_id = $app->param('blog_id');
1081    my $blog    = MT::Blog->load($blog_id)
1082        or return $app->error($app->translate('Can\'t load blog #[_1].', $blog_id));
1083   
1084    my $archive_type;
1085
1086    my ( $obj, $orig_obj, $orig_file );
1087    if ($id) {
1088        $obj = $class->load($id)
1089          || return $app->error(
1090            $app->translate( "No such [_1].", $class->class_label ) );
1091        return $app->error( $app->translate("Invalid parameter") )
1092          unless $obj->blog_id == $blog_id;
1093        if ( $type eq 'entry' ) {
1094            return $app->error( $app->translate("Permission denied.") )
1095              unless $perms->can_edit_entry( $obj, $author );
1096            return $app->error( $app->translate("Permission denied.") )
1097              if ( $obj->status ne $app->param('status') )
1098              && !( $perms->can_edit_entry( $obj, $author, 1 ) );
1099            $archive_type = 'Individual';
1100        }
1101        elsif ( $type eq 'page' ) {
1102            $archive_type = 'Page';
1103        }
1104        $orig_obj = $obj->clone;
1105        $orig_file = archive_file_for( $orig_obj, $blog, $archive_type );
1106    }
1107    else {
1108        $obj = $class->new;
1109    }
1110    my $status_old = $id ? $obj->status : 0;
1111    my $names = $obj->column_names;
1112
1113    ## Get rid of category_id param, because we don't want to just set it
1114    ## in the Entry record; save it for later when we will set the Placement.
1115    my ( $cat_id, @add_cat ) = split /\s*,\s*/,
1116      ( $app->param('category_ids') || '' );
1117    $app->delete_param('category_id');
1118    if ($id) {
1119        ## Delete the author_id param (if present), because we don't want to
1120        ## change the existing author.
1121        $app->delete_param('author_id');
1122    }
1123
1124    my %values = map { $_ => scalar $app->param($_) } @$names;
1125    delete $values{'id'} unless $app->param('id');
1126    ## Strip linefeed characters.
1127    for my $col (qw( text excerpt text_more keywords )) {
1128        $values{$col} =~ tr/\r//d if $values{$col};
1129    }
1130    $values{allow_comments} = 0
1131      if !defined( $values{allow_comments} )
1132      || $app->param('allow_comments') eq '';
1133    delete $values{week_number}
1134      if ( $app->param('week_number') || '' ) eq '';
1135    delete $values{basename}
1136      unless $perms->can_publish_post || $perms->can_edit_all_posts;
1137    $obj->set_values( \%values );
1138    $obj->allow_pings(0)
1139      if !defined $app->param('allow_pings')
1140      || $app->param('allow_pings') eq '';
1141    my $ao_d = $app->param('authored_on_date');
1142    my $ao_t = $app->param('authored_on_time');
1143
1144    if ( !$id ) {
1145
1146        #  basename check for this new entry...
1147        if (   ( my $basename = $app->param('basename') )
1148            && !$app->param('basename_manual')
1149            && $type eq 'entry' )
1150        {
1151            my $exist =
1152              $class->exist( { blog_id => $blog_id, basename => $basename } );
1153            if ($exist) {
1154                $obj->basename( MT::Util::make_unique_basename($obj) );
1155            }
1156        }
1157    }
1158
1159    if ( $type eq 'page' ) {
1160
1161        # -1 is a special id for identifying the 'root' folder
1162        $cat_id = 0 if $cat_id == -1;
1163        my $dup_it = $class->load_iter(
1164            {
1165                blog_id  => $blog_id,
1166                basename => $obj->basename,
1167                class    => 'page',
1168                ( $id ? ( id => $id ) : () )
1169            },
1170            { ( $id ? ( not => { id => 1 } ) : () ) }
1171        );
1172        while ( my $p = $dup_it->() ) {
1173            my $p_folder = $p->folder;
1174            my $dup_folder_path =
1175              defined $p_folder ? $p_folder->publish_path() : '';
1176            my $folder = MT::Folder->load($cat_id) if $cat_id;
1177            my $folder_path = defined $folder ? $folder->publish_path() : '';
1178            return $app->error(
1179                $app->translate(
1180"Same Basename has already been used. You should use an unique basename."
1181                )
1182            ) if ( $dup_folder_path eq $folder_path );
1183        }
1184
1185    }
1186
1187    if ( $type eq 'entry' ) {
1188        $obj->status( MT::Entry::HOLD() )
1189          if !$id
1190          && !$perms->can_publish_post
1191          && !$perms->can_edit_all_posts;
1192    }
1193
1194    my $filter_result = $app->run_callbacks( 'cms_save_filter.' . $type, $app );
1195
1196    if ( !$filter_result ) {
1197        my %param = ();
1198        $param{error}       = $app->errstr;
1199        $param{return_args} = $app->param('return_args');
1200        return $app->forward( "view", \%param );
1201    }
1202
1203    # check to make sure blog has site url and path defined.
1204    # otherwise, we can't publish a released entry
1205    if ( ( $obj->status || 0 ) != MT::Entry::HOLD() ) {
1206        if ( !$blog->site_path || !$blog->site_url ) {
1207            return $app->error(
1208                $app->translate(
1209"Your blog has not been configured with a site path and URL. You cannot publish entries until these are defined."
1210                )
1211            );
1212        }
1213    }
1214
1215    my ( $previous_old, $next_old );
1216    if (   ( $perms->can_publish_post || $perms->can_edit_all_posts )
1217        && ($ao_d) )
1218    {
1219        my %param = ();
1220        my $ao = $ao_d . ' ' . $ao_t;
1221        unless (
1222            $ao =~ m!^(\d{4})-(\d{1,2})-(\d{1,2})\s+(\d{1,2}):(\d{1,2})(?::(\d{1,2}))?$! )
1223        {
1224            $param{error} = $app->translate(
1225"Invalid date '[_1]'; authored on dates must be in the format YYYY-MM-DD HH:MM:SS.",
1226$ao
1227            );
1228        }
1229        my $s = $6 || 0;
1230            $param{error} = $app->translate(
1231                "Invalid date '[_1]'; authored on dates should be real dates.",
1232                $ao
1233          )
1234          if (
1235               $s > 59
1236            || $s < 0
1237            || $5 > 59
1238            || $5 < 0
1239            || $4 > 23
1240            || $4 < 0
1241            || $2 > 12
1242            || $2 < 1
1243            || $3 < 1
1244            || ( MT::Util::days_in( $2, $1 ) < $3
1245                && !MT::Util::leap_day( $0, $1, $2 ) )
1246          );
1247        $param{return_args} = $app->param('return_args');
1248        return $app->forward( "view", \%param ) if $param{error};
1249        if ($obj->authored_on) {
1250            $previous_old = $obj->previous(1);
1251            $next_old     = $obj->next(1);
1252        }
1253        my $ts = sprintf "%04d%02d%02d%02d%02d%02d", $1, $2, $3, $4, $5, $s;
1254        $obj->authored_on($ts);
1255    }
1256    my $is_new = $obj->id ? 0 : 1;
1257
1258    $app->_translate_naughty_words($obj);
1259
1260    $obj->modified_by( $author->id ) unless $is_new;
1261
1262    $app->run_callbacks( 'cms_pre_save.' . $type, $app, $obj, $orig_obj )
1263      || return $app->error(
1264        $app->translate(
1265            "Saving [_1] failed: [_2]",
1266            $class->class_label, $app->errstr
1267        )
1268      );
1269
1270    $obj->save
1271      or return $app->error(
1272        $app->translate(
1273            "Saving [_1] failed: [_2]",
1274            $class->class_label, $obj->errstr
1275        )
1276      );
1277
1278    my $message;
1279    if ($is_new) {
1280        $message =
1281          $app->translate( "[_1] '[_2]' (ID:[_3]) added by user '[_4]'",
1282            $class->class_label, $obj->title, $obj->id, $author->name );
1283    }
1284    elsif ( $orig_obj->status ne $obj->status ) {
1285        $message = $app->translate(
1286"[_1] '[_2]' (ID:[_3]) edited and its status changed from [_4] to [_5] by user '[_6]'",
1287            $class->class_label,
1288            $obj->title,
1289            $obj->id,
1290            $app->translate( MT::Entry::status_text( $orig_obj->status ) ),
1291            $app->translate( MT::Entry::status_text( $obj->status ) ),
1292            $author->name
1293        );
1294
1295    }
1296    else {
1297        $message =
1298          $app->translate( "[_1] '[_2]' (ID:[_3]) edited by user '[_4]'",
1299            $class->class_label, $obj->title, $obj->id, $author->name );
1300    }
1301    require MT::Log;
1302    $app->log(
1303        {
1304            message => $message,
1305            level   => MT::Log::INFO(),
1306            class   => $type,
1307            $is_new ? ( category => 'new' ) : ( category => 'edit' ),
1308            metadata => $obj->id
1309        }
1310    );
1311
1312    my $error_string = MT::callback_errstr();
1313
1314    ## Now that the object is saved, we can be certain that it has an
1315    ## ID. So we can now add/update/remove the primary placement.
1316    require MT::Placement;
1317    my $place =
1318      MT::Placement->load( { entry_id => $obj->id, is_primary => 1 } );
1319    if ($cat_id) {
1320        unless ($place) {
1321            $place = MT::Placement->new;
1322            $place->entry_id( $obj->id );
1323            $place->blog_id( $obj->blog_id );
1324            $place->is_primary(1);
1325        }
1326        $place->category_id($cat_id);
1327        $place->save;
1328    }
1329    else {
1330        if ( $place ) {
1331            $place->remove;
1332        }
1333    }
1334
1335    my $placements_updated;
1336
1337    # save secondary placements...
1338    my @place = MT::Placement->load(
1339        {
1340            entry_id   => $obj->id,
1341            is_primary => 0
1342        }
1343    );
1344    for my $place (@place) {
1345        $place->remove;
1346        $placements_updated = 1;
1347    }
1348    for my $cat_id (@add_cat) {
1349        my $cat = $cat_class->load($cat_id);
1350
1351        # blog_id sanity check
1352        next if !$cat || $cat->blog_id != $obj->blog_id;
1353
1354        my $place = MT::Placement->new;
1355        $place->entry_id( $obj->id );
1356        $place->blog_id( $obj->blog_id );
1357        $place->is_primary(0);
1358        $place->category_id($cat_id);
1359        $place->save
1360          or return $app->error(
1361            $app->translate( "Saving placement failed: [_1]", $place->errstr )
1362          );
1363        $placements_updated = 1;
1364    }
1365
1366    $app->run_callbacks( 'cms_post_save.' . $type, $app, $obj, $orig_obj );
1367
1368    ## If the saved status is RELEASE, or if the *previous* status was
1369    ## RELEASE, then rebuild entry archives, indexes, and send the
1370    ## XML-RPC ping(s). Otherwise the status was and is HOLD, and we
1371    ## don't have to do anything.
1372    if ( ( $obj->status || 0 ) == MT::Entry::RELEASE()
1373        || $status_old eq MT::Entry::RELEASE() )
1374    {
1375        if ( $app->config('DeleteFilesAtRebuild') && $orig_obj ) {
1376            my $file = archive_file_for( $obj, $blog, $archive_type );
1377            if ( $file ne $orig_file || $obj->status != MT::Entry::RELEASE() ) {
1378                $app->publisher->remove_entry_archive_file(
1379                    Entry       => $orig_obj,
1380                    ArchiveType => $archive_type
1381                );
1382            }
1383        }
1384
1385        # If there are no static pages, just rebuild indexes.
1386        if ( $blog->count_static_templates($archive_type) == 0
1387            || MT::Util->launch_background_tasks() )
1388        {
1389            my $res = MT::Util::start_background_task(
1390                sub {
1391                    $app->run_callbacks('pre_build');
1392                    $app->rebuild_entry(
1393                        Entry             => $obj,
1394                        BuildDependencies => 1,
1395                        OldEntry          => $orig_obj,
1396                        OldPrevious       => ($previous_old)
1397                        ? $previous_old->id
1398                        : undef,
1399                        OldNext => ($next_old) ? $next_old->id : undef
1400                    ) or return $app->publish_error();
1401                    $app->run_callbacks( 'rebuild', $blog );
1402                    $app->run_callbacks( 'post_build' );
1403                    1;
1404                }
1405            );
1406            return unless $res;
1407            return ping_continuation($app,
1408                $obj, $blog,
1409                OldStatus => $status_old,
1410                IsNew     => $is_new,
1411            );
1412        }
1413        else {
1414            return $app->redirect(
1415                $app->uri(
1416                    'mode' => 'start_rebuild',
1417                    args   => {
1418                        blog_id    => $obj->blog_id,
1419                        'next'     => 0,
1420                        type       => 'entry-' . $obj->id,
1421                        entry_id   => $obj->id,
1422                        is_new     => $is_new,
1423                        old_status => $status_old,
1424                        (
1425                            $previous_old
1426                            ? ( old_previous => $previous_old->id )
1427                            : ()
1428                        ),
1429                        ( $next_old ? ( old_next => $next_old->id ) : () )
1430                    }
1431                )
1432            );
1433        }
1434    }
1435    _finish_rebuild_ping( $app, $obj, !$id );
1436}
1437
1438sub save_entries {
1439    my $app   = shift;
1440    my $perms = $app->permissions;
1441    my $type  = $app->param('_type');
1442    return $app->errtrans("Permission denied.")
1443      unless $perms
1444      && (
1445        $type eq 'page'
1446        ? ( $perms->can_manage_pages )
1447        : (      $perms->can_publish_post
1448              || $perms->can_create_post
1449              || $perms->can_edit_all_posts )
1450      );
1451
1452    $app->validate_magic() or return;
1453
1454    my $q = $app->param;
1455    my @p = $q->param;
1456    require MT::Entry;
1457    require MT::Placement;
1458    require MT::Log;
1459    my $blog_id        = $q->param('blog_id');
1460    my $this_author    = $app->user;
1461    my $this_author_id = $this_author->id;
1462    for my $p (@p) {
1463        next unless $p =~ /^category_id_(\d+)/;
1464        my $id    = $1;
1465        my $entry = MT::Entry->load($id)
1466            or next;
1467        return $app->error( $app->translate("Permission denied.") )
1468            unless $perms
1469              && (
1470                $type eq 'page'
1471                ? ( $perms->can_manage_pages )
1472                : (      $perms->can_publish_post
1473                      || $perms->can_create_post
1474                      || $perms->can_edit_all_posts )
1475              );
1476        my $orig_obj = $entry->clone;
1477        if ( $perms->can_edit_entry( $entry, $this_author ) ) {
1478            my $author_id = $q->param( 'author_id_' . $id );
1479            $entry->author_id( $author_id ? $author_id : 0 );
1480            $entry->title( scalar $q->param( 'title_' . $id ) );
1481        }
1482        if ( $perms->can_edit_entry( $entry, $this_author, 1 ) )
1483        {    ## can he/she change status?
1484            $entry->status( scalar $q->param( 'status_' . $id ) );
1485            my $co = $q->param( 'created_on_' . $id );
1486            unless ( $co =~
1487                m!(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2})(?::(\d{2}))?! )
1488            {
1489                return $app->error(
1490                    $app->translate(
1491"Invalid date '[_1]'; authored on dates must be in the format YYYY-MM-DD HH:MM:SS.",
1492                        $co
1493                    )
1494                );
1495            }
1496            my $s = $6 || 0;
1497
1498            # Emit an error message if the date is bogus.
1499            return $app->error(
1500                $app->translate(
1501"Invalid date '[_1]'; authored on dates should be real dates.",
1502                    $co
1503                )
1504              )
1505              if $s > 59
1506              || $s < 0
1507              || $5 > 59
1508              || $5 < 0
1509              || $4 > 23
1510              || $4 < 0
1511              || $2 > 12
1512              || $2 < 1
1513              || $3 < 1
1514              || ( MT::Util::days_in( $2, $1 ) < $3
1515                && !MT::Util::leap_day( $0, $1, $2 ) );
1516
1517            # FIXME: Should be assigning the publish_date field here
1518            my $ts = sprintf "%04d%02d%02d%02d%02d%02d", $1, $2, $3, $4, $5, $s;
1519            if ($type eq 'page' ) {
1520                $entry->modified_on($ts);
1521            } else {
1522                $entry->authored_on($ts);
1523            }
1524        }
1525        $app->run_callbacks( 'cms_pre_save.' . $type, $app, $entry, $orig_obj )
1526          || return $app->error(
1527            $app->translate(
1528                "Saving [_1] failed: [_2]",
1529                $entry->class_label, $app->errstr
1530            )
1531          );
1532        $entry->save
1533          or return $app->error(
1534            $app->translate(
1535                "Saving entry '[_1]' failed: [_2]", $entry->title,
1536                $entry->errstr
1537            )
1538          );
1539        my $cat_id = $q->param("category_id_$id");
1540        my $place  = MT::Placement->load(
1541            {
1542                entry_id   => $id,
1543                is_primary => 1
1544            }
1545        );
1546        if ( $place && !$cat_id ) {
1547            $place->remove
1548              or return $app->error(
1549                $app->translate(
1550                    "Removing placement failed: [_1]",
1551                    $place->errstr
1552                )
1553              );
1554        }
1555        elsif ($cat_id) {
1556            unless ($place) {
1557                $place = MT::Placement->new;
1558                $place->entry_id($id);
1559                $place->blog_id($blog_id);
1560                $place->is_primary(1);
1561            }
1562            $place->category_id( scalar $q->param($p) );
1563            $place->save
1564              or return $app->error(
1565                $app->translate(
1566                    "Saving placement failed: [_1]",
1567                    $place->errstr
1568                )
1569              );
1570        }
1571        my $message;
1572        if ( $orig_obj->status ne $entry->status ) {
1573            $message = $app->translate(
1574"[_1] '[_2]' (ID:[_3]) edited and its status changed from [_4] to [_5] by user '[_6]'",
1575                $entry->class_label,
1576                $entry->title,
1577                $entry->id,
1578                $app->translate( MT::Entry::status_text( $orig_obj->status ) ),
1579                $app->translate( MT::Entry::status_text( $entry->status ) ),
1580                $this_author->name
1581            );
1582        }
1583        else {
1584            $message =
1585              $app->translate( "[_1] '[_2]' (ID:[_3]) edited by user '[_4]'",
1586                $entry->class_label, $entry->title, $entry->id,
1587                $this_author->name );
1588        }
1589        $app->log(
1590            {
1591                message  => $message,
1592                level    => MT::Log::INFO(),
1593                class    => $entry->class,
1594                category => 'edit',
1595                metadata => $entry->id
1596            }
1597        );
1598        $app->run_callbacks( 'cms_post_save.' . $type, $app, $entry, $orig_obj );
1599    }
1600    $app->add_return_arg( 'saved' => 1, is_power_edit => 1 );
1601    $app->call_return;
1602}
1603
1604sub send_pings {
1605    my $app = shift;
1606    my $q   = $app->param;
1607    $app->validate_magic() or return;
1608    require MT::Entry;
1609    require MT::Blog;
1610    my $blog  = MT::Blog->load( scalar $q->param('blog_id') );
1611    my $entry = MT::Entry->load( scalar $q->param('entry_id') );
1612    ## MT::ping_and_save pings each of the necessary URLs, then processes
1613    ## the return value from MT::ping to update the list of URLs pinged
1614    ## and not successfully pinged. It returns the return value from
1615    ## MT::ping for further processing. If a fatal error occurs, it returns
1616    ## undef.
1617    my $results = $app->ping_and_save(
1618        Blog      => $blog,
1619        Entry     => $entry,
1620        OldStatus => scalar $q->param('old_status')
1621    ) or return;
1622    my $has_errors = 0;
1623    require MT::Log;
1624    for my $res (@$results) {
1625        $has_errors++,
1626          $app->log(
1627            {
1628                message => $app->translate(
1629                    "Ping '[_1]' failed: [_2]",
1630                    $res->{url},
1631                    encode_text( $res->{error}, undef, undef )
1632                ),
1633                class => 'system',
1634                level => MT::Log::WARNING()
1635            }
1636          ) unless $res->{good};
1637    }
1638    _finish_rebuild_ping( $app, $entry, scalar $q->param('is_new'),
1639        $has_errors );
1640}
1641
1642sub pinged_urls {
1643    my $app   = shift;
1644    my $perms = $app->permissions
1645      or return $app->error( $app->translate("No permissions") );
1646    my %param;
1647    my $entry_id = $app->param('entry_id');
1648    require MT::Entry;
1649    my $entry = MT::Entry->load($entry_id)
1650        or return $app->error($app->translate('Can\'t load entry #[_1].', $entry_id));
1651    $param{url_loop} = [ map { { url => $_ } } @{ $entry->pinged_url_list } ];
1652    $param{failed_url_loop} =
1653      [ map { { url => $_ } }
1654          @{ $entry->pinged_url_list( OnlyFailures => 1 ) } ];
1655    $app->load_tmpl( 'popup/pinged_urls.tmpl', \%param );
1656}
1657
1658sub save_entry_prefs {
1659    my $app   = shift;
1660    my $perms = $app->permissions
1661      or return $app->error( $app->translate("No permissions") );
1662    $app->validate_magic() or return;
1663    my $q     = $app->param;
1664    my $prefs = $app->_entry_prefs_from_params;
1665    $perms->entry_prefs($prefs);
1666    $perms->save
1667      or return $app->error(
1668        $app->translate( "Saving permissions failed: [_1]", $perms->errstr ) );
1669    $app->send_http_header("text/json");
1670    return "true";
1671}
1672
1673sub publish_entries {
1674    my $app = shift;
1675    require MT::Entry;
1676    update_entry_status( $app, MT::Entry::RELEASE(), $app->param('id') );
1677}
1678
1679sub draft_entries {
1680    my $app = shift;
1681    require MT::Entry;
1682    update_entry_status( $app, MT::Entry::HOLD(), $app->param('id') );
1683}
1684
1685sub open_batch_editor {
1686    my $app = shift;
1687    my @ids = $app->param('id');
1688
1689    $app->param( 'is_power_edit', 1 );
1690    $app->param( 'filter',        'power_edit' );
1691    $app->param( 'filter_val',    \@ids );
1692    $app->mode(
1693        'list_' . ( 'entry' eq $app->param('_type') ? 'entries' : 'pages' ) );
1694    $app->forward( "list_entry", { type => $app->param('_type') } );
1695}
1696
1697sub build_entry_table {
1698    my $app = shift;
1699    my (%args) = @_;
1700
1701    my $app_author = $app->user;
1702    my $perms      = $app->permissions;
1703    my $type       = $args{type};
1704    my $class      = $app->model($type);
1705
1706    my $list_pref = $app->list_pref($type);
1707    if ( $args{is_power_edit} ) {
1708        delete $list_pref->{view_expanded};
1709    }
1710    my $iter;
1711    if ( $args{load_args} ) {
1712        $iter = $class->load_iter( @{ $args{load_args} } );
1713    }
1714    elsif ( $args{iter} ) {
1715        $iter = $args{iter};
1716    }
1717    elsif ( $args{items} ) {
1718        $iter = sub { shift @{ $args{items} } };
1719    }
1720    return [] unless $iter;
1721    my $limit         = $args{limit};
1722    my $is_power_edit = $args{is_power_edit} || 0;
1723    my $param         = $args{param} || {};
1724
1725    ## Load list of categories for display in filter pulldown (and selection
1726    ## pulldown on power edit page).
1727    my ( $c_data, %cats );
1728    my $blog_id = $app->param('blog_id');
1729    if ($blog_id) {
1730        $c_data = $app->_build_category_list(
1731            blog_id => $blog_id,
1732            type    => $class->container_type,
1733        );
1734        my $i = 0;
1735        for my $row (@$c_data) {
1736            $row->{category_index} = $i++;
1737            my $spacer = $row->{category_label_spacer} || '';
1738            $spacer =~ s/\&nbsp;/\\u00A0/g;
1739            $row->{category_label_js} =
1740              $spacer . encode_js( $row->{category_label} );
1741            $cats{ $row->{category_id} } = $row;
1742        }
1743        $param->{category_loop} = $c_data;
1744    }
1745
1746    my ( $date_format, $datetime_format );
1747
1748    if ($is_power_edit) {
1749        $date_format          = "%Y.%m.%d";
1750        $datetime_format      = "%Y-%m-%d %H:%M:%S";
1751    }
1752    else {
1753        $date_format     = MT::App::CMS::LISTING_DATE_FORMAT();
1754        $datetime_format = MT::App::CMS::LISTING_DATETIME_FORMAT();
1755    }
1756
1757    my @cat_list;
1758    if ($is_power_edit) {
1759        @cat_list =
1760          sort { $cats{$a}->{category_index} <=> $cats{$b}->{category_index} }
1761          keys %cats;
1762    }
1763
1764    my @data;
1765    my %blogs;
1766    require MT::Blog;
1767    my $title_max_len   = const('DISPLAY_LENGTH_EDIT_ENTRY_TITLE');
1768    my $excerpt_max_len = const('DISPLAY_LENGTH_EDIT_ENTRY_TEXT_FROM_EXCERPT');
1769    my $text_max_len    = const('DISPLAY_LENGTH_EDIT_ENTRY_TEXT_BREAK_UP');
1770    my %blog_perms;
1771    $blog_perms{ $perms->blog_id } = $perms if $perms;
1772    while ( my $obj = $iter->() ) {
1773        my $blog_perms;
1774        if ( !$app_author->is_superuser() ) {
1775            $blog_perms = $blog_perms{ $obj->blog_id }
1776              || $app_author->blog_perm( $obj->blog_id );
1777        }
1778
1779        my $row = $obj->column_values;
1780        $row->{text} ||= '';
1781        if ( my $ts =
1782            ( $type eq 'page' ) ? $obj->modified_on : $obj->authored_on )
1783        {
1784            $row->{created_on_formatted} =
1785              format_ts( $date_format, $ts, $obj->blog, $app->user ? $app->user->preferred_language : undef );
1786            $row->{created_on_time_formatted} =
1787              format_ts( $datetime_format, $ts, $obj->blog, $app->user ? $app->user->preferred_language : undef );
1788            $row->{created_on_relative} =
1789              relative_date( $ts, time, $obj->blog );
1790        }
1791        my $author = $obj->author;
1792        $row->{author_name} =
1793          $author ? $author->name : $app->translate('(user deleted)');
1794        if ( my $cat = $obj->category ) {
1795            $row->{category_label}    = $cat->label;
1796            $row->{category_basename} = $cat->basename;
1797        }
1798        else {
1799            $row->{category_label}    = '';
1800            $row->{category_basename} = '';
1801        }
1802        $row->{file_extension} = $obj->blog ? $obj->blog->file_extension : '';
1803        $row->{title_short} = $obj->title;
1804        if ( !defined( $row->{title_short} ) || $row->{title_short} eq '' ) {
1805            my $title = remove_html( $obj->text );
1806            $row->{title_short} =
1807              substr_text( defined($title) ? $title : "", 0, $title_max_len )
1808              . '...';
1809        }
1810        else {
1811            $row->{title_short} = remove_html( $row->{title_short} );
1812            $row->{title_short} =
1813              substr_text( $row->{title_short}, 0, $title_max_len + 3 ) . '...'
1814              if length_text( $row->{title_short} ) > $title_max_len;
1815        }
1816        if ( $row->{excerpt} ) {
1817            $row->{excerpt} = remove_html( $row->{excerpt} );
1818        }
1819        if ( !$row->{excerpt} ) {
1820            my $text = remove_html( $row->{text} ) || '';
1821            $row->{excerpt} = first_n_text( $text, $excerpt_max_len );
1822            if ( length($text) > length( $row->{excerpt} ) ) {
1823                $row->{excerpt} .= ' ...';
1824            }
1825        }
1826        $row->{text} = break_up_text( $row->{text}, $text_max_len )
1827          if $row->{text};
1828        $row->{title_long} = remove_html( $obj->title );
1829        $row->{status_text} =
1830          $app->translate( MT::Entry::status_text( $obj->status ) );
1831        $row->{ "status_" . MT::Entry::status_text( $obj->status ) } = 1;
1832        $row->{has_edit_access} = $app_author->is_superuser
1833          || ( ( 'entry' eq $type )
1834            && $blog_perms
1835            && $blog_perms->can_edit_entry( $obj, $app_author ) )
1836          || ( ( 'page' eq $type )
1837            && $blog_perms
1838            && $blog_perms->can_manage_pages );
1839        if ($is_power_edit) {
1840            $row->{has_publish_access} = $app_author->is_superuser
1841              || ( ( 'entry' eq $type )
1842                && $blog_perms
1843                && $blog_perms->can_edit_entry( $obj, $app_author, 1 ) )
1844              || ( ( 'page' eq $type )
1845                && $blog_perms
1846                && $blog_perms->can_manage_pages );
1847            $row->{is_editable} = $row->{has_edit_access};
1848
1849            ## This is annoying. In order to generate and pre-select the
1850            ## category, user, and status pull down menus, we need to
1851            ## have a separate *copy* of the list of categories and
1852            ## users for every entry listed, so that each row in the list
1853            ## can "know" whether it is selected for this entry or not.
1854            my @this_c_data;
1855            my $this_category_id = $obj->category ? $obj->category->id : undef;
1856            for my $c_id (@cat_list) {
1857                push @this_c_data, { %{ $cats{$c_id} } };
1858                $this_c_data[-1]{category_is_selected} = $this_category_id
1859                  && $this_category_id == $c_id ? 1 : 0;
1860            }
1861            $row->{row_category_loop} = \@this_c_data;
1862
1863            if ( $obj->author ) {
1864                $row->{row_author_name} = $obj->author->name;
1865                $row->{row_author_id}   = $obj->author->id;
1866            } else {
1867                $row->{row_author_name} = $app->translate(
1868                    '(user deleted - ID:[_1])',
1869                    $obj->author_id
1870                );
1871                $row->{row_author_id} = $obj->author_id,
1872             }
1873        }
1874        if ( my $blog = $blogs{ $obj->blog_id } ||=
1875            MT::Blog->load( $obj->blog_id ) )
1876        {
1877            $row->{weblog_id}   = $blog->id;
1878            $row->{weblog_name} = $blog->name;
1879        }
1880        if ( $obj->status == MT::Entry::RELEASE() ) {
1881            $row->{entry_permalink} = $obj->permalink;
1882        }
1883        $row->{object} = $obj;
1884        push @data, $row;
1885    }
1886    return [] unless @data;
1887
1888    $param->{entry_table}[0] = {%$list_pref};
1889    $param->{object_loop} = $param->{entry_table}[0]{object_loop} = \@data;
1890    $app->load_list_actions( $type, \%$param )
1891      unless $is_power_edit;
1892    \@data;
1893}
1894
1895sub quickpost_js {
1896    my $app     = shift;
1897    my ($type)  = @_;
1898    my $blog_id = $app->blog->id;
1899    my $blog    = $app->model('blog')->load($blog_id)
1900        or return $app->error($app->translate('Can\'t load blog #[_1].', $blog_id));
1901    my %args    = ( '_type' => $type, blog_id => $blog_id, qp => 1 );
1902    my $uri = $app->base . $app->uri( 'mode' => 'view', args => \%args );
1903    my $script = qq!javascript:d=document;w=window;t='';if(d.selection)t=d.selection.createRange().text;else{if(d.getSelection)t=d.getSelection();else{if(w.getSelection)t=w.getSelection()}}void(w.open('$uri&title='+encodeURIComponent(d.title)+'&text='+encodeURIComponent(d.location.href)+encodeURIComponent('<br/><br/>')+encodeURIComponent(t),'_blank','scrollbars=yes,status=yes,resizable=yes,location=yes'))!;
1904    # Translate the phrase here to avoid ActivePerl DLL bug.
1905    $app->translate('<a href="[_1]">QuickPost to [_2]</a> - Drag this link to your browser\'s toolbar then click it when you are on a site you want to blog about.', encode_html($script), $blog->name);
1906}
1907
1908sub can_view {
1909    my ( $eh, $app, $id, $objp ) = @_;
1910    my $perms = $app->permissions;
1911    if (   !$id
1912        && !$perms->can_create_post )
1913    {
1914        return 0;
1915    }
1916    if ($id) {
1917        my $obj = $objp->force();
1918        if ( !$perms->can_edit_entry( $obj, $app->user ) ) {
1919            return 0;
1920        }
1921    }
1922    1;
1923}
1924
1925sub can_delete {
1926    my ( $eh, $app, $obj ) = @_;
1927    my $author = $app->user;
1928    return 1 if $author->is_superuser();
1929    my $perms = $app->permissions;
1930    if ( !$perms || $perms->blog_id != $obj->blog_id ) {
1931        $perms ||= $author->permissions( $obj->blog_id );
1932    }
1933    return $perms && $perms->can_edit_entry( $obj, $author );
1934}
1935
1936sub pre_save {
1937    my $eh = shift;
1938    my ( $app, $obj ) = @_;
1939
1940    # save tags
1941    my $tags = $app->param('tags');
1942    if ( defined $tags ) {
1943        my $blog = $app->blog;
1944        my $fields = $blog->smart_replace_fields;
1945        if ( $fields =~ m/tags/ig ) {
1946            $tags = MT::App::CMS::_convert_word_chars( $app, $tags );
1947        }
1948
1949        require MT::Tag;
1950        my $tag_delim = chr( $app->user->entry_prefs->{tag_delim} );
1951        my @tags = MT::Tag->split( $tag_delim, $tags );
1952        if (@tags) {
1953            $obj->set_tags(@tags);
1954        }
1955        else {
1956            $obj->remove_tags();
1957        }
1958    }
1959
1960    # update text heights if necessary
1961    if ( my $perms = $app->permissions ) {
1962        my $prefs = $perms->entry_prefs || $app->load_default_entry_prefs;
1963        my $text_height = $app->param('text_height');
1964        if ( defined $text_height ) {
1965            my ($pref_text_height) = $prefs =~ m/\bbody:(\d+)\b/;
1966            $pref_text_height ||= 0;
1967            if ( $text_height != $pref_text_height ) {
1968                if ( $prefs =~ m/\bbody\b/ ) {
1969                    $prefs =~ s/\bbody(:\d+)\b/body:$text_height/;
1970                }
1971                else {
1972                    $prefs = 'body:' . $text_height . ',' . $prefs;
1973                }
1974            }
1975        }
1976        if ( $prefs ne ( $perms->entry_prefs || '' ) ) {
1977            $perms->entry_prefs($prefs);
1978            $perms->save;
1979        }
1980    }
1981    $obj->discover_tb_from_entry();
1982    1;
1983}
1984
1985sub post_save {
1986    my $eh = shift;
1987    my ( $app, $obj ) = @_;
1988    my $sess_obj = $app->autosave_session_obj;
1989    $sess_obj->remove if $sess_obj;
1990    1;
1991}
1992
1993sub post_delete {
1994    my ( $eh, $app, $obj ) = @_;
1995
1996    my $sess_obj = $app->autosave_session_obj;
1997    $sess_obj->remove if $sess_obj;
1998
1999    $app->log(
2000        {
2001            message => $app->translate(
2002                "Entry '[_1]' (ID:[_2]) deleted by '[_3]'",
2003                $obj->title, $obj->id, $app->user->name
2004            ),
2005            level    => MT::Log::INFO(),
2006            class    => 'system',
2007            category => 'delete'
2008        }
2009    );
2010}
2011
2012sub update_entry_status {
2013    my $app = shift;
2014    my ( $new_status, @ids ) = @_;
2015    return $app->errtrans("Need a status to update entries")
2016      unless $new_status;
2017    return $app->errtrans("Need entries to update status")
2018      unless @ids;
2019    my @bad_ids;
2020    my %rebuild_these;
2021    require MT::Entry;
2022
2023    foreach my $id (@ids) {
2024        my $entry = MT::Entry->load($id)
2025          or return $app->errtrans(
2026            "One of the entries ([_1]) did not actually exist", $id );
2027        next if $entry->status == $new_status;
2028        if ( $app->config('DeleteFilesAtRebuild')
2029            && ( MT::Entry::RELEASE() eq $entry->status ) )
2030        {
2031            my $archive_type =
2032              $entry->class eq 'page'
2033              ? 'Page'
2034              : 'Individual';
2035            $app->publisher->remove_entry_archive_file(
2036                Entry       => $entry,
2037                ArchiveType => $archive_type
2038            );
2039        }
2040        my $old_status = $entry->status;
2041        $entry->status($new_status);
2042        $entry->save() and $rebuild_these{$id} = 1;
2043        my $message = $app->translate(
2044            "[_1] '[_2]' (ID:[_3]) status changed from [_4] to [_5]",
2045            $entry->class_label,
2046            $entry->title,
2047            $entry->id,
2048            $app->translate( MT::Entry::status_text($old_status) ),
2049            $app->translate( MT::Entry::status_text($new_status) )
2050        );
2051        $app->log(
2052            {
2053                message  => $message,
2054                level    => MT::Log::INFO(),
2055                class    => $entry->class,
2056                category => 'edit',
2057                metadata => $entry->id
2058            }
2059        );
2060    }
2061    $app->rebuild_these( \%rebuild_these, how => MT::App::CMS::NEW_PHASE() );
2062}
2063
2064sub _finish_rebuild_ping {
2065    my $app = shift;
2066    my ( $entry, $is_new, $ping_errors ) = @_;
2067    $app->redirect(
2068        $app->uri(
2069            'mode' => 'view',
2070            args   => {
2071                '_type' => $entry->class,
2072                blog_id => $entry->blog_id,
2073                id      => $entry->id,
2074                ( $is_new ? ( saved_added => 1 ) : ( saved_changes => 1 ) ),
2075                ( $ping_errors ? ( ping_errors => 1 ) : () )
2076            }
2077        )
2078    );
2079}
2080
2081sub ping_continuation {
2082    my $app = shift;
2083    my ( $entry, $blog, %options ) = @_;
2084    my $list = $app->needs_ping(
2085        Entry     => $entry,
2086        Blog      => $blog,
2087        OldStatus => $options{OldStatus}
2088    );
2089    require MT::Entry;
2090    if ( $entry->status == MT::Entry::RELEASE() && $list ) {
2091        my @urls = map { { url => $_ } } @$list;
2092        $app->load_tmpl(
2093            'pinging.tmpl',
2094            {
2095                blog_id    => $blog->id,
2096                entry_id   => $entry->id,
2097                old_status => $options{OldStatus},
2098                is_new     => $options{IsNew},
2099                url_list   => \@urls,
2100            }
2101        );
2102    }
2103    else {
2104        _finish_rebuild_ping( $app, $entry, $options{IsNew} );
2105    }
2106}
2107
2108sub delete {
2109    my $app = shift;
2110    $app->validate_magic() or return;
2111
2112    require MT::Blog;
2113    my $q       = $app->param;
2114    my $blog_id = $q->param('blog_id');
2115    my $blog    = MT::Blog->load($blog_id)
2116        or return $app->error($app->translate('Can\'t load blog #[_1].', $blog_id));
2117
2118    my $can_background =
2119        ( $blog->count_static_templates('Individual') == 0
2120            || MT::Util->launch_background_tasks() ) ? 1 : 0;
2121
2122    my %rebuild_recip;
2123    my $at = $blog->archive_type;
2124    my @at;
2125    if ( $at && $at ne 'None' ) {
2126        my @at_orig = split( /,/, $at );
2127        @at = grep { $_ ne 'Individual' && $_ ne 'Page' } @at_orig;
2128    }
2129
2130    for my $id ( $q->param('id') ) {
2131        my $class = $app->model("entry");
2132        my $obj   = $class->load($id);
2133        return $app->call_return unless $obj;
2134
2135        $app->run_callbacks( 'cms_delete_permission_filter.entry', $app, $obj )
2136          || return $app->error(
2137            $app->translate( "Permission denied: [_1]", $app->errstr() ) );
2138
2139        # Remove Individual archive file.
2140        if ( $app->config('DeleteFilesAtRebuild') ) {
2141            $app->publisher->remove_entry_archive_file( Entry => $obj, );
2142        }
2143        if (   $app->config('RebuildAtDelete')
2144            || $app->config('DeleteFilesAtRebuild') )
2145        {
2146            for my $at (@at) {
2147                my $archiver = $app->publisher->archiver($at);
2148                next unless $archiver;
2149
2150                # Remove archive file if archive file has not entries.
2151                my $to_delete =
2152                    ( $archiver->archive_entries_count( $blog, $at, $obj ) == 1 ) ? 1 : 0
2153                    if $archiver->can('archive_entries_count');
2154                if ( $to_delete && $app->config('DeleteFilesAtRebuild') ) {
2155                     $app->publisher->remove_entry_archive_file(
2156                         Entry       => $obj,
2157                         ArchiveType => $at
2158                     );
2159                }
2160                next if $to_delete;
2161
2162                # Make rebuild recip
2163                if ( $app->config('RebuildAtDelete') ) {
2164                    my ( $start, $end ) = $archiver->date_range( $obj->authored_on )
2165                        if $archiver->date_based() && $archiver->can('date_range');
2166
2167                    if ( $archiver->category_based() ) {
2168                        my $categories = $obj->categories();
2169                        for my $cat (@$categories) {
2170                            if ( $archiver->date_based() ) {
2171                                $rebuild_recip{$at}{ $cat->id }{ $start . $end }
2172                                  {'Start'} = $start;
2173                                $rebuild_recip{$at}{ $cat->id }{ $start . $end }
2174                                  {'End'} = $end;
2175                                $rebuild_recip{$at}{ $cat->id }{ $start . $end }
2176                                  {'File'} =
2177                                  MT::Util::archive_file_for( $obj, $blog, $at,
2178                                    $cat, undef, undef, undef );
2179                            }
2180                            else {
2181                                $rebuild_recip{$at}{ $cat->id }{id} = $cat->id;
2182                                $rebuild_recip{$at}{ $cat->id }{'File'} =
2183                                  MT::Util::archive_file_for( $obj, $blog, $at,
2184                                    $cat, undef, undef, undef );
2185                            }
2186                        }
2187                    }
2188                    elsif ( $archiver->author_based() ) {
2189                        if ( $archiver->date_based() ) {
2190                            $rebuild_recip{$at}{ $obj->author->id }{ $start . $end }
2191                              {'Start'} = $start;
2192                            $rebuild_recip{$at}{ $obj->author->id }{ $start . $end }
2193                              {'End'} = $end;
2194                            $rebuild_recip{$at}{ $obj->author->id }{ $start . $end }
2195                              {'File'} =
2196                              MT::Util::archive_file_for( $obj, $blog, $at, undef,
2197                                undef, undef, $obj->author );
2198                        }
2199                        else {
2200                            $rebuild_recip{$at}{ $obj->author->id }{id} =
2201                              $obj->author->id;
2202                            $rebuild_recip{$at}{ $obj->author->id }{'File'} =
2203                              MT::Util::archive_file_for( $obj, $blog, $at, undef,
2204                                undef, undef, $obj->author );
2205                        }
2206                    }
2207                    elsif ( $archiver->date_based() ) {
2208                        $rebuild_recip{$at}{ $start . $end }{'Start'} = $start;
2209                        $rebuild_recip{$at}{ $start . $end }{'End'}   = $end;
2210                        $rebuild_recip{$at}{ $start . $end }{'File'} =
2211                          MT::Util::archive_file_for( $obj, $blog, $at, undef,
2212                            undef, undef, undef );
2213                    }
2214                    if ( my $prev = $obj->previous(1) ) {
2215                        $rebuild_recip{Individual}{ $prev->id }{id} = $prev->id;
2216                        $rebuild_recip{Individual}{ $prev->id }{'File'} =
2217                          MT::Util::archive_file_for( $prev, $blog, 'Individual',
2218                            undef, undef, undef, undef );
2219                    }
2220                    if ( my $next = $obj->next(1) ) {
2221                        $rebuild_recip{Individual}{ $next->id }{id} = $next->id;
2222                        $rebuild_recip{Individual}{ $next->id }{'File'} =
2223                          MT::Util::archive_file_for( $next, $blog, 'Individual',
2224                            undef, undef, undef, undef );
2225                    }
2226                }
2227            }
2228        }
2229
2230        # Remove object from database
2231        $obj->remove()
2232            or return $app->errtrans(
2233                'Removing [_1] failed: [_2]',
2234                $app->translate('entry'),
2235                $obj->errstr
2236            );
2237        $app->run_callbacks( 'cms_post_delete.entry', $app, $obj );
2238    }
2239
2240    $app->add_return_arg( saved_deleted => 1 );
2241    if ( $q->param('is_power_edit') ) {
2242        $app->add_return_arg( is_power_edit => 1 );
2243    }
2244
2245    if ( $app->config('RebuildAtDelete') ) {
2246        if ($can_background) {
2247            my $res = MT::Util::start_background_task(
2248                sub {
2249                    my $res = $app->rebuild_archives(
2250                        Blog             => $blog,
2251                        Recip            => \%rebuild_recip,
2252                    ) or return $app->publish_error();
2253                    $app->rebuild_indexes( Blog => $blog )
2254                        or return $app->publish_error();
2255                    $app->run_callbacks( 'rebuild', $blog );
2256                    1;
2257                }
2258            );
2259        }
2260        else {
2261            $app->rebuild_archives(
2262                Blog             => $blog,
2263                Recip            => \%rebuild_recip,
2264            ) or return $app->publish_error();
2265            $app->rebuild_indexes( Blog => $blog )
2266                or return $app->publish_error();
2267
2268            $app->run_callbacks( 'rebuild', $blog );
2269        }
2270
2271        $app->add_return_arg( no_rebuild => 1 );
2272        my %params = (
2273            is_full_screen  => 1,
2274            redirect_target => $app->app_path
2275              . $app->script . '?'
2276              . $app->return_args,
2277        );
2278        return $app->load_tmpl( 'rebuilding.tmpl', \%params );
2279    }
2280
2281    return $app->call_return();
2282}
2283
22841;
Note: See TracBrowser for help on using the browser.