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

Revision 1715, 83.5 kB (checked in by fumiakiy, 20 months ago)

Webmaster can save pages in batch. BugId:67906

  • 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                $param->{
153                    'allow_comments_'
154                      . (
155                        defined $q->param('allow_comments')
156                        ? $q->param('allow_comments')
157                        : $blog->allow_comments_default
158                      )
159                  }
160                  = 1;
161                $param->{allow_comments} = $blog->allow_comments_default
162                  unless defined $q->param('allow_comments');
163                $param->{allow_pings} = $blog->allow_pings_default
164                  unless defined $q->param('allow_pings');
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('main_template',     1);
854    $ctx->var('archive_template',  1);
855    $ctx->var('entry_template',    1);
856    $ctx->var('feedback_template', 1);
857    $ctx->var('archive_class',     'entry-archive');
858    $ctx->var('preview_template',  1);
859    my $html = $tmpl->output;
860    my %param;
861    unless ( defined($html) ) {
862        my $preview_error = $app->translate( "Publish error: [_1]",
863            MT::Util::encode_html( $tmpl->errstr ) );
864        $param{preview_error} = $preview_error;
865        my $tmpl_plain = $app->load_tmpl('preview_entry_content.tmpl');
866        $tmpl->text( $tmpl_plain->text );
867        $html = $tmpl->output;
868        defined($html)
869          or return $app->error(
870            $app->translate( "Publish error: [_1]", $tmpl->errstr ) );
871        $fullscreen = 1;
872    }
873
874    # If MT is configured to do 'local' previews, convert all
875    # the normal blog URLs into the domain used by MT itself (ie,
876    # blog is published to www.example.com, which is a different
877    # server from where MT runs, mt.example.com; previews therefore
878    # should occur locally, so replace all http://www.example.com/
879    # with http://mt.example.com/).
880    my ($old_url, $new_url);
881    if ($app->config('LocalPreviews')) {
882        $old_url = $blog->site_url;
883        $old_url =~ s!^(https?://[^/]+?/)(.*)?!$1!;
884        $new_url = $app->base . '/';
885        $html =~ s!\Q$old_url\E!$new_url!g;
886    }
887
888    if ( !$fullscreen ) {
889        my $fmgr = $blog->file_mgr;
890
891        ## Determine if we need to build directory structure,
892        ## and build it if we do. DirUmask determines
893        ## directory permissions.
894        require File::Basename;
895        my $path = File::Basename::dirname($archive_file);
896        $path =~ s!/$!!
897          unless $path eq '/';    ## OS X doesn't like / at the end in mkdir().
898        unless ( $fmgr->exists($path) ) {
899            $fmgr->mkpath($path);
900        }
901
902        if ( $fmgr->exists($path) && $fmgr->can_write($path) ) {
903            $fmgr->put_data( $html, $archive_file );
904            $param{preview_file} = $preview_basename;
905            my $preview_url = $entry->archive_url;
906            $preview_url =~ s! / \Q$orig_file\E ( /? ) $!/$preview_basename$file_ext$1!x;
907
908            # We also have to translate the URL used for the
909            # published file to be on the MT app domain.
910            if (defined $new_url) {
911                $preview_url =~ s!^\Q$old_url\E!$new_url!;
912            }
913
914            $param{preview_url}  = $preview_url;
915
916            # we have to make a record of this preview just in case it
917            # isn't cleaned up by re-editing, saving or cancelling on
918            # by the user.
919            require MT::Session;
920            my $sess_obj = MT::Session->get_by_key(
921                {
922                    id   => $preview_basename,
923                    kind => 'TF',                # TF = Temporary File
924                    name => $archive_file,
925                }
926            );
927            $sess_obj->start(time);
928            $sess_obj->save;
929        }
930        else {
931            $fullscreen = 1;
932            $param{preview_error} = $app->translate(
933                "Unable to create preview file in this location: [_1]", $path );
934            my $tmpl_plain = $app->load_tmpl('preview_entry_content.tmpl');
935            $tmpl->text( $tmpl_plain->text );
936            $tmpl->reset_tokens;
937            $html = $tmpl->output;
938            $param{preview_body} = $html;
939        }
940    }
941    else {
942        $param{preview_body} = $html;
943    }
944    $param{id} = $id if $id;
945    $param{new_object} = $param{id} ? 0 : 1;
946    $param{title} = $entry->title;
947    my $cols = $entry_class->column_names;
948
949    for my $col (@$cols) {
950        next
951          if $col eq 'created_on'
952          || $col eq 'created_by'
953          || $col eq 'modified_on'
954          || $col eq 'modified_by'
955          || $col eq 'authored_on'
956          || $col eq 'author_id'
957          || $col eq 'pinged_urls'
958          || $col eq 'tangent_cache'
959          || $col eq 'template_id'
960          || $col eq 'class'
961          || $col eq 'meta';
962        if ( $col eq 'basename' ) {
963            if (   ( !defined $q->param('basename') )
964                || ( $q->param('basename') eq '' ) )
965            {
966                $q->param( 'basename', $q->param('basename_old') );
967            }
968        }
969        push @data,
970          {
971            data_name  => $col,
972            data_value => scalar $q->param($col)
973          };
974    }
975    for my $data (
976        qw( authored_on_date authored_on_time basename_manual basename_old category_ids tags )
977      )
978    {
979        push @data,
980          {
981            data_name  => $data,
982            data_value => scalar $q->param($data)
983          };
984    }
985
986    $param{entry_loop} = \@data;
987    my $list_mode;
988    my $list_title;
989    if ( $type eq 'page' ) {
990        $list_title = 'Pages';
991        $list_mode  = 'list_pages';
992    }
993    else {
994        $list_title = 'Entries';
995        $list_mode  = 'list_entries';
996    }
997    if ($id) {
998        $app->add_breadcrumb(
999            $app->translate($list_title),
1000            $app->uri(
1001                'mode' => $list_mode,
1002                args   => { blog_id => $blog_id }
1003            )
1004        );
1005        $app->add_breadcrumb( $entry->title || $app->translate('(untitled)') );
1006    }
1007    else {
1008        $app->add_breadcrumb( $app->translate($list_title),
1009            $app->uri( 'mode' => $list_mode, args => { blog_id => $blog_id } )
1010        );
1011        $app->add_breadcrumb(
1012            $app->translate( 'New [_1]', $entry_class->class_label ) );
1013        $param{nav_new_entry} = 1;
1014    }
1015    $param{object_type}  = $type;
1016    $param{object_label} = $entry_class->class_label;
1017    if ($fullscreen) {
1018        return $app->load_tmpl( 'preview_entry.tmpl', \%param );
1019    }
1020    else {
1021        return $app->load_tmpl( 'preview_strip.tmpl', \%param );
1022    }
1023}
1024
1025sub cfg_entry {
1026    my $app     = shift;
1027    my $q       = $app->param;
1028    my $blog_id = scalar $q->param('blog_id');
1029    return $app->return_to_dashboard( redirect => 1 )
1030      unless $blog_id;
1031    $q->param( '_type', 'blog' );
1032    $q->param( 'id',    scalar $q->param('blog_id') );
1033    $app->forward("view",
1034        {
1035            output       => 'cfg_entry.tmpl',
1036            screen_class => 'settings-screen entry-screen'
1037        }
1038    );
1039}
1040
1041sub save {
1042    my $app = shift;
1043    $app->validate_magic or return;
1044
1045    $app->remove_preview_file;
1046
1047    if ( $app->param('is_power_edit') ) {
1048        return $app->save_entries(@_);
1049    }
1050    my $author = $app->user;
1051    my $type = $app->param('_type') || 'entry';
1052
1053    my $class = $app->model($type)
1054      or retrun $app->errtrans("Invalid parameter");
1055
1056    my $cat_class = $app->model( $class->container_type );
1057
1058    my $perms = $app->permissions
1059      or return $app->errtrans("Permission denied.");
1060
1061    if ( $type eq 'page' ) {
1062        return $app->errtrans("Permission denied.")
1063          unless $perms->can_manage_pages;
1064    }
1065
1066    my $id = $app->param('id');
1067    if ( !$id ) {
1068        return $app->errtrans("Permission denied.")
1069          unless ( ( 'entry' eq $type ) && $perms->can_create_post )
1070          || ( ( 'page' eq $type ) && $perms->can_manage_pages );
1071    }
1072
1073    $app->validate_magic() or return;
1074
1075    # check for autosave
1076    if ( $app->param('_autosave') ) {
1077        return $app->autosave_object();
1078    }
1079
1080    require MT::Blog;
1081    my $blog_id = $app->param('blog_id');
1082    my $blog    = MT::Blog->load($blog_id);
1083
1084    my $archive_type;
1085
1086    my ( $obj, $orig_obj, $orig_file );
1087    if ($id) {
1088        $obj = $class->load($id)
1089          || return $app->error(
1090            $app->translate( "No such [_1].", $class->class_label ) );
1091        return $app->error( $app->translate("Invalid parameter") )
1092          unless $obj->blog_id == $blog_id;
1093        if ( $type eq 'entry' ) {
1094            return $app->error( $app->translate("Permission denied.") )
1095              unless $perms->can_edit_entry( $obj, $author );
1096            return $app->error( $app->translate("Permission denied.") )
1097              if ( $obj->status ne $app->param('status') )
1098              && !( $perms->can_edit_entry( $obj, $author, 1 ) );
1099            $archive_type = 'Individual';
1100        }
1101        elsif ( $type eq 'page' ) {
1102            $archive_type = 'Page';
1103        }
1104        $orig_obj = $obj->clone;
1105        $orig_file = archive_file_for( $orig_obj, $blog, $archive_type );
1106    }
1107    else {
1108        $obj = $class->new;
1109    }
1110    my $status_old = $id ? $obj->status : 0;
1111    my $names = $obj->column_names;
1112
1113    ## Get rid of category_id param, because we don't want to just set it
1114    ## in the Entry record; save it for later when we will set the Placement.
1115    my ( $cat_id, @add_cat ) = split /\s*,\s*/,
1116      ( $app->param('category_ids') || '' );
1117    $app->delete_param('category_id');
1118    if ($id) {
1119        ## Delete the author_id param (if present), because we don't want to
1120        ## change the existing author.
1121        $app->delete_param('author_id');
1122    }
1123
1124    my %values = map { $_ => scalar $app->param($_) } @$names;
1125    delete $values{'id'} unless $app->param('id');
1126    ## Strip linefeed characters.
1127    for my $col (qw( text excerpt text_more keywords )) {
1128        $values{$col} =~ tr/\r//d if $values{$col};
1129    }
1130    $values{allow_comments} = 0
1131      if !defined( $values{allow_comments} )
1132      || $app->param('allow_comments') eq '';
1133    delete $values{week_number}
1134      if ( $app->param('week_number') || '' ) eq '';
1135    delete $values{basename}
1136      unless $perms->can_publish_post || $perms->can_edit_all_posts;
1137    $obj->set_values( \%values );
1138    $obj->allow_pings(0)
1139      if !defined $app->param('allow_pings')
1140      || $app->param('allow_pings') eq '';
1141    my $ao_d = $app->param('authored_on_date');
1142    my $ao_t = $app->param('authored_on_time');
1143
1144    if ( !$id ) {
1145
1146        #  basename check for this new entry...
1147        if (   ( my $basename = $app->param('basename') )
1148            && !$app->param('basename_manual')
1149            && $type eq 'entry' )
1150        {
1151            my $cnt =
1152              $class->count( { blog_id => $blog_id, basename => $basename } );
1153            if ($cnt) {
1154                $obj->basename( MT::Util::make_unique_basename($obj) );
1155            }
1156        }
1157    }
1158
1159    if ( $type eq 'page' ) {
1160
1161        # -1 is a special id for identifying the 'root' folder
1162        $cat_id = 0 if $cat_id == -1;
1163        my $dup_it = $class->load_iter(
1164            {
1165                blog_id  => $blog_id,
1166                basename => $obj->basename,
1167                class    => 'page',
1168                ( $id ? ( id => $id ) : () )
1169            },
1170            { ( $id ? ( not => { id => 1 } ) : () ) }
1171        );
1172        while ( my $p = $dup_it->() ) {
1173            my $p_folder = $p->folder;
1174            my $dup_folder_path =
1175              defined $p_folder ? $p_folder->publish_path() : '';
1176            my $folder = MT::Folder->load($cat_id) if $cat_id;
1177            my $folder_path = defined $folder ? $folder->publish_path() : '';
1178            return $app->error(
1179                $app->translate(
1180"Same Basename has already been used. You should use an unique basename."
1181                )
1182            ) if ( $dup_folder_path eq $folder_path );
1183        }
1184
1185    }
1186
1187    if ( $type eq 'entry' ) {
1188        $obj->status( MT::Entry::HOLD() )
1189          if !$id
1190          && !$perms->can_publish_post
1191          && !$perms->can_edit_all_posts;
1192    }
1193
1194    my $filter_result = $app->run_callbacks( 'cms_save_filter.' . $type, $app );
1195
1196    if ( !$filter_result ) {
1197        my %param = ();
1198        $param{error}       = $app->errstr;
1199        $param{return_args} = $app->param('return_args');
1200        return $app->forward( "view", \%param );
1201    }
1202
1203    # check to make sure blog has site url and path defined.
1204    # otherwise, we can't publish a released entry
1205    if ( ( $obj->status || 0 ) != MT::Entry::HOLD() ) {
1206        if ( !$blog->site_path || !$blog->site_url ) {
1207            return $app->error(
1208                $app->translate(
1209"Your blog has not been configured with a site path and URL. You cannot publish entries until these are defined."
1210                )
1211            );
1212        }
1213    }
1214
1215    my ( $previous_old, $next_old );
1216    if (   ( $perms->can_publish_post || $perms->can_edit_all_posts )
1217        && ($ao_d) )
1218    {
1219        my $ao = $ao_d . ' ' . $ao_t;
1220        unless (
1221            $ao =~ m!^(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2})(?::(\d{2}))?$! )
1222        {
1223            return $app->error(
1224                $app->translate(
1225"Invalid date '[_1]'; authored on dates must be in the format YYYY-MM-DD HH:MM:SS.",
1226$ao
1227                )
1228            );
1229        }
1230        my $s = $6 || 0;
1231        return $app->error(
1232            $app->translate(
1233                "Invalid date '[_1]'; authored on dates should be real dates.",
1234                $ao
1235            )
1236          )
1237          if (
1238               $s > 59
1239            || $s < 0
1240            || $5 > 59
1241            || $5 < 0
1242            || $4 > 23
1243            || $4 < 0
1244            || $2 > 12
1245            || $2 < 1
1246            || $3 < 1
1247            || ( MT::Util::days_in( $2, $1 ) < $3
1248                && !MT::Util::leap_day( $0, $1, $2 ) )
1249          );
1250        if ($obj->authored_on) {
1251            $previous_old = $obj->previous(1);
1252            $next_old     = $obj->next(1);
1253        }
1254        my $ts = sprintf "%04d%02d%02d%02d%02d%02d", $1, $2, $3, $4, $5, $s;
1255        $obj->authored_on($ts);
1256    }
1257    my $is_new = $obj->id ? 0 : 1;
1258
1259    $app->_translate_naughty_words($obj);
1260
1261    $obj->modified_by( $author->id ) unless $is_new;
1262
1263    $app->run_callbacks( 'cms_pre_save.' . $type, $app, $obj, $orig_obj )
1264      || return $app->error(
1265        $app->translate(
1266            "Saving [_1] failed: [_2]",
1267            $class->class_label, $app->errstr
1268        )
1269      );
1270
1271    $obj->save
1272      or return $app->error(
1273        $app->translate(
1274            "Saving [_1] failed: [_2]",
1275            $class->class_label, $obj->errstr
1276        )
1277      );
1278
1279    my $message;
1280    if ($is_new) {
1281        $message =
1282          $app->translate( "[_1] '[_2]' (ID:[_3]) added by user '[_4]'",
1283            $class->class_label, $obj->title, $obj->id, $author->name );
1284    }
1285    elsif ( $orig_obj->status ne $obj->status ) {
1286        $message = $app->translate(
1287"[_1] '[_2]' (ID:[_3]) edited and its status changed from [_4] to [_5] by user '[_6]'",
1288            $class->class_label,
1289            $obj->title,
1290            $obj->id,
1291            $app->translate( MT::Entry::status_text( $orig_obj->status ) ),
1292            $app->translate( MT::Entry::status_text( $obj->status ) ),
1293            $author->name
1294        );
1295
1296    }
1297    else {
1298        $message =
1299          $app->translate( "[_1] '[_2]' (ID:[_3]) edited by user '[_4]'",
1300            $class->class_label, $obj->title, $obj->id, $author->name );
1301    }
1302    require MT::Log;
1303    $app->log(
1304        {
1305            message => $message,
1306            level   => MT::Log::INFO(),
1307            class   => $type,
1308            $is_new ? ( category => 'new' ) : ( category => 'edit' ),
1309            metadata => $obj->id
1310        }
1311    );
1312
1313    my $error_string = MT::callback_errstr();
1314
1315    ## Now that the object is saved, we can be certain that it has an
1316    ## ID. So we can now add/update/remove the primary placement.
1317    require MT::Placement;
1318    my $place =
1319      MT::Placement->load( { entry_id => $obj->id, is_primary => 1 } );
1320    if ($cat_id) {
1321        unless ($place) {
1322            $place = MT::Placement->new;
1323            $place->entry_id( $obj->id );
1324            $place->blog_id( $obj->blog_id );
1325            $place->is_primary(1);
1326        }
1327        $place->category_id($cat_id);
1328        $place->save;
1329    }
1330    else {
1331        if ( $place ) {
1332            $place->remove;
1333        }
1334    }
1335
1336    my $placements_updated;
1337
1338    # save secondary placements...
1339    my @place = MT::Placement->load(
1340        {
1341            entry_id   => $obj->id,
1342            is_primary => 0
1343        }
1344    );
1345    for my $place (@place) {
1346        $place->remove;
1347        $placements_updated = 1;
1348    }
1349    for my $cat_id (@add_cat) {
1350        my $cat = $cat_class->load($cat_id);
1351
1352        # blog_id sanity check
1353        next if $cat->blog_id != $obj->blog_id;
1354
1355        my $place = MT::Placement->new;
1356        $place->entry_id( $obj->id );
1357        $place->blog_id( $obj->blog_id );
1358        $place->is_primary(0);
1359        $place->category_id($cat_id);
1360        $place->save
1361          or return $app->error(
1362            $app->translate( "Saving placement failed: [_1]", $place->errstr )
1363          );
1364        $placements_updated = 1;
1365    }
1366
1367    $app->run_callbacks( 'cms_post_save.' . $type, $app, $obj, $orig_obj );
1368
1369    ## If the saved status is RELEASE, or if the *previous* status was
1370    ## RELEASE, then rebuild entry archives, indexes, and send the
1371    ## XML-RPC ping(s). Otherwise the status was and is HOLD, and we
1372    ## don't have to do anything.
1373    if ( ( $obj->status || 0 ) == MT::Entry::RELEASE()
1374        || $status_old eq MT::Entry::RELEASE() )
1375    {
1376        if ( $app->config('DeleteFilesAtRebuild') && $orig_obj ) {
1377            my $file = archive_file_for( $obj, $blog, $archive_type );
1378            if ( $file ne $orig_file || $obj->status != MT::Entry::RELEASE() ) {
1379                $app->publisher->remove_entry_archive_file(
1380                    Entry       => $orig_obj,
1381                    ArchiveType => $archive_type
1382                );
1383            }
1384        }
1385
1386        # If there are no static pages, just rebuild indexes.
1387        if ( $blog->count_static_templates($archive_type) == 0
1388            || MT::Util->launch_background_tasks() )
1389        {
1390            my $res = MT::Util::start_background_task(
1391                sub {
1392                    $app->rebuild_entry(
1393                        Entry             => $obj,
1394                        BuildDependencies => 1,
1395                        OldEntry          => $orig_obj,
1396                        OldPrevious       => ($previous_old)
1397                        ? $previous_old->id
1398                        : undef,
1399                        OldNext => ($next_old) ? $next_old->id : undef
1400                    ) or return $app->publish_error();
1401                    $app->run_callbacks( 'rebuild', $blog );
1402                    1;
1403                }
1404            );
1405            return unless $res;
1406            return ping_continuation($app,
1407                $obj, $blog,
1408                OldStatus => $status_old,
1409                IsNew     => $is_new,
1410            );
1411        }
1412        else {
1413            return $app->redirect(
1414                $app->uri(
1415                    'mode' => 'start_rebuild',
1416                    args   => {
1417                        blog_id    => $obj->blog_id,
1418                        'next'     => 0,
1419                        type       => 'entry-' . $obj->id,
1420                        entry_id   => $obj->id,
1421                        is_new     => $is_new,
1422                        old_status => $status_old,
1423                        (
1424                            $previous_old
1425                            ? ( old_previous => $previous_old->id )
1426                            : ()
1427                        ),
1428                        ( $next_old ? ( old_next => $next_old->id ) : () )
1429                    }
1430                )
1431            );
1432        }
1433    }
1434    _finish_rebuild_ping( $app, $obj, !$id );
1435}
1436
1437sub save_entries {
1438    my $app   = shift;
1439    my $perms = $app->permissions;
1440    my $type  = $app->param('_type');
1441    return $app->errtrans("Permission denied.")
1442      unless $perms
1443      && (
1444        $type eq 'page'
1445        ? ( $perms->can_manage_pages )
1446        : (      $perms->can_publish_post
1447              || $perms->can_create_post
1448              || $perms->can_edit_all_posts )
1449      );
1450
1451    $app->validate_magic() or return;
1452
1453    my $q = $app->param;
1454    my @p = $q->param;
1455    require MT::Entry;
1456    require MT::Placement;
1457    require MT::Log;
1458    my $blog_id        = $q->param('blog_id');
1459    my $this_author    = $app->user;
1460    my $this_author_id = $this_author->id;
1461    for my $p (@p) {
1462        next unless $p =~ /^category_id_(\d+)/;
1463        my $id    = $1;
1464        my $entry = MT::Entry->load($id);
1465        return $app->error( $app->translate("Permission denied.") )
1466            unless $perms
1467              && (
1468                $type eq 'page'
1469                ? ( $perms->can_manage_pages )
1470                : (      $perms->can_publish_post
1471                      || $perms->can_create_post
1472                      || $perms->can_edit_all_posts )
1473              );
1474        my $orig_obj = $entry->clone;
1475        if ( $perms->can_edit_entry( $entry, $this_author ) ) {
1476            my $author_id = $q->param( 'author_id_' . $id );
1477            $entry->author_id( $author_id ? $author_id : 0 );
1478            $entry->title( scalar $q->param( 'title_' . $id ) );
1479        }
1480        if ( $perms->can_edit_entry( $entry, $this_author, 1 ) )
1481        {    ## can he/she change status?
1482            $entry->status( scalar $q->param( 'status_' . $id ) );
1483            my $co = $q->param( 'created_on_' . $id );
1484            unless ( $co =~
1485                m!(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2})(?::(\d{2}))?! )
1486            {
1487                return $app->error(
1488                    $app->translate(
1489"Invalid date '[_1]'; authored on dates must be in the format YYYY-MM-DD HH:MM:SS.",
1490                        $co
1491                    )
1492                );
1493            }
1494            my $s = $6 || 0;
1495
1496            # Emit an error message if the date is bogus.
1497            return $app->error(
1498                $app->translate(
1499"Invalid date '[_1]'; authored on dates should be real dates.",
1500                    $co
1501                )
1502              )
1503              if $s > 59
1504              || $s < 0
1505              || $5 > 59
1506              || $5 < 0
1507              || $4 > 23
1508              || $4 < 0
1509              || $2 > 12
1510              || $2 < 1
1511              || $3 < 1
1512              || ( MT::Util::days_in( $2, $1 ) < $3
1513                && !MT::Util::leap_day( $0, $1, $2 ) );
1514
1515            # FIXME: Should be assigning the publish_date field here
1516            my $ts = sprintf "%04d%02d%02d%02d%02d%02d", $1, $2, $3, $4, $5, $s;
1517            if ($type eq 'page' ) {
1518                $entry->modified_on($ts);
1519            } else {
1520                $entry->authored_on($ts);
1521            }
1522        }
1523        $app->run_callbacks( 'cms_pre_save.' . $type, $app, $entry, $orig_obj )
1524          || return $app->error(
1525            $app->translate(
1526                "Saving [_1] failed: [_2]",
1527                $entry->class_label, $app->errstr
1528            )
1529          );
1530        $entry->save
1531          or return $app->error(
1532            $app->translate(
1533                "Saving entry '[_1]' failed: [_2]", $entry->title,
1534                $entry->errstr
1535            )
1536          );
1537        my $cat_id = $q->param("category_id_$id");
1538        my $place  = MT::Placement->load(
1539            {
1540                entry_id   => $id,
1541                is_primary => 1
1542            }
1543        );
1544        if ( $place && !$cat_id ) {
1545            $place->remove
1546              or return $app->error(
1547                $app->translate(
1548                    "Removing placement failed: [_1]",
1549                    $place->errstr
1550                )
1551              );
1552        }
1553        elsif ($cat_id) {
1554            unless ($place) {
1555                $place = MT::Placement->new;
1556                $place->entry_id($id);
1557                $place->blog_id($blog_id);
1558                $place->is_primary(1);
1559            }
1560            $place->category_id( scalar $q->param($p) );
1561            $place->save
1562              or return $app->error(
1563                $app->translate(
1564                    "Saving placement failed: [_1]",
1565                    $place->errstr
1566                )
1567              );
1568        }
1569        my $message;
1570        if ( $orig_obj->status ne $entry->status ) {
1571            $message = $app->translate(
1572"[_1] '[_2]' (ID:[_3]) edited and its status changed from [_4] to [_5] by user '[_6]'",
1573                $entry->class_label,
1574                $entry->title,
1575                $entry->id,
1576                $app->translate( MT::Entry::status_text( $orig_obj->status ) ),
1577                $app->translate( MT::Entry::status_text( $entry->status ) ),
1578                $this_author->name
1579            );
1580        }
1581        else {
1582            $message =
1583              $app->translate( "[_1] '[_2]' (ID:[_3]) edited by user '[_4]'",
1584                $entry->class_label, $entry->title, $entry->id,
1585                $this_author->name );
1586        }
1587        $app->log(
1588            {
1589                message  => $message,
1590                level    => MT::Log::INFO(),
1591                class    => $entry->class,
1592                category => 'edit',
1593                metadata => $entry->id
1594            }
1595        );
1596        $app->run_callbacks( 'cms_post_save.' . $type, $app, $entry, $orig_obj );
1597    }
1598    $app->add_return_arg( 'saved' => 1, is_power_edit => 1 );
1599    $app->call_return;
1600}
1601
1602sub send_pings {
1603    my $app = shift;
1604    my $q   = $app->param;
1605    $app->validate_magic() or return;
1606    require MT::Entry;
1607    require MT::Blog;
1608    my $blog  = MT::Blog->load( scalar $q->param('blog_id') );
1609    my $entry = MT::Entry->load( scalar $q->param('entry_id') );
1610    ## MT::ping_and_save pings each of the necessary URLs, then processes
1611    ## the return value from MT::ping to update the list of URLs pinged
1612    ## and not successfully pinged. It returns the return value from
1613    ## MT::ping for further processing. If a fatal error occurs, it returns
1614    ## undef.
1615    my $results = $app->ping_and_save(
1616        Blog      => $blog,
1617        Entry     => $entry,
1618        OldStatus => scalar $q->param('old_status')
1619    ) or return;
1620    my $has_errors = 0;
1621    require MT::Log;
1622    for my $res (@$results) {
1623        $has_errors++,
1624          $app->log(
1625            {
1626                message => $app->translate(
1627                    "Ping '[_1]' failed: [_2]",
1628                    $res->{url},
1629                    encode_text( $res->{error}, undef, undef )
1630                ),
1631                class => 'system',
1632                level => MT::Log::WARNING()
1633            }
1634          ) unless $res->{good};
1635    }
1636    _finish_rebuild_ping( $app, $entry, scalar $q->param('is_new'),
1637        $has_errors );
1638}
1639
1640sub entry_notify {
1641    my $app   = shift;
1642    my $user  = $app->user;
1643    my $perms = $app->permissions;
1644    return $app->error( $app->translate("No permissions.") )
1645      unless $perms->can_send_notifications;
1646
1647    my $q        = $app->param;
1648    my $entry_id = $q->param('entry_id')
1649      or return $app->error( $app->translate("No entry ID provided") );
1650    require MT::Entry;
1651    require MT::Blog;
1652    my $entry = MT::Entry->load($entry_id)
1653      or return $app->error(
1654        $app->translate( "No such entry '[_1]'", $entry_id ) );
1655    my $blog  = MT::Blog->load( $entry->blog_id );
1656    my $param = {};
1657    $param->{entry_id} = $entry_id;
1658    return $app->load_tmpl( "dialog/entry_notify.tmpl", $param );
1659}
1660
1661sub send_notify {
1662    my $app = shift;
1663    $app->validate_magic() or return;
1664    my $q        = $app->param;
1665    my $entry_id = $q->param('entry_id')
1666      or return $app->error( $app->translate("No entry ID provided") );
1667    require MT::Entry;
1668    require MT::Blog;
1669    my $entry = MT::Entry->load($entry_id)
1670      or return $app->error(
1671        $app->translate( "No such entry '[_1]'", $entry_id ) );
1672    my $blog = MT::Blog->load( $entry->blog_id );
1673
1674    my $user = $app->user;
1675    $app->blog($blog);
1676    my $perms = $user->permissions($blog);
1677    return $app->error( $app->translate("No permissions.") )
1678      unless $perms->can_send_notifications;
1679
1680    my $author = $entry->author;
1681    return $app->error(
1682        $app->translate( "No email address for user '[_1]'", $author->name ) )
1683      unless $author->email;
1684
1685    my $cols = 72;
1686    my %params;
1687    $params{blog} = $blog;
1688    $params{entry} = $entry;
1689    $params{author} = $author;
1690
1691    if ( $q->param('send_excerpt') ) {
1692        $params{send_excerpt} = 1;
1693    }
1694    $params{message} = wrap_text( $q->param('message'), $cols, '', '' );
1695    if ( $q->param('send_body') ) {
1696        $params{send_body} = 1;
1697    }
1698
1699    my $entry_editurl = $app->uri(
1700        'mode' => 'view',
1701        args   => {
1702            '_type' => 'entry',
1703            blog_id => $entry->blog_id,
1704            id      => $entry->id,
1705        }
1706    );
1707    if ( $entry_editurl =~ m|^/| ) {
1708        my ($blog_domain) = $blog->archive_url =~ m|(.+://[^/]+)|;
1709        $entry_editurl = $blog_domain . $entry_editurl;
1710    }
1711    $params{entry_editurl} = $entry_editurl;
1712
1713    my $addrs;
1714    if ( $q->param('send_notify_list') ) {
1715        require MT::Notification;
1716        my $iter = MT::Notification->load_iter( { blog_id => $blog->id } );
1717        while ( my $note = $iter->() ) {
1718            next unless is_valid_email( $note->email );
1719            $addrs->{ $note->email } = 1;
1720        }
1721    }
1722
1723    if ( $q->param('send_notify_emails') ) {
1724        my @addr = split /[\n\r,]+/, $q->param('send_notify_emails');
1725        for my $a (@addr) {
1726            next unless is_valid_email($a);
1727            $addrs->{$a} = 1;
1728        }
1729    }
1730
1731    keys %$addrs
1732      or return $app->error(
1733        $app->translate(
1734            "No valid recipients found for the entry notification.")
1735      );
1736
1737    my $body = $app->build_email( 'notify-entry.tmpl', \%params );
1738
1739    my $subj =
1740      $app->translate( "[_1] Update: [_2]", $blog->name, $entry->title );
1741    if ( $app->current_language ne 'ja' ) {    # FIXME perhaps move to MT::I18N
1742        $subj =~ s![\x80-\xFF]!!g;
1743    }
1744    my $address =
1745      defined $author->nickname
1746      ? $author->nickname . ' <' . $author->email . '>'
1747      : $author->email;
1748    my %head = (
1749        id      => 'notify_entry',
1750        To      => $address,
1751        From    => $address,
1752        Subject => $subj,
1753    );
1754    my $charset = $app->config('MailEncoding')
1755      || $app->charset;
1756    $head{'Content-Type'} = qq(text/plain; charset="$charset");
1757    my $i = 1;
1758    require MT::Mail;
1759    MT::Mail->send( \%head, $body )
1760      or return $app->error(
1761        $app->translate(
1762            "Error sending mail ([_1]); try another MailTransfer setting?",
1763            MT::Mail->errstr
1764        )
1765      );
1766    delete $head{To};
1767
1768    foreach my $email ( keys %{$addrs} ) {
1769        next unless $email;
1770        if ( $app->config('EmailNotificationBcc') ) {
1771            push @{ $head{Bcc} }, $email;
1772            if ( $i++ % 20 == 0 ) {
1773                MT::Mail->send( \%head, $body )
1774                  or return $app->error(
1775                    $app->translate(
1776"Error sending mail ([_1]); try another MailTransfer setting?",
1777                        MT::Mail->errstr
1778                    )
1779                  );
1780                @{ $head{Bcc} } = ();
1781            }
1782        }
1783        else {
1784            $head{To} = $email;
1785            MT::Mail->send( \%head, $body )
1786              or return $app->error(
1787                $app->translate(
1788"Error sending mail ([_1]); try another MailTransfer setting?",
1789                    MT::Mail->errstr
1790                )
1791              );
1792            delete $head{To};
1793        }
1794    }
1795    if ( $head{Bcc} && @{ $head{Bcc} } ) {
1796        MT::Mail->send( \%head, $body )
1797          or return $app->error(
1798            $app->translate(
1799                "Error sending mail ([_1]); try another MailTransfer setting?",
1800                MT::Mail->errstr
1801            )
1802          );
1803    }
1804    $app->redirect(
1805        $app->uri(
1806            'mode' => 'view',
1807            args   => {
1808                '_type'      => $entry->class,
1809                blog_id      => $entry->blog_id,
1810                id           => $entry->id,
1811                saved_notify => 1
1812            }
1813        )
1814    );
1815}
1816
1817sub pinged_urls {
1818    my $app   = shift;
1819    my $perms = $app->permissions
1820      or return $app->error( $app->translate("No permissions") );
1821    my %param;
1822    my $entry_id = $app->param('entry_id');
1823    require MT::Entry;
1824    my $entry = MT::Entry->load($entry_id);
1825    $param{url_loop} = [ map { { url => $_ } } @{ $entry->pinged_url_list } ];
1826    $param{failed_url_loop} =
1827      [ map { { url => $_ } }
1828          @{ $entry->pinged_url_list( OnlyFailures => 1 ) } ];
1829    $app->load_tmpl( 'popup/pinged_urls.tmpl', \%param );
1830}
1831
1832sub save_entry_prefs {
1833    my $app   = shift;
1834    my $perms = $app->permissions
1835      or return $app->error( $app->translate("No permissions") );
1836    $app->validate_magic() or return;
1837    my $q     = $app->param;
1838    my $prefs = $app->_entry_prefs_from_params;
1839    $perms->entry_prefs($prefs);
1840    $perms->save
1841      or return $app->error(
1842        $app->translate( "Saving permissions failed: [_1]", $perms->errstr ) );
1843    $app->send_http_header("text/json");
1844    return "true";
1845}
1846
1847sub publish_entries {
1848    my $app = shift;
1849    require MT::Entry;
1850    update_entry_status( $app, MT::Entry::RELEASE(), $app->param('id') );
1851}
1852
1853sub draft_entries {
1854    my $app = shift;
1855    require MT::Entry;
1856    update_entry_status( $app, MT::Entry::HOLD(), $app->param('id') );
1857}
1858
1859sub open_batch_editor {
1860    my $app = shift;
1861    my @ids = $app->param('id');
1862
1863    $app->param( 'is_power_edit', 1 );
1864    $app->param( 'filter',        'power_edit' );
1865    $app->param( 'filter_val',    \@ids );
1866    $app->mode(
1867        'list_' . ( 'entry' eq $app->param('_type') ? 'entries' : 'pages' ) );
1868    $app->forward( "list_entry", { type => $app->param('_type') } );
1869}
1870
1871sub build_entry_table {
1872    my $app = shift;
1873    my (%args) = @_;
1874
1875    my $app_author = $app->user;
1876    my $perms      = $app->permissions;
1877    my $type       = $args{type};
1878    my $class      = $app->model($type);
1879
1880    my $list_pref = $app->list_pref($type);
1881    if ( $args{is_power_edit} ) {
1882        delete $list_pref->{view_expanded};
1883    }
1884    my $iter;
1885    if ( $args{load_args} ) {
1886        $iter = $class->load_iter( @{ $args{load_args} } );
1887    }
1888    elsif ( $args{iter} ) {
1889        $iter = $args{iter};
1890    }
1891    elsif ( $args{items} ) {
1892        $iter = sub { shift @{ $args{items} } };
1893    }
1894    return [] unless $iter;
1895    my $limit         = $args{limit};
1896    my $is_power_edit = $args{is_power_edit} || 0;
1897    my $param         = $args{param} || {};
1898
1899    ## Load list of categories for display in filter pulldown (and selection
1900    ## pulldown on power edit page).
1901    my ( $c_data, %cats );
1902    my $blog_id = $app->param('blog_id');
1903    if ($blog_id) {
1904        $c_data = $app->_build_category_list(
1905            blog_id => $blog_id,
1906            type    => $class->container_type,
1907        );
1908        my $i = 0;
1909        for my $row (@$c_data) {
1910            $row->{category_index} = $i++;
1911            my $spacer = $row->{category_label_spacer} || '';
1912            $spacer =~ s/\&nbsp;/\\u00A0/g;
1913            $row->{category_label_js} =
1914              $spacer . encode_js( $row->{category_label} );
1915            $cats{ $row->{category_id} } = $row;
1916        }
1917        $param->{category_loop} = $c_data;
1918    }
1919
1920    my ( $date_format, $datetime_format );
1921
1922    if ($is_power_edit) {
1923        $date_format          = "%Y.%m.%d";
1924        $datetime_format      = "%Y-%m-%d %H:%M:%S";
1925    }
1926    else {
1927        $date_format     = MT::App::CMS::LISTING_DATE_FORMAT();
1928        $datetime_format = MT::App::CMS::LISTING_DATETIME_FORMAT();
1929    }
1930
1931    my @cat_list;
1932    if ($is_power_edit) {
1933        @cat_list =
1934          sort { $cats{$a}->{category_index} <=> $cats{$b}->{category_index} }
1935          keys %cats;
1936    }
1937
1938    my @data;
1939    my %blogs;
1940    require MT::Blog;
1941    my $title_max_len   = const('DISPLAY_LENGTH_EDIT_ENTRY_TITLE');
1942    my $excerpt_max_len = const('DISPLAY_LENGTH_EDIT_ENTRY_TEXT_FROM_EXCERPT');
1943    my $text_max_len    = const('DISPLAY_LENGTH_EDIT_ENTRY_TEXT_BREAK_UP');
1944    my %blog_perms;
1945    $blog_perms{ $perms->blog_id } = $perms if $perms;
1946    while ( my $obj = $iter->() ) {
1947        my $blog_perms;
1948        if ( !$app_author->is_superuser() ) {
1949            $blog_perms = $blog_perms{ $obj->blog_id }
1950              || $app_author->blog_perm( $obj->blog_id );
1951        }
1952
1953        my $row = $obj->column_values;
1954        $row->{text} ||= '';
1955        if ( my $ts =
1956            ( $type eq 'page' ) ? $obj->modified_on : $obj->authored_on )
1957        {
1958            $row->{created_on_formatted} =
1959              format_ts( $date_format, $ts, $obj->blog, $app->user ? $app->user->preferred_language : undef );
1960            $row->{created_on_time_formatted} =
1961              format_ts( $datetime_format, $ts, $obj->blog, $app->user ? $app->user->preferred_language : undef );
1962            $row->{created_on_relative} =
1963              relative_date( $ts, time, $obj->blog );
1964        }
1965        my $author = $obj->author;
1966        $row->{author_name} =
1967          $author ? $author->name : $app->translate('(user deleted)');
1968        if ( my $cat = $obj->category ) {
1969            $row->{category_label}    = $cat->label;
1970            $row->{category_basename} = $cat->basename;
1971        }
1972        else {
1973            $row->{category_label}    = '';
1974            $row->{category_basename} = '';
1975        }
1976        $row->{file_extension} = $obj->blog ? $obj->blog->file_extension : '';
1977        $row->{title_short} = $obj->title;
1978        if ( !defined( $row->{title_short} ) || $row->{title_short} eq '' ) {
1979            my $title = remove_html( $obj->text );
1980            $row->{title_short} =
1981              substr_text( defined($title) ? $title : "", 0, $title_max_len )
1982              . '...';
1983        }
1984        else {
1985            $row->{title_short} = remove_html( $row->{title_short} );
1986            $row->{title_short} =
1987              substr_text( $row->{title_short}, 0, $title_max_len + 3 ) . '...'
1988              if length_text( $row->{title_short} ) > $title_max_len;
1989        }
1990        if ( $row->{excerpt} ) {
1991            $row->{excerpt} = remove_html( $row->{excerpt} );
1992        }
1993        if ( !$row->{excerpt} ) {
1994            my $text = remove_html( $row->{text} ) || '';
1995            $row->{excerpt} = first_n_text( $text, $excerpt_max_len );
1996            if ( length($text) > length( $row->{excerpt} ) ) {
1997                $row->{excerpt} .= ' ...';
1998            }
1999        }
2000        $row->{text} = break_up_text( $row->{text}, $text_max_len )
2001          if $row->{text};
2002        $row->{title_long} = remove_html( $obj->title );
2003        $row->{status_text} =
2004          $app->translate( MT::Entry::status_text( $obj->status ) );
2005        $row->{ "status_" . MT::Entry::status_text( $obj->status ) } = 1;
2006        $row->{has_edit_access} = $app_author->is_superuser
2007          || ( ( 'entry' eq $type )
2008            && $blog_perms
2009            && $blog_perms->can_edit_entry( $obj, $app_author ) )
2010          || ( ( 'page' eq $type )
2011            && $blog_perms
2012            && $blog_perms->can_manage_pages );
2013        if ($is_power_edit) {
2014            $row->{has_publish_access} = $app_author->is_superuser
2015              || ( ( 'entry' eq $type )
2016                && $blog_perms
2017                && $blog_perms->can_edit_entry( $obj, $app_author, 1 ) )
2018              || ( ( 'page' eq $type )
2019                && $blog_perms
2020                && $blog_perms->can_manage_pages );
2021            $row->{is_editable} = $row->{has_edit_access};
2022
2023            ## This is annoying. In order to generate and pre-select the
2024            ## category, user, and status pull down menus, we need to
2025            ## have a separate *copy* of the list of categories and
2026            ## users for every entry listed, so that each row in the list
2027            ## can "know" whether it is selected for this entry or not.
2028            my @this_c_data;
2029            my $this_category_id = $obj->category ? $obj->category->id : undef;
2030            for my $c_id (@cat_list) {
2031                push @this_c_data, { %{ $cats{$c_id} } };
2032                $this_c_data[-1]{category_is_selected} = $this_category_id
2033                  && $this_category_id == $c_id ? 1 : 0;
2034            }
2035            $row->{row_category_loop} = \@this_c_data;
2036
2037            if ( $obj->author ) {
2038                $row->{row_author_name} = $obj->author->name;
2039                $row->{row_author_id}   = $obj->author->id;
2040            } else {
2041                $row->{row_author_name} = $app->translate(
2042                    '(user deleted - ID:[_1])',
2043                    $obj->author_id
2044                );
2045                $row->{row_author_id} = $obj->author_id,
2046             }
2047        }
2048        if ( my $blog = $blogs{ $obj->blog_id } ||=
2049            MT::Blog->load( $obj->blog_id ) )
2050        {
2051            $row->{weblog_id}   = $blog->id;
2052            $row->{weblog_name} = $blog->name;
2053        }
2054        if ( $obj->status == MT::Entry::RELEASE() ) {
2055            $row->{entry_permalink} = $obj->permalink;
2056        }
2057        $row->{object} = $obj;
2058        push @data, $row;
2059    }
2060    return [] unless @data;
2061
2062    $param->{entry_table}[0] = {%$list_pref};
2063    $param->{object_loop} = $param->{entry_table}[0]{object_loop} = \@data;
2064    $app->load_list_actions( $type, \%$param )
2065      unless $is_power_edit;
2066    \@data;
2067}
2068
2069sub quickpost_js {
2070    my $app     = shift;
2071    my ($type)  = @_;
2072    my $blog_id = $app->blog->id;
2073    my $blog    = $app->model('blog')->load($blog_id);
2074    my %args    = ( '_type' => $type, blog_id => $blog_id, qp => 1 );
2075    my $uri = $app->base . $app->uri( 'mode' => 'view', args => \%args );
2076    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'))!;
2077    # Translate the phrase here to avoid ActivePerl DLL bug.
2078    $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);
2079}
2080
2081sub can_view {
2082    my ( $eh, $app, $id, $objp ) = @_;
2083    my $perms = $app->permissions;
2084    if (   !$id
2085        && !$perms->can_create_post )
2086    {
2087        return 0;
2088    }
2089    if ($id) {
2090        my $obj = $objp->force();
2091        if ( !$perms->can_edit_entry( $obj, $app->user ) ) {
2092            return 0;
2093        }
2094    }
2095    1;
2096}
2097
2098sub can_delete {
2099    my ( $eh, $app, $obj ) = @_;
2100    my $author = $app->user;
2101    return 1 if $author->is_superuser();
2102    my $perms = $app->permissions;
2103    if ( !$perms || $perms->blog_id != $obj->blog_id ) {
2104        $perms ||= $author->permissions( $obj->blog_id );
2105    }
2106    return $perms && $perms->can_edit_entry( $obj, $author );
2107}
2108
2109sub pre_save {
2110    my $eh = shift;
2111    my ( $app, $obj ) = @_;
2112
2113    # save tags
2114    my $tags = $app->param('tags');
2115    if ( defined $tags ) {
2116        my $blog = $app->blog;
2117        my $fields = $blog->smart_replace_fields;
2118        if ( $fields =~ m/tags/ig ) {
2119            $tags = MT::App::CMS::_convert_word_chars( $app, $tags );
2120        }
2121
2122        require MT::Tag;
2123        my $tag_delim = chr( $app->user->entry_prefs->{tag_delim} );
2124        my @tags = MT::Tag->split( $tag_delim, $tags );
2125        if (@tags) {
2126            $obj->set_tags(@tags);
2127        }
2128        else {
2129            $obj->remove_tags();
2130        }
2131    }
2132
2133    # update text heights if necessary
2134    if ( my $perms = $app->permissions ) {
2135        my $prefs = $perms->entry_prefs || $app->load_default_entry_prefs;
2136        my $text_height = $app->param('text_height');
2137        if ( defined $text_height ) {
2138            my ($pref_text_height) = $prefs =~ m/\bbody:(\d+)\b/;
2139            $pref_text_height ||= 0;
2140            if ( $text_height != $pref_text_height ) {
2141                if ( $prefs =~ m/\bbody\b/ ) {
2142                    $prefs =~ s/\bbody(:\d+)\b/body:$text_height/;
2143                }
2144                else {
2145                    $prefs = 'body:' . $text_height . ',' . $prefs;
2146                }
2147            }
2148        }
2149        if ( $prefs ne ( $perms->entry_prefs || '' ) ) {
2150            $perms->entry_prefs($prefs);
2151            $perms->save;
2152        }
2153    }
2154    $obj->discover_tb_from_entry();
2155    1;
2156}
2157
2158sub post_save {
2159    my $eh = shift;
2160    my ( $app, $obj ) = @_;
2161    my $sess_obj = $app->autosave_session_obj;
2162    $sess_obj->remove if $sess_obj;
2163    1;
2164}
2165
2166sub post_delete {
2167    my ( $eh, $app, $obj ) = @_;
2168
2169    my $sess_obj = $app->autosave_session_obj;
2170    $sess_obj->remove if $sess_obj;
2171
2172    $app->log(
2173        {
2174            message => $app->translate(
2175                "Entry '[_1]' (ID:[_2]) deleted by '[_3]'",
2176                $obj->title, $obj->id, $app->user->name
2177            ),
2178            level    => MT::Log::INFO(),
2179            class    => 'system',
2180            category => 'delete'
2181        }
2182    );
2183}
2184
2185sub update_entry_status {
2186    my $app = shift;
2187    my ( $new_status, @ids ) = @_;
2188    return $app->errtrans("Need a status to update entries")
2189      unless $new_status;
2190    return $app->errtrans("Need entries to update status")
2191      unless @ids;
2192    my @bad_ids;
2193    my %rebuild_these;
2194    require MT::Entry;
2195
2196    foreach my $id (@ids) {
2197        my $entry = MT::Entry->load($id)
2198          or return $app->errtrans(
2199            "One of the entries ([_1]) did not actually exist", $id );
2200        next if $entry->status == $new_status;
2201        if ( $app->config('DeleteFilesAtRebuild')
2202            && ( MT::Entry::RELEASE() eq $entry->status ) )
2203        {
2204            my $archive_type =
2205              $entry->class eq 'page'
2206              ? 'Page'
2207              : 'Individual';
2208            $app->publisher->remove_entry_archive_file(
2209                Entry       => $entry,
2210                ArchiveType => $archive_type
2211            );
2212        }
2213        my $old_status = $entry->status;
2214        $entry->status($new_status);
2215        $entry->save() and $rebuild_these{$id} = 1;
2216        my $message = $app->translate(
2217            "[_1] '[_2]' (ID:[_3]) status changed from [_4] to [_5]",
2218            $entry->class_label,
2219            $entry->title,
2220            $entry->id,
2221            $app->translate( MT::Entry::status_text($old_status) ),
2222            $app->translate( MT::Entry::status_text($new_status) )
2223        );
2224        $app->log(
2225            {
2226                message  => $message,
2227                level    => MT::Log::INFO(),
2228                class    => $entry->class,
2229                category => 'edit',
2230                metadata => $entry->id
2231            }
2232        );
2233    }
2234    $app->rebuild_these( \%rebuild_these, how => MT::App::CMS::NEW_PHASE() );
2235}
2236
2237sub _finish_rebuild_ping {
2238    my $app = shift;
2239    my ( $entry, $is_new, $ping_errors ) = @_;
2240    $app->redirect(
2241        $app->uri(
2242            'mode' => 'view',
2243            args   => {
2244                '_type' => $entry->class,
2245                blog_id => $entry->blog_id,
2246                id      => $entry->id,
2247                ( $is_new ? ( saved_added => 1 ) : ( saved_changes => 1 ) ),
2248                ( $ping_errors ? ( ping_errors => 1 ) : () )
2249            }
2250        )
2251    );
2252}
2253
2254sub ping_continuation {
2255    my $app = shift;
2256    my ( $entry, $blog, %options ) = @_;
2257    my $list = $app->needs_ping(
2258        Entry     => $entry,
2259        Blog      => $blog,
2260        OldStatus => $options{OldStatus}
2261    );
2262    require MT::Entry;
2263    if ( $entry->status == MT::Entry::RELEASE() && $list ) {
2264        my @urls = map { { url => $_ } } @$list;
2265        $app->load_tmpl(
2266            'pinging.tmpl',
2267            {
2268                blog_id    => $blog->id,
2269                entry_id   => $entry->id,
2270                old_status => $options{OldStatus},
2271                is_new     => $options{IsNew},
2272                url_list   => \@urls,
2273            }
2274        );
2275    }
2276    else {
2277        _finish_rebuild_ping( $app, $entry, $options{IsNew} );
2278    }
2279}
2280
2281sub delete {
2282    my $app = shift;
2283    $app->validate_magic() or return;
2284
2285    require MT::Blog;
2286    my $q       = $app->param;
2287    my $blog_id = $q->param('blog_id');
2288    my $blog    = MT::Blog->load($blog_id);
2289
2290    my $can_background =
2291        ( $blog->count_static_templates('Individual') == 0
2292            || MT::Util->launch_background_tasks() ) ? 1 : 0;
2293
2294    my %rebuild_recip;
2295    my $at = $blog->archive_type;
2296    my @at;
2297    if ( $at && $at ne 'None' ) {
2298        my @at_orig = split( /,/, $at );
2299        @at = grep { $_ ne 'Individual' && $_ ne 'Page' } @at_orig;
2300    }
2301
2302    for my $id ( $q->param('id') ) {
2303        my $class = $app->model("entry");
2304        my $obj   = $class->load($id);
2305        return $app->call_return unless $obj;
2306
2307        $app->run_callbacks( 'cms_delete_permission_filter.entry', $app, $obj )
2308          || return $app->error(
2309            $app->translate( "Permission denied: [_1]", $app->errstr() ) );
2310
2311        if (   $app->config('RebuildAtDelete')
2312            || $app->config('DeleteFilesAtRebuild') )
2313        {
2314            # Remove Induvidual archive file.
2315            if ( $app->config('DeleteFilesAtRebuild') ) {
2316                $app->publisher->remove_entry_archive_file( Entry => $obj, );
2317            }
2318
2319            for my $at (@at) {
2320                my $archiver = $app->publisher->archiver($at);
2321                next unless $archiver;
2322
2323                # Remove archive file if archive file has not entries.
2324                my $deleted = 0;
2325                if ( $app->config('DeleteFilesAtRebuild') ) {
2326                    my $count =
2327                        $archiver->can('archive_entries_count')
2328                      ? $archiver->archive_entries_count( $blog, $at, $obj )
2329                      : 0;
2330                    if ( $count == 1 ) {
2331                        $app->publisher->remove_entry_archive_file(
2332                            Entry       => $obj,
2333                            ArchiveType => $at
2334                        );
2335                        $deleted = 1;
2336                    }
2337                }
2338
2339                # Make rebuild recip
2340                if ( $app->config('DeleteFilesAtRebuild') ) {
2341                    next if $deleted;
2342
2343                    my ( $start, $end ) = $archiver->date_range( $obj->authored_on )
2344                        if $archiver->date_based() && $archiver->can('date_range');
2345
2346                    if ( $archiver->category_based() ) {
2347                        my $categories = $obj->categories();
2348                        for my $cat (@$categories) {
2349                            if ( $archiver->date_based() ) {
2350                                $rebuild_recip{$at}{ $cat->id }{ $start . $end }
2351                                  {'Start'} = $start;
2352                                $rebuild_recip{$at}{ $cat->id }{ $start . $end }
2353                                  {'End'} = $end;
2354                                $rebuild_recip{$at}{ $cat->id }{ $start . $end }
2355                                  {'File'} =
2356                                  MT::Util::archive_file_for( $obj, $blog, $at,
2357                                    $cat, undef, undef, undef );
2358                            }
2359                            else {
2360                                $rebuild_recip{$at}{ $cat->id }{id} = $cat->id;
2361                                $rebuild_recip{$at}{ $cat->id }{'File'} =
2362                                  MT::Util::archive_file_for( $obj, $blog, $at,
2363                                    $cat, undef, undef, undef );
2364                            }
2365                        }
2366                    }
2367                    elsif ( $archiver->author_based() ) {
2368                        if ( $archiver->date_based() ) {
2369                            $rebuild_recip{$at}{ $obj->author->id }{ $start . $end }
2370                              {'Start'} = $start;
2371                            $rebuild_recip{$at}{ $obj->author->id }{ $start . $end }
2372                              {'End'} = $end;
2373                            $rebuild_recip{$at}{ $obj->author->id }{ $start . $end }
2374                              {'File'} =
2375                              MT::Util::archive_file_for( $obj, $blog, $at, undef,
2376                                undef, undef, $obj->author );
2377                        }
2378                        else {
2379                            $rebuild_recip{$at}{ $obj->author->id }{id} =
2380                              $obj->author->id;
2381                            $rebuild_recip{$at}{ $obj->author->id }{'File'} =
2382                              MT::Util::archive_file_for( $obj, $blog, $at, undef,
2383                                undef, undef, $obj->author );
2384                        }
2385                    }
2386                    elsif ( $archiver->date_based() ) {
2387                        $rebuild_recip{$at}{ $start . $end }{'Start'} = $start;
2388                        $rebuild_recip{$at}{ $start . $end }{'End'}   = $end;
2389                        $rebuild_recip{$at}{ $start . $end }{'File'} =
2390                          MT::Util::archive_file_for( $obj, $blog, $at, undef,
2391                            undef, undef, undef );
2392                    }
2393                    if (