root/branches/release-33/lib/MT/CMS/Entry.pm @ 1746

Revision 1746, 83.7 kB (checked in by auno, 20 months ago)

changed the way to show date and time error message. BugzID:65714
* suppress the auto-saved information when user get errors
* accept the number without zero padding for date and time

  • 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->count( { 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            $blog_timezone = $blog->server_offset();
143            if ( $type eq 'entry' ) {
144
145                # We only use new entry defaults on new entries.
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
168        require POSIX;
169        my @now = offset_time_list( time, $blog );
170        $param->{authored_on_date} = $q->param('authored_on_date')
171          || POSIX::strftime( "%Y-%m-%d", @now );
172        $param->{authored_on_time} = $q->param('authored_on_time')
173          || POSIX::strftime( "%H:%M:%S", @now );
174    }
175
176    ## Load categories and process into loop for category pull-down.
177    require MT::Placement;
178    my $cat_id = $param->{category_id};
179    my $depth  = 0;
180    my %places;
181
182    # set the dirty flag in js?
183    $param->{dirty} = $q->param('dirty') ? 1 : 0;
184
185    if ($id) {
186        my @places =
187          MT::Placement->load( { entry_id => $id, is_primary => 0 } );
188        %places = map { $_->category_id => 1 } @places;
189    }
190    my $cats = $q->param('category_ids');
191    if ( defined $cats ) {
192        if ( my @cats = split /,/, $cats ) {
193            $cat_id = $cats[0];
194            %places = map { $_ => 1 } @cats;
195        }
196    }
197    if ( $q->param('reedit') ) {
198        $param->{reedit} = 1;
199        if ( !$q->param('basename_manual') ) {
200            $param->{'basename'} = '';
201        }
202    }
203    if ($blog) {
204        $param->{file_extension} = $blog->file_extension || '';
205        $param->{file_extension} = '.' . $param->{file_extension}
206          if $param->{file_extension} ne '';
207    }
208    else {
209        $param->{file_extension} = 'html';
210    }
211
212    ## Now load user's preferences and customization for new/edit
213    ## entry page.
214    if ($perms) {
215        my $pref_param = $app->load_entry_prefs( $perms->entry_prefs );
216        %$param = ( %$param, %$pref_param );
217        $param->{disp_prefs_bar_colspan} = $param->{new_object} ? 1 : 2;
218
219        # Completion for tags
220        my $auth_prefs = $author->entry_prefs;
221        if ( my $delim = chr( $auth_prefs->{tag_delim} ) ) {
222            if ( $delim eq ',' ) {
223                $param->{'auth_pref_tag_delim_comma'} = 1;
224            }
225            elsif ( $delim eq ' ' ) {
226                $param->{'auth_pref_tag_delim_space'} = 1;
227            }
228            else {
229                $param->{'auth_pref_tag_delim_other'} = 1;
230            }
231            $param->{'auth_pref_tag_delim'} = $delim;
232        }
233
234        require JSON;
235        my $json = JSON->new( autoconv => 0 ); # stringifies numbers this way
236        $param->{tags_js} =
237          $json->objToJson(
238            MT::Tag->cache( blog_id => $blog_id, class => 'MT::Entry', private => 1 )
239          );
240
241        $param->{can_edit_categories} = $perms->can_edit_categories;
242    }
243
244    my $data = $app->_build_category_list(
245        blog_id => $blog_id,
246        markers => 1,
247        type    => $class->container_type,
248    );
249    my $top_cat = $cat_id;
250    my @sel_cats;
251    my $cat_tree = [];
252    if ( $type eq 'page' ) {
253        push @$cat_tree,
254          {
255            id    => -1,
256            label => '/',
257            basename => '/',
258            path  => [],
259          };
260        $top_cat ||= -1;
261    }
262    foreach (@$data) {
263        next unless exists $_->{category_id};
264        if ( $type eq 'page' ) {
265            $_->{category_path_ids} ||= [];
266            unshift @{ $_->{category_path_ids} }, -1;
267        }
268        push @$cat_tree,
269          {
270            id => $_->{category_id},
271            label => $_->{category_label} . ( $type eq 'page' ? '/' : '' ),
272            basename => $_->{category_basename} . ( $type eq 'page' ? '/' : '' ),
273            path => $_->{category_path_ids} || [],
274          };
275        push @sel_cats, $_->{category_id}
276          if $places{ $_->{category_id} }
277          && $_->{category_id} != $cat_id;
278    }
279    $param->{category_tree} = $cat_tree;
280    unshift @sel_cats, $top_cat if defined $top_cat && $top_cat ne "";
281    $param->{selected_category_loop}   = \@sel_cats;
282    $param->{have_multiple_categories} = scalar @$data > 1;
283
284    $param->{basename_limit} = ( $blog ? $blog->basename_limit : 0 ) || 30;
285
286    if ( $q->param('tags') ) {
287        $param->{tags} = $q->param('tags');
288    }
289    else {
290        if ($obj) {
291            my $tag_delim = chr( $app->user->entry_prefs->{tag_delim} );
292            require MT::Tag;
293            my $tags = MT::Tag->join( $tag_delim, $obj->tags );
294            $param->{tags} = $tags;
295        }
296    }
297
298    ## Load text filters if user displays them
299    my %entry_filters;
300    if ( defined( my $filter = $q->param('convert_breaks') ) ) {
301        $entry_filters{$filter} = 1;
302    }
303    elsif ($obj) {
304        %entry_filters = map { $_ => 1 } @{ $obj->text_filters };
305    }
306    elsif ($blog) {
307        my $cb = $author->text_format || $blog->convert_paras;
308        $cb = '__default__' if $cb eq '1';
309        $entry_filters{$cb} = 1;
310        $param->{convert_breaks} = $cb;
311    }
312    my $filters = MT->all_text_filters;
313    $param->{text_filters} = [];
314    for my $filter ( keys %$filters ) {
315        push @{ $param->{text_filters} },
316          {
317            filter_key      => $filter,
318            filter_label    => $filters->{$filter}{label},
319            filter_selected => $entry_filters{$filter},
320            filter_docs     => $filters->{$filter}{docs},
321          };
322    }
323    $param->{text_filters} =
324      [ sort { $a->{filter_key} cmp $b->{filter_key} }
325          @{ $param->{text_filters} } ];
326    unshift @{ $param->{text_filters} },
327      {
328        filter_key      => '0',
329        filter_label    => $app->translate('None'),
330        filter_selected => ( !keys %entry_filters ),
331      };
332
333    if ($blog) {
334        if ( !defined $param->{convert_breaks} ) {
335            my $cb = $blog->convert_paras;
336            $cb = '__default__' if $cb eq '1';
337            $param->{convert_breaks} = $cb;
338        }
339        my $ext = ( $blog->file_extension || '' );
340        $ext = '.' . $ext if $ext ne '';
341        $param->{blog_file_extension} = $ext;
342    }
343
344    my $rte;
345    if ($param->{convert_breaks} eq 'richtext') {
346        ## Rich Text editor
347        $rte = lc($app->config('RichTextEditor'));
348    }
349    else {
350        $rte = 'archetype';
351    }
352    my $editors = $app->registry("richtext_editors");
353    my $edit_reg = $editors->{$rte} || $editors->{archetype};
354    my $rich_editor_tmpl;
355    if ($rich_editor_tmpl = $edit_reg->{plugin}->load_tmpl($edit_reg->{template})) {
356        $param->{rich_editor} = $rte;
357        $param->{rich_editor_tmpl} = $rich_editor_tmpl;
358    }
359
360    $param->{object_type}  = $type;
361    $param->{quickpost_js} = MT::CMS::Entry::quickpost_js($app, $type);
362    if ( 'page' eq $type ) {
363        $param->{search_label} = $app->translate('pages');
364        $param->{output}       = 'edit_entry.tmpl';
365        $param->{screen_class} = 'edit-page edit-entry';
366    }
367    $param->{sitepath_configured} = $blog && $blog->site_path ? 1 : 0;
368    1;
369}
370
371sub list {
372    my $app = shift;
373    my ($param) = @_;
374    $param ||= {};
375
376    require MT::Entry;
377    my $type = $param->{type} || MT::Entry->class_type;
378    my $pkg = $app->model($type) or return "Invalid request.";
379
380    my $q     = $app->param;
381    my $perms = $app->permissions;
382    if ( $type eq 'page' ) {
383        if ( $perms
384            && ( !$perms->can_manage_pages ) )
385        {
386            return $app->errtrans("Permission denied.");
387        }
388    }
389    else {
390        if (
391            $perms
392            && (   !$perms->can_edit_all_posts
393                && !$perms->can_create_post
394                && !$perms->can_publish_post )
395          )
396        {
397            return $app->errtrans("Permission denied.");
398        }
399    }
400
401    my $list_pref = $app->list_pref($type);
402    my %param     = %$list_pref;
403    my $blog_id   = $q->param('blog_id');
404    my %terms;
405    $terms{blog_id} = $blog_id if $blog_id;
406    $terms{class} = $type;
407    my $limit = $list_pref->{rows};
408    my $offset = $app->param('offset') || 0;
409
410    if ( !$blog_id && !$app->user->is_superuser ) {
411        require MT::Permission;
412        $terms{blog_id} = [
413            map { $_->blog_id }
414              grep { $_->can_create_post || $_->can_edit_all_posts }
415              MT::Permission->load( { author_id => $app->user->id } )
416        ];
417    }
418
419    my %arg;
420    my $filter_key = $q->param('filter_key') || '';
421    my $filter_col = $q->param('filter')     || '';
422    my $filter_val = $q->param('filter_val');
423
424    # check blog_id for deciding to apply category filter or not
425    my ( $filter_name, $filter_value );    # human-readable versions
426    if ( !exists( $terms{$filter_col} ) ) {
427        if ( $filter_col eq 'category_id' ) {
428            $filter_name = $app->translate('Category');
429            require MT::Category;
430            my $cat = MT::Category->load($filter_val);
431            return $app->errtrans( "Load failed: [_1]", MT::Category->errstr )
432              unless $cat;
433            if ( $cat->blog_id != $blog_id ) {
434                $filter_key = '';
435                $filter_col = '';
436                $filter_val = '';
437            }
438            $filter_value = $cat->label;
439        }
440        elsif ( $filter_col eq 'asset_id' ) {
441            $filter_name = $app->translate('Asset');
442            my $asset_class = MT->model('asset');
443            my $asset = $asset_class->load($filter_val);
444            return $app->errtrans( "Load failed: [_1]", $asset_class->errstr )
445              unless $asset;
446            if ($asset->blog_id != $blog_id) {
447                $filter_key = '';
448                $filter_col = '';
449                $filter_val = '';
450            }
451            $filter_value = $param{asset_label} = $asset->label;
452        }
453    }
454    if ( $filter_col && $filter_val ) {
455        if ( 'power_edit' eq $filter_col ) {
456            $filter_col = 'id';
457            unless ( 'ARRAY' eq ref($filter_val) ) {
458                my @values = $app->param('filter_val');
459                $filter_val = \@values;
460            }
461        }
462        if ( !exists( $terms{$filter_col} ) ) {
463            if ( $filter_col eq 'category_id' ) {
464                $arg{'join'} = MT::Placement->join_on(
465                    'entry_id',
466                    { category_id => $filter_val },
467                    { unique      => 1 }
468                );
469            }
470            elsif ( $filter_col eq 'asset_id' ) {
471                $arg{'join'} = MT->model('objectasset')->join_on(
472                    'object_id',
473                    { object_ds => $type,
474                      asset_id  => $filter_val },
475                    { unique    => 1 }
476                );
477            }
478            elsif (( $filter_col eq 'normalizedtag' )
479                || ( $filter_col eq 'exacttag' ) )
480            {
481                my $normalize = ( $filter_col eq 'normalizedtag' );
482                require MT::Tag;
483                require MT::ObjectTag;
484                my $tag_delim   = chr( $app->user->entry_prefs->{tag_delim} );
485                my @filter_vals = MT::Tag->split( $tag_delim, $filter_val );
486                my @filter_tags = @filter_vals;
487                if ($normalize) {
488                    push @filter_tags, MT::Tag->normalize($_)
489                      foreach @filter_vals;
490                }
491                my @tags = MT::Tag->load( { name => [@filter_tags] },
492                    { binary => { name => 1 } } );
493                my @tag_ids;
494                foreach (@tags) {
495                    push @tag_ids, $_->id;
496                    if ($normalize) {
497                        my @more = MT::Tag->load(
498                            { n8d_id => $_->n8d_id ? $_->n8d_id : $_->id } );
499                        push @tag_ids, $_->id foreach @more;
500                    }
501                }
502                @tag_ids = (0) unless @tags;
503                $arg{'join'} = MT::ObjectTag->join_on(
504                    'object_id',
505                    {
506                        tag_id            => \@tag_ids,
507                        object_datasource => $pkg->datasource
508                    },
509                    { unique => 1 }
510                );
511            }
512            else {
513                $terms{$filter_col} = $filter_val;
514            }
515            $param{filter_args} = "&filter=" . encode_url($filter_col) . "&filter_val=" . encode_url($filter_val);
516
517            if (   ( $filter_col eq 'normalizedtag' )
518                || ( $filter_col eq 'exacttag' ) )
519            {
520                $filter_name  = $app->translate('Tag');
521                $filter_value = $filter_val;
522            }
523            elsif ( $filter_col eq 'author_id' ) {
524                $filter_name = $app->translate('User');
525                my $author = MT::Author->load($filter_val);
526                return $app->errtrans( "Load failed: [_1]", MT::Author->errstr )
527                  unless $author;
528                $filter_value = $author->name;
529            }
530            elsif ( $filter_col eq 'status' ) {
531                $filter_name = $app->translate('Entry Status');
532                $filter_value =
533                  $app->translate( MT::Entry::status_text($filter_val) );
534            }
535            if ( $filter_name && $filter_value ) {
536                $param{filter}                        = $filter_col;
537                $param{ 'filter_col_' . $filter_col } = 1;
538                $param{filter_val}                    = $filter_val;
539            }
540        }
541        $param{filter_unpub} = $filter_col eq 'status';
542    }
543    elsif ($filter_key) {
544        my $filters = $app->registry("list_filters", "entry") || {};
545        if ( my $filter = $filters->{$filter_key} ) {
546            if ( my $code = $filter->{code}
547                || $app->handler_to_coderef( $filter->{handler} ) )
548            {
549                $param{filter_key}   = $filter_key;
550                $param{filter_label} = $filter->{label};
551                $code->( \%terms, \%arg );
552            }
553        }
554    }
555    require MT::Category;
556    require MT::Placement;
557
558    my $total = $pkg->count( \%terms, \%arg ) || 0;
559    $arg{'sort'} = $type eq 'page' ? 'modified_on' : 'authored_on';
560    $arg{direction} = 'descend';
561    $arg{limit}     = $limit + 1;
562    if ( $total && $offset > $total - 1 ) {
563        $arg{offset} = $offset = $total - $limit;
564    }
565    elsif ( $offset && ( ( $offset < 0 ) || ( $total - $offset < $limit ) ) ) {
566        $arg{offset} = $offset = $total - $offset;
567    }
568    else {
569        $arg{offset} = $offset if $offset;
570    }
571
572    my $iter = $pkg->load_iter( \%terms, \%arg );
573
574    my $is_power_edit = $q->param('is_power_edit');
575    if ($is_power_edit) {
576        $param{has_expanded_mode} = 0;
577        delete $param{view_expanded};
578    }
579    else {
580        $param{has_expanded_mode} = 1;
581    }
582    my $data = build_entry_table( $app,
583        iter          => $iter,
584        is_power_edit => $is_power_edit,
585        param         => \%param,
586        type          => $type
587    );
588    delete $_->{object} foreach @$data;
589    delete $param{entry_table} unless @$data;
590
591    ## We tried to load $limit + 1 entries above; if we actually got
592    ## $limit + 1 back, we know we have another page of entries.
593    my $have_next_entry = @$data > $limit;
594    pop @$data while @$data > $limit;
595    if ($offset) {
596        $param{prev_offset}     = 1;
597        $param{prev_offset_val} = $offset - $limit;
598        $param{prev_offset_val} = 0 if $param{prev_offset_val} < 0;
599    }
600    if ($have_next_entry) {
601        $param{next_offset}     = 1;
602        $param{next_offset_val} = $offset + $limit;
603    }
604
605    $iter = MT::Author->load_iter(
606        { type => MT::Author::AUTHOR() },
607        {
608            'join' => $pkg->join_on(
609                'author_id',
610                { $blog_id ? ( blog_id => $blog_id ) : () },
611                {
612                    'unique'  => 1,
613                    'sort'    => 'authored_on',
614                    direction => 'descend'
615                }
616            ),
617            limit => 51,
618        }
619    );
620    my %seen;
621    my @authors;
622    while ( my $au = $iter->() ) {
623        next if $seen{ $au->id };
624        $seen{ $au->id } = 1;
625        my $row = {
626            author_name => $au->name,
627            author_id   => $au->id
628        };
629        push @authors, $row;
630        if ( @authors == 50 ) {
631            $iter->('finish');
632            last;
633        }
634    }
635    $param{entry_author_loop} = \@authors;
636
637    # $iter = $app->model('asset')->load_iter(
638    #     { class => '*', blog_id => $blog_id },
639    #     {
640    #         'join' => MT->model('objectasset')->join_on(
641    #             'asset_id',
642    #             {},
643    #             { unique => 1 }
644    #         ),
645    #         'sort'    => 'created_on',
646    #         direction => 'descend',
647    #     }
648    # );
649    # %seen = ();
650    # my @assets;
651    # while ( my $asset = $iter->() ) {
652    #     next if $seen{ $asset->id };
653    #     $seen{ $asset->id } = 1;
654    #     my $row = {
655    #         asset_label => $asset->label,
656    #         asset_id    => $asset->id,
657    #     };
658    #     push @assets, $row;
659    #     if ( @assets == 50 ) {
660    #         $iter->('finish');
661    #         last;
662    #     }
663    # }
664    # if ($filter_col eq 'asset_id' && !$seen{$filter_val}) {
665    #     push @assets, {
666    #         asset_label => $param{asset_label},
667    #         asset_id    => $filter_val,
668    #     };
669    # }
670    # $param{entry_asset_loop} = \@assets;
671
672    $param{page_actions}        = $app->page_actions( $app->mode );
673    $param{list_filters}        = $app->list_filters('entry');
674    $param{can_power_edit}      = $blog_id && !$is_power_edit;
675    $param{can_republish}       = $blog_id ? $perms->can_rebuild : 1;
676    $param{is_power_edit}       = $is_power_edit;
677    $param{saved_deleted}       = $q->param('saved_deleted');
678    $param{no_rebuild}          = $q->param('no_rebuild');
679    $param{saved}               = $q->param('saved');
680    $param{limit}               = $limit;
681    $param{offset}              = $offset;
682    $param{object_type}         = $type;
683    $param{object_label}        = $pkg->class_label;
684    $param{object_label_plural} = $param{search_label} =
685      $pkg->class_label_plural;
686    $param{list_start}  = $offset + 1;
687    $param{list_end}    = $offset + scalar @$data;
688    $param{list_total}  = $total;
689    $param{next_max}    = $param{list_total} - $limit;
690    $param{next_max}    = 0 if ( $param{next_max} || 0 ) < $offset + 1;
691    $param{nav_entries} = 1;
692    $param{feed_label}  = $app->translate( "[_1] Feed", $pkg->class_label );
693    $param{feed_url} =
694      $app->make_feed_link( $type, $blog_id ? { blog_id => $blog_id } : undef );
695    $app->add_breadcrumb( $pkg->class_label_plural );
696    $param{listing_screen} = 1;
697
698    unless ($blog_id) {
699        $param{system_overview_nav} = 1;
700    }
701    $param{container_label} = $pkg->container_label;
702    unless ( $param{screen_class} ) {
703        $param{screen_class} = "list-$type";
704        $param{screen_class} .= " list-entry"
705          if $param{object_type} eq "page";  # to piggyback on list-entry styles
706    }
707    $param{mode}            = $app->mode;
708    if ( my $blog = MT::Blog->load($blog_id) ) {
709        $param{sitepath_unconfigured} = $blog->site_path ? 0 : 1;
710    }
711
712    $param->{return_args} ||= $app->make_return_args;
713    my @return_args = grep { $_ !~ /offset=\d/ } split /&/, $param->{return_args};
714    $param{return_args} = join '&', @return_args;
715    $param{return_args} .= "&offset=$offset" if $offset;
716    $param{screen_id} = "list-entry";
717    $param{screen_id} = "list-page"
718      if $param{object_type} eq "page";
719    if ( $param{is_power_edit} ) {
720        $param{screen_id} = "batch-edit-entry";
721        $param{screen_id} = "batch-edit-page"
722          if $param{object_type} eq "page";
723        $param{screen_class} .= " batch-edit";
724    }
725    $app->load_tmpl( "list_entry.tmpl", \%param );
726}
727
728sub preview {
729    my $app         = shift;
730    my $q           = $app->param;
731    my $type        = $q->param('_type') || 'entry';
732    my $entry_class = $app->model($type);
733    my $blog_id     = $q->param('blog_id');
734    my $blog        = $app->blog;
735    my $id          = $q->param('id');
736    my $entry;
737    my $user_id = $app->user->id;
738
739    if ($id) {
740        $entry = $entry_class->load( { id => $id, blog_id => $blog_id } )
741            or return $app->errtrans( "Invalid request." );
742        $user_id = $entry->author_id;
743    }
744    else {
745        $entry = $entry_class->new;
746        $entry->author_id($user_id);
747        $entry->id(-1); # fake out things like MT::Taggable::__load_tags
748        $entry->blog_id($blog_id);
749    }
750    my $cat;
751    my $names = $entry->column_names;
752
753    my %values = map { $_ => scalar $app->param($_) } @$names;
754    delete $values{'id'} unless $q->param('id');
755    ## Strip linefeed characters.
756    for my $col (qw( text excerpt text_more keywords )) {
757        $values{$col} =~ tr/\r//d if $values{$col};
758    }
759    $values{allow_comments} = 0
760      if !defined( $values{allow_comments} )
761      || $q->param('allow_comments') eq '';
762    $values{allow_pings} = 0
763      if !defined( $values{allow_pings} )
764      || $q->param('allow_pings') eq '';
765    $entry->set_values( \%values );
766
767    my $cat_ids = $q->param('category_ids');
768    if ($cat_ids) {
769        my @cats = split /,/, $cat_ids;
770        if (@cats) {
771            my $primary_cat = $cats[0];
772            $cat =
773              MT::Category->load( { id => $primary_cat, blog_id => $blog_id } );
774            my @categories = MT::Category->load( { id => \@cats, blog_id => $blog_id });
775            $entry->cache_property('category', undef, $cat);
776            $entry->cache_property('categories', undef, \@categories);
777        }
778    } else {
779        $entry->cache_property('category', undef, undef);
780        $entry->cache_property('categories', undef, []);
781    }
782    my $tag_delim = chr( $app->user->entry_prefs->{tag_delim} );
783    my @tag_names = MT::Tag->split( $tag_delim, $q->param('tags') );
784    if (@tag_names) {
785        my @tags;
786        foreach my $tag_name (@tag_names) {
787            my $tag = MT::Tag->new;
788            $tag->name($tag_name);
789            push @tags, $tag;
790        }
791        $entry->{__tags} = \@tag_names;
792        $entry->{__tag_objects} = \@tags;
793    }
794
795    my $date = $q->param('authored_on_date');
796    my $time = $q->param('authored_on_time');
797    my $ts   = $date . $time;
798    $ts =~ s/\D//g;
799    $entry->authored_on($ts);
800
801    my $preview_basename = $app->preview_object_basename;
802    $entry->basename($preview_basename);
803
804    require MT::TemplateMap;
805    require MT::Template;
806    my $tmpl_map = MT::TemplateMap->load(
807        {
808            archive_type => ( $type eq 'page' ? 'Page' : 'Individual' ),
809            is_preferred => 1,
810            blog_id => $blog_id,
811        }
812    );
813
814    my $tmpl;
815    my $fullscreen;
816    my $archive_file;
817    my $orig_file;
818    my $file_ext;
819    if ($tmpl_map) {
820        $tmpl         = MT::Template->load( $tmpl_map->template_id );
821        $file_ext = $blog->file_extension || '';
822        $archive_file = $entry->archive_file;
823
824        my $blog_path = $type eq 'page' ?
825            $blog->site_path :
826            ($blog->archive_path || $blog->site_path);
827        $archive_file = File::Spec->catfile( $blog_path, $archive_file );
828        require File::Basename;
829        my $path;
830        ( $orig_file, $path ) = File::Basename::fileparse( $archive_file );
831        $file_ext = '.' . $file_ext if $file_ext ne '';
832        $archive_file = File::Spec->catfile( $path, $preview_basename . $file_ext );
833    }
834    else {
835        $tmpl       = $app->load_tmpl('preview_entry_content.tmpl');
836        $fullscreen = 1;
837    }
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
1083    my $archive_type;
1084
1085    my ( $obj, $orig_obj, $orig_file );
1086    if ($id) {
1087        $obj = $class->load($id)
1088          || return $app->error(
1089            $app->translate( "No such [_1].", $class->class_label ) );
1090        return $app->error( $app->translate("Invalid parameter") )
1091          unless $obj->blog_id == $blog_id;
1092        if ( $type eq 'entry' ) {
1093            return $app->error( $app->translate("Permission denied.") )
1094              unless $perms->can_edit_entry( $obj, $author );
1095            return $app->error( $app->translate("Permission denied.") )
1096              if ( $obj->status ne $app->param('status') )
1097              && !( $perms->can_edit_entry( $obj, $author, 1 ) );
1098            $archive_type = 'Individual';
1099        }
1100        elsif ( $type eq 'page' ) {
1101            $archive_type = 'Page';
1102        }
1103        $orig_obj = $obj->clone;
1104        $orig_file = archive_file_for( $orig_obj, $blog, $archive_type );
1105    }
1106    else {
1107        $obj = $class->new;
1108    }
1109    my $status_old = $id ? $obj->status : 0;
1110    my $names = $obj->column_names;
1111
1112    ## Get rid of category_id param, because we don't want to just set it
1113    ## in the Entry record; save it for later when we will set the Placement.
1114    my ( $cat_id, @add_cat ) = split /\s*,\s*/,
1115      ( $app->param('category_ids') || '' );
1116    $app->delete_param('category_id');
1117    if ($id) {
1118        ## Delete the author_id param (if present), because we don't want to
1119        ## change the existing author.
1120        $app->delete_param('author_id');
1121    }
1122
1123    my %values = map { $_ => scalar $app->param($_) } @$names;
1124    delete $values{'id'} unless $app->param('id');
1125    ## Strip linefeed characters.
1126    for my $col (qw( text excerpt text_more keywords )) {
1127        $values{$col} =~ tr/\r//d if $values{$col};
1128    }
1129    $values{allow_comments} = 0
1130      if !defined( $values{allow_comments} )
1131      || $app->param('allow_comments') eq '';
1132    delete $values{week_number}
1133      if ( $app->param('week_number') || '' ) eq '';
1134    delete $values{basename}
1135      unless $perms->can_publish_post || $perms->can_edit_all_posts;
1136    $obj->set_values( \%values );
1137    $obj->allow_pings(0)
1138      if !defined $app->param('allow_pings')
1139      || $app->param('allow_pings') eq '';
1140    my $ao_d = $app->param('authored_on_date');
1141    my $ao_t = $app->param('authored_on_time');
1142
1143    if ( !$id ) {
1144
1145        #  basename check for this new entry...
1146        if (   ( my $basename = $app->param('basename') )
1147            && !$app->param('basename_manual')
1148            && $type eq 'entry' )
1149        {
1150            my $cnt =
1151              $class->count( { blog_id => $blog_id, basename => $basename } );
1152            if ($cnt) {
1153                $obj->basename( MT::Util::make_unique_basename($obj) );
1154            }
1155        }
1156    }
1157
1158    if ( $type eq 'page' ) {
1159
1160        # -1 is a special id for identifying the 'root' folder
1161        $cat_id = 0 if $cat_id == -1;
1162        my $dup_it = $class->load_iter(
1163            {
1164                blog_id  => $blog_id,
1165                basename => $obj->basename,
1166                class    => 'page',
1167                ( $id ? ( id => $id ) : () )
1168            },
1169            { ( $id ? ( not => { id => 1 } ) : () ) }
1170        );
1171        while ( my $p = $dup_it->() ) {
1172            my $p_folder = $p->folder;
1173            my $dup_folder_path =
1174              defined $p_folder ? $p_folder->publish_path() : '';
1175            my $folder = MT::Folder->load($cat_id) if $cat_id;
1176            my $folder_path = defined $folder ? $folder->publish_path() : '';
1177            return $app->error(
1178                $app->translate(
1179"Same Basename has already been used. You should use an unique basename."
1180                )
1181            ) if ( $dup_folder_path eq $folder_path );
1182        }
1183
1184    }
1185
1186    if ( $type eq 'entry' ) {
1187        $obj->status( MT::Entry::HOLD() )
1188          if !$id
1189          && !$perms->can_publish_post
1190          && !$perms->can_edit_all_posts;
1191    }
1192
1193    my $filter_result = $app->run_callbacks( 'cms_save_filter.' . $type, $app );
1194
1195    if ( !$filter_result ) {
1196        my %param = ();
1197        $param{error}       = $app->errstr;
1198        $param{return_args} = $app->param('return_args');
1199        return $app->forward( "view", \%param );
1200    }
1201
1202    # check to make sure blog has site url and path defined.
1203    # otherwise, we can't publish a released entry
1204    if ( ( $obj->status || 0 ) != MT::Entry::HOLD() ) {
1205        if ( !$blog->site_path || !$blog->site_url ) {
1206            return $app->error(
1207                $app->translate(
1208"Your blog has not been configured with a site path and URL. You cannot publish entries until these are defined."
1209                )
1210            );
1211        }
1212    }
1213
1214    my ( $previous_old, $next_old );
1215    if (   ( $perms->can_publish_post || $perms->can_edit_all_posts )
1216        && ($ao_d) )
1217    {
1218        my %param = ();
1219        my $ao = $ao_d . ' ' . $ao_t;
1220        unless (
1221            $ao =~ m!^(\d{4})-(\d{1,2})-(\d{1,2})\s+(\d{1,2}):(\d{1,2})(?::(\d{1,2}))?$! )
1222        {
1223            $param{error} = $app->translate(
1224"Invalid date '[_1]'; authored on dates must be in the format YYYY-MM-DD HH:MM:SS.",
1225$ao
1226            );
1227        }
1228        my $s = $6 || 0;
1229            $param{error} = $app->translate(
1230                "Invalid date '[_1]'; authored on dates should be real dates.",
1231                $ao
1232          )
1233          if (
1234               $s > 59
1235            || $s < 0
1236            || $5 > 59
1237            || $5 < 0
1238            || $4 > 23
1239            || $4 < 0
1240            || $2 > 12
1241            || $2 < 1
1242            || $3 < 1
1243            || ( MT::Util::days_in( $2, $1 ) < $3
1244                && !MT::Util::leap_day( $0, $1, $2 ) )
1245          );
1246        $param{return_args} = $app->param('return_args');
1247        return $app->forward( "view", \%param ) if $param{error};
1248        if ($obj->authored_on) {
1249            $previous_old = $obj->previous(1);
1250            $next_old     = $obj->next(1);
1251        }
1252        my $ts = sprintf "%04d%02d%02d%02d%02d%02d", $1, $2, $3, $4, $5, $s;
1253        $obj->authored_on($ts);
1254    }
1255    my $is_new = $obj->id ? 0 : 1;
1256
1257    $app->_translate_naughty_words($obj);
1258
1259    $obj->modified_by( $author->id ) unless $is_new;
1260
1261    $app->run_callbacks( 'cms_pre_save.' . $type, $app, $obj, $orig_obj )
1262      || return $app->error(
1263        $app->translate(
1264            "Saving [_1] failed: [_2]",
1265            $class->class_label, $app->errstr
1266        )
1267      );
1268
1269    $obj->save
1270      or return $app->error(
1271        $app->translate(
1272            "Saving [_1] failed: [_2]",
1273            $class->class_label, $obj->errstr
1274        )
1275      );
1276
1277    my $message;
1278    if ($is_new) {
1279        $message =
1280          $app->translate( "[_1] '[_2]' (ID:[_3]) added by user '[_4]'",
1281            $class->class_label, $obj->title, $obj->id, $author->name );
1282    }
1283    elsif ( $orig_obj->status ne $obj->status ) {
1284        $message = $app->translate(
1285"[_1] '[_2]' (ID:[_3]) edited and its status changed from [_4] to [_5] by user '[_6]'",
1286            $class->class_label,
1287            $obj->title,
1288            $obj->id,
1289            $app->translate( MT::Entry::status_text( $orig_obj->status ) ),
1290            $app->translate( MT::Entry::status_text( $obj->status ) ),
1291            $author->name
1292        );
1293
1294    }
1295    else {
1296        $message =
1297          $app->translate( "[_1] '[_2]' (ID:[_3]) edited by user '[_4]'",
1298            $class->class_label, $obj->title, $obj->id, $author->name );
1299    }
1300    require MT::Log;
1301    $app->log(
1302        {
1303            message => $message,
1304            level   => MT::Log::INFO(),
1305            class   => $type,
1306            $is_new ? ( category => 'new' ) : ( category => 'edit' ),
1307            metadata => $obj->id
1308        }
1309    );
1310
1311    my $error_string = MT::callback_errstr();
1312
1313    ## Now that the object is saved, we can be certain that it has an
1314    ## ID. So we can now add/update/remove the primary placement.
1315    require MT::Placement;
1316    my $place =
1317      MT::Placement->load( { entry_id => $obj->id, is_primary => 1 } );
1318    if ($cat_id) {
1319        unless ($place) {
1320            $place = MT::Placement->new;
1321            $place->entry_id( $obj->id );
1322            $place->blog_id( $obj->blog_id );
1323            $place->is_primary(1);
1324        }
1325        $place->category_id($cat_id);
1326        $place->save;
1327    }
1328    else {
1329        if ( $place ) {
1330            $place->remove;
1331        }
1332    }
1333
1334    my $placements_updated;
1335
1336    # save secondary placements...
1337    my @place = MT::Placement->load(
1338        {
1339            entry_id   => $obj->id,
1340            is_primary => 0
1341        }
1342    );
1343    for my $place (@place) {
1344        $place->remove;
1345        $placements_updated = 1;
1346    }
1347    for my $cat_id (@add_cat) {
1348        my $cat = $cat_class->load($cat_id);
1349
1350        # blog_id sanity check
1351        next if $cat->blog_id != $obj->blog_id;
1352
1353        my $place = MT::Placement->new;
1354        $place->entry_id( $obj->id );
1355        $place->blog_id( $obj->blog_id );
1356        $place->is_primary(0);
1357        $place->category_id($cat_id);
1358        $place->save
1359          or return $app->error(
1360            $app->translate( "Saving placement failed: [_1]", $place->errstr )
1361          );
1362        $placements_updated = 1;
1363    }
1364
1365    $app->run_callbacks( 'cms_post_save.' . $type, $app, $obj, $orig_obj );
1366
1367    ## If the saved status is RELEASE, or if the *previous* status was
1368    ## RELEASE, then rebuild entry archives, indexes, and send the
1369    ## XML-RPC ping(s). Otherwise the status was and is HOLD, and we
1370    ## don't have to do anything.
1371    if ( ( $obj->status || 0 ) == MT::Entry::RELEASE()
1372        || $status_old eq MT::Entry::RELEASE() )
1373    {
1374        if ( $app->config('DeleteFilesAtRebuild') && $orig_obj ) {
1375            my $file = archive_file_for( $obj, $blog, $archive_type );
1376            if ( $file ne $orig_file || $obj->status != MT::Entry::RELEASE() ) {
1377                $app->publisher->remove_entry_archive_file(
1378                    Entry       => $orig_obj,
1379                    ArchiveType => $archive_type
1380                );
1381            }
1382        }
1383
1384        # If there are no static pages, just rebuild indexes.
1385        if ( $blog->count_static_templates($archive_type) == 0
1386            || MT::Util->launch_background_tasks() )
1387        {
1388            my $res = MT::Util::start_background_task(
1389                sub {
1390                    $app->rebuild_entry(
1391                        Entry             => $obj,
1392                        BuildDependencies => 1,
1393                        OldEntry          => $orig_obj,
1394                        OldPrevious       => ($previous_old)
1395                        ? $previous_old->id
1396                        : undef,
1397                        OldNext => ($next_old) ? $next_old->id : undef
1398                    ) or return $app->publish_error();
1399                    $app->run_callbacks( 'rebuild', $blog );
1400                    1;
1401                }
1402            );
1403            return unless $res;
1404            return ping_continuation($app,
1405                $obj, $blog,
1406                OldStatus => $status_old,
1407                IsNew     => $is_new,
1408            );
1409        }
1410        else {
1411            return $app->redirect(
1412                $app->uri(
1413                    'mode' => 'start_rebuild',
1414                    args   => {
1415                        blog_id    => $obj->blog_id,
1416                        'next'     => 0,
1417                        type       => 'entry-' . $obj->id,
1418                        entry_id   => $obj->id,
1419                        is_new     => $is_new,
1420                        old_status => $status_old,
1421                        (
1422                            $previous_old
1423                            ? ( old_previous => $previous_old->id )
1424                            : ()
1425                        ),
1426                        ( $next_old ? ( old_next => $next_old->id ) : () )
1427                    }
1428                )
1429            );
1430        }
1431    }
1432    _finish_rebuild_ping( $app, $obj, !$id );
1433}
1434
1435sub save_entries {
1436    my $app   = shift;
1437    my $perms = $app->permissions;
1438    my $type  = $app->param('_type');
1439    return $app->errtrans("Permission denied.")
1440      unless $perms
1441      && (
1442        $type eq 'page'
1443        ? ( $perms->can_manage_pages )
1444        : (      $perms->can_publish_post
1445              || $perms->can_create_post
1446              || $perms->can_edit_all_posts )
1447      );
1448
1449    $app->validate_magic() or return;
1450
1451    my $q = $app->param;
1452    my @p = $q->param;
1453    require MT::Entry;
1454    require MT::Placement;
1455    require MT::Log;
1456    my $blog_id        = $q->param('blog_id');
1457    my $this_author    = $app->user;
1458    my $this_author_id = $this_author->id;
1459    for my $p (@p) {
1460        next unless $p =~ /^category_id_(\d+)/;
1461        my $id    = $1;
1462        my $entry = MT::Entry->load($id);
1463        return $app->error( $app->translate("Permission denied.") )
1464            unless $perms
1465              && (
1466                $type eq 'page'
1467                ? ( $perms->can_manage_pages )
1468                : (      $perms->can_publish_post
1469                      || $perms->can_create_post
1470                      || $perms->can_edit_all_posts )
1471              );
1472        my $orig_obj = $entry->clone;
1473        if ( $perms->can_edit_entry( $entry, $this_author ) ) {
1474            my $author_id = $q->param( 'author_id_' . $id );
1475            $entry->author_id( $author_id ? $author_id : 0 );
1476            $entry->title( scalar $q->param( 'title_' . $id ) );
1477        }
1478        if ( $perms->can_edit_entry( $entry, $this_author, 1 ) )
1479        {    ## can he/she change status?
1480            $entry->status( scalar $q->param( 'status_' . $id ) );
1481            my $co = $q->param( 'created_on_' . $id );
1482            unless ( $co =~
1483                m!(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2})(?::(\d{2}))?! )
1484            {
1485                return $app->error(
1486                    $app->translate(
1487"Invalid date '[_1]'; authored on dates must be in the format YYYY-MM-DD HH:MM:SS.",
1488                        $co
1489                    )
1490                );
1491            }
1492            my $s = $6 || 0;
1493
1494            # Emit an error message if the date is bogus.
1495            return $app->error(
1496                $app->translate(
1497"Invalid date '[_1]'; authored on dates should be real dates.",
1498                    $co
1499                )
1500              )
1501              if $s > 59
1502              || $s < 0
1503              || $5 > 59
1504              || $5 < 0
1505              || $4 > 23
1506              || $4 < 0
1507              || $2 > 12
1508              || $2 < 1
1509              || $3 < 1
1510              || ( MT::Util::days_in( $2, $1 ) < $3
1511                && !MT::Util::leap_day( $0, $1, $2 ) );
1512
1513            # FIXME: Should be assigning the publish_date field here
1514            my $ts = sprintf "%04d%02d%02d%02d%02d%02d", $1, $2, $3, $4, $5, $s;
1515            if ($type eq 'page' ) {
1516                $entry->modified_on($ts);
1517            } else {
1518                $entry->authored_on($ts);
1519            }
1520        }
1521        $app->run_callbacks( 'cms_pre_save.' . $type, $app, $entry, $orig_obj )
1522          || return $app->error(
1523            $app->translate(
1524                "Saving [_1] failed: [_2]",
1525                $entry->class_label, $app->errstr
1526            )
1527          );
1528        $entry->save
1529          or return $app->error(
1530            $app->translate(
1531                "Saving entry '[_1]' failed: [_2]", $entry->title,
1532                $entry->errstr
1533            )
1534          );
1535        my $cat_id = $q->param("category_id_$id");
1536        my $place  = MT::Placement->load(
1537            {
1538                entry_id   => $id,
1539                is_primary => 1
1540            }
1541        );
1542        if ( $place && !$cat_id ) {
1543            $place->remove
1544              or return $app->error(
1545                $app->translate(
1546                    "Removing placement failed: [_1]",
1547                    $place->errstr
1548                )
1549              );
1550        }
1551        elsif ($cat_id) {
1552            unless ($place) {
1553                $place = MT::Placement->new;
1554                $place->entry_id($id);
1555                $place->blog_id($blog_id);
1556                $place->is_primary(1);
1557            }
1558            $place->category_id( scalar $q->param($p) );
1559            $place->save
1560              or return $app->error(
1561                $app->translate(
1562                    "Saving placement failed: [_1]",
1563                    $place->errstr
1564                )
1565              );
1566        }
1567        my $message;
1568        if ( $orig_obj->status ne $entry->status ) {
1569            $message = $app->translate(
1570"[_1] '[_2]' (ID:[_3]) edited and its status changed from [_4] to [_5] by user '[_6]'",
1571                $entry->class_label,
1572                $entry->title,
1573                $entry->id,
1574                $app->translate( MT::Entry::status_text( $orig_obj->status ) ),
1575                $app->translate( MT::Entry::status_text( $entry->status ) ),
1576                $this_author->name
1577            );
1578        }
1579        else {
1580            $message =
1581              $app->translate( "[_1] '[_2]' (ID:[_3]) edited by user '[_4]'",
1582                $entry->class_label, $entry->title, $entry->id,
1583                $this_author->name );
1584        }
1585        $app->log(
1586            {
1587                message  => $message,
1588                level    => MT::Log::INFO(),
1589                class    => $entry->class,
1590                category => 'edit',
1591                metadata => $entry->id
1592            }
1593        );
1594        $app->run_callbacks( 'cms_post_save.' . $type, $app, $entry, $orig_obj );
1595    }
1596    $app->add_return_arg( 'saved' => 1, is_power_edit => 1 );
1597    $app->call_return;
1598}
1599
1600sub send_pings {
1601    my $app = shift;
1602    my $q   = $app->param;
1603    $app->validate_magic() or return;
1604    require MT::Entry;
1605    require MT::Blog;
1606    my $blog  = MT::Blog->load( scalar $q->param('blog_id') );
1607    my $entry = MT::Entry->load( scalar $q->param('entry_id') );
1608    ## MT::ping_and_save pings each of the necessary URLs, then processes
1609    ## the return value from MT::ping to update the list of URLs pinged
1610    ## and not successfully pinged. It returns the return value from
1611    ## MT::ping for further processing. If a fatal error occurs, it returns
1612    ## undef.
1613    my $results = $app->ping_and_save(
1614        Blog      => $blog,
1615        Entry     => $entry,
1616        OldStatus => scalar $q->param('old_status')
1617    ) or return;
1618    my $has_errors = 0;
1619    require MT::Log;
1620    for my $res (@$results) {
1621        $has_errors++,
1622          $app->log(
1623            {
1624                message => $app->translate(
1625                    "Ping '[_1]' failed: [_2]",
1626                    $res->{url},
1627                    encode_text( $res->{error}, undef, undef )
1628                ),
1629                class => 'system',
1630                level => MT::Log::WARNING()
1631            }
1632          ) unless $res->{good};
1633    }
1634    _finish_rebuild_ping( $app, $entry, scalar $q->param('is_new'),
1635        $has_errors );
1636}
1637
1638sub entry_notify {
1639    my $app   = shift;
1640    my $user  = $app->user;
1641    my $perms = $app->permissions;
1642    return $app->error( $app->translate("No permissions.") )
1643      unless $perms->can_send_notifications;
1644
1645    my $q        = $app->param;
1646    my $entry_id = $q->param('entry_id')
1647      or return $app->error( $app->translate("No entry ID provided") );
1648    require MT::Entry;
1649    require MT::Blog;
1650    my $entry = MT::Entry->load($entry_id)
1651      or return $app->error(
1652        $app->translate( "No such entry '[_1]'", $entry_id ) );
1653    my $blog  = MT::Blog->load( $entry->blog_id );
1654    my $param = {};
1655    $param->{entry_id} = $entry_id;
1656    return $app->load_tmpl( "dialog/entry_notify.tmpl", $param );
1657}
1658
1659sub send_notify {
1660    my $app = shift;
1661    $app->validate_magic() or return;
1662    my $q        = $app->param;
1663    my $entry_id = $q->param('entry_id')
1664      or return $app->error( $app->translate("No entry ID provided") );
1665    require MT::Entry;
1666    require MT::Blog;
1667    my $entry = MT::Entry->load($entry_id)
1668      or return $app->error(
1669        $app->translate( "No such entry '[_1]'", $entry_id ) );
1670    my $blog = MT::Blog->load( $entry->blog_id );
1671
1672    my $user = $app->user;
1673    $app->blog($blog);
1674    my $perms = $user->permissions($blog);
1675    return $app->error( $app->translate("No permissions.") )
1676      unless $perms->can_send_notifications;
1677
1678    my $author = $entry->author;
1679    return $app->error(
1680        $app->translate( "No email address for user '[_1]'", $author->name ) )
1681      unless $author->email;
1682
1683    my $cols = 72;
1684    my %params;
1685    $params{blog} = $blog;
1686    $params{entry} = $entry;
1687    $params{author} = $author;
1688
1689    if ( $q->param('send_excerpt') ) {
1690        $params{send_excerpt} = 1;
1691    }
1692    $params{message} = wrap_text( $q->param('message'), $cols, '', '' );
1693    if ( $q->param('send_body') ) {
1694        $params{send_body} = 1;
1695    }
1696
1697    my $entry_editurl = $app->uri(
1698        'mode' => 'view',
1699        args   => {
1700            '_type' => 'entry',
1701            blog_id => $entry->blog_id,
1702            id      => $entry->id,
1703        }
1704    );
1705    if ( $entry_editurl =~ m|^/| ) {
1706        my ($blog_domain) = $blog->archive_url =~ m|(.+://[^/]+)|;
1707        $entry_editurl = $blog_domain . $entry_editurl;
1708    }
1709    $params{entry_editurl} = $entry_editurl;
1710
1711    my $addrs;
1712    if ( $q->param('send_notify_list') ) {
1713        require MT::Notification;
1714        my $iter = MT::Notification->load_iter( { blog_id => $blog->id } );
1715        while ( my $note = $iter->() ) {
1716            next unless is_valid_email( $note->email );
1717            $addrs->{ $note->email } = 1;
1718        }
1719    }
1720
1721    if ( $q->param('send_notify_emails') ) {
1722        my @addr = split /[\n\r,]+/, $q->param('send_notify_emails');
1723        for my $a (@addr) {
1724            next unless is_valid_email($a);
1725            $addrs->{$a} = 1;
1726        }
1727    }
1728
1729    keys %$addrs
1730      or return $app->error(
1731        $app->translate(
1732            "No valid recipients found for the entry notification.")
1733      );
1734
1735    my $body = $app->build_email( 'notify-entry.tmpl', \%params );
1736
1737    my $subj =
1738      $app->translate( "[_1] Update: [_2]", $blog->name, $entry->title );
1739    if ( $app->current_language ne 'ja' ) {    # FIXME perhaps move to MT::I18N
1740        $subj =~ s![\x80-\xFF]!!g;
1741    }
1742    my $address =
1743      defined $author->nickname
1744      ? $author->nickname . ' <' . $author->email . '>'
1745      : $author->email;
1746    my %head = (
1747        id      => 'notify_entry',
1748        To      => $address,
1749        From    => $address,
1750        Subject => $subj,
1751    );
1752    my $charset = $app->config('MailEncoding')
1753      || $app->charset;
1754    $head{'Content-Type'} = qq(text/plain; charset="$charset");
1755    my $i = 1;
1756    require MT::Mail;
1757    MT::Mail->send( \%head, $body )
1758      or return $app->error(
1759        $app->translate(
1760            "Error sending mail ([_1]); try another MailTransfer setting?",
1761            MT::Mail->errstr
1762        )
1763      );
1764    delete $head{To};
1765
1766    foreach my $email ( keys %{$addrs} ) {
1767        next unless $email;
1768        if ( $app->config('EmailNotificationBcc') ) {
1769            push @{ $head{Bcc} }, $email;
1770            if ( $i++ % 20 == 0 ) {
1771                MT::Mail->send( \%head, $body )
1772                  or return $app->error(
1773                    $app->translate(
1774"Error sending mail ([_1]); try another MailTransfer setting?",
1775                        MT::Mail->errstr
1776                    )
1777                  );
1778                @{ $head{Bcc} } = ();
1779            }
1780        }
1781        else {
1782            $head{To} = $email;
1783            MT::Mail->send( \%head, $body )
1784              or return $app->error(
1785                $app->translate(
1786"Error sending mail ([_1]); try another MailTransfer setting?",
1787                    MT::Mail->errstr
1788                )
1789              );
1790            delete $head{To};
1791        }
1792    }
1793    if ( $head{Bcc} && @{ $head{Bcc} } ) {
1794        MT::Mail->send( \%head, $body )
1795          or return $app->error(
1796            $app->translate(
1797                "Error sending mail ([_1]); try another MailTransfer setting?",
1798                MT::Mail->errstr
1799            )
1800          );
1801    }
1802    $app->redirect(
1803        $app->uri(
1804            'mode' => 'view',
1805            args   => {
1806                '_type'      => $entry->class,
1807                blog_id      => $entry->blog_id,
1808                id           => $entry->id,
1809                saved_notify => 1
1810            }
1811        )
1812    );
1813}
1814
1815sub pinged_urls {
1816    my $app   = shift;
1817    my $perms = $app->permissions
1818      or return $app->error( $app->translate("No permissions") );
1819    my %param;
1820    my $entry_id = $app->param('entry_id');
1821    require MT::Entry;
1822    my $entry = MT::Entry->load($entry_id);
1823    $param{url_loop} = [ map { { url => $_ } } @{ $entry->pinged_url_list } ];
1824    $param{failed_url_loop} =
1825      [ map { { url => $_ } }
1826          @{ $entry->pinged_url_list( OnlyFailures => 1 ) } ];
1827    $app->load_tmpl( 'popup/pinged_urls.tmpl', \%param );
1828}
1829
1830sub save_entry_prefs {
1831    my $app   = shift;
1832    my $perms = $app->permissions
1833      or return $app->error( $app->translate("No permissions") );
1834    $app->validate_magic() or return;
1835    my $q     = $app->param;
1836    my $prefs = $app->_entry_prefs_from_params;
1837    $perms->entry_prefs($prefs);
1838    $perms->save
1839      or return $app->error(
1840        $app->translate( "Saving permissions failed: [_1]", $perms->errstr ) );
1841    $app->send_http_header("text/json");
1842    return "true";
1843}
1844
1845sub publish_entries {
1846    my $app = shift;
1847    require MT::Entry;
1848    update_entry_status( $app, MT::Entry::RELEASE(), $app->param('id') );
1849}
1850
1851sub draft_entries {
1852    my $app = shift;
1853    require MT::Entry;
1854    update_entry_status( $app, MT::Entry::HOLD(), $app->param('id') );
1855}
1856
1857sub open_batch_editor {
1858    my $app = shift;
1859    my @ids = $app->param('id');
1860
1861    $app->param( 'is_power_edit', 1 );
1862    $app->param( 'filter',        'power_edit' );
1863    $app->param( 'filter_val',    \@ids );
1864    $app->mode(
1865        'list_' . ( 'entry' eq $app->param('_type') ? 'entries' : 'pages' ) );
1866    $app->forward( "list_entry", { type => $app->param('_type') } );
1867}
1868
1869sub build_entry_table {
1870    my $app = shift;
1871    my (%args) = @_;
1872
1873    my $app_author = $app->user;
1874    my $perms      = $app->permissions;
1875    my $type       = $args{type};
1876    my $class      = $app->model($type);
1877
1878    my $list_pref = $app->list_pref($type);
1879    if ( $args{is_power_edit} ) {
1880        delete $list_pref->{view_expanded};
1881    }
1882    my $iter;
1883    if ( $args{load_args} ) {
1884        $iter = $class->load_iter( @{ $args{load_args} } );
1885    }
1886    elsif ( $args{iter} ) {
1887        $iter = $args{iter};
1888    }
1889    elsif ( $args{items} ) {
1890        $iter = sub { shift @{ $args{items} } };
1891    }
1892    return [] unless $iter;
1893    my $limit         = $args{limit};
1894    my $is_power_edit = $args{is_power_edit} || 0;
1895    my $param         = $args{param} || {};
1896
1897    ## Load list of categories for display in filter pulldown (and selection
1898    ## pulldown on power edit page).
1899    my ( $c_data, %cats );
1900    my $blog_id = $app->param('blog_id');
1901    if ($blog_id) {
1902        $c_data = $app->_build_category_list(
1903            blog_id => $blog_id,
1904            type    => $class->container_type,
1905        );
1906        my $i = 0;
1907        for my $row (@$c_data) {
1908            $row->{category_index} = $i++;
1909            my $spacer = $row->{category_label_spacer} || '';
1910            $spacer =~ s/\&nbsp;/\\u00A0/g;
1911            $row->{category_label_js} =
1912              $spacer . encode_js( $row->{category_label} );
1913            $cats{ $row->{category_id} } = $row;
1914        }
1915        $param->{category_loop} = $c_data;
1916    }
1917
1918    my ( $date_format, $datetime_format );
1919
1920    if ($is_power_edit) {
1921        $date_format          = "%Y.%m.%d";
1922        $datetime_format      = "%Y-%m-%d %H:%M:%S";
1923    }
1924    else {
1925        $date_format     = MT::App::CMS::LISTING_DATE_FORMAT();
1926        $datetime_format = MT::App::CMS::LISTING_DATETIME_FORMAT();
1927    }
1928
1929    my @cat_list;
1930    if ($is_power_edit) {
1931        @cat_list =
1932          sort { $cats{$a}->{category_index} <=> $cats{$b}->{category_index} }
1933          keys %cats;
1934    }
1935
1936    my @data;
1937    my %blogs;
1938    require MT::Blog;
1939    my $title_max_len   = const('DISPLAY_LENGTH_EDIT_ENTRY_TITLE');
1940    my $excerpt_max_len = const('DISPLAY_LENGTH_EDIT_ENTRY_TEXT_FROM_EXCERPT');
1941    my $text_max_len    = const('DISPLAY_LENGTH_EDIT_ENTRY_TEXT_BREAK_UP');
1942    my %blog_perms;
1943    $blog_perms{ $perms->blog_id } = $perms if $perms;
1944    while ( my $obj = $iter->() ) {
1945        my $blog_perms;
1946        if ( !$app_author->is_superuser() ) {
1947            $blog_perms = $blog_perms{ $obj->blog_id }
1948              || $app_author->blog_perm( $obj->blog_id );
1949        }
1950
1951        my $row = $obj->column_values;
1952        $row->{text} ||= '';
1953        if ( my $ts =
1954            ( $type eq 'page' ) ? $obj->modified_on : $obj->authored_on )
1955        {
1956            $row->{created_on_formatted} =
1957              format_ts( $date_format, $ts, $obj->blog, $app->user ? $app->user->preferred_language : undef );
1958            $row->{created_on_time_formatted} =
1959              format_ts( $datetime_format, $ts, $obj->blog, $app->user ? $app->user->preferred_language : undef );
1960            $row->{created_on_relative} =
1961              relative_date( $ts, time, $obj->blog );
1962        }
1963        my $author = $obj->author;
1964        $row->{author_name} =
1965          $author ? $author->name : $app->translate('(user deleted)');
1966        if ( my $cat = $obj->category ) {
1967            $row->{category_label}    = $cat->label;
1968            $row->{category_basename} = $cat->basename;
1969        }
1970        else {
1971            $row->{category_label}    = '';
1972            $row->{category_basename} = '';
1973        }
1974        $row->{file_extension} = $obj->blog ? $obj->blog->file_extension : '';
1975        $row->{title_short} = $obj->title;
1976        if ( !defined( $row->{title_short} ) || $row->{title_short} eq '' ) {
1977            my $title = remove_html( $obj->text );
1978            $row->{title_short} =
1979              substr_text( defined($title) ? $title : "", 0, $title_max_len )
1980              . '...';
1981        }
1982        else {
1983            $row->{title_short} = remove_html( $row->{title_short} );
1984            $row->{title_short} =
1985              substr_text( $row->{title_short}, 0, $title_max_len + 3 ) . '...'
1986              if length_text( $row->{title_short} ) > $title_max_len;
1987        }
1988        if ( $row->{excerpt} ) {
1989            $row->{excerpt} = remove_html( $row->{excerpt} );
1990        }
1991        if ( !$row->{excerpt} ) {
1992            my $text = remove_html( $row->{text} ) || '';
1993            $row->{excerpt} = first_n_text( $text, $excerpt_max_len );
1994            if ( length($text) > length( $row->{excerpt} ) ) {
1995                $row->{excerpt} .= ' ...';
1996            }
1997        }
1998        $row->{text} = break_up_text( $row->{text}, $text_max_len )
1999          if $row->{text};
2000        $row->{title_long} = remove_html( $obj->title );
2001        $row->{status_text} =
2002          $app->translate( MT::Entry::status_text( $obj->status ) );
2003        $row->{ "status_" . MT::Entry::status_text( $obj->status ) } = 1;
2004        $row->{has_edit_access} = $app_author->is_superuser
2005          || ( ( 'entry' eq $type )
2006            && $blog_perms
2007            && $blog_perms->can_edit_entry( $obj, $app_author ) )
2008          || ( ( 'page' eq $type )
2009            && $blog_perms
2010            && $blog_perms->can_manage_pages );
2011        if ($is_power_edit) {
2012            $row->{has_publish_access} = $app_author->is_superuser
2013              || ( ( 'entry' eq $type )
2014                && $blog_perms
2015                && $blog_perms->can_edit_entry( $obj, $app_author, 1 ) )
2016              || ( ( 'page' eq $type )
2017                && $blog_perms
2018                && $blog_perms->can_manage_pages );
2019            $row->{is_editable} = $row->{has_edit_access};
2020
2021            ## This is annoying. In order to generate and pre-select the
2022            ## category, user, and status pull down menus, we need to
2023            ## have a separate *copy* of the list of categories and
2024            ## users for every entry listed, so that each row in the list
2025            ## can "know" whether it is selected for this entry or not.
2026            my @this_c_data;
2027            my $this_category_id = $obj->category ? $obj->category->id : undef;
2028            for my $c_id (@cat_list) {
2029                push @this_c_data, { %{ $cats{$c_id} } };
2030                $this_c_data[-1]{category_is_selected} = $this_category_id
2031                  && $this_category_id == $c_id ? 1 : 0;
2032            }
2033            $row->{row_category_loop} = \@this_c_data;
2034
2035            if ( $obj->author ) {
2036                $row->{row_author_name} = $obj->author->name;
2037                $row->{row_author_id}   = $obj->author->id;
2038            } else {
2039                $row->{row_author_name} = $app->translate(
2040                    '(user deleted - ID:[_1])',
2041                    $obj->author_id
2042                );
2043                $row->{row_author_id} = $obj->author_id,
2044             }
2045        }
2046        if ( my $blog = $blogs{ $obj->blog_id } ||=
2047            MT::Blog->load( $obj->blog_id ) )
2048        {
2049            $row->{weblog_id}   = $blog->id;
2050            $row->{weblog_name} = $blog->name;
2051        }
2052        if ( $obj->status == MT::Entry::RELEASE() ) {
2053            $row->{entry_permalink} = $obj->permalink;
2054        }
2055        $row->{object} = $obj;
2056        push @data, $row;
2057    }
2058    return [] unless @data;
2059
2060    $param->{entry_table}[0] = {%$list_pref};
2061    $param->{object_loop} = $param->{entry_table}[0]{object_loop} = \@data;
2062    $app->load_list_actions( $type, \%$param )
2063      unless $is_power_edit;
2064    \@data;
2065}
2066
2067sub quickpost_js {
2068    my $app     = shift;
2069    my ($type)  = @_;
2070    my $blog_id = $app->blog->id;
2071    my $blog    = $app->model('blog')->load($blog_id);
2072    my %args    = ( '_type' => $type, blog_id => $blog_id, qp => 1 );
2073    my $uri = $app->base . $app->uri( 'mode' => 'view', args => \%args );
2074    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'))!;
2075    # Translate the phrase here to avoid ActivePerl DLL bug.
2076    $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);
2077}
2078
2079sub can_view {
2080    my ( $eh, $app, $id, $objp ) = @_;
2081    my $perms = $app->permissions;
2082    if (   !$id
2083        && !$perms->can_create_post )
2084    {
2085        return 0;
2086    }
2087    if ($id) {
2088        my $obj = $objp->force();
2089        if ( !$perms->can_edit_entry( $obj, $app->user ) ) {
2090            return 0;
2091        }
2092    }
2093    1;
2094}
2095
2096sub can_delete {
2097    my ( $eh, $app, $obj ) = @_;
2098    my $author = $app->user;
2099    return 1 if $author->is_superuser();
2100    my $perms = $app->permissions;
2101    if ( !$perms || $perms->blog_id != $obj->blog_id ) {
2102        $perms ||= $author->permissions( $obj->blog_id );
2103    }
2104    return $perms && $perms->can_edit_entry( $obj, $author );
2105}
2106
2107sub pre_save {
2108    my $eh = shift;
2109    my ( $app, $obj ) = @_;
2110
2111    # save tags
2112    my $tags = $app->param('tags');
2113    if ( defined $tags ) {
2114        my $blog = $app->blog;
2115        my $fields = $blog->smart_replace_fields;
2116        if ( $fields =~ m/tags/ig ) {
2117            $tags = MT::App::CMS::_convert_word_chars( $app, $tags );
2118        }
2119
2120        require MT::Tag;
2121        my $tag_delim = chr( $app->user->entry_prefs->{tag_delim} );
2122        my @tags = MT::Tag->split( $tag_delim, $tags );
2123        if (@tags) {
2124            $obj->set_tags(@tags);
2125        }
2126        else {
2127            $obj->remove_tags();
2128        }
2129    }
2130
2131    # update text heights if necessary
2132    if ( my $perms = $app->permissions ) {
2133        my $prefs = $perms->entry_prefs || $app->load_default_entry_prefs;
2134        my $text_height = $app->param('text_height');
2135        if ( defined $text_height ) {
2136            my ($pref_text_height) = $prefs =~ m/\bbody:(\d+)\b/;
2137            $pref_text_height ||= 0;
2138            if ( $text_height != $pref_text_height ) {
2139                if ( $prefs =~ m/\bbody\b/ ) {
2140                    $prefs =~ s/\bbody(:\d+)\b/body:$text_height/;
2141                }
2142                else {
2143                    $prefs = 'body:' . $text_height . ',' . $prefs;
2144                }
2145            }
2146        }
2147        if ( $prefs ne ( $perms->entry_prefs || '' ) ) {
2148            $perms->entry_prefs($prefs);
2149            $perms->save;
2150        }
2151    }
2152    $obj->discover_tb_from_entry();
2153    1;
2154}
2155
2156sub post_save {
2157    my $eh = shift;
2158    my ( $app, $obj ) = @_;
2159    my $sess_obj = $app->autosave_session_obj;
2160    $sess_obj->remove if $sess_obj;
2161    1;
2162}
2163
2164sub post_delete {
2165    my ( $eh, $app, $obj ) = @_;
2166
2167    my $sess_obj = $app->autosave_session_obj;
2168    $sess_obj->remove if $sess_obj;
2169
2170    $app->log(
2171        {
2172            message => $app->translate(
2173                "Entry '[_1]' (ID:[_2]) deleted by '[_3]'",
2174                $obj->title, $obj->id, $app->user->name
2175            ),
2176            level    => MT::Log::INFO(),
2177            class    => 'system',
2178            category => 'delete'
2179        }
2180    );
2181}
2182
2183sub update_entry_status {
2184    my $app = shift;
2185    my ( $new_status, @ids ) = @_;
2186    return $app->errtrans("Need a status to update entries")
2187      unless $new_status;
2188    return $app->errtrans("Need entries to update status")
2189      unless @ids;
2190    my @bad_ids;
2191    my %rebuild_these;
2192    require MT::Entry;
2193
2194    foreach my $id (@ids) {
2195        my $entry = MT::Entry->load($id)
2196          or return $app->errtrans(
2197            "One of the entries ([_1]) did not actually exist", $id );
2198        next if $entry->status == $new_status;
2199        if ( $app->config('DeleteFilesAtRebuild')
2200            && ( MT::Entry::RELEASE() eq $entry->status ) )
2201        {
2202            my $archive_type =
2203              $entry->class eq 'page'
2204              ? 'Page'
2205              : 'Individual';
2206            $app->publisher->remove_entry_archive_file(
2207                Entry       => $entry,
2208                ArchiveType => $archive_type
2209            );
2210        }
2211        my $old_status = $entry->status;
2212        $entry->status($new_status);
2213        $entry->save() and $rebuild_these{$id} = 1;
2214        my $message = $app->translate(
2215            "[_1] '[_2]' (ID:[_3]) status changed from [_4] to [_5]",
2216            $entry->class_label,
2217            $entry->title,
2218            $entry->id,
2219            $app->translate( MT::Entry::status_text($old_status) ),
2220            $app->translate( MT::Entry::status_text($new_status) )
2221        );
2222        $app->log(
2223            {
2224                message  => $message,
2225                level    => MT::Log::INFO(),
2226                class    => $entry->class,
2227                category => 'edit',
2228                metadata => $entry->id
2229            }
2230        );
2231    }
2232    $app->rebuild_these( \%rebuild_these, how => MT::App::CMS::NEW_PHASE() );
2233}
2234
2235sub _finish_rebuild_ping {
2236    my $app = shift;
2237    my ( $entry, $is_new, $ping_errors ) = @_;
2238    $app->redirect(
2239        $app->uri(
2240            'mode' => 'view',
2241            args   => {
2242                '_type' => $entry->class,
2243                blog_id => $entry->blog_id,
2244                id      => $entry->id,
2245                ( $is_new ? ( saved_added => 1 ) : ( saved_changes => 1 ) ),
2246                ( $ping_errors ? ( ping_errors => 1 ) : () )
2247            }
2248        )
2249    );
2250}
2251
2252sub ping_continuation {
2253    my $app = shift;
2254    my ( $entry, $blog, %options ) = @_;
2255    my $list = $app->needs_ping(
2256        Entry     => $entry,
2257        Blog      => $blog,
2258        OldStatus => $options{OldStatus}
2259    );
2260    require MT::Entry;
2261    if ( $entry->status == MT::Entry::RELEASE() && $list ) {
2262        my @urls = map { { url => $_ } } @$list;
2263        $app->load_tmpl(
2264            'pinging.tmpl',
2265            {
2266                blog_id    => $blog->id,
2267                entry_id   => $entry->id,
2268                old_status => $options{OldStatus},
2269                is_new     => $options{IsNew},
2270                url_list   => \@urls,
2271            }
2272        );
2273    }
2274    else {
2275        _finish_rebuild_ping( $app, $entry, $options{IsNew} );
2276    }
2277}
2278
2279sub delete {
2280    my $app = shift;
2281    $app->validate_magic() or return;
2282
2283    require MT::Blog;
2284    my $q       = $app->param;
2285    my $blog_id = $q->param('blog_id');
2286    my $blog    = MT::Blog->load($blog_id);
2287
2288    my $can_background =
2289        ( $blog->count_static_templates('Individual') == 0
2290            || MT::Util->launch_background_tasks() ) ? 1 : 0;
2291
2292    my %rebuild_recip;
2293    my $at = $blog->archive_type;
2294    my @at;
2295    if ( $at && $at ne 'None' ) {
2296        my @at_orig = split( /,/, $at );
2297        @at = grep { $_ ne 'Individual' && $_ ne 'Page' } @at_orig;
2298    }
2299
2300    for my $id ( $q->param('id') ) {
2301        my $class = $app->model("entry");
2302        my $obj   = $class->load($id);
2303        return $app->call_return unless $obj;
2304
2305        $app->run_callbacks( 'cms_delete_permission_filter.entry', $app, $obj )
2306          || return $app->error(
2307            $app->translate( "Permission denied: [_1]", $app->errstr() ) );
2308
2309        if (   $app->config('RebuildAtDelete')
2310            || $app->config('DeleteFilesAtRebuild') )
2311        {
2312            # Remove Induvidual archive file.
2313            if ( $app->config('DeleteFilesAtRebuild') ) {
2314                $app->publisher->remove_entry_archive_file( Entry => $obj, );
2315            }
2316
2317            for my $at (@at) {
2318                my $archiver = $app->publisher->archiver($at);
2319                next unless $archiver;
2320
2321                # Remove archive file if archive file has not entries.
2322                my $deleted = 0;
2323                if ( $app->config('DeleteFilesAtRebuild') ) {
2324                    my $count =
2325                        $archiver->can('archive_entries_count')
2326                      ? $archiver->archive_entries_count( $blog, $at, $obj )
2327                      : 0;
2328                    if ( $count == 1 ) {
2329                        $app->publisher->remove_entry_archive_file(
2330                            Entry       => $obj,
2331                            ArchiveType => $at
2332                        );
2333                        $deleted = 1;
2334                    }
2335                }
2336
2337                # Make rebuild recip
2338                if ( $app->config('DeleteFilesAtRebuild') ) {
2339                    next if $deleted;
2340
2341                    my ( $start, $end ) = $archiver->date_range( $obj->authored_on )
2342                        if $archiver->date_based() && $archiver->can('date_range');
2343
2344                    if ( $archiver->category_based() ) {
2345                        my $categories = $obj->categories();
2346                        for my $cat (@$categories) {
2347                            if ( $archiver->date_based() ) {
2348                                $rebuild_recip{$at}{ $cat->id }{ $start . $end }
2349                                  {'Start'} = $start;
2350                                $rebuild_recip{$at}{ $cat->id }{ $start . $end }
2351                                  {'End'} = $end;
2352                                $rebuild_recip{$at}{ $cat->id }{ $start . $end }
2353                                  {'File'} =
2354                                  MT::Util::archive_file_for( $obj, $blog, $at,
2355                                    $cat, undef, undef, undef );
2356                            }
2357                            else {
2358                                $rebuild_recip{$at}{ $cat->id }{id} = $cat->id;
2359                                $rebuild_recip{$at}{ $cat->id }{'File'} =
2360                                  MT::Util::archive_file_for( $obj, $blog, $at,
2361                                    $cat, undef, undef, undef );
2362                            }
2363                        }
2364                    }
2365                    elsif ( $archiver->author_based() ) {
2366                        if ( $archiver->date_based() ) {
2367                            $rebuild_recip{$at}{ $obj->author->id }{ $start . $end }
2368                              {'Start'} = $start;
2369                            $rebuild_recip{$at}{ $obj->author->id }{ $start . $end }
2370                              {'End'} = $end;
2371                            $rebuild_recip{$at}{ $obj->author->id }{ $start . $end }
2372                              {'File'} =
2373                              MT::Util::archive_file_for( $obj, $blog, $at, undef,
2374                                undef, undef, $obj->author );
2375                        }
2376                        else {
2377                            $rebuild_recip{$at}{ $obj->author->id }{id} =
2378                              $obj->author->id;
2379                            $rebuild_recip{$at}{ $obj->author->id }{'File'} =
2380                              MT::Util::archive_file_for( $obj, $blog, $at, undef,
2381                                undef, undef, $obj->author );
2382                        }
2383                    }
2384                    elsif ( $archiver->date_based() ) {
2385                        $rebuild_recip{$at}{ $start . $end }{'Start'} = $start;
2386                        $rebuild_recip{$at}{ $start . $end }{'End'}   = $end;
2387