root/trunk/lib/MT/CMS/Entry.pm @ 3082

Revision 3082, 74.7 kB (checked in by bchoate, 14 months ago)

Merging fireball branch changes to-date to trunk: svn merge -r2974:3081 http://code.sixapart.com/svn/movabletype/branches/fireball .

  • 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 <= $limit ) {
562        delete $arg{limit};
563        $offset = 0;
564    }
565    elsif ( $total && $offset > $total - 1 ) {
566        $arg{offset} = $offset = $total - $limit;
567    }
568    elsif ( $offset && ( ( $offset < 0 ) || ( $total - $offset < $limit ) ) ) {
569        $arg{offset} = $offset = $total - $limit;
570    }
571    else {
572        $arg{offset} = $offset if $offset;
573    }
574
575    my $iter = $pkg->load_iter( \%terms, \%arg );
576
577    my $is_power_edit = $q->param('is_power_edit');
578    if ($is_power_edit) {
579        $param{has_expanded_mode} = 0;
580        delete $param{view_expanded};
581    }
582    else {
583        $param{has_expanded_mode} = 1;
584    }
585    my $data = build_entry_table( $app,
586        iter          => $iter,
587        is_power_edit => $is_power_edit,
588        param         => \%param,
589        type          => $type
590    );
591    delete $_->{object} foreach @$data;
592    delete $param{entry_table} unless @$data;
593
594    ## We tried to load $limit + 1 entries above; if we actually got
595    ## $limit + 1 back, we know we have another page of entries.
596    my $have_next_entry = @$data > $limit;
597    pop @$data while @$data > $limit;
598    if ($offset) {
599        $param{prev_offset}     = 1;
600        $param{prev_offset_val} = $offset - $limit;
601        $param{prev_offset_val} = 0 if $param{prev_offset_val} < 0;
602    }
603    if ($have_next_entry) {
604        $param{next_offset}     = 1;
605        $param{next_offset_val} = $offset + $limit;
606    }
607
608    $iter = MT::Author->load_iter(
609        { type => MT::Author::AUTHOR() },
610        {
611            'join' => $pkg->join_on(
612                'author_id',
613                { $blog_id ? ( blog_id => $blog_id ) : () },
614                {
615                    'unique'  => 1,
616                    'sort'    => 'authored_on',
617                    direction => 'descend'
618                }
619            ),
620            limit => 51,
621        }
622    );
623    my %seen;
624    my @authors;
625    while ( my $au = $iter->() ) {
626        next if $seen{ $au->id };
627        $seen{ $au->id } = 1;
628        my $row = {
629            author_name => $au->name,
630            author_id   => $au->id
631        };
632        push @authors, $row;
633        if ( @authors == 50 ) {
634            $iter->end;
635            last;
636        }
637    }
638    $param{entry_author_loop} = \@authors;
639
640    # $iter = $app->model('asset')->load_iter(
641    #     { class => '*', blog_id => $blog_id },
642    #     {
643    #         'join' => MT->model('objectasset')->join_on(
644    #             'asset_id',
645    #             {},
646    #             { unique => 1 }
647    #         ),
648    #         'sort'    => 'created_on',
649    #         direction => 'descend',
650    #     }
651    # );
652    # %seen = ();
653    # my @assets;
654    # while ( my $asset = $iter->() ) {
655    #     next if $seen{ $asset->id };
656    #     $seen{ $asset->id } = 1;
657    #     my $row = {
658    #         asset_label => $asset->label,
659    #         asset_id    => $asset->id,
660    #     };
661    #     push @assets, $row;
662    #     if ( @assets == 50 ) {
663    #         $iter->end;
664    #         last;
665    #     }
666    # }
667    # if ($filter_col eq 'asset_id' && !$seen{$filter_val}) {
668    #     push @assets, {
669    #         asset_label => $param{asset_label},
670    #         asset_id    => $filter_val,
671    #     };
672    # }
673    # $param{entry_asset_loop} = \@assets;
674
675    $param{page_actions}        = $app->page_actions( $app->mode );
676    $param{list_filters}        = $app->list_filters('entry');
677    $param{can_power_edit}      = $blog_id && !$is_power_edit;
678    $param{can_republish}       = $blog_id
679                                    ? $perms->can_rebuild
680                                    : $app->user->is_superuser
681                                        ? 1
682                                        : 0;
683    $param{is_power_edit}       = $is_power_edit;
684    $param{saved_deleted}       = $q->param('saved_deleted');
685    $param{no_rebuild}          = $q->param('no_rebuild');
686    $param{saved}               = $q->param('saved');
687    $param{limit}               = $limit;
688    $param{offset}              = $offset;
689    $param{object_type}         = $type;
690    $param{object_label}        = $pkg->class_label;
691    $param{object_label_plural} = $param{search_label} =
692      $pkg->class_label_plural;
693    $param{list_start}  = $offset + 1;
694    $param{list_end}    = $offset + scalar @$data;
695    $param{list_total}  = $total;
696    $param{next_max}    = $param{list_total} - $limit;
697    $param{next_max}    = 0 if ( $param{next_max} || 0 ) < $offset + 1;
698    $param{nav_entries} = 1;
699    $param{feed_label}  = $app->translate( "[_1] Feed", $pkg->class_label );
700    $param{feed_url} =
701      $app->make_feed_link( $type, $blog_id ? { blog_id => $blog_id } : undef );
702    $app->add_breadcrumb( $pkg->class_label_plural );
703    $param{listing_screen} = 1;
704
705    unless ($blog_id) {
706        $param{system_overview_nav} = 1;
707    }
708    $param{container_label} = $pkg->container_label;
709    unless ( $param{screen_class} ) {
710        $param{screen_class} = "list-$type";
711        $param{screen_class} .= " list-entry"
712          if $param{object_type} eq "page";  # to piggyback on list-entry styles
713    }
714    $param{mode}            = $app->mode;
715    if ( my $blog = MT::Blog->load($blog_id) ) {
716        $param{sitepath_unconfigured} = $blog->site_path ? 0 : 1;
717    }
718
719    $param->{return_args} ||= $app->make_return_args;
720    my @return_args = grep { $_ !~ /offset=\d/ } split /&/, $param->{return_args};
721    $param{return_args} = join '&', @return_args;
722    $param{return_args} .= "&offset=$offset" if $offset;
723    $param{screen_id} = "list-entry";
724    $param{screen_id} = "list-page"
725      if $param{object_type} eq "page";
726    if ( $param{is_power_edit} ) {
727        $param{screen_id} = "batch-edit-entry";
728        $param{screen_id} = "batch-edit-page"
729          if $param{object_type} eq "page";
730        $param{screen_class} .= " batch-edit";
731    }
732    $app->load_tmpl( "list_entry.tmpl", \%param );
733}
734
735sub preview {
736    my $app         = shift;
737    my $q           = $app->param;
738    my $type        = $q->param('_type') || 'entry';
739    my $entry_class = $app->model($type);
740    my $blog_id     = $q->param('blog_id');
741    my $blog        = $app->blog;
742    my $id          = $q->param('id');
743    my $entry;
744    my $user_id = $app->user->id;
745
746    if ($id) {
747        $entry = $entry_class->load( { id => $id, blog_id => $blog_id } )
748            or return $app->errtrans( "Invalid request." );
749        $user_id = $entry->author_id;
750    }
751    else {
752        $entry = $entry_class->new;
753        $entry->author_id($user_id);
754        $entry->id(-1); # fake out things like MT::Taggable::__load_tags
755        $entry->blog_id($blog_id);
756    }
757    my $cat;
758    my $names = $entry->column_names;
759
760    my %values = map { $_ => scalar $app->param($_) } @$names;
761    delete $values{'id'} unless $q->param('id');
762    ## Strip linefeed characters.
763    for my $col (qw( text excerpt text_more keywords )) {
764        $values{$col} =~ tr/\r//d if $values{$col};
765    }
766    $values{allow_comments} = 0
767      if !defined( $values{allow_comments} )
768      || $q->param('allow_comments') eq '';
769    $values{allow_pings} = 0
770      if !defined( $values{allow_pings} )
771      || $q->param('allow_pings') eq '';
772    $entry->set_values( \%values );
773
774    my $cat_ids = $q->param('category_ids');
775    if ($cat_ids) {
776        my @cats = split /,/, $cat_ids;
777        if (@cats) {
778            my $primary_cat = $cats[0];
779            $cat =
780              MT::Category->load( { id => $primary_cat, blog_id => $blog_id } );
781            my @categories = MT::Category->load( { id => \@cats, blog_id => $blog_id });
782            $entry->cache_property('category', undef, $cat);
783            $entry->cache_property('categories', undef, \@categories);
784        }
785    } else {
786        $entry->cache_property('category', undef, undef);
787        $entry->cache_property('categories', undef, []);
788    }
789    my $tag_delim = chr( $app->user->entry_prefs->{tag_delim} );
790    my @tag_names = MT::Tag->split( $tag_delim, $q->param('tags') );
791    if (@tag_names) {
792        my @tags;
793        foreach my $tag_name (@tag_names) {
794            my $tag = MT::Tag->new;
795            $tag->name($tag_name);
796            push @tags, $tag;
797        }
798        $entry->{__tags} = \@tag_names;
799        $entry->{__tag_objects} = \@tags;
800    }
801
802    my $date = $q->param('authored_on_date');
803    my $time = $q->param('authored_on_time');
804    my $ts   = $date . $time;
805    $ts =~ s/\D//g;
806    $entry->authored_on($ts);
807
808    my $preview_basename = $app->preview_object_basename;
809    $entry->basename($preview_basename);
810
811    require MT::TemplateMap;
812    require MT::Template;
813    my $tmpl_map = MT::TemplateMap->load(
814        {
815            archive_type => ( $type eq 'page' ? 'Page' : 'Individual' ),
816            is_preferred => 1,
817            blog_id => $blog_id,
818        }
819    );
820
821    my $tmpl;
822    my $fullscreen;
823    my $archive_file;
824    my $orig_file;
825    my $file_ext;
826    if ($tmpl_map) {
827        $tmpl         = MT::Template->load( $tmpl_map->template_id );
828        $file_ext = $blog->file_extension || '';
829        $archive_file = $entry->archive_file;
830
831        my $blog_path = $type eq 'page' ?
832            $blog->site_path :
833            ($blog->archive_path || $blog->site_path);
834        $archive_file = File::Spec->catfile( $blog_path, $archive_file );
835        require File::Basename;
836        my $path;
837        ( $orig_file, $path ) = File::Basename::fileparse( $archive_file );
838        $file_ext = '.' . $file_ext if $file_ext ne '';
839        $archive_file = File::Spec->catfile( $path, $preview_basename . $file_ext );
840    }
841    else {
842        $tmpl       = $app->load_tmpl('preview_entry_content.tmpl');
843        $fullscreen = 1;
844    }
845    return $app->error($app->translate('Can\'t load template.')) unless $tmpl;
846
847    # translates naughty words when PublishCharset is NOT UTF-8
848    $app->_translate_naughty_words($entry);
849
850    $entry->convert_breaks( scalar $q->param('convert_breaks') );
851       
852    my @data = ( { data_name => 'author_id', data_value => $user_id } );
853    $app->run_callbacks( 'cms_pre_preview', $app, $entry, \@data );
854
855    my $ctx = $tmpl->context;
856    $ctx->stash( 'entry', $entry );
857    $ctx->stash( 'blog',  $blog );
858    $ctx->stash( 'category', $cat ) if $cat;
859    $ctx->{current_timestamp} = $ts;
860    $ctx->var('entry_template',    1);
861    $ctx->var('archive_template',  1);
862    $ctx->var('entry_template',    1);
863    $ctx->var('feedback_template', 1);
864    $ctx->var('archive_class',     'entry-archive');
865    $ctx->var('preview_template',  1);
866    my $html = $tmpl->output;
867    my %param;
868    unless ( defined($html) ) {
869        my $preview_error = $app->translate( "Publish error: [_1]",
870            MT::Util::encode_html( $tmpl->errstr ) );
871        $param{preview_error} = $preview_error;
872        my $tmpl_plain = $app->load_tmpl('preview_entry_content.tmpl');
873        $tmpl->text( $tmpl_plain->text );
874        $html = $tmpl->output;
875        defined($html)
876          or return $app->error(
877            $app->translate( "Publish error: [_1]", $tmpl->errstr ) );
878        $fullscreen = 1;
879    }
880
881    # If MT is configured to do 'local' previews, convert all
882    # the normal blog URLs into the domain used by MT itself (ie,
883    # blog is published to www.example.com, which is a different
884    # server from where MT runs, mt.example.com; previews therefore
885    # should occur locally, so replace all http://www.example.com/
886    # with http://mt.example.com/).
887    my ($old_url, $new_url);
888    if ($app->config('LocalPreviews')) {
889        $old_url = $blog->site_url;
890        $old_url =~ s!^(https?://[^/]+?/)(.*)?!$1!;
891        $new_url = $app->base . '/';
892        $html =~ s!\Q$old_url\E!$new_url!g;
893    }
894
895    if ( !$fullscreen ) {
896        my $fmgr = $blog->file_mgr;
897
898        ## Determine if we need to build directory structure,
899        ## and build it if we do. DirUmask determines
900        ## directory permissions.
901        require File::Basename;
902        my $path = File::Basename::dirname($archive_file);
903        $path =~ s!/$!!
904          unless $path eq '/';    ## OS X doesn't like / at the end in mkdir().
905        unless ( $fmgr->exists($path) ) {
906            $fmgr->mkpath($path);
907        }
908
909        if ( $fmgr->exists($path) && $fmgr->can_write($path) ) {
910            $fmgr->put_data( $html, $archive_file );
911            $param{preview_file} = $preview_basename;
912            my $preview_url = $entry->archive_url;
913            $preview_url =~ s! / \Q$orig_file\E ( /? ) $!/$preview_basename$file_ext$1!x;
914
915            # We also have to translate the URL used for the
916            # published file to be on the MT app domain.
917            if (defined $new_url) {
918                $preview_url =~ s!^\Q$old_url\E!$new_url!;
919            }
920
921            $param{preview_url}  = $preview_url;
922
923            # we have to make a record of this preview just in case it
924            # isn't cleaned up by re-editing, saving or cancelling on
925            # by the user.
926            require MT::Session;
927            my $sess_obj = MT::Session->get_by_key(
928                {
929                    id   => $preview_basename,
930                    kind => 'TF',                # TF = Temporary File
931                    name => $archive_file,
932                }
933            );
934            $sess_obj->start(time);
935            $sess_obj->save;
936        }
937        else {
938            $fullscreen = 1;
939            $param{preview_error} = $app->translate(
940                "Unable to create preview file in this location: [_1]", $path );
941            my $tmpl_plain = $app->load_tmpl('preview_entry_content.tmpl');
942            $tmpl->text( $tmpl_plain->text );
943            $tmpl->reset_tokens;
944            $html = $tmpl->output;
945            $param{preview_body} = $html;
946        }
947    }
948    else {
949        $param{preview_body} = $html;
950    }
951    $param{id} = $id if $id;
952    $param{new_object} = $param{id} ? 0 : 1;
953    $param{title} = $entry->title;
954    my $cols = $entry_class->column_names;
955
956    for my $col (@$cols) {
957        next
958          if $col eq 'created_on'
959          || $col eq 'created_by'
960          || $col eq 'modified_on'
961          || $col eq 'modified_by'
962          || $col eq 'authored_on'
963          || $col eq 'author_id'
964          || $col eq 'pinged_urls'
965          || $col eq 'tangent_cache'
966          || $col eq 'template_id'
967          || $col eq 'class'
968          || $col eq 'meta'
969          || $col eq 'comment_count'
970          || $col eq 'ping_count';
971        if ( $col eq 'basename' ) {
972            if (   ( !defined $q->param('basename') )
973                || ( $q->param('basename') eq '' ) )
974            {
975                $q->param( 'basename', $q->param('basename_old') );
976            }
977        }
978        push @data,
979          {
980            data_name  => $col,
981            data_value => scalar $q->param($col)
982          };
983    }
984    for my $data (
985        qw( authored_on_date authored_on_time basename_manual basename_old category_ids tags )
986      )
987    {
988        push @data,
989          {
990            data_name  => $data,
991            data_value => scalar $q->param($data)
992          };
993    }
994
995    $param{entry_loop} = \@data;
996    my $list_mode;
997    my $list_title;
998    if ( $type eq 'page' ) {
999        $list_title = 'Pages';
1000        $list_mode  = 'list_pages';
1001    }
1002    else {
1003        $list_title = 'Entries';
1004        $list_mode  = 'list_entries';
1005    }
1006    if ($id) {
1007        $app->add_breadcrumb(
1008            $app->translate($list_title),
1009            $app->uri(
1010                'mode' => $list_mode,
1011                args   => { blog_id => $blog_id }
1012            )
1013        );
1014        $app->add_breadcrumb( $entry->title || $app->translate('(untitled)') );
1015    }
1016    else {
1017        $app->add_breadcrumb( $app->translate($list_title),
1018            $app->uri( 'mode' => $list_mode, args => { blog_id => $blog_id } )
1019        );
1020        $app->add_breadcrumb(
1021            $app->translate( 'New [_1]', $entry_class->class_label ) );
1022        $param{nav_new_entry} = 1;
1023    }
1024    $param{object_type}  = $type;
1025    $param{object_label} = $entry_class->class_label;
1026    if ($fullscreen) {
1027        return $app->load_tmpl( 'preview_entry.tmpl', \%param );
1028    }
1029    else {
1030        $app->request('preview_object', $entry);
1031        return $app->load_tmpl( 'preview_strip.tmpl', \%param );
1032    }
1033}
1034
1035sub cfg_entry {
1036    my $app     = shift;
1037    my $q       = $app->param;
1038    my $blog_id = scalar $q->param('blog_id');
1039    return $app->return_to_dashboard( redirect => 1 )
1040      unless $blog_id;
1041    $q->param( '_type', 'blog' );
1042    $q->param( 'id',    scalar $q->param('blog_id') );
1043    $app->forward("view",
1044        {
1045            output       => 'cfg_entry.tmpl',
1046            screen_class => 'settings-screen entry-screen'
1047        }
1048    );
1049}
1050
1051sub save {
1052    my $app = shift;
1053    $app->validate_magic or return;
1054
1055    $app->remove_preview_file;
1056
1057    if ( $app->param('is_power_edit') ) {
1058        return $app->save_entries(@_);
1059    }
1060    my $author = $app->user;
1061    my $type = $app->param('_type') || 'entry';
1062
1063    my $class = $app->model($type)
1064      or return $app->errtrans("Invalid parameter");
1065
1066    my $cat_class = $app->model( $class->container_type );
1067
1068    my $perms = $app->permissions
1069      or return $app->errtrans("Permission denied.");
1070
1071    if ( $type eq 'page' ) {
1072        return $app->errtrans("Permission denied.")
1073          unless $perms->can_manage_pages;
1074    }
1075
1076    my $id = $app->param('id');
1077    if ( !$id ) {
1078        return $app->errtrans("Permission denied.")
1079          unless ( ( 'entry' eq $type ) && $perms->can_create_post )
1080          || ( ( 'page' eq $type ) && $perms->can_manage_pages );
1081    }
1082
1083    $app->validate_magic() or return;
1084
1085    # check for autosave
1086    if ( $app->param('_autosave') ) {
1087        return $app->autosave_object();
1088    }
1089
1090    require MT::Blog;
1091    my $blog_id = $app->param('blog_id');
1092    my $blog    = MT::Blog->load($blog_id)
1093        or return $app->error($app->translate('Can\'t load blog #[_1].', $blog_id));
1094   
1095    my $archive_type;
1096
1097    my ( $obj, $orig_obj, $orig_file );
1098    if ($id) {
1099        $obj = $class->load($id)
1100          || return $app->error(
1101            $app->translate( "No such [_1].", $class->class_label ) );
1102        return $app->error( $app->translate("Invalid parameter") )
1103          unless $obj->blog_id == $blog_id;
1104        if ( $type eq 'entry' ) {
1105            return $app->error( $app->translate("Permission denied.") )
1106              unless $perms->can_edit_entry( $obj, $author );
1107            return $app->error( $app->translate("Permission denied.") )
1108              if ( $obj->status ne $app->param('status') )
1109              && !( $perms->can_edit_entry( $obj, $author, 1 ) );
1110            $archive_type = 'Individual';
1111        }
1112        elsif ( $type eq 'page' ) {
1113            $archive_type = 'Page';
1114        }
1115        $orig_obj = $obj->clone;
1116        $orig_file = archive_file_for( $orig_obj, $blog, $archive_type );
1117    }
1118    else {
1119        $obj = $class->new;
1120    }
1121    my $status_old = $id ? $obj->status : 0;
1122    my $names = $obj->column_names;
1123
1124    ## Get rid of category_id param, because we don't want to just set it
1125    ## in the Entry record; save it for later when we will set the Placement.
1126    my ( $cat_id, @add_cat ) = split /\s*,\s*/,
1127      ( $app->param('category_ids') || '' );
1128    $app->delete_param('category_id');
1129    if ($id) {
1130        ## Delete the author_id param (if present), because we don't want to
1131        ## change the existing author.
1132        $app->delete_param('author_id');
1133    }
1134
1135    my %values = map { $_ => scalar $app->param($_) } @$names;
1136    delete $values{'id'} unless $app->param('id');
1137    ## Strip linefeed characters.
1138    for my $col (qw( text excerpt text_more keywords )) {
1139        $values{$col} =~ tr/\r//d if $values{$col};
1140    }
1141    $values{allow_comments} = 0
1142      if !defined( $values{allow_comments} )
1143      || $app->param('allow_comments') eq '';
1144    delete $values{week_number}
1145      if ( $app->param('week_number') || '' ) eq '';
1146    delete $values{basename}
1147      unless $perms->can_publish_post || $perms->can_edit_all_posts;
1148    $obj->set_values( \%values );
1149    $obj->allow_pings(0)
1150      if !defined $app->param('allow_pings')
1151      || $app->param('allow_pings') eq '';
1152    my $ao_d = $app->param('authored_on_date');
1153    my $ao_t = $app->param('authored_on_time');
1154
1155    if ( !$id ) {
1156
1157        #  basename check for this new entry...
1158        if (   ( my $basename = $app->param('basename') )
1159            && !$app->param('basename_manual')
1160            && $type eq 'entry' )
1161        {
1162            my $exist =
1163              $class->exist( { blog_id => $blog_id, basename => $basename } );
1164            if ($exist) {
1165                $obj->basename( MT::Util::make_unique_basename($obj) );
1166            }
1167        }
1168    }
1169
1170    if ( $type eq 'page' ) {
1171
1172        # -1 is a special id for identifying the 'root' folder
1173        $cat_id = 0 if $cat_id == -1;
1174        my $dup_it = $class->load_iter(
1175            {
1176                blog_id  => $blog_id,
1177                basename => $obj->basename,
1178                class    => 'page',
1179                ( $id ? ( id => $id ) : () )
1180            },
1181            { ( $id ? ( not => { id => 1 } ) : () ) }
1182        );
1183        while ( my $p = $dup_it->() ) {
1184            my $p_folder = $p->folder;
1185            my $dup_folder_path =
1186              defined $p_folder ? $p_folder->publish_path() : '';
1187            my $folder = MT::Folder->load($cat_id) if $cat_id;
1188            my $folder_path = defined $folder ? $folder->publish_path() : '';
1189            return $app->error(
1190                $app->translate(
1191"Same Basename has already been used. You should use an unique basename."
1192                )
1193            ) if ( $dup_folder_path eq $folder_path );
1194        }
1195
1196    }
1197
1198    if ( $type eq 'entry' ) {
1199        $obj->status( MT::Entry::HOLD() )
1200          if !$id
1201          && !$perms->can_publish_post
1202          && !$perms->can_edit_all_posts;
1203    }
1204
1205    my $filter_result = $app->run_callbacks( 'cms_save_filter.' . $type, $app );
1206
1207    if ( !$filter_result ) {
1208        my %param = ();
1209        $param{error}       = $app->errstr;
1210        $param{return_args} = $app->param('return_args');
1211        return $app->forward( "view", \%param );
1212    }
1213
1214    # check to make sure blog has site url and path defined.
1215    # otherwise, we can't publish a released entry
1216    if ( ( $obj->status || 0 ) != MT::Entry::HOLD() ) {
1217        if ( !$blog->site_path || !$blog->site_url ) {
1218            return $app->error(
1219                $app->translate(
1220"Your blog has not been configured with a site path and URL. You cannot publish entries until these are defined."
1221                )
1222            );
1223        }
1224    }
1225
1226    my ( $previous_old, $next_old );
1227    if (   ( $perms->can_publish_post || $perms->can_edit_all_posts )
1228        && ($ao_d) )
1229    {
1230        my %param = ();
1231        my $ao = $ao_d . ' ' . $ao_t;
1232        unless (
1233            $ao =~ m!^(\d{4})-(\d{1,2})-(\d{1,2})\s+(\d{1,2}):(\d{1,2})(?::(\d{1,2}))?$! )
1234        {
1235            $param{error} = $app->translate(
1236"Invalid date '[_1]'; authored on dates must be in the format YYYY-MM-DD HH:MM:SS.",
1237$ao
1238            );
1239        }
1240        my $s = $6 || 0;
1241            $param{error} = $app->translate(
1242                "Invalid date '[_1]'; authored on dates should be real dates.",
1243                $ao
1244          )
1245          if (
1246               $s > 59
1247            || $s < 0
1248            || $5 > 59
1249            || $5 < 0
1250            || $4 > 23
1251            || $4 < 0
1252            || $2 > 12
1253            || $2 < 1
1254            || $3 < 1
1255            || ( MT::Util::days_in( $2, $1 ) < $3
1256                && !MT::Util::leap_day( $0, $1, $2 ) )
1257          );
1258        $param{return_args} = $app->param('return_args');
1259        return $app->forward( "view", \%param ) if $param{error};
1260        if ($obj->authored_on) {
1261            $previous_old = $obj->previous(1);
1262            $next_old     = $obj->next(1);
1263        }
1264        my $ts = sprintf "%04d%02d%02d%02d%02d%02d", $1, $2, $3, $4, $5, $s;
1265        $obj->authored_on($ts);
1266    }
1267    my $is_new = $obj->id ? 0 : 1;
1268
1269    $app->_translate_naughty_words($obj);
1270
1271    $obj->modified_by( $author->id ) unless $is_new;
1272
1273    $app->run_callbacks( 'cms_pre_save.' . $type, $app, $obj, $orig_obj )
1274      || return $app->error(
1275        $app->translate(
1276            "Saving [_1] failed: [_2]",
1277            $class->class_label, $app->errstr
1278        )
1279      );
1280
1281    $obj->save
1282      or return $app->error(
1283        $app->translate(
1284            "Saving [_1] failed: [_2]",
1285            $class->class_label, $obj->errstr
1286        )
1287      );
1288
1289    my $message;
1290    if ($is_new) {
1291        $message =
1292          $app->translate( "[_1] '[_2]' (ID:[_3]) added by user '[_4]'",
1293            $class->class_label, $obj->title, $obj->id, $author->name );
1294    }
1295    elsif ( $orig_obj->status ne $obj->status ) {
1296        $message = $app->translate(
1297"[_1] '[_2]' (ID:[_3]) edited and its status changed from [_4] to [_5] by user '[_6]'",
1298            $class->class_label,
1299            $obj->title,
1300            $obj->id,
1301            $app->translate( MT::Entry::status_text( $orig_obj->status ) ),
1302            $app->translate( MT::Entry::status_text( $obj->status ) ),
1303            $author->name
1304        );
1305
1306    }
1307    else {
1308        $message =
1309          $app->translate( "[_1] '[_2]' (ID:[_3]) edited by user '[_4]'",
1310            $class->class_label, $obj->title, $obj->id, $author->name );
1311    }
1312    require MT::Log;
1313    $app->log(
1314        {
1315            message => $message,
1316            level   => MT::Log::INFO(),
1317            class   => $type,
1318            $is_new ? ( category => 'new' ) : ( category => 'edit' ),
1319            metadata => $obj->id
1320        }
1321    );
1322
1323    my $error_string = MT::callback_errstr();
1324
1325    ## Now that the object is saved, we can be certain that it has an
1326    ## ID. So we can now add/update/remove the primary placement.
1327    require MT::Placement;
1328    my $place =
1329      MT::Placement->load( { entry_id => $obj->id, is_primary => 1 } );
1330    if ($cat_id) {
1331        unless ($place) {
1332            $place = MT::Placement->new;
1333            $place->entry_id( $obj->id );
1334            $place->blog_id( $obj->blog_id );
1335            $place->is_primary(1);
1336        }
1337        $place->category_id($cat_id);
1338        $place->save;
1339        my $cat = $cat_class->load($cat_id);
1340        $obj->cache_property( 'category', undef, $cat );
1341    }
1342    else {
1343        if ( $place ) {
1344            $place->remove;
1345            $obj->cache_property( 'category', undef, undef );
1346        }
1347    }
1348
1349    my $placements_updated;
1350
1351    # save secondary placements...
1352    my @place = MT::Placement->load(
1353        {
1354            entry_id   => $obj->id,
1355            is_primary => 0
1356        }
1357    );
1358    for my $place (@place) {
1359        $place->remove;
1360        $placements_updated = 1;
1361    }
1362    my @add_cat_obj;
1363    for my $cat_id (@add_cat) {
1364        my $cat = $cat_class->load($cat_id);
1365
1366        # blog_id sanity check
1367        next if !$cat || $cat->blog_id != $obj->blog_id;
1368
1369        my $place = MT::Placement->new;
1370        $place->entry_id( $obj->id );
1371        $place->blog_id( $obj->blog_id );
1372        $place->is_primary(0);
1373        $place->category_id($cat_id);
1374        $place->save
1375          or return $app->error(
1376            $app->translate( "Saving placement failed: [_1]", $place->errstr )
1377          );
1378        $placements_updated = 1;
1379        push @add_cat_obj, $cat;
1380    }
1381    if ($placements_updated) {
1382        unshift @add_cat_obj, $obj->cache_property('category')
1383          if $obj->cache_property('category');
1384        $obj->cache_property( 'categories', undef, [] );
1385        $obj->cache_property( 'categories', undef, \@add_cat_obj );
1386    }
1387
1388    $app->run_callbacks( 'cms_post_save.' . $type, $app, $obj, $orig_obj );
1389
1390    ## If the saved status is RELEASE, or if the *previous* status was
1391    ## RELEASE, then rebuild entry archives, indexes, and send the
1392    ## XML-RPC ping(s). Otherwise the status was and is HOLD, and we
1393    ## don't have to do anything.
1394    if ( ( $obj->status || 0 ) == MT::Entry::RELEASE()
1395        || $status_old eq MT::Entry::RELEASE() )
1396    {
1397        if ( $app->config('DeleteFilesAtRebuild') && $orig_obj ) {
1398            my $file = archive_file_for( $obj, $blog, $archive_type );
1399            if ( $file ne $orig_file || $obj->status != MT::Entry::RELEASE() ) {
1400                $app->publisher->remove_entry_archive_file(
1401                    Entry       => $orig_obj,
1402                    ArchiveType => $archive_type
1403                );
1404            }
1405        }
1406
1407        # If there are no static pages, just rebuild indexes.
1408        if ( $blog->count_static_templates($archive_type) == 0
1409            || MT::Util->launch_background_tasks() )
1410        {
1411            my $res = MT::Util::start_background_task(
1412                sub {
1413                    $app->run_callbacks('pre_build');
1414                    $app->rebuild_entry(
1415                        Entry             => $obj,
1416                        BuildDependencies => 1,
1417                        OldEntry          => $orig_obj,
1418                        OldPrevious       => ($previous_old)
1419                        ? $previous_old->id
1420                        : undef,
1421                        OldNext => ($next_old) ? $next_old->id : undef
1422                    ) or return $app->publish_error();
1423                    $app->run_callbacks( 'rebuild', $blog );
1424                    $app->run_callbacks( 'post_build' );
1425                    1;
1426                }
1427            );
1428            return unless $res;
1429            return ping_continuation($app,
1430                $obj, $blog,
1431                OldStatus => $status_old,
1432                IsNew     => $is_new,
1433            );
1434        }
1435        else {
1436            return $app->redirect(
1437                $app->uri(
1438                    'mode' => 'start_rebuild',
1439                    args   => {
1440                        blog_id    => $obj->blog_id,
1441                        'next'     => 0,
1442                        type       => 'entry-' . $obj->id,
1443                        entry_id   => $obj->id,
1444                        is_new     => $is_new,
1445                        old_status => $status_old,
1446                        (
1447                            $previous_old
1448                            ? ( old_previous => $previous_old->id )
1449                            : ()
1450                        ),
1451                        ( $next_old ? ( old_next => $next_old->id ) : () )
1452                    }
1453                )
1454            );
1455        }
1456    }
1457    _finish_rebuild_ping( $app, $obj, !$id );
1458}
1459
1460sub save_entries {
1461    my $app   = shift;
1462    my $perms = $app->permissions;
1463    my $type  = $app->param('_type');
1464    return $app->errtrans("Permission denied.")
1465      unless $perms
1466      && (
1467        $type eq 'page'
1468        ? ( $perms->can_manage_pages )
1469        : (      $perms->can_publish_post
1470              || $perms->can_create_post
1471              || $perms->can_edit_all_posts )
1472      );
1473
1474    $app->validate_magic() or return;
1475
1476    my $q = $app->param;
1477    my @p = $q->param;
1478    require MT::Entry;
1479    require MT::Placement;
1480    require MT::Log;
1481    my $blog_id        = $q->param('blog_id');
1482    my $this_author    = $app->user;
1483    my $this_author_id = $this_author->id;
1484    for my $p (@p) {
1485        next unless $p =~ /^category_id_(\d+)/;
1486        my $id    = $1;
1487        my $entry = MT::Entry->load($id)
1488            or next;
1489        return $app->error( $app->translate("Permission denied.") )
1490            unless $perms
1491              && (
1492                $type eq 'page'
1493                ? ( $perms->can_manage_pages )
1494                : (      $perms->can_publish_post
1495                      || $perms->can_create_post
1496                      || $perms->can_edit_all_posts )
1497              );
1498        my $orig_obj = $entry->clone;
1499        if ( $perms->can_edit_entry( $entry, $this_author ) ) {
1500            my $author_id = $q->param( 'author_id_' . $id );
1501            $entry->author_id( $author_id ? $author_id : 0 );
1502            $entry->title( scalar $q->param( 'title_' . $id ) );
1503        }
1504        if ( $perms->can_edit_entry( $entry, $this_author, 1 ) )
1505        {    ## can he/she change status?
1506            $entry->status( scalar $q->param( 'status_' . $id ) );
1507            my $co = $q->param( 'created_on_' . $id );
1508            unless ( $co =~
1509                m!(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2})(?::(\d{2}))?! )
1510            {
1511                return $app->error(
1512                    $app->translate(
1513"Invalid date '[_1]'; authored on dates must be in the format YYYY-MM-DD HH:MM:SS.",
1514                        $co
1515                    )
1516                );
1517            }
1518            my $s = $6 || 0;
1519
1520            # Emit an error message if the date is bogus.
1521            return $app->error(
1522                $app->translate(
1523"Invalid date '[_1]'; authored on dates should be real dates.",
1524                    $co
1525                )
1526              )
1527              if $s > 59
1528              || $s < 0
1529              || $5 > 59
1530              || $5 < 0
1531              || $4 > 23
1532              || $4 < 0
1533              || $2 > 12
1534              || $2 < 1
1535              || $3 < 1
1536              || ( MT::Util::days_in( $2, $1 ) < $3
1537                && !MT::Util::leap_day( $0, $1, $2 ) );
1538
1539            # FIXME: Should be assigning the publish_date field here
1540            my $ts = sprintf "%04d%02d%02d%02d%02d%02d", $1, $2, $3, $4, $5, $s;
1541            if ($type eq 'page' ) {
1542                $entry->modified_on($ts);
1543            } else {
1544                $entry->authored_on($ts);
1545            }
1546        }
1547        $app->run_callbacks( 'cms_pre_save.' . $type, $app, $entry, $orig_obj )
1548          || return $app->error(
1549            $app->translate(
1550                "Saving [_1] failed: [_2]",
1551                $entry->class_label, $app->errstr
1552            )
1553          );
1554        $entry->save
1555          or return $app->error(
1556            $app->translate(
1557                "Saving entry '[_1]' failed: [_2]", $entry->title,
1558                $entry->errstr
1559            )
1560          );
1561        my $cat_id = $q->param("category_id_$id");
1562        my $place  = MT::Placement->load(
1563            {
1564                entry_id   => $id,
1565                is_primary => 1
1566            }
1567        );
1568        if ( $place && !$cat_id ) {
1569            $place->remove
1570              or return $app->error(
1571                $app->translate(
1572                    "Removing placement failed: [_1]",
1573                    $place->errstr
1574                )
1575              );
1576        }
1577        elsif ($cat_id) {
1578            unless ($place) {
1579                $place = MT::Placement->new;
1580                $place->entry_id($id);
1581                $place->blog_id($blog_id);
1582                $place->is_primary(1);
1583            }
1584            $place->category_id( scalar $q->param($p) );
1585            $place->save
1586              or return $app->error(
1587                $app->translate(
1588                    "Saving placement failed: [_1]",
1589                    $place->errstr
1590                )
1591              );
1592        }
1593        my $message;
1594        if ( $orig_obj->status ne $entry->status ) {
1595            $message = $app->translate(
1596"[_1] '[_2]' (ID:[_3]) edited and its status changed from [_4] to [_5] by user '[_6]'",
1597                $entry->class_label,
1598                $entry->title,
1599                $entry->id,
1600                $app->translate( MT::Entry::status_text( $orig_obj->status ) ),
1601                $app->translate( MT::Entry::status_text( $entry->status ) ),
1602                $this_author->name
1603            );
1604        }
1605        else {
1606            $message =
1607              $app->translate( "[_1] '[_2]' (ID:[_3]) edited by user '[_4]'",
1608                $entry->class_label, $entry->title, $entry->id,
1609                $this_author->name );
1610        }
1611        $app->log(
1612            {
1613                message  => $message,
1614                level    => MT::Log::INFO(),
1615                class    => $entry->class,
1616                category => 'edit',
1617                metadata => $entry->id
1618            }
1619        );
1620        $app->run_callbacks( 'cms_post_save.' . $type, $app, $entry, $orig_obj );
1621    }
1622    $app->add_return_arg( 'saved' => 1, is_power_edit => 1 );
1623    $app->call_return;
1624}
1625
1626sub send_pings {
1627    my $app = shift;
1628    my $q   = $app->param;
1629    $app->validate_magic() or return;
1630    require MT::Entry;
1631    require MT::Blog;
1632    my $blog  = MT::Blog->load( scalar $q->param('blog_id') );
1633    my $entry = MT::Entry->load( scalar $q->param('entry_id') );
1634    ## MT::ping_and_save pings each of the necessary URLs, then processes
1635    ## the return value from MT::ping to update the list of URLs pinged
1636    ## and not successfully pinged. It returns the return value from
1637    ## MT::ping for further processing. If a fatal error occurs, it returns
1638    ## undef.
1639    my $results = $app->ping_and_save(
1640        Blog      => $blog,
1641        Entry     => $entry,
1642        OldStatus => scalar $q->param('old_status')
1643    ) or return;
1644    my $has_errors = 0;
1645    require MT::Log;
1646    for my $res (@$results) {
1647        $has_errors++,
1648          $app->log(
1649            {
1650                message => $app->translate(
1651                    "Ping '[_1]' failed: [_2]",
1652                    $res->{url},
1653                    encode_text( $res->{error}, undef, undef )
1654                ),
1655                class => 'system',
1656                level => MT::Log::WARNING()
1657            }
1658          ) unless $res->{good};
1659    }
1660    _finish_rebuild_ping( $app, $entry, scalar $q->param('is_new'),
1661        $has_errors );
1662}
1663
1664sub pinged_urls {
1665    my $app   = shift;
1666    my $perms = $app->permissions
1667      or return $app->error( $app->translate("No permissions") );
1668    my %param;
1669    my $entry_id = $app->param('entry_id');
1670    require MT::Entry;
1671    my $entry = MT::Entry->load($entry_id)
1672        or return $app->error($app->translate('Can\'t load entry #[_1].', $entry_id));
1673    $param{url_loop} = [ map { { url => $_ } } @{ $entry->pinged_url_list } ];
1674    $param{failed_url_loop} =
1675      [ map { { url => $_ } }
1676          @{ $entry->pinged_url_list( OnlyFailures => 1 ) } ];
1677    $app->load_tmpl( 'popup/pinged_urls.tmpl', \%param );
1678}
1679
1680sub save_entry_prefs {
1681    my $app   = shift;
1682    my $perms = $app->permissions
1683      or return $app->error( $app->translate("No permissions") );
1684    $app->validate_magic() or return;
1685    my $q     = $app->param;
1686    my $prefs = $app->_entry_prefs_from_params;
1687    $perms->entry_prefs($prefs);
1688    $perms->save
1689      or return $app->error(
1690        $app->translate( "Saving permissions failed: [_1]", $perms->errstr ) );
1691    $app->send_http_header("text/json");
1692    return "true";
1693}
1694
1695sub publish_entries {
1696    my $app = shift;
1697    require MT::Entry;
1698    update_entry_status( $app, MT::Entry::RELEASE(), $app->param('id') );
1699}
1700
1701sub draft_entries {
1702    my $app = shift;
1703    require MT::Entry;
1704    update_entry_status( $app, MT::Entry::HOLD(), $app->param('id') );
1705}
1706
1707sub open_batch_editor {
1708    my $app = shift;
1709    my @ids = $app->param('id');
1710
1711    $app->param( 'is_power_edit', 1 );
1712    $app->param( 'filter',        'power_edit' );
1713    $app->param( 'filter_val',    \@ids );
1714    $app->mode(
1715        'list_' . ( 'entry' eq $app->param('_type') ? 'entries' : 'pages' ) );
1716    $app->forward( "list_entry", { type => $app->param('_type') } );
1717}
1718
1719sub build_entry_table {
1720    my $app = shift;
1721    my (%args) = @_;
1722
1723    my $app_author = $app->user;
1724    my $perms      = $app->permissions;
1725    my $type       = $args{type};
1726    my $class      = $app->model($type);
1727
1728    my $list_pref = $app->list_pref($type);
1729    if ( $args{is_power_edit} ) {
1730        delete $list_pref->{view_expanded};
1731    }
1732    my $iter;
1733    if ( $args{load_args} ) {
1734        $iter = $class->load_iter( @{ $args{load_args} } );
1735    }
1736    elsif ( $args{iter} ) {
1737        $iter = $args{iter};
1738    }
1739    elsif ( $args{items} ) {
1740        $iter = sub { shift @{ $args{items} } };
1741    }
1742    return [] unless $iter;
1743    my $limit         = $args{limit};
1744    my $is_power_edit = $args{is_power_edit} || 0;
1745    my $param         = $args{param} || {};
1746
1747    ## Load list of categories for display in filter pulldown (and selection
1748    ## pulldown on power edit page).
1749    my ( $c_data, %cats );
1750    my $blog_id = $app->param('blog_id');
1751    if ($blog_id) {
1752        $c_data = $app->_build_category_list(
1753            blog_id => $blog_id,
1754            type    => $class->container_type,
1755        );
1756        my $i = 0;
1757        for my $row (@$c_data) {
1758            $row->{category_index} = $i++;
1759            my $spacer = $row->{category_label_spacer} || '';
1760            $spacer =~ s/\&nbsp;/\\u00A0/g;
1761            $row->{category_label_js} =
1762              $spacer . encode_js( $row->{category_label} );
1763            $cats{ $row->{category_id} } = $row;
1764        }
1765        $param->{category_loop} = $c_data;
1766    }
1767
1768    my ( $date_format, $datetime_format );
1769
1770    if ($is_power_edit) {
1771        $date_format          = "%Y.%m.%d";
1772        $datetime_format      = "%Y-%m-%d %H:%M:%S";
1773    }
1774    else {
1775        $date_format     = MT::App::CMS::LISTING_DATE_FORMAT();
1776        $datetime_format = MT::App::CMS::LISTING_DATETIME_FORMAT();
1777    }
1778
1779    my @cat_list;
1780    if ($is_power_edit) {
1781        @cat_list =
1782          sort { $cats{$a}->{category_index} <=> $cats{$b}->{category_index} }
1783          keys %cats;
1784    }
1785
1786    my @data;
1787    my %blogs;
1788    require MT::Blog;
1789    my $title_max_len   = const('DISPLAY_LENGTH_EDIT_ENTRY_TITLE');
1790    my $excerpt_max_len = const('DISPLAY_LENGTH_EDIT_ENTRY_TEXT_FROM_EXCERPT');
1791    my $text_max_len    = const('DISPLAY_LENGTH_EDIT_ENTRY_TEXT_BREAK_UP');
1792    my %blog_perms;
1793    $blog_perms{ $perms->blog_id } = $perms if $perms;
1794    while ( my $obj = $iter->() ) {
1795        my $blog_perms;
1796        if ( !$app_author->is_superuser() ) {
1797            $blog_perms = $blog_perms{ $obj->blog_id }
1798              || $app_author->blog_perm( $obj->blog_id );
1799        }
1800
1801        my $row = $obj->column_values;
1802        $row->{text} ||= '';
1803        if ( my $ts =
1804            ( $type eq 'page' ) ? $obj->modified_on : $obj->authored_on )
1805        {
1806            $row->{created_on_formatted} =
1807              format_ts( $date_format, $ts, $obj->blog, $app->user ? $app->user->preferred_language : undef );
1808            $row->{created_on_time_formatted} =
1809              format_ts( $datetime_format, $ts, $obj->blog, $app->user ? $app->user->preferred_language : undef );
1810            $row->{created_on_relative} =
1811              relative_date( $ts, time, $obj->blog );
1812        }
1813        my $author = $obj->author;
1814        $row->{author_name} =
1815          $author ? $author->name : $app->translate('(user deleted)');
1816        if ( my $cat = $obj->category ) {
1817            $row->{category_label}    = $cat->label;
1818            $row->{category_basename} = $cat->basename;
1819        }
1820        else {
1821            $row->{category_label}    = '';
1822            $row->{category_basename} = '';
1823        }
1824        $row->{file_extension} = $obj->blog ? $obj->blog->file_extension : '';
1825        $row->{title_short} = $obj->title;
1826        if ( !defined( $row->{title_short} ) || $row->{title_short} eq '' ) {
1827            my $title = remove_html( $obj->text );
1828            $row->{title_short} =
1829              substr_text( defined($title) ? $title : "", 0, $title_max_len )
1830              . '...';
1831        }
1832        else {
1833            $row->{title_short} = remove_html( $row->{title_short} );
1834            $row->{title_short} =
1835              substr_text( $row->{title_short}, 0, $title_max_len + 3 ) . '...'
1836              if length_text( $row->{title_short} ) > $title_max_len;
1837        }
1838        if ( $row->{excerpt} ) {
1839            $row->{excerpt} = remove_html( $row->{excerpt} );
1840        }
1841        if ( !$row->{excerpt} ) {
1842            my $text = remove_html( $row->{text} ) || '';
1843            $row->{excerpt} = first_n_text( $text, $excerpt_max_len );
1844            if ( length($text) > length( $row->{excerpt} ) ) {
1845                $row->{excerpt} .= ' ...';
1846            }
1847        }
1848        $row->{text} = break_up_text( $row->{text}, $text_max_len )
1849          if $row->{text};
1850        $row->{title_long} = remove_html( $obj->title );
1851        $row->{status_text} =
1852          $app->translate( MT::Entry::status_text( $obj->status ) );
1853        $row->{ "status_" . MT::Entry::status_text( $obj->status ) } = 1;
1854        $row->{has_edit_access} = $app_author->is_superuser
1855          || ( ( 'entry' eq $type )
1856            && $blog_perms
1857            && $blog_perms->can_edit_entry( $obj, $app_author ) )
1858          || ( ( 'page' eq $type )
1859            && $blog_perms
1860            && $blog_perms->can_manage_pages );
1861        if ($is_power_edit) {
1862            $row->{has_publish_access} = $app_author->is_superuser
1863              || ( ( 'entry' eq $type )
1864                && $blog_perms
1865                && $blog_perms->can_edit_entry( $obj, $app_author, 1 ) )
1866              || ( ( 'page' eq $type )
1867                && $blog_perms
1868                && $blog_perms->can_manage_pages );
1869            $row->{is_editable} = $row->{has_edit_access};
1870
1871            ## This is annoying. In order to generate and pre-select the
1872            ## category, user, and status pull down menus, we need to
1873            ## have a separate *copy* of the list of categories and
1874            ## users for every entry listed, so that each row in the list
1875            ## can "know" whether it is selected for this entry or not.
1876            my @this_c_data;
1877            my $this_category_id = $obj->category ? $obj->category->id : undef;
1878            for my $c_id (@cat_list) {
1879                push @this_c_data, { %{ $cats{$c_id} } };
1880                $this_c_data[-1]{category_is_selected} = $this_category_id
1881                  && $this_category_id == $c_id ? 1 : 0;
1882            }
1883            $row->{row_category_loop} = \@this_c_data;
1884
1885            if ( $obj->author ) {
1886                $row->{row_author_name} = $obj->author->name;
1887                $row->{row_author_id}   = $obj->author->id;
1888            } else {
1889                $row->{row_author_name} = $app->translate(
1890                    '(user deleted - ID:[_1])',
1891                    $obj->author_id
1892                );
1893                $row->{row_author_id} = $obj->author_id,
1894             }
1895        }
1896        if ( my $blog = $blogs{ $obj->blog_id } ||=
1897            MT::Blog->load( $obj->blog_id ) )
1898        {
1899            $row->{weblog_id}   = $blog->id;
1900            $row->{weblog_name} = $blog->name;
1901        }
1902        if ( $obj->status == MT::Entry::RELEASE() ) {
1903            $row->{entry_permalink} = $obj->permalink;
1904        }
1905        $row->{object} = $obj;
1906        push @data, $row;
1907    }
1908    return [] unless @data;
1909
1910    $param->{entry_table}[0] = {%$list_pref};
1911    $param->{object_loop} = $param->{entry_table}[0]{object_loop} = \@data;
1912    $app->load_list_actions( $type, \%$param )
1913      unless $is_power_edit;
1914    \@data;
1915}
1916
1917sub quickpost_js {
1918    my $app     = shift;
1919    my ($type)  = @_;
1920    my $blog_id = $app->blog->id;
1921    my $blog    = $app->model('blog')->load($blog_id)
1922        or return $app->error($app->translate('Can\'t load blog #[_1].', $blog_id));
1923    my %args    = ( '_type' => $type, blog_id => $blog_id, qp => 1 );
1924    my $uri = $app->base . $app->uri( 'mode' => 'view', args => \%args );
1925    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'))!;
1926    # Translate the phrase here to avoid ActivePerl DLL bug.
1927    $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);
1928}
1929
1930sub can_view {
1931    my ( $eh, $app, $id, $objp ) = @_;
1932    my $perms = $app->permissions;
1933    if (   !$id
1934        && !$perms->can_create_post )
1935    {
1936        return 0;
1937    }
1938    if ($id) {
1939        my $obj = $objp->force();
1940        if ( !$perms->can_edit_entry( $obj, $app->user ) ) {
1941            return 0;
1942        }
1943    }
1944    1;
1945}
1946
1947sub can_delete {
1948    my ( $eh, $app, $obj ) = @_;
1949    my $author = $app->user;
1950    return 1 if $author->is_superuser();
1951    my $perms = $app->permissions;
1952    if ( !$perms || $perms->blog_id != $obj->blog_id ) {
1953        $perms ||= $author->permissions( $obj->blog_id );
1954    }
1955    return $perms && $perms->can_edit_entry( $obj, $author );
1956}
1957
1958sub pre_save {
1959    my $eh = shift;
1960    my ( $app, $obj ) = @_;
1961
1962    # save tags
1963    my $tags = $app->param('tags');
1964    if ( defined $tags ) {
1965        my $blog = $app->blog;
1966        my $fields = $blog->smart_replace_fields;
1967        if ( $fields =~ m/tags/ig ) {
1968            $tags = MT::App::CMS::_convert_word_chars( $app, $tags );
1969        }
1970
1971        require MT::Tag;
1972        my $tag_delim = chr( $app->user->entry_prefs->{tag_delim} );
1973        my @tags = MT::Tag->split( $tag_delim, $tags );
1974        if (@tags) {
1975            $obj->set_tags(@tags);
1976        }
1977        else {
1978            $obj->remove_tags();
1979        }
1980    }
1981
1982    # update text heights if necessary
1983    if ( my $perms = $app->permissions ) {
1984        my $prefs = $perms->entry_prefs || $app->load_default_entry_prefs;
1985        my $text_height = $app->param('text_height');
1986        if ( defined $text_height ) {
1987            my ($pref_text_height) = $prefs =~ m/\bbody:(\d+)\b/;
1988            $pref_text_height ||= 0;
1989            if ( $text_height != $pref_text_height ) {
1990                if ( $prefs =~ m/\bbody\b/ ) {
1991                    $prefs =~ s/\bbody(:\d+)\b/body:$text_height/;
1992                }
1993                else {
1994                    $prefs = 'body:' . $text_height . ',' . $prefs;
1995                }
1996            }
1997        }
1998        if ( $prefs ne ( $perms->entry_prefs || '' ) ) {
1999            $perms->entry_prefs($prefs);
2000            $perms->save;
2001        }
2002    }
2003    $obj->discover_tb_from_entry();
2004    1;
2005}
2006
2007sub post_save {
2008    my $eh = shift;
2009    my ( $app, $obj ) = @_;
2010    my $sess_obj = $app->autosave_session_obj;
2011    $sess_obj->remove if $sess_obj;
2012    1;
2013}
2014
2015sub post_delete {
2016    my ( $eh, $app, $obj ) = @_;
2017
2018    my $sess_obj = $app->autosave_session_obj;
2019    $sess_obj->remove if $sess_obj;
2020
2021    $app->log(
2022        {
2023            message => $app->translate(
2024                "Entry '[_1]' (ID:[_2]) deleted by '[_3]'",
2025                $obj->title, $obj->id, $app->user->name
2026            ),
2027            level    => MT::Log::INFO(),
2028            class    => 'system',
2029            category => 'delete'
2030        }
2031    );
2032}
2033
2034sub update_entry_status {
2035    my $app = shift;
2036    my ( $new_status, @ids ) = @_;
2037    return $app->errtrans("Need a status to update entries")
2038      unless $new_status;
2039    return $app->errtrans("Need entries to update status")
2040      unless @ids;
2041    my @bad_ids;
2042    my %rebuild_these;
2043    require MT::Entry;
2044
2045    foreach my $id (@ids) {
2046        my $entry = MT::Entry->load($id)
2047          or return $app->errtrans(
2048            "One of the entries ([_1]) did not actually exist", $id );
2049        if ( $app->config('DeleteFilesAtRebuild')
2050            && ( MT::Entry::RELEASE() eq $entry->status ) )
2051        {
2052            my $archive_type =
2053              $entry->class eq 'page'
2054              ? 'Page'
2055              : 'Individual';
2056            $app->publisher->remove_entry_archive_file(
2057                Entry       => $entry,
2058                ArchiveType => $archive_type
2059            );
2060        }
2061        my $old_status = $entry->status;
2062        $entry->status($new_status);
2063        $entry->save() and $rebuild_these{$id} = 1;
2064        my $message = $app->translate(
2065            "[_1] '[_2]' (ID:[_3]) status changed from [_4] to [_5]",
2066            $entry->class_label,
2067            $entry->title,
2068            $entry->id,
2069            $app->translate( MT::Entry::status_text($old_status) ),
2070            $app->translate( MT::Entry::status_text($new_status) )
2071        );
2072        $app->log(
2073            {
2074                message  => $message,
2075                level    => MT::Log::INFO(),
2076                class    => $entry->class,
2077                category => 'edit',
2078                metadata => $entry->id
2079            }
2080        );
2081    }
2082    $app->rebuild_these( \%rebuild_these, how => MT::App::CMS::NEW_PHASE() );
2083}
2084
2085sub _finish_rebuild_ping {
2086    my $app = shift;
2087    my ( $entry, $is_new, $ping_errors ) = @_;
2088    $app->redirect(
2089        $app->uri(
2090            'mode' => 'view',
2091            args   => {
2092                '_type' => $entry->class,
2093                blog_id => $entry->blog_id,
2094                id      => $entry->id,
2095                ( $is_new ? ( saved_added => 1 ) : ( saved_changes => 1 ) ),
2096                ( $ping_errors ? ( ping_errors => 1 ) : () )
2097            }
2098        )
2099    );
2100}
2101
2102sub ping_continuation {
2103    my $app = shift;
2104    my ( $entry, $blog, %options ) = @_;
2105    my $list = $app->needs_ping(
2106        Entry     => $entry,
2107        Blog      => $blog,
2108        OldStatus => $options{OldStatus}
2109    );
2110    require MT::Entry;
2111    if ( $entry->status == MT::Entry::RELEASE() && $list ) {
2112        my @urls = map { { url => $_ } } @$list;
2113        $app->load_tmpl(
2114            'pinging.tmpl',
2115            {
2116                blog_id    => $blog->id,
2117                entry_id   => $entry->id,
2118                old_status => $options{OldStatus},
2119                is_new     => $options{IsNew},
2120                url_list   => \@urls,
2121            }
2122        );
2123    }
2124    else {
2125        _finish_rebuild_ping( $app, $entry, $options{IsNew} );
2126    }
2127}
2128
2129sub delete {
2130    my $app = shift;
2131    $app->validate_magic() or return;
2132    require MT::Blog;
2133    my $q       = $app->param;
2134    my $blog_id = $q->param('blog_id');
2135    my $blog    = MT::Blog->load($blog_id)
2136        or return $app->error($app->translate('Can\'t load blog #[_1].', $blog_id));
2137
2138    my $can_background =
2139        ( $blog->count_static_templates('Individual') == 0
2140            || MT::Util->launch_background_tasks() ) ? 1 : 0;
2141
2142    my %rebuild_recipe;
2143    for my $id ( $q->param('id') ) {
2144        my $class = $app->model("entry");
2145        my $obj   = $class->load($id);
2146        return $app->call_return unless $obj;
2147
2148        $app->run_callbacks( 'cms_delete_permission_filter.entry', $app, $obj )
2149          || return $app->error(
2150            $app->translate( "Permission denied: [_1]", $app->errstr() ) );
2151
2152        my %recipe = $app->publisher->rebuild_deleted_entry(
2153            Entry => $obj,
2154            Blog  => $blog);
2155
2156        # Remove object from database
2157        $obj->remove()
2158            or return $app->errtrans(
2159                'Removing [_1] failed: [_2]',
2160                $app->translate('entry'),
2161                $obj->errstr
2162            );
2163        $app->run_callbacks( 'cms_post_delete.entry', $app, $obj );
2164    }
2165
2166    $app->add_return_arg( saved_deleted => 1 );
2167    if ( $q->param('is_power_edit') ) {
2168        $app->add_return_arg( is_power_edit => 1 );
2169    }
2170
2171    if ( $app->config('RebuildAtDelete') ) {
2172        if ($can_background) {
2173            my $res = MT::Util::start_background_task(
2174                sub {
2175                    my $res = $app->rebuild_archives(
2176                        Blog             => $blog,
2177                        Recipe           => \%rebuild_recipe,
2178                    ) or return $app->publish_error();
2179                    $app->rebuild_indexes( Blog => $blog )
2180                        or return $app->publish_error();
2181                    $app->run_callbacks( 'rebuild', $blog );
2182                    1;
2183                }
2184            );
2185        }
2186        else {
2187            $app->rebuild_archives(
2188                Blog             => $blog,
2189                Recipe           => \%rebuild_recipe,
2190            ) or return $app->publish_error();
2191            $app->rebuild_indexes( Blog => $blog )
2192                or return $app->publish_error();
2193
2194            $app->run_callbacks( 'rebuild', $blog );
2195        }
2196
2197        $app->add_return_arg( no_rebuild => 1 );
2198        my %params = (
2199            is_full_screen  => 1,
2200            redirect_target => $app->app_path
2201              . $app->script . '?'
2202              . $app->return_args,
2203        );
2204        return $app->load_tmpl( 'rebuilding.tmpl', \%params );
2205    }
2206
2207    return $app->call_return();
2208}
2209
22101;
Note: See TracBrowser for help on using the browser.