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

Revision 1741, 83.5 kB (checked in by bsmith, 20 months ago)

bugzid:75115 - remove 'main_template' variable

  • 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('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 $ao = $ao_d . ' ' . $ao_t;
1219        unless (
1220            $ao =~ m!^(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2})(?::(\d{2}))?$! )
1221        {
1222            return $app->error(
1223                $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        }
1229        my $s = $6 || 0;
1230        return $app->error(
1231            $app->translate(
1232                "Invalid date '[_1]'; authored on dates should be real dates.",
1233                $ao
1234            )
1235          )
1236          if (
1237               $s > 59
1238            || $s < 0
1239            || $5 > 59
1240            || $5 < 0
1241            || $4 > 23
1242            || $4 < 0
1243            || $2 > 12
1244            || $2 < 1
1245            || $3 < 1
1246            || ( MT::Util::days_in( $2, $1 ) < $3
1247                && !MT::Util::leap_day( $0, $1, $2 ) )
1248          );
1249        if ($obj->authored_on) {
1250            $previous_old = $obj->previous(1);
1251            $next_old     = $obj->next(1);
1252        }
1253        my $ts = sprintf "%04d%02d%02d%02d%02d%02d", $1, $2, $3, $4, $5, $s;
1254        $obj->authored_on($ts);
1255    }
1256    my $is_new = $obj->id ? 0 : 1;
1257
1258    $app->_translate_naughty_words($obj);
1259
1260    $obj->modified_by( $author->id ) unless $is_new;
1261
1262    $app->run_callbacks( 'cms_pre_save.' . $type, $app, $obj, $orig_obj )
1263      || return $app->error(
1264        $app->translate(
1265            "Saving [_1] failed: [_2]",
1266            $class->class_label, $app->errstr
1267        )
1268      );
1269
1270    $obj->save
1271      or return $app->error(
1272        $app->translate(
1273            "Saving [_1] failed: [_2]",
1274            $class->class_label, $obj->errstr
1275        )
1276      );
1277
1278    my $message;
1279    if ($is_new) {
1280        $message =
1281          $app->translate( "[_1] '[_2]' (ID:[_3]) added by user '[_4]'",
1282            $class->class_label, $obj->title, $obj->id, $author->name );
1283    }
1284    elsif ( $orig_obj->status ne $obj->status ) {
1285        $message = $app->translate(
1286"[_1] '[_2]' (ID:[_3]) edited and its status changed from [_4] to [_5] by user '[_6]'",
1287            $class->class_label,
1288            $obj->title,
1289            $obj->id,
1290            $app->translate( MT::Entry::status_text( $orig_obj->status ) ),
1291            $app->translate( MT::Entry::status_text( $obj->status ) ),
1292            $author->name
1293        );
1294
1295    }
1296    else {
1297        $message =
1298          $app->translate( "[_1] '[_2]' (ID:[_3]) edited by user '[_4]'",
1299            $class->class_label, $obj->title, $obj->id, $author->name );
1300    }
1301    require MT::Log;
1302    $app->log(
1303        {
1304            message => $message,
1305            level   => MT::Log::INFO(),
1306            class   => $type,
1307            $is_new ? ( category => 'new' ) : ( category => 'edit' ),
1308            metadata => $obj->id
1309        }
1310    );
1311
1312    my $error_string = MT::callback_errstr();
1313
1314    ## Now that the object is saved, we can be certain that it has an
1315    ## ID. So we can now add/update/remove the primary placement.
1316    require MT::Placement;
1317    my $place =
1318      MT::Placement->load( { entry_id => $obj->id, is_primary => 1 } );
1319    if ($cat_id) {
1320        unless ($place) {
1321            $place = MT::Placement->new;
1322            $place->entry_id( $obj->id );
1323            $place->blog_id( $obj->blog_id );
1324            $place->is_primary(1);
1325        }
1326        $place->category_id($cat_id);
1327        $place->save;
1328    }
1329    else {
1330        if ( $place ) {
1331            $place->remove;
1332        }
1333    }
1334
1335    my $placements_updated;
1336
1337    # save secondary placements...
1338    my @place = MT::Placement->load(
1339        {
1340            entry_id   => $obj->id,
1341            is_primary => 0
1342        }
1343    );
1344    for my $place (@place) {
1345        $place->remove;
1346        $placements_updated = 1;
1347    }
1348    for my $cat_id (@add_cat) {
1349        my $cat = $cat_class->load($cat_id);
1350
1351        # blog_id sanity check
1352        next if $cat->blog_id != $obj->blog_id;
1353
1354        my $place = MT::Placement->new;
1355        $place->entry_id( $obj->id );
1356        $place->blog_id( $obj->blog_id );
1357        $place->is_primary(0);
1358        $place->category_id($cat_id);
1359        $place->save
1360          or return $app->error(
1361            $app->translate( "Saving placement failed: [_1]", $place->errstr )
1362          );
1363        $placements_updated = 1;
1364    }
1365
1366    $app->run_callbacks( 'cms_post_save.' . $type, $app, $obj, $orig_obj );
1367
1368    ## If the saved status is RELEASE, or if the *previous* status was
1369    ## RELEASE, then rebuild entry archives, indexes, and send the
1370    ## XML-RPC ping(s). Otherwise the status was and is HOLD, and we
1371    ## don't have to do anything.
1372    if ( ( $obj->status || 0 ) == MT::Entry::RELEASE()
1373        || $status_old eq MT::Entry::RELEASE() )
1374    {
1375        if ( $app->config('DeleteFilesAtRebuild') && $orig_obj ) {
1376            my $file = archive_file_for( $obj, $blog, $archive_type );
1377            if ( $file ne $orig_file || $obj->status != MT::Entry::RELEASE() ) {
1378                $app->publisher->remove_entry_archive_file(
1379                    Entry       => $orig_obj,
1380                    ArchiveType => $archive_type
1381                );
1382            }
1383        }
1384
1385        # If there are no static pages, just rebuild indexes.
1386        if ( $blog->count_static_templates($archive_type) == 0
1387            || MT::Util->launch_background_tasks() )
1388        {
1389            my $res = MT::Util::start_background_task(
1390                sub {
1391                    $app->rebuild_entry(
1392                        Entry             => $obj,
1393                        BuildDependencies => 1,
1394                        OldEntry          => $orig_obj,
1395                        OldPrevious       => ($previous_old)
1396                        ? $previous_old->id
1397                        : undef,
1398                        OldNext => ($next_old) ? $next_old->id : undef
1399                    ) or return $app->publish_error();
1400                    $app->run_callbacks( 'rebuild', $blog );
1401                    1;
1402                }
1403            );
1404            return unless $res;
1405            return ping_continuation($app,
1406                $obj, $blog,
1407                OldStatus => $status_old,
1408                IsNew     => $is_new,
1409            );
1410        }
1411        else {
1412            return $app->redirect(
1413                $app->uri(
1414                    'mode' => 'start_rebuild',
1415                    args   => {
1416                        blog_id    => $obj->blog_id,
1417                        'next'     => 0,
1418                        type       => 'entry-' . $obj->id,
1419                        entry_id   => $obj->id,
1420                        is_new     => $is_new,
1421                        old_status => $status_old,
1422                        (
1423                            $previous_old
1424                            ? ( old_previous => $previous_old->id )
1425                            : ()
1426                        ),
1427                        ( $next_old ? ( old_next => $next_old->id ) : () )
1428                    }
1429                )
1430            );
1431        }
1432    }
1433    _finish_rebuild_ping( $app, $obj, !$id );
1434}
1435
1436sub save_entries {
1437    my $app   = shift;
1438    my $perms = $app->permissions;
1439    my $type  = $app->param('_type');
1440    return $app->errtrans("Permission denied.")
1441      unless $perms
1442      && (
1443        $type eq 'page'
1444        ? ( $perms->can_manage_pages )
1445        : (      $perms->can_publish_post
1446              || $perms->can_create_post
1447              || $perms->can_edit_all_posts )
1448      );
1449
1450    $app->validate_magic() or return;
1451
1452    my $q = $app->param;
1453    my @p = $q->param;
1454    require MT::Entry;
1455    require MT::Placement;
1456    require MT::Log;
1457    my $blog_id        = $q->param('blog_id');
1458    my $this_author    = $app->user;
1459    my $this_author_id = $this_author->id;
1460    for my $p (@p) {
1461        next unless $p =~ /^category_id_(\d+)/;
1462        my $id    = $1;
1463        my $entry = MT::Entry->load($id);
1464        return $app->error( $app->translate("Permission denied.") )
1465            unless $perms
1466              && (
1467                $type eq 'page'
1468                ? ( $perms->can_manage_pages )
1469                : (      $perms->can_publish_post
1470                      || $perms->can_create_post
1471                      || $perms->can_edit_all_posts )
1472              );
1473        my $orig_obj = $entry->clone;
1474        if ( $perms->can_edit_entry( $entry, $this_author ) ) {
1475            my $author_id = $q->param( 'author_id_' . $id );
1476            $entry->author_id( $author_id ? $author_id : 0 );
1477            $entry->title( scalar $q->param( 'title_' . $id ) );
1478        }
1479        if ( $perms->can_edit_entry( $entry, $this_author, 1 ) )
1480        {    ## can he/she change status?
1481            $entry->status( scalar $q->param( 'status_' . $id ) );
1482            my $co = $q->param( 'created_on_' . $id );
1483            unless ( $co =~
1484                m!(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2})(?::(\d{2}))?! )
1485            {
1486                return $app->error(
1487                    $app->translate(
1488"Invalid date '[_1]'; authored on dates must be in the format YYYY-MM-DD HH:MM:SS.",
1489                        $co
1490                    )
1491                );
1492            }
1493            my $s = $6 || 0;
1494
1495            # Emit an error message if the date is bogus.
1496            return $app->error(
1497                $app->translate(
1498"Invalid date '[_1]'; authored on dates should be real dates.",
1499                    $co
1500                )
1501              )
1502              if $s > 59
1503              || $s < 0
1504              || $5 > 59
1505              || $5 < 0
1506              || $4 > 23
1507              || $4 < 0
1508              || $2 > 12
1509              || $2 < 1
1510              || $3 < 1
1511              || ( MT::Util::days_in( $2, $1 ) < $3
1512                && !MT::Util::leap_day( $0, $1, $2 ) );
1513
1514            # FIXME: Should be assigning the publish_date field here
1515            my $ts = sprintf "%04d%02d%02d%02d%02d%02d", $1, $2, $3, $4, $5, $s;
1516            if ($type eq 'page' ) {
1517                $entry->modified_on($ts);
1518            } else {
1519                $entry->authored_on($ts);
1520            }
1521        }
1522        $app->run_callbacks( 'cms_pre_save.' . $type, $app, $entry, $orig_obj )
1523          || return $app->error(
1524            $app->translate(
1525                "Saving [_1] failed: [_2]",
1526                $entry->class_label, $app->errstr
1527            )
1528          );
1529        $entry->save
1530          or return $app->error(
1531            $app->translate(
1532                "Saving entry '[_1]' failed: [_2]", $entry->title,
1533                $entry->errstr
1534            )
1535          );
1536        my $cat_id = $q->param("category_id_$id");
1537        my $place  = MT::Placement->load(
1538            {
1539                entry_id   => $id,
1540                is_primary => 1
1541            }
1542        );
1543        if ( $place && !$cat_id ) {
1544            $place->remove
1545              or return $app->error(
1546                $app->translate(
1547                    "Removing placement failed: [_1]",
1548                    $place->errstr
1549                )
1550              );
1551        }
1552        elsif ($cat_id) {
1553            unless ($place) {
1554                $place = MT::Placement->new;
1555                $place->entry_id($id);
1556                $place->blog_id($blog_id);
1557                $place->is_primary(1);
1558            }
1559            $place->category_id( scalar $q->param($p) );
1560            $place->save
1561              or return $app->error(
1562                $app->translate(
1563                    "Saving placement failed: [_1]",
1564                    $place->errstr
1565                )
1566              );
1567        }
1568        my $message;
1569        if ( $orig_obj->status ne $entry->status ) {
1570            $message = $app->translate(
1571"[_1] '[_2]' (ID:[_3]) edited and its status changed from [_4] to [_5] by user '[_6]'",
1572                $entry->class_label,
1573                $entry->title,
1574                $entry->id,
1575                $app->translate( MT::Entry::status_text( $orig_obj->status ) ),
1576                $app->translate( MT::Entry::status_text( $entry->status ) ),
1577                $this_author->name
1578            );
1579        }
1580        else {
1581            $message =
1582              $app->translate( "[_1] '[_2]' (ID:[_3]) edited by user '[_4]'",
1583                $entry->class_label, $entry->title, $entry->id,
1584                $this_author->name );
1585        }
1586        $app->log(
1587            {
1588                message  => $message,
1589                level    => MT::Log::INFO(),
1590                class    => $entry->class,
1591                category => 'edit',
1592                metadata => $entry->id
1593            }
1594        );
1595        $app->run_callbacks( 'cms_post_save.' . $type, $app, $entry, $orig_obj );
1596    }
1597    $app->add_return_arg( 'saved' => 1, is_power_edit => 1 );
1598    $app->call_return;
1599}
1600
1601sub send_pings {
1602    my $app = shift;
1603    my $q   = $app->param;
1604    $app->validate_magic() or return;
1605    require MT::Entry;
1606    require MT::Blog;
1607    my $blog  = MT::Blog->load( scalar $q->param('blog_id') );
1608    my $entry = MT::Entry->load( scalar $q->param('entry_id') );
1609    ## MT::ping_and_save pings each of the necessary URLs, then processes
1610    ## the return value from MT::ping to update the list of URLs pinged
1611    ## and not successfully pinged. It returns the return value from
1612    ## MT::ping for further processing. If a fatal error occurs, it returns
1613    ## undef.
1614    my $results = $app->ping_and_save(
1615        Blog      => $blog,
1616        Entry     => $entry,
1617        OldStatus => scalar $q->param('old_status')
1618    ) or return;
1619    my $has_errors = 0;
1620    require MT::Log;
1621    for my $res (@$results) {
1622        $has_errors++,
1623          $app->log(
1624            {
1625                message => $app->translate(
1626                    "Ping '[_1]' failed: [_2]",
1627                    $res->{url},
1628                    encode_text( $res->{error}, undef, undef )
1629                ),
1630                class => 'system',
1631                level => MT::Log::WARNING()
1632            }
1633          ) unless $res->{good};
1634    }
1635    _finish_rebuild_ping( $app, $entry, scalar $q->param('is_new'),
1636        $has_errors );
1637}
1638
1639sub entry_notify {
1640    my $app   = shift;
1641    my $user  = $app->user;
1642    my $perms = $app->permissions;
1643    return $app->error( $app->translate("No permissions.") )
1644      unless $perms->can_send_notifications;
1645
1646    my $q        = $app->param;
1647    my $entry_id = $q->param('entry_id')
1648      or return $app->error( $app->translate("No entry ID provided") );
1649    require MT::Entry;
1650    require MT::Blog;
1651    my $entry = MT::Entry->load($entry_id)
1652      or return $app->error(
1653        $app->translate( "No such entry '[_1]'", $entry_id ) );
1654    my $blog  = MT::Blog->load( $entry->blog_id );
1655    my $param = {};
1656    $param->{entry_id} = $entry_id;
1657    return $app->load_tmpl( "dialog/entry_notify.tmpl", $param );
1658}
1659
1660sub send_notify {
1661    my $app = shift;
1662    $app->validate_magic() or return;
1663    my $q        = $app->param;
1664    my $entry_id = $q->param('entry_id')
1665      or return $app->error( $app->translate("No entry ID provided") );
1666    require MT::Entry;
1667    require MT::Blog;
1668    my $entry = MT::Entry->load($entry_id)
1669      or return $app->error(
1670        $app->translate( "No such entry '[_1]'", $entry_id ) );
1671    my $blog = MT::Blog->load( $entry->blog_id );
1672
1673    my $user = $app->user;
1674    $app->blog($blog);
1675    my $perms = $user->permissions($blog);
1676    return $app->error( $app->translate("No permissions.") )
1677      unless $perms->can_send_notifications;
1678
1679    my $author = $entry->author;
1680    return $app->error(
1681        $app->translate( "No email address for user '[_1]'", $author->name ) )
1682      unless $author->email;
1683
1684    my $cols = 72;
1685    my %params;
1686    $params{blog} = $blog;
1687    $params{entry} = $entry;
1688    $params{author} = $author;
1689
1690    if ( $q->param('send_excerpt') ) {
1691        $params{send_excerpt} = 1;
1692    }
1693    $params{message} = wrap_text( $q->param('message'), $cols, '', '' );
1694    if ( $q->param('send_body') ) {
1695        $params{send_body} = 1;
1696    }
1697
1698    my $entry_editurl = $app->uri(
1699        'mode' => 'view',
1700        args   => {
1701            '_type' => 'entry',
1702            blog_id => $entry->blog_id,
1703            id      => $entry->id,
1704        }
1705    );
1706    if ( $entry_editurl =~ m|^/| ) {
1707        my ($blog_domain) = $blog->archive_url =~ m|(.+://[^/]+)|;
1708        $entry_editurl = $blog_domain . $entry_editurl;
1709    }
1710    $params{entry_editurl} = $entry_editurl;
1711
1712    my $addrs;
1713    if ( $q->param('send_notify_list') ) {
1714        require MT::Notification;
1715        my $iter = MT::Notification->load_iter( { blog_id => $blog->id } );
1716        while ( my $note = $iter->() ) {
1717            next unless is_valid_email( $note->email );
1718            $addrs->{ $note->email } = 1;
1719        }
1720    }
1721
1722    if ( $q->param('send_notify_emails') ) {
1723        my @addr = split /[\n\r,]+/, $q->param('send_notify_emails');
1724        for my $a (@addr) {
1725            next unless is_valid_email($a);
1726            $addrs->{$a} = 1;
1727        }
1728    }
1729
1730    keys %$addrs
1731      or return $app->error(
1732        $app->translate(
1733            "No valid recipients found for the entry notification.")
1734      );
1735
1736    my $body = $app->build_email( 'notify-entry.tmpl', \%params );
1737
1738    my $subj =
1739      $app->translate( "[_1] Update: [_2]", $blog->name, $entry->title );
1740    if ( $app->current_language ne 'ja' ) {    # FIXME perhaps move to MT::I18N
1741        $subj =~ s![\x80-\xFF]!!g;
1742    }
1743    my $address =
1744      defined $author->nickname
1745      ? $author->nickname . ' <' . $author->email . '>'
1746      : $author->email;
1747    my %head = (
1748        id      => 'notify_entry',
1749        To      => $address,
1750        From    => $address,
1751        Subject => $subj,
1752    );
1753    my $charset = $app->config('MailEncoding')
1754      || $app->charset;
1755    $head{'Content-Type'} = qq(text/plain; charset="$charset");
1756    my $i = 1;
1757    require MT::Mail;
1758    MT::Mail->send( \%head, $body )
1759      or return $app->error(
1760        $app->translate(
1761            "Error sending mail ([_1]); try another MailTransfer setting?",
1762            MT::Mail->errstr
1763        )
1764      );
1765    delete $head{To};
1766
1767    foreach my $email ( keys %{$addrs} ) {
1768        next unless $email;
1769        if ( $app->config('EmailNotificationBcc') ) {
1770            push @{ $head{Bcc} }, $email;
1771            if ( $i++ % 20 == 0 ) {
1772                MT::Mail->send( \%head, $body )
1773                  or return $app->error(
1774                    $app->translate(
1775"Error sending mail ([_1]); try another MailTransfer setting?",
1776                        MT::Mail->errstr
1777                    )
1778                  );
1779                @{ $head{Bcc} } = ();
1780            }
1781        }
1782        else {
1783            $head{To} = $email;
1784            MT::Mail->send( \%head, $body )
1785              or return $app->error(
1786                $app->translate(
1787"Error sending mail ([_1]); try another MailTransfer setting?",
1788                    MT::Mail->errstr
1789                )
1790              );
1791            delete $head{To};
1792        }
1793    }
1794    if ( $head{Bcc} && @{ $head{Bcc} } ) {
1795        MT::Mail->send( \%head, $body )
1796          or return $app->error(
1797            $app->translate(
1798                "Error sending mail ([_1]); try another MailTransfer setting?",
1799                MT::Mail->errstr
1800            )
1801          );
1802    }
1803    $app->redirect(
1804        $app->uri(
1805            'mode' => 'view',
1806            args   => {
1807                '_type'      => $entry->class,
1808                blog_id      => $entry->blog_id,
1809                id           => $entry->id,
1810                saved_notify => 1
1811            }
1812        )
1813    );
1814}
1815
1816sub pinged_urls {
1817    my $app   = shift;
1818    my $perms = $app->permissions
1819      or return $app->error( $app->translate("No permissions") );
1820    my %param;
1821    my $entry_id = $app->param('entry_id');
1822    require MT::Entry;
1823    my $entry = MT::Entry->load($entry_id);
1824    $param{url_loop} = [ map { { url => $_ } } @{ $entry->pinged_url_list } ];
1825    $param{failed_url_loop} =
1826      [ map { { url => $_ } }
1827          @{ $entry->pinged_url_list( OnlyFailures => 1 ) } ];
1828    $app->load_tmpl( 'popup/pinged_urls.tmpl', \%param );
1829}
1830
1831sub save_entry_prefs {
1832    my $app   = shift;
1833    my $perms = $app->permissions
1834      or return $app->error( $app->translate("No permissions") );
1835    $app->validate_magic() or return;
1836    my $q     = $app->param;
1837    my $prefs = $app->_entry_prefs_from_params;
1838    $perms->entry_prefs($prefs);
1839    $perms->save
1840      or return $app->error(
1841        $app->translate( "Saving permissions failed: [_1]", $perms->errstr ) );
1842    $app->send_http_header("text/json");
1843    return "true";
1844}
1845
1846sub publish_entries {
1847    my $app = shift;
1848    require MT::Entry;
1849    update_entry_status( $app, MT::Entry::RELEASE(), $app->param('id') );
1850}
1851
1852sub draft_entries {
1853    my $app = shift;
1854    require MT::Entry;
1855    update_entry_status( $app, MT::Entry::HOLD(), $app->param('id') );
1856}
1857
1858sub open_batch_editor {
1859    my $app = shift;
1860    my @ids = $app->param('id');
1861
1862    $app->param( 'is_power_edit', 1 );
1863    $app->param( 'filter',        'power_edit' );
1864    $app->param( 'filter_val',    \@ids );
1865    $app->mode(
1866        'list_' . ( 'entry' eq $app->param('_type') ? 'entries' : 'pages' ) );
1867    $app->forward( "list_entry", { type => $app->param('_type') } );
1868}
1869
1870sub build_entry_table {
1871    my $app = shift;
1872    my (%args) = @_;
1873
1874    my $app_author = $app->user;
1875    my $perms      = $app->permissions;
1876    my $type       = $args{type};
1877    my $class      = $app->model($type);
1878
1879    my $list_pref = $app->list_pref($type);
1880    if ( $args{is_power_edit} ) {
1881        delete $list_pref->{view_expanded};
1882    }
1883    my $iter;
1884    if ( $args{load_args} ) {
1885        $iter = $class->load_iter( @{ $args{load_args} } );
1886    }
1887    elsif ( $args{iter} ) {
1888        $iter = $args{iter};
1889    }
1890    elsif ( $args{items} ) {
1891        $iter = sub { shift @{ $args{items} } };
1892    }
1893    return [] unless $iter;
1894    my $limit         = $args{limit};
1895    my $is_power_edit = $args{is_power_edit} || 0;
1896    my $param         = $args{param} || {};
1897
1898    ## Load list of categories for display in filter pulldown (and selection
1899    ## pulldown on power edit page).
1900    my ( $c_data, %cats );
1901    my $blog_id = $app->param('blog_id');
1902    if ($blog_id) {
1903        $c_data = $app->_build_category_list(
1904            blog_id => $blog_id,
1905            type    => $class->container_type,
1906        );
1907        my $i = 0;
1908        for my $row (@$c_data) {
1909            $row->{category_index} = $i++;
1910            my $spacer = $row->{category_label_spacer} || '';
1911            $spacer =~ s/\&nbsp;/\\u00A0/g;
1912            $row->{category_label_js} =
1913              $spacer . encode_js( $row->{category_label} );
1914            $cats{ $row->{category_id} } = $row;
1915        }
1916        $param->{category_loop} = $c_data;
1917    }
1918
1919    my ( $date_format, $datetime_format );
1920
1921    if ($is_power_edit) {
1922        $date_format          = "%Y.%m.%d";
1923        $datetime_format      = "%Y-%m-%d %H:%M:%S";
1924    }
1925    else {
1926        $date_format     = MT::App::CMS::LISTING_DATE_FORMAT();
1927        $datetime_format = MT::App::CMS::LISTING_DATETIME_FORMAT();
1928    }
1929
1930    my @cat_list;
1931    if ($is_power_edit) {
1932        @cat_list =
1933          sort { $cats{$a}->{category_index} <=> $cats{$b}->{category_index} }
1934          keys %cats;
1935    }
1936
1937    my @data;
1938    my %blogs;
1939    require MT::Blog;
1940    my $title_max_len   = const('DISPLAY_LENGTH_EDIT_ENTRY_TITLE');
1941    my $excerpt_max_len = const('DISPLAY_LENGTH_EDIT_ENTRY_TEXT_FROM_EXCERPT');
1942    my $text_max_len    = const('DISPLAY_LENGTH_EDIT_ENTRY_TEXT_BREAK_UP');
1943    my %blog_perms;
1944    $blog_perms{ $perms->blog_id } = $perms if $perms;
1945    while ( my $obj = $iter->() ) {
1946        my $blog_perms;
1947        if ( !$app_author->is_superuser() ) {
1948            $blog_perms = $blog_perms{ $obj->blog_id }
1949              || $app_author->blog_perm( $obj->blog_id );
1950        }
1951
1952        my $row = $obj->column_values;
1953        $row->{text} ||= '';
1954        if ( my $ts =
1955            ( $type eq 'page' ) ? $obj->modified_on : $obj->authored_on )
1956        {
1957            $row->{created_on_formatted} =
1958              format_ts( $date_format, $ts, $obj->blog, $app->user ? $app->user->preferred_language : undef );
1959            $row->{created_on_time_formatted} =
1960              format_ts( $datetime_format, $ts, $obj->blog, $app->user ? $app->user->preferred_language : undef );
1961            $row->{created_on_relative} =
1962              relative_date( $ts, time, $obj->blog );
1963        }
1964        my $author = $obj->author;
1965        $row->{author_name} =
1966          $author ? $author->name : $app->translate('(user deleted)');
1967        if ( my $cat = $obj->category ) {
1968            $row->{category_label}    = $cat->label;
1969            $row->{category_basename} = $cat->basename;
1970        }
1971        else {
1972            $row->{category_label}    = '';
1973            $row->{category_basename} = '';
1974        }
1975        $row->{file_extension} = $obj->blog ? $obj->blog->file_extension : '';
1976        $row->{title_short} = $obj->title;
1977        if ( !defined( $row->{title_short} ) || $row->{title_short} eq '' ) {
1978            my $title = remove_html( $obj->text );
1979            $row->{title_short} =
1980              substr_text( defined($title) ? $title : "", 0, $title_max_len )
1981              . '...';
1982        }
1983        else {
1984            $row->{title_short} = remove_html( $row->{title_short} );
1985            $row->{title_short} =
1986              substr_text( $row->{title_short}, 0, $title_max_len + 3 ) . '...'
1987              if length_text( $row->{title_short} ) > $title_max_len;
1988        }
1989        if ( $row->{excerpt} ) {
1990            $row->{excerpt} = remove_html( $row->{excerpt} );
1991        }
1992        if ( !$row->{excerpt} ) {
1993            my $text = remove_html( $row->{text} ) || '';
1994            $row->{excerpt} = first_n_text( $text, $excerpt_max_len );
1995            if ( length($text) > length( $row->{excerpt} ) ) {
1996                $row->{excerpt} .= ' ...';
1997            }
1998        }
1999        $row->{text} = break_up_text( $row->{text}, $text_max_len )
2000          if $row->{text};
2001        $row->{title_long} = remove_html( $obj->title );
2002        $row->{status_text} =
2003          $app->translate( MT::Entry::status_text( $obj->status ) );
2004        $row->{ "status_" . MT::Entry::status_text( $obj->status ) } = 1;
2005        $row->{has_edit_access} = $app_author->is_superuser
2006          || ( ( 'entry' eq $type )
2007            && $blog_perms
2008            && $blog_perms->can_edit_entry( $obj, $app_author ) )
2009          || ( ( 'page' eq $type )
2010            && $blog_perms
2011            && $blog_perms->can_manage_pages );
2012        if ($is_power_edit) {
2013            $row->{has_publish_access} = $app_author->is_superuser
2014              || ( ( 'entry' eq $type )
2015                && $blog_perms
2016                && $blog_perms->can_edit_entry( $obj, $app_author, 1 ) )
2017              || ( ( 'page' eq $type )
2018                && $blog_perms
2019                && $blog_perms->can_manage_pages );
2020            $row->{is_editable} = $row->{has_edit_access};
2021
2022            ## This is annoying. In order to generate and pre-select the
2023            ## category, user, and status pull down menus, we need to
2024            ## have a separate *copy* of the list of categories and
2025            ## users for every entry listed, so that each row in the list
2026            ## can "know" whether it is selected for this entry or not.
2027            my @this_c_data;
2028            my $this_category_id = $obj->category ? $obj->category->id : undef;
2029            for my $c_id (@cat_list) {
2030                push @this_c_data, { %{ $cats{$c_id} } };
2031                $this_c_data[-1]{category_is_selected} = $this_category_id
2032                  && $this_category_id == $c_id ? 1 : 0;
2033            }
2034            $row->{row_category_loop} = \@this_c_data;
2035
2036            if ( $obj->author ) {
2037                $row->{row_author_name} = $obj->author->name;
2038                $row->{row_author_id}   = $obj->author->id;
2039            } else {
2040                $row->{row_author_name} = $app->translate(
2041                    '(user deleted - ID:[_1])',
2042                    $obj->author_id
2043                );
2044                $row->{row_author_id} = $obj->author_id,
2045             }
2046        }
2047        if ( my $blog = $blogs{ $obj->blog_id } ||=
2048            MT::Blog->load( $obj->blog_id ) )
2049        {
2050            $row->{weblog_id}   = $blog->id;
2051            $row->{weblog_name} = $blog->name;
2052        }
2053        if ( $obj->status == MT::Entry::RELEASE() ) {
2054            $row->{entry_permalink} = $obj->permalink;
2055        }
2056        $row->{object} = $obj;
2057        push @data, $row;
2058    }
2059    return [] unless @data;
2060
2061    $param->{entry_table}[0] = {%$list_pref};
2062    $param->{object_loop} = $param->{entry_table}[0]{object_loop} = \@data;
2063    $app->load_list_actions( $type, \%$param )
2064      unless $is_power_edit;
2065    \@data;
2066}
2067
2068sub quickpost_js {
2069    my $app     = shift;
2070    my ($type)  = @_;
2071    my $blog_id = $app->blog->id;
2072    my $blog    = $app->model('blog')->load($blog_id);
2073    my %args    = ( '_type' => $type, blog_id => $blog_id, qp => 1 );
2074    my $uri = $app->base . $app->uri( 'mode' => 'view', args => \%args );
2075    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'))!;
2076    # Translate the phrase here to avoid ActivePerl DLL bug.
2077    $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);
2078}
2079
2080sub can_view {
2081    my ( $eh, $app, $id, $objp ) = @_;
2082    my $perms = $app->permissions;
2083    if (   !$id
2084        && !$perms->can_create_post )
2085    {
2086        return 0;
2087    }
2088    if ($id) {
2089        my $obj = $objp->force();
2090        if ( !$perms->can_edit_entry( $obj, $app->user ) ) {
2091            return 0;
2092        }
2093    }
2094    1;
2095}
2096
2097sub can_delete {
2098    my ( $eh, $app, $obj ) = @_;
2099    my $author = $app->user;
2100    return 1 if $author->is_superuser();
2101    my $perms = $app->permissions;
2102    if ( !$perms || $perms->blog_id != $obj->blog_id ) {
2103        $perms ||= $author->permissions( $obj->blog_id );
2104    }
2105    return $perms && $perms->can_edit_entry( $obj, $author );
2106}
2107
2108sub pre_save {
2109    my $eh = shift;
2110    my ( $app, $obj ) = @_;
2111
2112    # save tags
2113    my $tags = $app->param('tags');
2114    if ( defined $tags ) {
2115        my $blog = $app->blog;
2116        my $fields = $blog->smart_replace_fields;
2117        if ( $fields =~ m/tags/ig ) {
2118            $tags = MT::App::CMS::_convert_word_chars( $app, $tags );
2119        }
2120
2121        require MT::Tag;
2122        my $tag_delim = chr( $app->user->entry_prefs->{tag_delim} );
2123        my @tags = MT::Tag->split( $tag_delim, $tags );
2124        if (@tags) {
2125            $obj->set_tags(@tags);
2126        }
2127        else {
2128            $obj->remove_tags();
2129        }
2130    }
2131
2132    # update text heights if necessary
2133    if ( my $perms = $app->permissions ) {
2134        my $prefs = $perms->entry_prefs || $app->load_default_entry_prefs;
2135        my $text_height = $app->param('text_height');
2136        if ( defined $text_height ) {
2137            my ($pref_text_height) = $prefs =~ m/\bbody:(\d+)\b/;
2138            $pref_text_height ||= 0;
2139            if ( $text_height != $pref_text_height ) {
2140                if ( $prefs =~ m/\bbody\b/ ) {
2141                    $prefs =~ s/\bbody(:\d+)\b/body:$text_height/;
2142                }
2143                else {
2144                    $prefs = 'body:' . $text_height . ',' . $prefs;
2145                }
2146            }
2147        }
2148        if ( $prefs ne ( $perms->entry_prefs || '' ) ) {
2149            $perms->entry_prefs($prefs);
2150            $perms->save;
2151        }
2152    }
2153    $obj->discover_tb_from_entry();
2154    1;
2155}
2156
2157sub post_save {
2158    my $eh = shift;
2159    my ( $app, $obj ) = @_;
2160    my $sess_obj = $app->autosave_session_obj;
2161    $sess_obj->remove if $sess_obj;
2162    1;
2163}
2164
2165sub post_delete {
2166    my ( $eh, $app, $obj ) = @_;
2167
2168    my $sess_obj = $app->autosave_session_obj;
2169    $sess_obj->remove if $sess_obj;
2170
2171    $app->log(
2172        {
2173            message => $app->translate(
2174                "Entry '[_1]' (ID:[_2]) deleted by '[_3]'",
2175                $obj->title, $obj->id, $app->user->name
2176            ),
2177            level    => MT::Log::INFO(),
2178            class    => 'system',
2179            category => 'delete'
2180        }
2181    );
2182}
2183
2184sub update_entry_status {
2185    my $app = shift;
2186    my ( $new_status, @ids ) = @_;
2187    return $app->errtrans("Need a status to update entries")
2188      unless $new_status;
2189    return $app->errtrans("Need entries to update status")
2190      unless @ids;
2191    my @bad_ids;
2192    my %rebuild_these;
2193    require MT::Entry;
2194
2195    foreach my $id (@ids) {
2196        my $entry = MT::Entry->load($id)
2197          or return $app->errtrans(
2198            "One of the entries ([_1]) did not actually exist", $id );
2199        next if $entry->status == $new_status;
2200        if ( $app->config('DeleteFilesAtRebuild')
2201            && ( MT::Entry::RELEASE() eq $entry->status ) )
2202        {
2203            my $archive_type =
2204              $entry->class eq 'page'
2205              ? 'Page'
2206              : 'Individual';
2207            $app->publisher->remove_entry_archive_file(
2208                Entry       => $entry,
2209                ArchiveType => $archive_type
2210            );
2211        }
2212        my $old_status = $entry->status;
2213        $entry->status($new_status);
2214        $entry->save() and $rebuild_these{$id} = 1;
2215        my $message = $app->translate(
2216            "[_1] '[_2]' (ID:[_3]) status changed from [_4] to [_5]",
2217            $entry->class_label,
2218            $entry->title,
2219            $entry->id,
2220            $app->translate( MT::Entry::status_text($old_status) ),
2221            $app->translate( MT::Entry::status_text($new_status) )
2222        );
2223        $app->log(
2224            {
2225                message  => $message,
2226                level    => MT::Log::INFO(),
2227                class    => $entry->class,
2228                category => 'edit',
2229                metadata => $entry->id
2230            }
2231        );
2232    }
2233    $app->rebuild_these( \%rebuild_these, how => MT::App::CMS::NEW_PHASE() );
2234}
2235
2236sub _finish_rebuild_ping {
2237    my $app = shift;
2238    my ( $entry, $is_new, $ping_errors ) = @_;
2239    $app->redirect(
2240        $app->uri(
2241            'mode' => 'view',
2242            args   => {
2243                '_type' => $entry->class,
2244                blog_id => $entry->blog_id,
2245                id      => $entry->id,
2246                ( $is_new ? ( saved_added => 1 ) : ( saved_changes => 1 ) ),
2247                ( $ping_errors ? ( ping_errors => 1 ) : () )
2248            }
2249        )
2250    );
2251}
2252
2253sub ping_continuation {
2254    my $app = shift;
2255    my ( $entry, $blog, %options ) = @_;
2256    my $list = $app->needs_ping(
2257        Entry     => $entry,
2258        Blog      => $blog,
2259        OldStatus => $options{OldStatus}
2260    );
2261    require MT::Entry;
2262    if ( $entry->status == MT::Entry::RELEASE() && $list ) {
2263        my @urls = map { { url => $_ } } @$list;
2264        $app->load_tmpl(
2265            'pinging.tmpl',
2266            {
2267                blog_id    => $blog->id,
2268                entry_id   => $entry->id,
2269                old_status => $options{OldStatus},
2270                is_new     => $options{IsNew},
2271                url_list   => \@urls,
2272            }
2273        );
2274    }
2275    else {
2276        _finish_rebuild_ping( $app, $entry, $options{IsNew} );
2277    }
2278}
2279
2280sub delete {
2281    my $app = shift;
2282    $app->validate_magic() or return;
2283
2284    require MT::Blog;
2285    my $q       = $app->param;
2286    my $blog_id = $q->param('blog_id');
2287    my $blog    = MT::Blog->load($blog_id);
2288
2289    my $can_background =
2290        ( $blog->count_static_templates('Individual') == 0
2291            || MT::Util->launch_background_tasks() ) ? 1 : 0;
2292
2293    my %rebuild_recip;
2294    my $at = $blog->archive_type;
2295    my @at;
2296    if ( $at && $at ne 'None' ) {
2297        my @at_orig = split( /,/, $at );
2298        @at = grep { $_ ne 'Individual' && $_ ne 'Page' } @at_orig;
2299    }
2300
2301    for my $id ( $q->param('id') ) {
2302        my $class = $app->model("entry");
2303        my $obj   = $class->load($id);
2304        return $app->call_return unless $obj;
2305
2306        $app->run_callbacks( 'cms_delete_permission_filter.entry', $app, $obj )
2307          || return $app->error(
2308            $app->translate( "Permission denied: [_1]", $app->errstr() ) );
2309
2310        if (   $app->config('RebuildAtDelete')
2311            || $app->config('DeleteFilesAtRebuild') )
2312        {
2313            # Remove Induvidual archive file.
2314            if ( $app->config('DeleteFilesAtRebuild') ) {
2315                $app->publisher->remove_entry_archive_file( Entry => $obj, );
2316            }
2317
2318            for my $at (@at) {
2319                my $archiver = $app->publisher->archiver($at);
2320                next unless $archiver;
2321
2322                # Remove archive file if archive file has not entries.
2323                my $deleted = 0;
2324                if ( $app->config('DeleteFilesAtRebuild') ) {
2325                    my $count =
2326                        $archiver->can('archive_entries_count')
2327                      ? $archiver->archive_entries_count( $blog, $at, $obj )
2328                      : 0;
2329                    if ( $count == 1 ) {
2330                        $app->publisher->remove_entry_archive_file(
2331                            Entry       => $obj,
2332                            ArchiveType => $at
2333                        );
2334                        $deleted = 1;
2335                    }
2336                }
2337
2338                # Make rebuild recip
2339                if ( $app->config('DeleteFilesAtRebuild') ) {
2340                    next if $deleted;
2341
2342                    my ( $start, $end ) = $archiver->date_range( $obj->authored_on )
2343                        if $archiver->date_based() && $archiver->can('date_range');
2344
2345                    if ( $archiver->category_based() ) {
2346                        my $categories = $obj->categories();
2347                        for my $cat (@$categories) {
2348                            if ( $archiver->date_based() ) {
2349                                $rebuild_recip{$at}{ $cat->id }{ $start . $end }
2350                                  {'Start'} = $start;
2351                                $rebuild_recip{$at}{ $cat->id }{ $start . $end }
2352                                  {'End'} = $end;
2353                                $rebuild_recip{$at}{ $cat->id }{ $start . $end }
2354                                  {'File'} =
2355                                  MT::Util::archive_file_for( $obj, $blog, $at,
2356                                    $cat, undef, undef, undef );
2357                            }
2358                            else {
2359                                $rebuild_recip{$at}{ $cat->id }{id} = $cat->id;
2360                                $rebuild_recip{$at}{ $cat->id }{'File'} =
2361                                  MT::Util::archive_file_for( $obj, $blog, $at,
2362                                    $cat, undef, undef, undef );
2363                            }
2364                        }
2365                    }
2366                    elsif ( $archiver->author_based() ) {
2367                        if ( $archiver->date_based() ) {
2368                            $rebuild_recip{$at}{ $obj->author->id }{ $start . $end }
2369                              {'Start'} = $start;
2370                            $rebuild_recip{$at}{ $obj->author->id }{ $start . $end }
2371                              {'End'} = $end;
2372                            $rebuild_recip{$at}{ $obj->author->id }{ $start . $end }
2373                              {'File'} =
2374                              MT::Util::archive_file_for( $obj, $blog, $at, undef,
2375                                undef, undef, $obj->author );
2376                        }
2377                        else {
2378                            $rebuild_recip{$at}{ $obj->author->id }{id} =
2379                              $obj->author->id;
2380                            $rebuild_recip{$at}{ $obj->author->id }{'File'} =
2381                              MT::Util::archive_file_for( $obj, $blog, $at, undef,
2382                                undef, undef, $obj->author );
2383                        }
2384                    }
2385                    elsif ( $archiver->date_based() ) {
2386                        $rebuild_recip{$at}{ $start . $end }{'Start'} = $start;
2387                        $rebuild_recip{$at}{ $start . $end }{'End'}   = $end;
2388                        $rebuild_recip{$at}{ $start . $end }{'File'} =
2389                          MT::Util::archive_file_for( $obj, $blog, $at, undef,
2390                            undef, undef, undef );
2391                    }
2392                    if ( my $prev = $obj->previous(1) ) {</