root/branches/release-39/lib/MT/CMS/Entry.pm @ 2417

Revision 2417, 78.8 kB (checked in by fumiakiy, 19 months ago)

Do not include comment_count and ping_count aggregation columns to the form in preview screen. Postgres does not accept empty string to integer column. BugId:79430

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