root/branches/release-39/lib/MT/CMS/Blog.pm @ 2520

Revision 2520, 82.1 kB (checked in by takayama, 18 months ago)

Fixed BugId:80038
* Applied patch. thanks to Ogawa-san

  • Property svn:keywords set to Id Revision
Line 
1package MT::CMS::Blog;
2
3use strict;
4
5sub edit {
6    my $cb = shift;
7    my ($app, $id, $obj, $param) = @_;
8
9    my $q = $app->param;
10    my $cfg = $app->config;
11    my $blog = $app->blog;
12    my $blog_id = $id;
13
14    if ($id) {
15        my $output = $param->{output} ||= 'cfg_prefs.tmpl';
16        $param->{need_full_rebuild}  = 1 if $q->param('need_full_rebuild');
17        $param->{need_index_rebuild} = 1 if $q->param('need_index_rebuild');
18        $param->{show_ip_info} = $cfg->ShowIPInformation;
19        $param->{use_plugins} = $cfg->UsePlugins;
20
21        my $entries_on_index = ( $obj->entries_on_index || 0 );
22        if ($entries_on_index) {
23            $param->{'list_on_index'} = $entries_on_index;
24            $param->{'posts'}         = 1;
25        }
26        else {
27            $param->{'list_on_index'} = ( $obj->days_on_index || 0 );
28            $param->{'days'} = 1;
29        }
30        my $lang = $obj->language || 'en';
31        $lang = 'en' if lc($lang) eq 'en-us' || lc($lang) eq 'en_us';
32        $lang = 'ja' if lc($lang) eq 'jp';
33        $param->{ 'language_' . $lang } = 1;
34
35        $param->{system_allow_comments} = $cfg->AllowComments;
36        $param->{system_allow_pings}    = $cfg->AllowPings;
37        $param->{tk_available}          = eval { require MIME::Base64; 1; }
38          && eval { require LWP::UserAgent; 1 };
39        $param->{'auto_approve_commenters'} =
40          !$obj->manual_approve_commenters;
41        $param->{identity_system}     = $app->config('IdentitySystem');
42        $param->{handshake_return}    = $app->base . $app->mt_uri;
43        $param->{"moderate_comments"} = $obj->moderate_unreg_comments;
44        $param->{ "moderate_comments_"
45              . ( $obj->moderate_unreg_comments || 0 ) } = 1;
46        $param->{ "moderate_pings_" . ( $obj->moderate_pings || 0 ) } = 1;
47
48        my $cmtauth_reg = $app->registry('commenter_authenticators');
49        foreach my $auth ( keys %$cmtauth_reg ) {
50            $cmtauth_reg->{$auth}->{disabled} = 1
51              if exists( $cmtauth_reg->{$auth}->{condition} )
52              && !( $cmtauth_reg->{$auth}->{condition}->() );
53        }
54        if ( my $auths = $blog->commenter_authenticators ) {
55            foreach ( split ',', $auths ) {
56                if ( 'MovableType' eq $_ ) {
57                    $param->{enabled_MovableType} = 1;
58                }
59                else {
60                    $cmtauth_reg->{$_}->{enabled} = 1;
61                }
62            }
63        }
64        my @cmtauth_loop;
65        foreach ( keys %$cmtauth_reg ) {
66            $cmtauth_reg->{$_}->{key} = $_;
67            if (
68                UNIVERSAL::isa(
69                    $cmtauth_reg->{$_}->{plugin}, 'MT::Plugin'
70                )
71              )
72            {
73                push @cmtauth_loop, $cmtauth_reg->{$_};
74            }
75        }
76        unshift @cmtauth_loop, $cmtauth_reg->{'TypeKey'}
77          if exists( $cmtauth_reg->{'TypeKey'} )
78          && $blog->remote_auth_token;
79        unshift @cmtauth_loop, $cmtauth_reg->{'Vox'}
80          if exists $cmtauth_reg->{'Vox'};
81        unshift @cmtauth_loop, $cmtauth_reg->{'LiveJournal'}
82          if exists $cmtauth_reg->{'LiveJournal'};
83        unshift @cmtauth_loop, $cmtauth_reg->{'OpenID'}
84          if exists $cmtauth_reg->{'OpenID'};
85
86        $param->{cmtauth_loop} = \@cmtauth_loop;
87
88        if ( $output eq 'cfg_prefs.tmpl' ) {
89            $app->add_breadcrumb( $app->translate('General Settings') );
90
91            my $lang = $obj->language || 'en';
92            $lang = 'en' if lc($lang) eq 'en-us' || lc($lang) eq 'en_us';
93            $lang = 'ja' if lc($lang) eq 'jp';
94            $param->{ 'language_' . $lang } = 1;
95
96            if ( $obj->cc_license ) {
97                $param->{cc_license_name} =
98                  MT::Util::cc_name( $obj->cc_license );
99                $param->{cc_license_image_url} =
100                  MT::Util::cc_image( $obj->cc_license );
101                $param->{cc_license_url} =
102                  MT::Util::cc_url( $obj->cc_license );
103            }
104        }
105        elsif ( $output eq 'cfg_entry.tmpl' ) {
106            ## load entry preferences for new/edit entry page of the blog
107            my $pref_param = $app->load_entry_prefs;
108            %$param = ( %$param, %$pref_param );
109            $param->{ 'sort_order_posts_'
110                  . ( $obj->sort_order_posts || 0 ) } = 1;
111            $param->{ 'status_default_' . $obj->status_default } = 1
112              if $obj->status_default;
113            $param->{ 'allow_comments_default_'
114                  . ( $obj->allow_comments_default || 0 ) } = 1;
115            $param->{system_allow_pings} =
116              $cfg->AllowPings && $blog->allow_pings;
117            $param->{system_allow_comments} = $cfg->AllowComments
118              && ( $blog->allow_reg_comments
119                || $blog->allow_unreg_comments );
120            my $replace_fields = $blog->smart_replace_fields || '';
121            my @replace_fields = split( /,/, $replace_fields );
122            foreach my $fld (@replace_fields) {
123                $param->{ 'nwc_' . $fld } = 1;
124            }
125            $param->{ 'nwc_smart_replace_' . ( $blog->smart_replace || 0 ) } = 1;
126            $param->{ 'nwc_replace_none' } = ( $blog->smart_replace || 0 ) == 2;
127        }
128        elsif ( $output eq 'cfg_web_services.tmpl' ) {
129            $param->{system_disabled_notify_pings} =
130              $cfg->DisableNotificationPings;
131            $param->{system_allow_outbound_pings} =
132              $cfg->OutboundTrackbackLimit eq 'any';
133            my %selected_pings = map { $_ => 1 }
134              split ',', ($obj->update_pings || '');
135            my $pings = $app->registry('ping_servers');
136            my @pings;
137            push @pings,
138              {
139                key   => $_,
140                label => $pings->{$_}->{label},
141                exists( $selected_pings{$_} ) ? ( selected => 1 ) : (),
142              } foreach keys %$pings;
143            $param->{pings_loop} = \@pings;
144        }
145        elsif ( $output eq 'cfg_comments.tmpl' ) {
146            $param->{email_new_comments_1} =
147              ( $obj->email_new_comments || 0 ) == 1;
148            $param->{email_new_comments_2} =
149              ( $obj->email_new_comments || 0 ) == 2;
150            $param->{nofollow_urls}     = $obj->nofollow_urls;
151            $param->{follow_auth_links} = $obj->follow_auth_links;
152            $param->{ 'sort_order_comments_'
153                  . ( $obj->sort_order_comments || 0 ) } = 1;
154            $param->{global_sanitize_spec} = $cfg->GlobalSanitizeSpec;
155            $param->{ 'sanitize_spec_' . ( $obj->sanitize_spec ? 1 : 0 ) } =
156              1;
157            $param->{sanitize_spec_manual} = $obj->sanitize_spec
158              if $obj->sanitize_spec;
159            $param->{allow_comments} = $blog->allow_reg_comments
160              || $blog->allow_unreg_comments;
161            $param->{use_comment_confirmation} =
162              defined $blog->use_comment_confirmation
163              ? $blog->use_comment_confirmation
164              : 0;
165            $param->{system_allow_comments} = $cfg->AllowComments
166              && ( $blog->allow_reg_comments
167                || $blog->allow_unreg_comments );
168            my @cps = MT->captcha_providers;
169
170            foreach my $cp (@cps) {
171                if ( ( $blog->captcha_provider || '' ) eq $cp->{key} ) {
172                    $cp->{selected} = 1;
173                }
174            }
175            $param->{captcha_loop} = \@cps;
176        }
177        elsif ( $output eq 'cfg_trackbacks.tmpl' ) {
178            $param->{email_new_pings_1} = ( $obj->email_new_pings || 0 ) == 1;
179            $param->{email_new_pings_2} = ( $obj->email_new_pings || 0 ) == 2;
180            $param->{nofollow_urls}     = $obj->nofollow_urls;
181            $param->{system_allow_selected_pings} =
182              $cfg->OutboundTrackbackLimit eq 'selected';
183            $param->{system_allow_outbound_pings} =
184              $cfg->OutboundTrackbackLimit eq 'any';
185            $param->{system_allow_local_pings} =
186                 ( $cfg->OutboundTrackbackLimit eq 'local' )
187              || ( $cfg->OutboundTrackbackLimit eq 'any' );
188        }
189        elsif ( $output eq 'cfg_registration.tmpl' ) {
190            $param->{commenter_authenticators} =
191              $obj->commenter_authenticators;
192            my $registration = $cfg->CommenterRegistration;
193            if ( $registration->{Allow} ) {
194                $param->{registration} =
195                  $blog->allow_commenter_regist ? 1 : 0;
196            }
197            else {
198                $param->{system_disallow_registration} = 1;
199            }
200            $param->{allow_reg_comments} = $blog->allow_reg_comments;
201            $param->{allow_unreg_comments} = $blog->allow_unreg_comments;
202            $param->{require_typekey_emails} = $obj->require_typekey_emails;
203        }
204        elsif ( $output eq 'cfg_spam.tmpl' ) {
205            my $threshold = $obj->junk_score_threshold || 0;
206            $threshold = '+' . $threshold if $threshold > 0;
207            $param->{junk_score_threshold} = $threshold;
208            $param->{junk_folder_expiry}   = $obj->junk_folder_expiry || 60;
209            $param->{auto_delete_junk}     = $obj->junk_folder_expiry;
210        }
211        elsif ( $output eq 'cfg_archives.tmpl' ) {
212            $app->add_breadcrumb( $app->translate('Publishing Settings') );
213            if (   $obj->column('archive_path')
214                || $obj->column('archive_url') )
215            {
216                $param->{enable_archive_paths} = 1;
217                $param->{archive_path}         = $obj->column('archive_path');
218                $param->{archive_url}          = $obj->column('archive_url');
219            }
220            else {
221                $param->{archive_path} = '';
222                $param->{archive_url}  = '';
223            }
224            $param->{ 'archive_type_preferred_'
225                  . $blog->archive_type_preferred } = 1
226              if $blog->archive_type_preferred;
227            my $at = $blog->archive_type;
228            if ( $at && $at ne 'None' ) {
229                my @at = split /,/, $at;
230                for my $at (@at) {
231                    $param->{ 'archive_type_' . $at } = 1;
232                }
233            }
234            require MT::PublishOption;
235            if ( $app->model('template')->exist(
236                    { blog_id => $blog->id, build_type => MT::PublishOption::DYNAMIC() })
237              || $app->model('templatemap')->exist(
238                    { blog_id => $blog->id, build_type => MT::PublishOption::DYNAMIC() }) )
239            {
240                $param->{dynamic_enabled} = 1;
241                $param->{warning_include} = 1 unless $blog->include_system eq 'php' || $blog->include_system eq '' ;
242            }
243            eval "require List::Util; require Scalar::Util;";
244            unless ($@) {
245                $param->{can_use_publish_queue} = 1;
246            }
247            if ( $blog->publish_queue ) {
248                $param->{publish_queue} = 1;
249            }
250            if ( $blog->include_cache ) {
251                $param->{include_cache} = 1;
252            }
253        }
254        elsif ( $output eq 'cfg_plugin.tmpl' ) {
255            $app->add_breadcrumb( $app->translate('Plugin Settings') );
256            $param->{blog_view} = 1;
257            require MT::CMS::Plugin;
258            MT::CMS::Plugin::build_plugin_table( $app,
259                param => $param,
260                scope => 'blog:' . $blog_id
261            );
262            $param->{can_config} = 1;
263        }
264        else {
265            $app->add_breadcrumb( $app->translate('Settings') );
266        }
267        ( my $offset = $obj->server_offset ) =~ s![-\.]!_!g;
268        $offset =~ s!_0+$!!; # fix syntax highlight ->!
269        $param->{ 'server_offset_' . $offset } = 1;
270        if ( $output eq 'cfg_comments.tmpl' ) {
271            ## Load text filters.
272            $param->{text_filters_comments} =
273              $app->load_text_filters( $obj->convert_paras_comments,
274                'comment' );
275        }
276        elsif ( $output eq 'cfg_entry.tmpl' ) {
277            ## Load text filters.
278            $param->{text_filters} =
279              $app->load_text_filters( $obj->convert_paras, 'entry' );
280        }
281        $param->{nav_config} = 1;
282        $param->{error} = $app->errstr if $app->errstr;
283    } else {
284        $app->add_breadcrumb( $app->translate('New Blog') );
285        ( my $tz = $cfg->DefaultTimezone ) =~ s![-\.]!_!g;
286        $tz =~ s!_00$!!; # fix syntax highlight ->!
287        $param->{ 'server_offset_' . $tz } = 1;
288        $param->{'can_edit_config'}        = $app->user->can_create_blog;
289        $param->{'can_set_publish_paths'}  = $app->user->can_create_blog;
290
291        my $sets = $app->registry("template_sets");
292        $sets->{$_}{key} = $_ for keys %$sets;
293        $sets->{'mt_blog'}{selected} = 1;
294        $sets = $app->filter_conditional_list([ values %$sets ]);
295        no warnings;
296        @$sets = sort { $a->{order} <=> $b->{order} } @$sets;
297        $param->{'template_set_loop'} = $sets;
298        $param->{'template_set_index'} = $#$sets;
299    }
300
301    if (   !$param->{site_path}
302        && !( $param->{site_path} = $app->config('DefaultSiteRoot') ) )
303    {
304        my $cwd = $app->document_root;
305        $cwd = File::Spec->catdir($cwd, 'BLOG-NAME'); # for including the end of directory separator
306        $cwd =~ s!BLOG-NAME\z!!;                      # canonpath() remove it
307        $cwd =~ s!([\\/])cgi(?:-bin)?([\\/].*)?$!$1!;
308        $cwd =~ s!([\\/])mt[\\/]?$!$1!i;
309        $param->{suggested_site_path} = $cwd;
310    }
311    if ( !$param->{id} ) {
312        if ( $param->{site_path} ) {
313            $param->{site_path} =
314              File::Spec->catdir( $param->{site_path}, 'BLOG-NAME' );
315        }
316        else {
317            $param->{suggested_site_path} =
318              File::Spec->catdir( $param->{suggested_site_path},
319                'BLOG-NAME' );
320        }
321    }
322
323    # If not yet defined, set the site_url to the config default, if one exists.
324    $param->{site_url} ||= $app->config('DefaultSiteURL');
325    if ( !$param->{site_url} ) {
326        $param->{suggested_site_url} = $app->base . '/';
327        $param->{suggested_site_url} =~ s!/cgi(?:-bin)?(/.*)?$!/!;
328        $param->{suggested_site_url} =~ s!/mt/?$!/!i;
329    }
330    if ( !$param->{id} ) {
331        if ( $param->{site_url} ) {
332            $param->{site_url} .= '/'
333              unless $param->{site_url} =~ /\/$/;
334            $param->{site_url} .= 'BLOG-NAME/';
335        }
336        else {
337            $param->{suggested_site_url} .= '/'
338              unless $param->{suggested_site_url} =~ /\/$/;
339            $param->{suggested_site_url} .= 'BLOG-NAME/';
340        }
341    }
342    1;
343}
344
345sub list {
346    my $app = shift;
347
348    $app->return_to_dashboard( redirect => 1 ) if $app->param('blog_id');
349
350    my $author    = $app->user;
351    my $list_pref = $app->list_pref('blog');
352
353    my $limit  = $list_pref->{rows};
354    my $offset = $app->param('offset') || 0;
355    my $args   = { offset => $offset, sort => 'name' };
356    $args->{limit} = $limit + 1;
357    unless ( $author->is_superuser ) {
358        $args->{join} = MT::Permission->join_on(
359            'blog_id',
360            { author_id => $author->id },
361            { unique    => 1 }
362        );
363    }
364    my $blog_class       = $app->model('blog');
365    my %param            = %$list_pref;
366    my @blogs            = $blog_class->load( undef, $args );
367    my $can_edit_authors = $author->is_superuser;
368    my $blog_loop        = make_blog_list( $app, \@blogs );
369
370    if ($blog_loop) {
371        ## We tried to load $limit + 1 entries above; if we actually got
372        ## $limit + 1 back, we know we have another page of entries.
373        my $have_next = @$blog_loop > $limit;
374        pop @$blog_loop while @$blog_loop > $limit;
375        if ($offset) {
376            $param{prev_offset}     = 1;
377            $param{prev_offset_val} = $offset - $limit;
378            $param{prev_offset_val} = 0 if $param{prev_offset_val} < 0;
379        }
380        if ($have_next) {
381            $param{next_offset}     = 1;
382            $param{next_offset_val} = $offset + $limit;
383        }
384    }
385    $param{offset}      = $offset;
386    $param{object_type} = 'blog';
387    $param{list_start}  = $offset + 1;
388    delete $args->{limit};
389    delete $args->{offset};
390    $param{list_total} = $blog_class->count( undef, $args );
391    $param{list_end}        = $offset + ( $blog_loop ? scalar @$blog_loop : 0 );
392    $param{next_max}        = $param{list_total} - $limit;
393    $param{next_max}        = 0 if ( $param{next_max} || 0 ) < $offset + 1;
394    $param{can_create_blog} = $author->can_create_blog;
395    $param{saved_deleted}   = $app->param('saved_deleted');
396    $param{refreshed}       = $app->param('refreshed');
397    $param{nav_blogs}       = 1;
398    $param{list_noncron}    = 1;
399    $param{search_label}    = $app->translate('Blogs');
400
401    if ($blog_loop) {
402        $param{object_loop} = $param{blog_table}[0]{object_loop} = $blog_loop;
403        $app->load_list_actions( 'blog', \%param );
404    }
405
406    $param{page_actions} = $app->page_actions('list_blog');
407    $param{feed_name}    = $app->translate("Blog Activity Feed");
408    $param{feed_url}     = $app->make_feed_link('blog');
409    $app->add_breadcrumb( $app->translate("Blogs") );
410    $param{nav_weblogs} = 1;
411    $param{object_label} = $blog_class->class_label;
412    $param{object_label_plural} = $blog_class->class_label_plural;
413    $param{screen_class} = "list-blog";
414    $param{screen_id} = "list-blog";
415    $param{listing_screen} = 1;
416    return $app->load_tmpl( 'list_blog.tmpl', \%param );
417}
418
419sub cfg_archives {
420    my $app = shift;
421    my %param;
422    %param = %{ $_[0] } if $_[0];
423    my $q = $app->param;
424
425    my $blog_id = $q->param('blog_id');
426
427    return $app->return_to_dashboard( redirect => 1 ) unless $blog_id;
428
429    my $blog = $app->model('blog')->load($blog_id)
430        or return $app->error($app->translate('Can\'t load blog #[_1].', $blog_id));
431    my @data;
432    for my $at ( split /\s*,\s*/, $blog->archive_type ) {
433        my $archiver = $app->publisher->archiver($at);
434        next unless $archiver;
435        next if 'entry' ne $archiver->entry_class;
436        my $archive_label = $archiver->archive_label;
437        $archive_label = $at unless $archive_label;
438        $archive_label = $archive_label->() if ( ref $archive_label ) eq 'CODE';
439        push @data,
440          {
441            archive_type_translated => $archive_label,
442            archive_type            => $at,
443            archive_type_is_preferred =>
444              ( $blog->archive_type_preferred eq $at ? 1 : 0 ),
445          };
446    }
447    @data = sort { MT::App::CMS::archive_type_sorter( $a, $b ) } @data;
448    $param{entry_archive_types} = \@data;
449    $param{saved_deleted}       = 1 if $q->param('saved_deleted');
450    $param{saved_added}         = 1 if $q->param('saved_added');
451    $param{archives_changed}    = 1 if $q->param('archives_changed');
452    $param{no_writedir}         = $q->param('no_writedir');
453    $param{no_cachedir}         = $q->param('no_cachedir');
454    $param{no_writecache}       = $q->param('no_writecache');
455    $param{include_system}      = $blog->include_system || '';
456
457    my $mtview_path = File::Spec->catfile( $blog->site_path(), "mtview.php" );
458
459    if ( -f $mtview_path ) {
460        open my ($fh), $mtview_path;
461        while ( my $line = <$fh> ) {
462            $param{dynamic_caching} = 1
463              if $line =~ m/^\s*\$mt->caching\s*=\s*true;/i;
464            $param{dynamic_conditional} = 1
465              if $line =~ /^\s*\$mt->conditional\s*=\s*true;/i;
466        }
467        close $fh;
468    }
469    $param{output} = 'cfg_archives.tmpl';
470    $q->param( '_type', 'blog' );
471    $q->param( 'id',    $blog_id );
472    $param{screen_class} = "settings-screen archive-settings";
473    $param{object_type}  = 'author';
474    $param{search_label} = $app->translate('Users');
475    $app->forward( "view", \%param );
476}
477
478sub cfg_prefs {
479    my $app     = shift;
480    my $q       = $app->param;
481    my $blog_id = scalar $q->param('blog_id');
482    return $app->return_to_dashboard( redirect => 1 )
483      unless $blog_id;
484    $q->param( '_type', 'blog' );
485    $q->param( 'id',    $blog_id );
486    my $blog_prefs = $app->user_blog_prefs;
487    my $perms      = $app->permissions;
488    return $app->error( $app->translate('Permission denied.') )
489      unless $app->user->is_superuser()
490      || (
491        $perms
492        && (   $perms->can_edit_config
493            || $perms->can_administer_blog
494            || $perms->can_set_publish_paths )
495      );
496    my $output = 'cfg_prefs.tmpl';
497    $app->forward("view",
498        {
499            output       => $output,
500            screen_class => 'settings-screen general-screen'
501        }
502    );
503}
504
505sub cfg_web_services {
506    my $app     = shift;
507    my $q       = $app->param;
508    my $blog_id = scalar $q->param('blog_id');
509    return $app->return_to_dashboard( redirect => 1 )
510      unless $blog_id;
511    $q->param( '_type', 'blog' );
512    $q->param( 'id',    scalar $q->param('blog_id') );
513    $app->forward( "view",
514        {
515            output       => 'cfg_web_services.tmpl',
516            screen_class => 'settings-screen web-services-settings'
517        }
518    );
519}
520
521sub rebuild_phase {
522    my $app  = shift;
523    my $type = $app->param('_type') || 'entry';
524    my @ids  = $app->param('id');
525    $app->{goback} = "window.location='" . $app->return_uri . "'";
526    $app->{value} ||= $app->translate('Go Back');
527    if ( $type eq 'entry' ) {
528        my %ids = map { $_ => 1 } @ids;
529        return $app->rebuild_these( \%ids );
530    }
531    elsif ( $type eq 'template' ) {
532        require MT::Template;
533        foreach (@ids) {
534            my $template = MT::Template->load($_);
535            $app->rebuild_indexes(
536                Template => $template,
537                Force    => 1
538            ) or return;
539        }
540    }
541    $app->run_callbacks('post_build');
542    $app->call_return;
543}
544
545sub rebuild_pages {
546    my $app   = shift;
547    my $perms = $app->permissions
548      or return $app->error( $app->translate("No permissions") );
549    require MT::Entry;
550    require MT::Blog;
551    my $q             = $app->param;
552    my $start_time    = $q->param('start_time');
553
554    if ( ! $start_time ) {
555        # start of build; invoke callback
556        $app->run_callbacks('pre_build');
557        $start_time = time;
558    }
559
560    my $blog_id       = int($q->param('blog_id'));
561    return $app->errtrans("Invalid request.") unless $blog_id;
562
563    my $blog          = MT::Blog->load($blog_id)
564        or return $app->error($app->translate('Can\'t load blog #[_1].', $blog_id));
565    my $order         = $q->param('type');
566    my @order         = split /,/, $order;
567    my $next          = $q->param('next');
568    my $done          = 0;
569    my $type          = $order[$next];
570
571    my $pub           = $app->publisher;
572    $pub->start_time( $start_time )
573        if $start_time;  # force start time to parameter start_time
574
575    my $archiver      = $pub->archiver($type);
576    my $archive_label = $archiver ? $archiver->archive_label : '';
577
578    $archive_label = $app->translate($type) unless $archive_label;
579    $archive_label = $archive_label->() if ( ref $archive_label ) eq 'CODE';
580    $next++;
581    $done++ if $next >= @order;
582    my $offset = 0;
583    my ($total) = $q->param('total');
584
585    my $with_indexes = $q->param('with_indexes');
586    my $no_static = $q->param('no_static');
587    my $template_id = $q->param('template_id');
588    my $map_id = $q->param('templatemap_id');
589
590    my ($tmpl_saved);
591
592    # Make sure errors go to a sensible place when in fs mode
593    # TODO: create contin. earlier, pass it thru
594    if ( $app->param('fs') ) {
595        my ( $type, $obj_id ) = $app->param('type') =~ m/(entry|index)-(\d+)/;
596        if ( $type && $obj_id ) {
597            my $edit_type = $type;
598            $edit_type = 'template' if $type eq 'index';
599            if ($type eq 'entry') {
600                require MT::Entry;
601                my $entry = MT::Entry->load($obj_id);
602                $edit_type = $entry ? $entry->class : 'entry';
603            }
604            $app->{goback} =
605              "window.location='"
606              . $app->object_edit_uri( $edit_type, $obj_id ) . "'";
607            $app->{value} ||= $app->translate('Go Back');
608        }
609    }
610
611    if ( $type eq 'all' ) {
612        return $app->error( $app->translate("Permission denied.") )
613          unless $perms->can_rebuild;
614
615        # FIXME: Rebuild the entire blog????
616        $app->rebuild( BlogID => $blog_id )
617          or return $app->publish_error();
618    }
619    elsif ( $type eq 'index' ) {
620        return $app->error( $app->translate("Permission denied.") )
621          unless $perms->can_rebuild;
622        $app->rebuild_indexes( BlogID => $blog_id )
623            or return $app->publish_error();
624    }
625    elsif ( $type =~ /^index-(\d+)$/ ) {
626        return $app->error( $app->translate("Permission denied.") )
627          unless $perms->can_rebuild;
628        my $tmpl_id = $1;
629        require MT::Template;
630        $tmpl_saved = MT::Template->load($tmpl_id);
631        $app->rebuild_indexes(
632            BlogID   => $blog_id,
633            Template => $tmpl_saved,
634            Force    => 1
635        ) or return $app->publish_error();
636        $order = "index template '". $tmpl_saved->name . "'";
637    }
638    elsif ( $type =~ /^entry-(\d+)$/ ) {
639        my $entry_id = $1;
640        require MT::Entry;
641        my $entry = MT::Entry->load($entry_id);
642        return $app->error( $app->translate("Permission denied.") )
643          unless $perms->can_edit_entry( $entry, $app->user );
644        $app->rebuild_entry(
645            Entry             => $entry,
646            BuildDependencies => 1,
647            OldPrevious       => $q->param('old_previous'),
648            OldNext           => $q->param('old_next')
649        ) or return $app->publish_error();
650        $order = "entry '" . $entry->title . "'";
651    }
652    elsif ( $archiver && $archiver->category_based ) {
653        return $app->error( $app->translate("Permission denied.") )
654          unless $perms->can_rebuild;
655        $offset = $q->param('offset') || 0;
656        my $start = time;
657        my $count = 0;
658        my $cb    = sub {
659            my $result = time - $start > 20 ? 0 : 1;
660            $count++ if $result;
661            return $result;
662        };
663        if ( $offset < $total ) {
664            $app->rebuild(
665                BlogID         => $blog_id,
666                ArchiveType    => $type,
667                NoIndexes      => 1,
668                Offset         => $offset,
669                Limit          => $app->config->EntriesPerRebuild,
670                FilterCallback => $cb,
671            ) or return $app->publish_error();
672            $offset += $count;
673        }
674        if ( $offset < $total ) {
675            $done-- if $done;
676            $next--;
677        }
678        else {
679            $offset = 0;
680        }
681    }
682    elsif ($type) {
683        my $special = 0;
684        my @options = $app->{rebuild_options} ||= {};
685        $app->run_callbacks( 'rebuild_options', $app, \@options );
686        for my $optn (@options) {
687            if ( ( $optn->{key} || '' ) eq $type ) {
688                $optn->{code}->();
689                $special = 1;
690            }
691        }
692        if ( !$special ) {
693            return $app->error( $app->translate("Permission denied.") )
694              unless $perms->can_rebuild;
695            $offset = $q->param('offset') || 0;
696            if ( $offset < $total ) {
697                my $start = time;
698                my $count = 0;
699                my $cb    = sub {
700                    my $result = time - $start > 20 ? 0 : 1;
701                    $count++ if $result;
702                    return $result;
703                };
704                $app->rebuild(
705                    BlogID      => $blog_id,
706                    ArchiveType => $type,
707                    !$with_indexes ? ( NoIndexes => 1 ) : (),
708                    Offset         => $offset,
709                    Limit          => $app->config->EntriesPerRebuild,
710                    FilterCallback => $cb,
711                    $no_static ? ( NoStatic   => 1 )            : (),
712                    $template_id ? ( TemplateID => $template_id, Force => 1 ) : (),
713                    $map_id ? ( TemplateMap => $template_id, Force => 1 ) : (),
714                ) or return $app->publish_error();
715                $offset += $count;
716            }
717            if ( $offset < $total ) {
718                $done-- if $done;
719                $next--;
720            }
721            else {
722                $offset = 0;
723            }
724        }
725    }
726
727    # Rebuild done--now form the continuation.
728    unless ($done) {
729        my $dynamic   = 0;
730        my $type_name = $order[$next];
731
732        ## If we're moving on to the next rebuild step, recalculate the
733        ## limit.
734        my $static_count;
735        if ( $type_name !~ m/^index/ ) {
736            $static_count = $blog->count_static_templates($type_name) || 0;
737        }
738        else {
739            $static_count = 1;
740        }
741        if ( !$static_count ) {
742            $dynamic = 1;
743        }
744        elsif ( defined($offset) && $offset == 0 ) {
745            $dynamic = 0;
746        }
747        if ( $offset == 0 ) {
748
749            # determine total
750            if ( my $archiver = $app->publisher->archiver($type_name) ) {
751                if ( $archiver->entry_based || $archiver->date_based ) {
752                    my $entry_class = $archiver->entry_class || 'entry';
753                    require MT::Entry;
754                    my $terms = {
755                        class   => $entry_class,
756                        status  => MT::Entry::RELEASE(),
757                        blog_id => $blog_id,
758                    };
759                    $total = MT::Entry->count($terms);
760                }
761                elsif ( $archiver->category_based ) {
762                    require MT::Category;
763                    my $terms = { blog_id => $blog_id, };
764                    $total = MT::Category->count($terms);
765                }
766                elsif ( $archiver->author_based ) {
767                    require MT::Author;
768                    require MT::Entry;
769                    my $terms = {
770                        blog_id => $blog_id,
771                        status  => MT::Entry::RELEASE(),
772                        class   => 'entry',
773                    };
774                    $total = MT::Author->count(
775                        undef,
776                        {
777                            join   => MT::Entry->join_on( 'author_id', $terms, { unique => 1 } ),
778                            unique => 1,
779                        }
780                    );
781                }
782            }
783        }
784
785        my $type = $order[$next];
786        if ($type) {
787            $archiver      = $app->publisher->archiver($type);
788            $archive_label = $archiver ? $archiver->archive_label : '';
789            $archive_label = $app->translate($type) unless $archive_label;
790            $archive_label = $archive_label->()
791              if ( ref $archive_label ) eq 'CODE';
792        }
793
794        my $complete =
795          $total
796          ? ( $total == $offset ? 100 : int( ( $offset / $total ) * 100 ) )
797          : 0;
798
799        my %param = (
800            build_type      => $order,
801            build_next      => $next,
802            build_type_name => $archive_label,
803            archives        => $archiver ? 1 : 0,
804            total           => $total,
805            offset          => $offset,
806            complete        => $complete,
807            start_time      => $start_time,
808            incomplete      => 100 - $complete,
809            entry_id        => scalar $q->param('entry_id'),
810            dynamic         => $dynamic,
811            is_new          => scalar $q->param('is_new'),
812            old_status      => scalar $q->param('old_status'),
813            is_full_screen  => scalar $q->param('fs'),
814            with_indexes    => scalar $q->param('with_indexes'),
815            no_static       => scalar $q->param('no_static'),
816            template_id     => scalar $q->param('template_id'),
817            return_args     => scalar $q->param('return_args')
818        );
819        $app->load_tmpl( 'rebuilding.tmpl', \%param );
820    }
821    else {
822        $app->run_callbacks( 'post_build' );
823        if ( $q->param('entry_id') ) {
824            require MT::Entry;
825            my $entry = MT::Entry->load( scalar $q->param('entry_id') )
826                or return $app->error($app->translate('Can\'t load entry #[_1].', $q->param('entry_id')));
827            require MT::Blog;
828            my $blog = MT::Blog->load( $entry->blog_id )
829                or return $app->error($app->translate('Can\'t load blog #[_1].', $entry->blog_id));
830            require MT::CMS::Entry;
831            MT::CMS::Entry::ping_continuation( $app,
832                $entry, $blog,
833                OldStatus => scalar $q->param('old_status'),
834                IsNew     => scalar $q->param('is_new'),
835            );
836        }
837        else {
838            my $all          = $order =~ /,/;
839            my $type         = $order;
840            my $is_one_index = $order =~ /index template/;
841            my $is_entry     = $order =~ /entry/;
842            my $built_type;
843            if ( $is_entry || $is_one_index ) {
844                ( $built_type = $type ) =~
845                  s/^(entry|index template)/$app->translate($1)/e;
846            }
847            else {
848                $built_type = $app->translate($type);
849            }
850            my %param = (
851                all             => $all,
852                type            => $archive_label,
853                is_one_index    => $is_one_index,
854                is_entry        => $is_entry,
855                archives        => $type ne 'index',
856                start_timestamp => MT::Util::epoch2ts($blog, $start_time),
857                total_time      => time - $start_time,
858            );
859            if ($is_one_index) {
860                $param{tmpl_url} = $blog->site_url;
861                $param{tmpl_url} .= '/' if $param{tmpl_url} !~ m!/$!;
862                $param{tmpl_url} .= $tmpl_saved->outfile;
863            }
864            if ( $q->param('fs') ) {    # full screen--go to a useful app page
865                if ( my $return_args = $q->param('return_args') ) {
866                    $app->call_return;
867                }
868                else {
869                    my $type = $q->param('type');
870                    $type =~ /index-(\d+)/;
871                    my $tmpl_id = $1;
872                    $app->run_callbacks( 'rebuild', $blog );
873                    return $app->redirect(
874                        $app->uri(
875                            'mode' => 'view',
876                            args   => {
877                                '_type'       => 'template',
878                                id            => $tmpl_id,
879                                blog_id       => $blog->id,
880                                saved_rebuild => 1
881                            }
882                        )
883                    );
884                }
885            }
886            else {    # popup--just go to cnfrmn. page
887                return $app->load_tmpl( 'popup/rebuilt.tmpl', \%param );
888            }
889        }
890    }
891}
892
893sub rebuild_new_phase {
894    my ($app) = @_;
895    my %reb_set = map { $_ => 1 } $app->param('id');
896    $app->rebuild_these( \%reb_set, how => MT::App::CMS::NEW_PHASE() );
897}
898
899sub start_rebuild_pages {
900    my $app           = shift;
901    my $q             = $app->param;
902    my $start_time    = $q->param('start_time');
903
904    if ( ! $start_time ) {
905        # start of build; invoke callback
906        $app->run_callbacks('pre_build');
907        $start_time = time;
908    }
909
910    my $type          = $q->param('type') || '';
911    my $next          = $q->param('next') || 0;
912    my @order         = split /,/, $type;
913    my $total         = $q->param('total') || 0;
914    my $type_name     = $order[$next];
915    my $archiver      = $app->publisher->archiver($type_name);
916    my $archive_label = $archiver ? $archiver->archive_label : '';
917    $archive_label = $app->translate($type_name) unless $archive_label;
918    $archive_label = $archive_label->() if ( ref $archive_label ) eq 'CODE';
919    my $blog_id = $q->param('blog_id');
920
921    my $with_indexes   = $q->param('with_indexes');
922    my $no_static      = $q->param('no_static');
923    my $template_id    = $q->param('template_id');
924
925    if ($archiver) {
926        if ( $archiver->entry_based || $archiver->date_based ) {
927            my $entry_class = $archiver->entry_class || 'entry';
928            require MT::Entry;
929            my $terms = {
930                class   => $entry_class,
931                status  => MT::Entry::RELEASE(),
932                blog_id => $blog_id,
933            };
934            $total = MT::Entry->count($terms);
935        }
936        elsif ( $archiver->category_based ) {
937            require MT::Category;
938            my $terms = {
939                blog_id => $blog_id,
940                class   => $archiver->category_class,
941            };
942            $total = MT::Category->count($terms);
943        }
944        elsif ( $archiver->author_based ) {
945            require MT::Author;
946            require MT::Entry;
947            my $terms = {
948                blog_id => $blog_id,
949                status  => MT::Entry::RELEASE(),
950                class => 'entry',
951            };
952            $total = MT::Author->count(
953                undef,
954                {
955                    join   => MT::Entry->join_on( 'author_id', $terms, { unique => 1 } ),
956                    unique => 1,
957                }
958            );
959        }
960    }
961
962    my %param = (
963        build_type      => $type,
964        build_next      => $next,
965        total           => $total,
966        start_time      => $start_time,
967        complete        => 0,
968        incomplete      => 100,
969        build_type_name => $archive_label,
970        with_indexes    => $with_indexes,
971        no_static       => $no_static,
972        template_id     => $template_id,
973        return_args     => $app->return_args
974    );
975
976    if ( $type_name =~ /^index-(\d+)$/ ) {
977        my $tmpl_id = $1;
978        require MT::Template;
979        my $tmpl = MT::Template->load($tmpl_id)
980            or return $app->error($app->translate('Can\'t load template #[_1].', $tmpl_id));
981        $param{build_type_name} =
982          $app->translate( "index template '[_1]'", $tmpl->name );
983        $param{is_one_index} = 1;
984    }
985    elsif ( $type_name =~ /^entry-(\d+)$/ ) {
986        my $entry_id = $1;
987        require MT::Entry;
988        my $entry = MT::Entry->load($entry_id)
989            or return $app->error($app->translate('Can\'t load entry #[_1].', $entry_id));
990        $param{build_type_name} =
991          $app->translate( "[_1] '[_2]'", $entry->class_label, $entry->title );
992        $param{is_entry} = 1;
993        $param{entry_id} = $entry_id;
994        for my $col (qw( is_new old_status old_next old_previous )) {
995            $param{$col} = $q->param($col);
996        }
997    }
998    $param{is_full_screen} = ( $param{is_entry} )
999      || $q->param('single_template');
1000    $param{page_titles} = [ { bc_name => 'Rebuilding' } ];
1001    $app->load_tmpl( 'rebuilding.tmpl', \%param );
1002}
1003
1004sub _create_build_order {
1005    my ( $app, $blog, $param ) = @_;
1006
1007    my $at = $blog->archive_type || '';
1008    my ( @blog_at, @at, @data );
1009    my $archiver;
1010    my $archive_label;
1011
1012    if ( $at && $at ne 'None' ) {
1013        @blog_at = split /,/, $at;
1014        require MT::PublishOption;
1015        foreach my $t (@blog_at) {
1016            $archiver = $app->publisher->archiver($t);
1017            next unless $archiver;    # ignore unknown archive types
1018            next if MT::PublishOption::archive_build_type($blog->id, $t) == MT::PublishOption::DISABLED();
1019            push @at, $t;
1020            $archive_label = $archiver->archive_label;
1021            $archive_label = $at unless $archive_label;
1022            $archive_label = $archive_label->()
1023              if ( ref $archive_label ) eq 'CODE';
1024            push(
1025                @data,
1026                {
1027                    archive_type       => $t,
1028                    archive_type_label => $archive_label
1029                }
1030            );
1031        }
1032    }
1033    $param->{archive_type_loop} = \@data;
1034    $param->{build_order} = join ',', @at, 'index';
1035    1;
1036}
1037
1038sub rebuild_confirm {
1039    my $app     = shift;
1040    my $blog_id = $app->param('blog_id');
1041    require MT::Blog;
1042    my $blog = MT::Blog->load($blog_id)
1043        or return $app->error($app->translate('Can\'t load blog #[_1].', $blog_id));
1044
1045    my %param     = (
1046        build_next        => 0,
1047    );
1048    _create_build_order( $app, $blog, \%param );
1049
1050    $param{index_selected} = ( $app->param('prompt') || "" ) eq 'index';
1051
1052    if ( my $tmpl_id = $app->param('tmpl_id') ) {
1053        require MT::Template;
1054        my $tmpl = MT::Template->load($tmpl_id)
1055            or return $app->error($app->translate('Can\'t load template #[_1].', $tmpl_id));
1056        $param{index_tmpl_id}   = $tmpl->id;
1057        $param{index_tmpl_name} = $tmpl->name;
1058    }
1059    my $options = $app->registry("rebuild_options") || {};
1060    my @options;
1061    if ($options) {
1062        foreach my $opt ( keys %$options ) {
1063            $options->{$opt}{key} ||= $opt;
1064            push @options, $options->{$opt};
1065        }
1066    }
1067    $app->run_callbacks( 'rebuild_options', $app, \@options );
1068    my $rebuild_options = $app->filter_conditional_list( \@options );
1069    $param{rebuild_option_loop} = $rebuild_options;
1070    $param{refocus}             = 1;
1071    $app->add_breadcrumb( $app->translate('Publish Site') );
1072    $app->load_tmpl( 'popup/rebuild_confirm.tmpl', \%param );
1073}
1074
1075sub save_favorite_blogs {
1076    my $app = shift;
1077    $app->validate_magic() or return;
1078    my $fav = $app->param('id');
1079    return unless int($fav) > 0;
1080    $app->add_to_favorite_blogs($fav);
1081    $app->send_http_header("text/javascript+json");
1082    return 'true';
1083}
1084
1085sub cc_return {
1086    my $app   = shift;
1087    my $code  = $app->param('license_code');
1088    my $url   = $app->param('license_url');
1089    my $image = $app->param('license_button');
1090    my %param = ( license_name => MT::Util::cc_name($code) );
1091    if ($url) {
1092        $param{license_code} = "$code $url $image";
1093    }
1094    else {
1095        $param{license_code} = $code;
1096    }
1097    $app->load_tmpl( 'cc_return.tmpl', \%param );
1098}
1099
1100sub handshake {
1101    my $app               = shift;
1102    my $blog_id           = $app->param('blog_id');
1103    my $remote_auth_token = $app->param('remote_auth_token');
1104
1105    my %param = ();
1106    $param{remote_auth_token} = $remote_auth_token;
1107    $app->load_tmpl( 'handshake_return.tmpl', \%param );
1108}
1109
1110sub update_welcome_message {
1111    my $app = shift;
1112    $app->validate_magic or return;
1113
1114    my $perms = $app->permissions;
1115    return $app->errtrans("Permission denied.")
1116      unless $perms && $perms->can_edit_config;
1117
1118    my $blog_id    = $app->param('blog_id');
1119    my $message    = $app->param('welcome-message-text');
1120    my $blog_class = $app->model('blog');
1121    my $blog       = $blog_class->load($blog_id)
1122      or return $app->error( $app->translate("Invalid blog") );
1123    $blog->welcome_msg($message);
1124    $blog->save;
1125    $app->redirect(
1126        $app->uri( mode => 'menu', args => { blog_id => $blog_id } ) );
1127}
1128
1129sub dialog_select_weblog {
1130    my $app = shift;
1131
1132    #return $app->errtrans("Permission denied.")
1133    #    unless $app->user->is_superuser;
1134
1135    my $favorites = $app->param('select_favorites');
1136    my %favorite;
1137    my $confirm_js;
1138    my $terms = {};
1139    my $args  = {};
1140    if ($favorites) {
1141        my $auth = $app->user or return;
1142        if ( my @favs = @{ $auth->favorite_blogs || [] } ) {
1143            $terms->{id} = \@favs;
1144            $args->{not}{id} = 1;
1145        }
1146        $confirm_js = 'saveFavorite';
1147    }
1148
1149    my $hasher = sub {
1150        my ( $obj, $row ) = @_;
1151        $row->{label} = $row->{name};
1152        $row->{'link'} = $row->{site_url};
1153    };
1154
1155    $app->listing(
1156        {
1157            type     => 'blog',
1158            code     => $hasher,
1159            template => 'dialog/select_weblog.tmpl',
1160            terms    => $terms,
1161            args     => $args,
1162            params   => {
1163                dialog_title  => $app->translate("Select Blog"),
1164                items_prompt  => $app->translate("Selected Blog"),
1165                search_prompt => $app->translate(
1166                    "Type a blog name to filter the choices below."),
1167                panel_label       => $app->translate("Blog Name"),
1168                panel_description => $app->translate("Description"),
1169                panel_type        => 'blog',
1170                panel_multi       => defined $app->param('multi')
1171                ? $app->param('multi')
1172                : 0,
1173                panel_searchable => 1,
1174                panel_first      => 1,
1175                panel_last       => 1,
1176                list_noncron     => 1,
1177                return_url       => $app->uri . '?'
1178                  . ( $app->param('return_args') || '' ),
1179                confirm_js => $confirm_js,
1180                idfield    => ( $app->param('idfield') || '' ),
1181                namefield  => ( $app->param('namefield') || '' ),
1182            },
1183        }
1184    );
1185}
1186
1187sub can_view {
1188    my ( $eh, $app, $id ) = @_;
1189    my $perms = $app->permissions;
1190    if ( $id
1191        && ( $perms->can_set_publish_paths && !$perms->can_administer_blog ) )
1192    {
1193        return 1 if 'view' eq $app->mode;
1194    }
1195    if (
1196        (
1197            $id && !(
1198                   $perms->can_edit_config
1199                || $perms->can_set_publish_paths
1200                || $perms->can_manage_feedback
1201            )
1202        )
1203        || ( !$id && !$app->user->can_create_blog )
1204      )
1205    {
1206        return 0;
1207    }
1208    1;
1209}
1210
1211sub can_save {
1212    my ( $eh, $app, $id ) = @_;
1213    my $perms = $app->permissions;
1214    return ( $id
1215          && ( $perms->can_edit_config || $perms->can_set_publish_paths ) )
1216      || ( !$id && $app->user->can_create_blog );
1217}
1218
1219sub can_delete {
1220    my ( $eh, $app, $obj ) = @_;
1221    my $author = $app->user;
1222    return 1 if $author->is_superuser();
1223    require MT::Permission;
1224    my $perms = $author->permissions( $obj->id );
1225    return $perms && $perms->can_administer_blog;
1226}
1227
1228sub pre_save {
1229    my $eh = shift;
1230    my ( $app, $obj ) = @_;
1231    if ( !$app->param('overlay')
1232        && $app->param('cfg_screen') )
1233    {
1234
1235        # Checkbox options have to be blanked if they aren't passed.
1236        my $screen = $app->param('cfg_screen');
1237        my @fields;
1238        if ( $screen eq 'cfg_web_services' ) {
1239        }
1240        elsif ( $screen eq 'cfg_archives' ) {
1241        }
1242        elsif ( $screen eq 'cfg_templatemaps' ) {
1243        }
1244        elsif ( $screen eq 'cfg_comments' ) {
1245            @fields = qw( allow_comment_html autolink_urls
1246              use_comment_confirmation );
1247        }
1248        elsif ( $screen eq 'cfg_registration' ) {
1249            @fields = qw( allow_commenter_regist
1250              require_comment_emails allow_unreg_comments
1251              require_typekey_emails );
1252        }
1253        elsif ( $screen eq 'cfg_entry' ) {
1254            @fields = qw( allow_comments_default
1255              allow_pings_default );
1256        }
1257        elsif ( $screen eq 'cfg_trackbacks' ) {
1258            @fields = qw( allow_pings moderate_pings
1259              autodiscover_links internal_autodiscovery );
1260        }
1261        elsif ( $screen eq 'cfg_plugins' ) {
1262        }
1263        for my $cb (@fields) {
1264            unless ( defined $app->param($cb) ) {
1265
1266      # two possibilities: user unchecked the option, or user was not allowed to
1267      # set the value (and therefore there was no field to submit).
1268                my $perms = $app->permissions;
1269                if (
1270                    $app->user->is_superuser
1271                    || (
1272                        $perms
1273                        && (   $perms->can_administer_blog
1274                            || $perms->can_edit_config )
1275                    )
1276                  )
1277                {
1278                    $obj->$cb(0);
1279                }
1280                else {
1281                    delete $obj->{column_values}->{$cb};
1282                    delete $obj->{changed_cols}->{$cb};
1283                }
1284            }
1285        }
1286        if ( $screen eq 'cfg_comments' ) {
1287
1288            # value for comments:  1 == Accept from anyone
1289            #                      2 == Accept authenticated only
1290            #                      0 == No comments
1291            if ( $app->param('allow_comments') ) {
1292                $obj->allow_reg_comments(1);
1293            }
1294            else {
1295                $obj->allow_unreg_comments(0);
1296                $obj->allow_reg_comments(0);
1297            }
1298            $obj->moderate_unreg_comments( $app->param('moderate_comments') );
1299            $obj->nofollow_urls( $app->param('nofollow_urls')         ? 1 : 0 );
1300            $obj->follow_auth_links( $app->param('follow_auth_links') ? 1 : 0 );
1301            my $cp_old = $obj->captcha_provider;
1302            $obj->captcha_provider( $app->param('captcha_provider') );
1303            my $rebuild = $cp_old ne $obj->captcha_provider ? 1 : 0;
1304            $app->add_return_arg( need_full_rebuild => 1 ) if $rebuild;
1305        }
1306        if ( $screen eq 'cfg_web_services' ) {
1307            my $tok = '';
1308            ( $tok = $obj->remote_auth_token ) =~ s/\s//g;
1309            $obj->remote_auth_token($tok);
1310
1311            my $ping_servers = $app->registry('ping_servers');
1312            my @pings_list;
1313            push @pings_list, $_ foreach grep {
1314                defined( $app->param( 'ping_' . $_ ) )
1315                  && $app->param( 'ping_' . $_ )
1316              }
1317              keys %$ping_servers;
1318            $obj->update_pings( join( ',', @pings_list ) );
1319        }
1320        if ( $screen eq 'cfg_entry' ) {
1321            my %param = $_[0] ? %{ $_[0] } : ();
1322            my $pref_param = $app->load_entry_prefs;
1323            %param = ( %param, %$pref_param );
1324        }
1325        if ( $screen eq 'cfg_trackbacks' ) {
1326            if ( my $pings = $app->param('allow_pings') ) {
1327                if ($pings) {
1328                    $obj->moderate_pings( $app->param('moderate_pings') );
1329                    $obj->nofollow_urls( $app->param('nofollow_urls') ? 1 : 0 );
1330                }
1331                else {
1332                    $obj->moderate_pings(1);
1333                    $obj->email_new_pings(1);
1334                }
1335            }
1336        }
1337        if ( $screen eq 'cfg_registration' ) {
1338            $obj->allow_commenter_regist(
1339                $app->param('allow_commenter_regist') );
1340            $obj->allow_unreg_comments( $app->param('allow_unreg_comments') );
1341            if ( $app->param('allow_unreg_comments') ) {
1342                $obj->require_comment_emails(
1343                    $app->param('require_comment_emails') );
1344            }
1345            else {
1346                $obj->require_comment_emails(0);
1347            }
1348            my @authenticators;
1349
1350            my $c = $app->registry('commenter_authenticators');
1351            foreach ( keys %$c ) {
1352                if ( $app->param( 'enabled_' . $_ ) ) {
1353                    push @authenticators, $_;
1354                }
1355            }
1356            push @authenticators, 'MovableType'
1357              if $app->param('enabled_MovableType');
1358            my $c_old = $obj->commenter_authenticators;
1359            $obj->commenter_authenticators( join( ',', @authenticators ) );
1360            my $rebuild = $obj->commenter_authenticators ne $c_old ? 1 : 0;
1361            if ( $app->param('enabled_TypeKey') ) {
1362                $rebuild = $obj->require_typekey_emails ? 0 : 1;
1363                $obj->require_typekey_emails(
1364                    $app->param('require_typekey_emails') );
1365            }
1366            else {
1367                $obj->require_typekey_emails(0);
1368            }
1369            my $tok = '';
1370            ( $tok = $obj->remote_auth_token ) =~ s/\s//g;
1371            $obj->remote_auth_token($tok);
1372
1373            $app->add_return_arg( need_full_rebuild => 1 ) if $rebuild;
1374        }
1375        if ( $screen eq 'cfg_spam' ) {
1376            my $threshold = $app->param('junk_score_threshold');
1377            $threshold =~ s/\+//;
1378            $threshold ||= 0;
1379            $obj->junk_score_threshold($threshold);
1380            if ( my $expiry = $app->param('junk_folder_expiry') ) {
1381                $obj->junk_folder_expiry($expiry);
1382            }
1383            my $perms = $app->permissions;
1384            unless ( defined $app->param('auto_delete_junk') ) {
1385                if (
1386                    $app->user->is_superuser
1387                    || (
1388                        $perms
1389                        && (   $perms->can_administer_blog
1390                            || $perms->can_edit_config )
1391                    )
1392                  )
1393                {
1394                    $obj->junk_folder_expiry(0);
1395                }
1396                else {
1397                    delete $obj->{column_values}{junk_folder_expiry};
1398                    delete $obj->{changed_cols}{junk_folder_expiry};
1399                }
1400            }
1401        }
1402        if ( $screen eq 'cfg_entry' ) {
1403            my %param = $_[0] ? %{ $_[0] } : ();
1404            my $pref_param = $app->load_entry_prefs;
1405            %param = ( %param, %$pref_param );
1406            $param{ 'sort_order_posts_' . ( $obj->sort_order_posts || 0 ) } = 1;
1407            $param{words_in_excerpt} = 40
1408              unless defined $param{words_in_excerpt}
1409              && $param{words_in_excerpt} ne '';
1410            if ( $app->param('days_or_posts') eq 'days' ) {
1411                $obj->days_on_index( $app->param('list_on_index') );
1412                $obj->entries_on_index(0);
1413            }
1414            else {
1415                $obj->entries_on_index( $app->param('list_on_index') );
1416                $obj->days_on_index(0);
1417            }
1418            $obj->basename_limit(15)
1419              if $obj->basename_limit < 15;    # 15 is the *minimum*
1420            $obj->basename_limit(250)
1421              if $obj->basename_limit > 250;    # 15 is the *maximum*
1422        }
1423        if ( $screen eq 'cfg_archives' ) {
1424            $obj->include_system( $app->param('include_system') || '' );
1425            if ( !$app->param('enable_archive_paths') ) {
1426                $obj->archive_url('');
1427                $obj->archive_path('');
1428            }
1429        }
1430        if ( $screen eq 'cfg_publish_profile' ) {
1431            if ( my $dcty = $app->param('dynamicity') ) {
1432                $obj->custom_dynamic_templates($dcty);
1433            }
1434        }
1435    }
1436    else {
1437
1438        #$obj->is_dynamic(0) unless defined $app->{query}->param('is_dynamic');
1439    }
1440
1441    if ( ( $obj->sanitize_spec || '' ) eq '1' ) {
1442        $obj->sanitize_spec( scalar $app->param('sanitize_spec_manual') );
1443    }
1444
1445    1;
1446}
1447
1448sub _update_finfos {
1449    my ($app, $new_virtual, $where) = @_;
1450    my $finfo_class = MT->model('fileinfo');
1451    my $driver = $finfo_class->driver;
1452    my $dbd = $driver->dbd;
1453
1454    my $stmt = $dbd->sql_class->new;
1455
1456    if ($where) {
1457        my $new_where = {};
1458        while (my ($key, $val) = each %$where) {
1459            my $new_key = $dbd->db_column_name($finfo_class->datasource, $key);
1460            $new_where->{$new_key} = $val;
1461        }
1462        $stmt->add_complex_where([ $new_where ]);
1463    }
1464    my $virtual_col = $dbd->db_column_name($finfo_class->datasource, 'virtual');
1465    $stmt->add_complex_where([ {
1466        $virtual_col => [
1467            { op => '!=', value => $new_virtual },
1468            \"is null",
1469        ]
1470    } ]);
1471
1472    my $sql = join q{ }, 'UPDATE', $driver->table_for($finfo_class), 'SET',
1473        $virtual_col, '= ?', $stmt->as_sql_where();
1474
1475    my $dbh = $driver->rw_handle;
1476    $dbh->do($sql, {}, $new_virtual, @{ $stmt->{bind} })
1477        or return $app->error($dbh->errstr || $DBI::errstr);
1478    1;
1479}
1480
1481sub post_save {
1482    my $eh = shift;
1483    my ( $app, $obj, $original ) = @_;
1484
1485    my $perms = $app->permissions;
1486    return 1
1487      unless $app->user->is_superuser
1488      || $app->user->can_create_blog
1489      || ( $perms && $perms->can_edit_config );
1490
1491    my $screen = $app->param('cfg_screen') || '';
1492    if ( $screen eq 'cfg_publish_profile' ) {
1493        if ( my $dcty = $app->param('dynamicity') ) {
1494            # Apply publishing rules for templates based on
1495            # publishing method selected:
1496            #     none (0% publish queue, all static)
1497            #     async_all (100% publish queue)
1498            #     async_partial (high-priority templates publish synchronously (main index, preferred indiv. archives, feed templates))
1499            #     all (100% dynamic)
1500            #     archives (archives dynamic, static indexes)
1501            #     custom (custom configuration)
1502
1503            update_publishing_profile(
1504                $app,
1505                $obj
1506            );
1507
1508            if (($dcty eq 'none') || ($dcty =~ m/^async/)) {
1509                _update_finfos($app, 0);
1510            }
1511            elsif ($dcty eq 'all') {
1512                _update_finfos($app, 1);
1513            }
1514            elsif ($dcty eq 'archives') {
1515                # Only archives have template maps.
1516                _update_finfos($app, 1, { templatemap_id => \'is not null' });
1517                _update_finfos($app, 0, { templatemap_id => \'is null' });
1518            }
1519        }
1520
1521        cfg_publish_profile_save($app, $obj) or return;
1522    }
1523    if ( $screen eq 'cfg_archives' ) {
1524        # If either of the publishing paths changed, rebuild the fileinfos.
1525        my $path_changed = 0;
1526        for my $path_field (qw( site_path archive_path site_url archive_url )) {
1527            $path_changed = 1 && last if $app->param($path_field)
1528                && $app->param($path_field) ne $original->$path_field();
1529        }
1530
1531        if ($path_changed) {
1532            $app->rebuild( BlogID => $obj->id, NoStatic => 1 )
1533                or return $app->publish_error();
1534        }
1535
1536        cfg_archives_save($app, $obj) or return;
1537    }
1538    if ( $screen eq 'cfg_prefs' ) {
1539        my $blog_id = $obj->id;
1540
1541        # FIXME: Needs to exclude MT::Permission records for groups
1542        $app->model('permission')
1543          ->load( { blog_id => $blog_id, author_id => 0 } );
1544        if ( !$perms ) {
1545            $perms = $app->model('permission')->new;
1546            $perms->blog_id($blog_id);
1547            $perms->author_id(0);
1548        }
1549    }
1550    if ( $screen eq 'cfg_entry' ) {
1551        my $blog_id = $obj->id;
1552
1553        # FIXME: Needs to exclude MT::Permission records for groups
1554        my $perms =
1555          $app->model('permission')
1556          ->load( { blog_id => $blog_id, author_id => 0 } );
1557        if ( !$perms ) {
1558            $perms = $app->model('permission')->new;
1559            $perms->blog_id($blog_id);
1560            $perms->author_id(0);
1561        }
1562        my $prefs = $app->_entry_prefs_from_params;
1563        if ($prefs) {
1564            $perms->entry_prefs($prefs);
1565            $perms->save
1566              or return $app->errtrans( "Saving permissions failed: [_1]",
1567                $perms->errstr );
1568        }
1569    }
1570
1571    if ( !$original->id ) {    # If the object is new, the "orignal" was blank
1572        ## If this is a new blog, we need to set up a permissions
1573        ## record for the existing user.
1574        $obj->create_default_templates( $obj->template_set );
1575
1576        # Add this blog to the user's "favorite blogs", pushing any 10th
1577        # blog off the list
1578        my $auth = $app->user;
1579
1580        # FIXME: Should we still be doing this?
1581        my $perms = $app->model('permission')->new;
1582        $perms->author_id( $auth->id );
1583        $perms->blog_id( $obj->id );
1584        $perms->set_full_permissions;
1585        $perms->save;
1586
1587        # permission granted - need to update commenting cookie
1588        my %cookies = $app->cookies();
1589        $app->cookie_val();
1590        my ($x, $y, $remember) = split(/::/, $cookies{$app->user_cookie()}->value);
1591        my $cookie  = $cookies{'commenter_id'};
1592        my $cookie_value = $cookie ? $cookie->value : '';
1593        my ($id, $blog_ids) = split(':', $cookie_value);
1594        if ( $blog_ids ne 'S' && $blog_ids ne 'N' ) {
1595            $blog_ids .= ",'" . $obj->id . "'";
1596        }
1597        my $timeout = $remember ? '+10y' : 0;
1598        $timeout = '+' . $app->config->CommentSessionTimeout . 's' unless $timeout;
1599        my %id_kookee = (-name => "commenter_id",
1600                           -value => $auth->id . ':' . $blog_ids,
1601                           -path => '/',
1602                           ($timeout ? (-expires => $timeout) : ()));
1603        $app->bake_cookie(%id_kookee);
1604
1605        require MT::Log;
1606        $app->log(
1607            {
1608                message => $app->translate(
1609                    "Blog '[_1]' (ID:[_2]) created by '[_3]'",
1610                    $obj->name, $obj->id, $auth->name
1611                ),
1612                level    => MT::Log::INFO(),
1613                class    => 'blog',
1614                category => 'new',
1615            }
1616        );
1617
1618        $app->run_callbacks( 'blog_template_set_change', { blog => $obj } );
1619    }
1620    else {
1621
1622        # if you've changed the comment configuration
1623        if (
1624            (
1625                grep { $original->column($_) ne $obj->column($_) }
1626                qw(allow_unreg_comments allow_reg_comments remote_auth_token)
1627            )
1628          )
1629        {
1630            if ( RegistrationAffectsArchives( $obj->id, 'Individual' ) ) {
1631                $app->add_return_arg( need_full_rebuild => 1 );
1632            }
1633            else {
1634                $app->add_return_arg( need_index_rebuild => 1 );
1635            }
1636        }
1637
1638        # if other settings were changed that would affect published pages:
1639        if ( grep { $original->column($_) ne $obj->column($_) }
1640            qw(allow_pings allow_comment_html) )
1641        {
1642            $app->add_return_arg( need_full_rebuild => 1 );
1643        }
1644
1645        if ( ($original->template_set || '') ne ($obj->template_set || '') ) {
1646            $app->run_callbacks( 'blog_template_set_change', { blog => $obj } );
1647            $app->add_return_arg( need_full_rebuild => 1 );
1648        }
1649    }
1650    1;
1651}
1652
1653sub save_filter {
1654    my $eh    = shift;
1655    my ($app) = @_;
1656    my $name  = $app->param('name');
1657    if ( defined $name ) {
1658        $name =~ s/(^\s+|\s+$)//g;
1659        $app->param( 'name', $name );
1660    }
1661    my $perms = $app->permissions;
1662    my $screen = $app->param('cfg_screen') || '';
1663    return $eh->error( MT->translate("You did not specify a blog name.") )
1664      if ( !( $screen && $perms->can_edit_config )
1665        && ( defined $app->param('name') && ( $app->param('name') eq '' ) ) );
1666    return $eh->error( MT->translate("Site URL must be an absolute URL.") )
1667      if ( $screen eq 'cfg_archives' )
1668      && $perms->can_set_publish_paths
1669      && $app->param('site_url') !~ m.^https?://.;
1670    return $eh->error( MT->translate("Archive URL must be an absolute URL.") )
1671      if ( $screen eq 'cfg_archives' )
1672      && $perms->can_set_publish_paths
1673      && $app->param('archive_url') !~ m.^https?://.
1674      && $app->param('enable_archive_paths');
1675    return $eh->error( MT->translate("You did not specify an Archive Root.") )
1676      if ( $screen eq 'cfg_archives' )
1677      && $app->param('archive_path') =~ m/^\s*$/
1678      && $app->param('enable_archive_paths');
1679    return 1;
1680}
1681
1682sub post_delete {
1683    my ( $eh, $app, $obj ) = @_;
1684
1685    $app->log(
1686        {
1687            message => $app->translate(
1688                "Blog '[_1]' (ID:[_2]) deleted by '[_3]'",
1689                $obj->name, $obj->id, $app->user->name
1690            ),
1691            level    => MT::Log::INFO(),
1692            class    => 'blog',
1693            category => 'delete'
1694        }
1695    );
1696    require MT::CMS::User;
1697    MT::CMS::User::_delete_pseudo_association($app, undef, $obj->id);
1698}
1699
1700sub make_blog_list {
1701    my $app = shift;
1702    my ($blogs) = @_;
1703
1704    my $author = $app->user;
1705    my $data;
1706    my $can_edit_authors = 1 if $author->is_superuser;
1707    my @blog_ids = map { $_->id } @$blogs; 
1708    my %counts;
1709    my $e_iter = $app->model('entry')->count_group_by(
1710        { blog_id => \@blog_ids },
1711        { group => [ 'blog_id' ] }
1712    );
1713    while ( my ($e_count, $e_blog_id) = $e_iter->() ) {
1714        $counts{$e_blog_id}{'entry'} = $e_count;
1715    }
1716    my $c_iter = $app->model('comment')->count_group_by(
1717        { blog_id => \@blog_ids },
1718        { group => [ 'blog_id' ] }
1719    );
1720    while ( my ($c_count, $c_blog_id) = $c_iter->() ) {
1721        $counts{$c_blog_id}{'comment'} = $c_count;
1722    }
1723    my $p_iter = $app->model('tbping')->count_group_by(
1724        { blog_id => \@blog_ids },
1725        { group => [ 'blog_id' ] }
1726    );
1727    while ( my ($p_count, $p_blog_id) = $p_iter->() ) {
1728        $counts{$p_blog_id}{'ping'} = $p_count;
1729    }
1730
1731    for my $blog (@$blogs) {
1732        my $blog_id = $blog->id;
1733        my $perms   = $author->permissions($blog_id);
1734        my $row     = {
1735            id          => $blog->id,
1736            name        => $blog->name,
1737            description => $blog->description,
1738            site_url    => $blog->site_url
1739        };
1740        $row->{num_entries}  = $counts{$blog_id}{'entry'};
1741        $row->{num_comments} = $counts{$blog_id}{'comment'};
1742        $row->{num_pings}    = $counts{$blog_id}{'ping'};
1743        $row->{can_create_post}  = $perms->can_create_post;
1744        $row->{can_edit_entries} = $perms->can_create_post
1745          || $perms->can_edit_all_posts
1746          || $perms->can_publish_post;
1747        $row->{can_edit_templates} = $perms->can_edit_templates;
1748        $row->{can_edit_config}    = $perms->can_edit_config
1749          || $perms->can_administer_blog;
1750        $row->{can_set_publish_paths} = $perms->can_set_publish_paths
1751          || $perms->can_administer_blog;
1752        $row->{can_manage_feedback} = $perms->can_manage_feedback;
1753        $row->{can_edit_assets}     = $perms->can_edit_assets;
1754        $row->{can_administer_blog} = $perms->can_administer_blog;
1755        push @$data, $row;
1756    }
1757    $data;
1758}
1759
1760sub build_blog_table {
1761    my $app = shift;
1762    my (%args) = @_;
1763
1764    my $blog_class    = $app->model('blog');
1765    my $tbp_class     = $app->model('ping');
1766    my $entry_class   = $app->model('entry');
1767    my $comment_class = $app->model('comment');
1768
1769    my $iter;
1770    if ( $args{load_args} ) {
1771        my $class = $app->model('blog');
1772        $iter = $class->load_iter( @{ $args{load_args} } );
1773    }
1774    elsif ( $args{iter} ) {
1775        $iter = $args{iter};
1776    }
1777    elsif ( $args{items} ) {
1778        $iter = sub { pop @{ $args{items} } };
1779    }
1780    return [] unless $iter;
1781    my $param = $args{param};
1782
1783    my $author           = $app->user;
1784    my $can_edit_authors = $author->is_superuser;
1785    my @data;
1786    my $i;
1787    my ( $entry_count, $ping_count, $comment_count );
1788    while ( my $blog = $iter->() ) {
1789        my $blog_id = $blog->id;
1790        my $row     = {
1791            id          => $blog->id,
1792            name        => $blog->name,
1793            description => $blog->description,
1794            site_url    => $blog->site_url
1795        };
1796
1797        # we should use count by group here...
1798        $row->{num_entries} =
1799          ( $entry_count ? $entry_count->{$blog_id} : $entry_count->{$blog_id} =
1800              MT::Entry->count( { blog_id => $blog_id } ) )
1801          || 0;
1802        $row->{num_comments} = (
1803              $comment_count
1804            ? $comment_count->{$blog_id}
1805            : $comment_count->{$blog_id} = MT::Comment->count(
1806                { blog_id => $blog_id, junk_status => MT::Comment::NOT_JUNK() }
1807            )
1808          )
1809          || 0;
1810        $row->{num_pings} = (
1811            $ping_count ? $ping_count->{$blog_id} : $ping_count->{$blog_id} =
1812              MT::TBPing->count(
1813                { blog_id => $blog_id, junk_status => MT::TBPing::NOT_JUNK() }
1814              )
1815        ) || 0;
1816        $row->{num_authors} = 0;
1817
1818        # FIXME: This isn't efficient
1819        my $iter = MT::Permission->load_iter(
1820            {
1821                blog_id => [ 0, $blog_id ],
1822
1823                #    role_mask => [ 2, undef ]
1824                #}, {
1825                #    range_incl => { 'role_mask' => 1 }
1826            }
1827        );
1828        my %a;
1829        while ( my $p = $iter->() ) {
1830            next if exists $a{ $p->author_id };
1831            $a{ $p->author_id } = 1;
1832            $row->{num_authors}++ if $p->can_create_post;
1833        }
1834        if ( $author->is_superuser ) {
1835            $row->{can_create_post}       = 1;
1836            $row->{can_edit_entries}      = 1;
1837            $row->{can_edit_templates}    = 1;
1838            $row->{can_edit_config}       = 1;
1839            $row->{can_set_publish_paths} = 1;
1840            $row->{can_administer_blog}   = 1;
1841        }
1842        else {
1843            my $perms = $author->permissions($blog_id);
1844            $row->{can_create_post}  = $perms->can_create_post;
1845            $row->{can_edit_entries} = $perms->can_create_post
1846              || $perms->can_edit_all_posts
1847              || $perms->can_publish_post;
1848            $row->{can_edit_templates} = $perms->can_edit_templates;
1849            $row->{can_edit_config}    = $perms->can_edit_config
1850              || $perms->can_administer_blog;
1851            $row->{can_set_publish_paths} = $perms->can_set_publish_paths
1852              || $perms->can_administer_blog;
1853            $row->{can_administer_blog} = $perms->can_administer_blog;
1854        }
1855        $row->{object} = $blog;
1856        push @data, $row;
1857    }
1858
1859    if (@data) {
1860        $param->{blog_table}[0]{object_loop} = \@data;
1861        $app->load_list_actions( 'blog', \%$param );
1862        $param->{object_loop} = $param->{blog_table}[0]{object_loop};
1863    }
1864
1865    \@data;
1866}
1867
1868sub cfg_blog {
1869    my $q = $_[0]->{query};
1870    $q->param( '_type', 'blog' );
1871    $q->param( 'id',    scalar $q->param('blog_id') );
1872    $_[0]->forward( "view", { output => 'cfg_prefs.tmpl' } );
1873}
1874
1875sub cfg_archives_save {
1876    my $app = shift;
1877    my ($blog) = @_;
1878
1879    my $at = $app->param('preferred_archive_type');
1880    $blog->archive_type_preferred($at);
1881    $blog->include_cache( $app->param('include_cache') ? 1 : 0 );
1882    require MT::PublishOption;
1883    if ( ( $app->model('template')->exist(
1884            { blog_id => $blog->id, build_type => MT::PublishOption::DYNAMIC() })
1885        || $app->model('templatemap')->exist(
1886            { blog_id => $blog->id, build_type => MT::PublishOption::DYNAMIC() }) ) )
1887    {
1888        # dynamic enabled and caching option may have changed - update mtview
1889        my $cache       = $app->param('dynamic_cache')       ? 1 : 0;
1890        my $conditional = $app->param('dynamic_conditional') ? 1 : 0;
1891        _create_mtview( $blog, $blog->site_path, $cache, $conditional );
1892        _create_dynamiccache_dir( $blog, $blog->site_path ) if $cache;
1893        if ( $blog->archive_path ) {
1894            _create_mtview( $blog, $blog->archive_path, $cache, $conditional );
1895            _create_dynamiccache_dir( $blog, $blog->archive_path ) if $cache;
1896        }
1897    }
1898    $blog->save
1899      or return $app->error(
1900        $app->translate( "Saving blog failed: [_1]", $blog->errstr ) );
1901
1902    1;
1903}
1904
1905sub cfg_publish_profile_save {
1906    my $app = shift;
1907    my ($blog) = @_;
1908
1909    my $dcty = $app->param('dynamicity') || 'none';
1910    my $pq = $dcty =~ m/^async/ ? 1 : 0;
1911    $blog->publish_queue( $pq );
1912    if ( $dcty eq 'all' || $dcty eq 'archives' ) {
1913        # update the dynamic publishing options if they changed
1914        update_dynamicity(
1915            $app,
1916            $blog
1917        );
1918    }
1919    $blog->save
1920      or return $app->error(
1921        $app->translate( "Saving blog failed: [_1]", $blog->errstr ) );
1922
1923    1;
1924}
1925
1926# FIXME: Faulty, since it doesn't take into account module includes
1927sub RegistrationAffectsArchives {
1928    my ( $blog_id, $archive_type ) = @_;
1929    require MT::TemplateMap;
1930    require MT::Template;
1931    my @tms = MT::TemplateMap->load(
1932        {
1933            archive_type  => $archive_type,
1934            blog_id       => $blog_id
1935        }
1936    );
1937    grep { !$_->build_dynamic && ($_->text =~ /<MT:?IfRegistration/i) }
1938      map { MT::Template->load( $_->template_id ) } @tms;
1939}
1940
1941sub update_publishing_profile {
1942    my $app = shift;
1943    my ( $blog ) = @_;
1944
1945    my $dcty = $blog->custom_dynamic_templates;
1946
1947    require MT::PublishOption;
1948    require MT::Template;
1949
1950    if ( ($dcty eq 'none') || ($dcty =~ m/^async/) ) {
1951        my @templates = MT::Template->load( {
1952            blog_id => $blog->id,
1953            # FIXME: enumeration of types
1954            type =>
1955              [ 'index', 'archive', 'individual', 'page', 'category' ],
1956          } );
1957        for my $tmpl (@templates) {
1958            my $bt = $tmpl->build_type || 0;
1959            # Do not make automatic modifications to templates with these
1960            # manually configured build types
1961            next if $bt == MT::PublishOption::DISABLED();
1962            next if $bt == MT::PublishOption::MANUALLY();
1963            next if $bt == MT::PublishOption::SCHEDULED();
1964
1965            if ($dcty eq 'async_partial') {
1966                # these should be build synchronously
1967                if (($tmpl->identifier || '') =~ m/^(main_index|feed_recent)$/) {
1968                    $tmpl->build_type(MT::PublishOption::ONDEMAND());
1969                } else {
1970                    if (($tmpl->type eq 'individual') || ($tmpl->type eq 'page')) {
1971                        my @tmpl_maps = MT::TemplateMap->load( { template_id => $tmpl->id } );
1972                        foreach my $tmpl_map (@tmpl_maps) {
1973                            if (($tmpl_map->archive_type =~ m/^(Individual|Page)$/) &&
1974                                ($tmpl_map->is_preferred)) {
1975                                    $tmpl_map->build_type(MT::PublishOption::ONDEMAND());
1976                                $tmpl_map->save;
1977                                next;
1978                            }
1979                            if ( $tmpl_map->build_type != MT::PublishOption::ASYNC() ) {
1980                                $tmpl_map->build_type(MT::PublishOption::ASYNC());
1981                                $tmpl_map->save;
1982                            }
1983                        }
1984                    }
1985                    else {
1986                        # updates all template maps too
1987                        $tmpl->build_type(MT::PublishOption::ASYNC());
1988                    }
1989                }
1990            } elsif ($dcty eq 'async_all') {
1991                $tmpl->build_type(MT::PublishOption::ASYNC());
1992            } else {
1993                $tmpl->build_type(MT::PublishOption::ONDEMAND());
1994            }
1995            $tmpl->save();
1996        }
1997    }
1998    elsif ( $dcty eq 'archives' ) {
1999        my @templates = MT::Template->load( {
2000            blog_id => $blog->id,
2001            # FIXME: enumeration of types
2002            type =>
2003              [ 'index', 'archive', 'individual', 'page', 'category' ],
2004          } );
2005        for my $tmpl (@templates) {
2006            my $bt = $tmpl->build_type || 0;
2007            next if $bt == MT::PublishOption::DISABLED();
2008            next if $bt == MT::PublishOption::MANUALLY();
2009            next if $bt == MT::PublishOption::SCHEDULED();
2010
2011            $tmpl->build_type( $tmpl->type ne 'index' ? MT::PublishOption::DYNAMIC() : MT::PublishOption::ONDEMAND() );
2012            $tmpl->save();
2013        }
2014    }
2015    elsif ( $dcty eq 'all' ) {
2016        my @templates = MT::Template->load(
2017            {
2018                blog_id => $blog->id,
2019
2020                # FIXME: enumeration of types
2021                type =>
2022                  [ 'index', 'archive', 'individual', 'page', 'category' ],
2023            }
2024        );
2025        for my $tmpl (@templates) {
2026            my $bt = $tmpl->build_type || 0;
2027            next if $bt == MT::PublishOption::DISABLED();
2028            next if $bt == MT::PublishOption::MANUALLY();
2029            next if $bt == MT::PublishOption::SCHEDULED();
2030
2031            $tmpl->build_type( MT::PublishOption::DYNAMIC() );
2032            $tmpl->save();
2033        }
2034    }
2035    return 1;
2036}
2037
2038sub update_dynamicity {
2039    my $app = shift;
2040    my ( $blog ) = @_;
2041
2042    my $cache       = $app->param('dynamic_cache')       ? 1 : 0;
2043    my $conditional = $app->param('dynamic_conditional') ? 1 : 0;
2044
2045    require MT::PublishOption;
2046    if ( $app->model('template')->exist(
2047            { blog_id => $blog->id, build_type => MT::PublishOption::DYNAMIC() })
2048      || $app->model('templatemap')->exist(
2049            { blog_id => $blog->id, build_type => MT::PublishOption::DYNAMIC() }) )
2050    {
2051        # dynamic publishing enabled
2052        prepare_dynamic_publishing($app, $blog, $cache, $conditional, $blog->site_path, $blog->site_url);
2053        if ( $blog->archive_path ) {
2054            prepare_dynamic_publishing($app, $blog, $cache, $conditional, $blog->archive_path, $blog->archive_url);
2055        }
2056        my $compiled_template_path =
2057          File::Spec->catfile( $blog->site_path(), 'templates_c' );
2058        if ( -d $compiled_template_path ) {
2059            $app->add_return_arg( 'no_writecache' => 1 )
2060              unless ( -w $compiled_template_path );
2061        }
2062        else {
2063            $app->add_return_arg( 'no_cachedir' => 1 )
2064              unless ( -d $compiled_template_path );
2065        }
2066
2067        # FIXME: use FileMgr
2068        if ($cache) {
2069            my $cache_path = File::Spec->catfile( $blog->site_path(), 'cache' );
2070            if ( -d $cache_path ) {
2071                $app->add_return_arg( 'no_write_cache_path' => 1 )
2072                  unless ( -w $cache_path );
2073            }
2074            else {
2075                $app->add_return_arg( 'no_cache_path' => 1 )
2076                  unless ( -d $cache_path );
2077            }
2078        }
2079    }
2080}
2081
2082sub _create_mtview {
2083    my ( $blog, $site_path, $cache, $conditional ) = @_;
2084
2085    my $mtview_path = File::Spec->catfile( $site_path, "mtview.php" );
2086    eval {
2087        my $mv_contents = '';
2088        if ( -f $mtview_path ) {
2089            open( my $mv, "<$mtview_path" );
2090            while ( my $line = <$mv> ) {
2091                $mv_contents .= $line if ( $line !~ m!^//|<\?(?:php)?|\?>! );
2092            }
2093            close $mv;
2094        }
2095        my $cgi_path = MT->instance->server_path() || "";
2096        $cgi_path =~ s!/*$!!;
2097        my $mtphp_path = File::Spec->canonpath("$cgi_path/php/mt.php");
2098        my $blog_id    = $blog->id;
2099        my $config     = MT->instance->{cfg_file};
2100        my $cache_code = $cache ? "\n    \$mt->caching = true;" : '';
2101        my $conditional_code =
2102          $conditional ? "\n    \$mt->conditional = true;" : '';
2103        my $new_mtview = <<NEW_MTVIEW;
2104
2105    include('$mtphp_path');
2106    \$mt = new MT($blog_id, '$config');$cache_code$conditional_code
2107    \$mt->view();
2108NEW_MTVIEW
2109
2110        if ( $new_mtview ne substr( $mv_contents, 0, length($new_mtview) ) ) {
2111            $mv_contents =~ s!\n!\n//!gs;
2112            my $mtview = <<MTVIEW;
2113<?php
2114$new_mtview
2115$mv_contents
2116?>
2117MTVIEW
2118
2119            $blog->file_mgr->mkpath( $site_path );
2120            open( my $mv, ">$mtview_path" )
2121              || die "Couldn't open $mtview_path for appending";
2122            print $mv $mtview || die "Couldn't write to $mtview_path";
2123            close $mv;
2124        }
2125    };
2126    if ($@) { print STDERR $@; }
2127}
2128
2129sub _create_dynamiccache_dir {
2130    my ( $blog, $site_path ) = @_;
2131
2132    # FIXME: use FileMgr
2133    my $cache_path = File::Spec->catfile( $site_path, 'cache' );
2134    my $fmgr = $blog->file_mgr;
2135    my $saved_umask = MT->config->DirUmask;
2136    MT->config->DirUmask('0000');
2137    $fmgr->mkpath($cache_path);
2138    MT->config->DirUmask($saved_umask);
2139    my $message;
2140    if ( -d $cache_path ) {
2141        $message = MT->translate(
2142'Error: Movable Type cannot write to the template cache directory. Please check the permissions for the directory called <code>[_1]</code> underneath your blog directory.',
2143            'cache'
2144        ) unless ( -w $cache_path );
2145    }
2146    else {
2147        $message = MT->translate(
2148'Error: Movable Type was not able to create a directory to cache your dynamic templates. You should create a directory called <code>[_1]</code> underneath your blog directory.',
2149            'cache'
2150        ) unless ( -d $cache_path );
2151    }
2152    if ( $message ) {
2153        MT->log(
2154            {
2155                message => $message,
2156                level   => MT::Log::ERROR(),
2157                class   => 'system',
2158            }
2159        );
2160    }
2161}
2162
2163sub prepare_dynamic_publishing {
2164    my ( $cb, $blog, $cache, $conditional, $site_path, $site_url ) = @_;
2165
2166    my $htaccess_path = File::Spec->catfile( $site_path, ".htaccess" );
2167    my $mtview_path   = File::Spec->catfile( $site_path, "mtview.php" );
2168
2169    ## Don't re-create when files are there in callback.
2170    return 1
2171      if !defined($cache)
2172      && !defined($conditional)
2173      && ( 'MT::Callback' eq ref($cb) )
2174      && ( -f $htaccess_path )
2175      && ( -f $mtview_path );
2176
2177    # IIS itself does not handle .htaccess,
2178    # but IISPassword (3rd party) does and dies with this.
2179    if ( $ENV{SERVER_SOFTWARE} !~ /Microsoft-IIS/ ) {
2180        eval {
2181            require URI;
2182            my $mtview_server_url = new URI( $site_url );
2183            $mtview_server_url = $mtview_server_url->path();
2184            $mtview_server_url .=
2185              ( $mtview_server_url =~ m|/$| ? "" : "/" ) . "mtview.php";
2186
2187            my $contents = "";
2188            if ( open( HT, $htaccess_path ) ) {
2189                local $/ = undef;
2190                $contents = <HT>;
2191                close HT;
2192            }
2193            if ( $contents !~ /^\s*Rewrite(Cond|Engine|Rule)\b/m ) {
2194                my $htaccess = <<HTACCESS;
2195
2196## %%%%%%% Movable Type generated this part; don't remove this line! %%%%%%%
2197# Disable fancy indexes, so mtview.php gets a chance...
2198Options -Indexes +SymLinksIfOwnerMatch
2199  <IfModule mod_rewrite.c>
2200  # The mod_rewrite solution is the preferred way to invoke
2201  # dynamic pages, because of its flexibility.
2202
2203  # Add mtview.php to the list of DirectoryIndex options, listing it last,
2204  # so it is invoked only if the common choices aren't present...
2205  <IfModule mod_dir.c>
2206    DirectoryIndex index.php index.html index.htm default.htm default.html default.asp $mtview_server_url
2207  </IfModule>
2208
2209  RewriteEngine on
2210
2211  # don't serve mtview.php if the request is for a real directory
2212  # (allows the DirectoryIndex lookup to function)
2213  RewriteCond %{REQUEST_FILENAME} !-d
2214
2215  # don't serve mtview.php if the request is for a real file
2216  # (allows the actual file to be served)
2217  RewriteCond %{REQUEST_FILENAME} !-f
2218  # anything else is handed to mtview.php for resolution
2219  # passthrough query parameters
2220  RewriteRule ^(.*)(\\?.*)\?\$ $mtview_server_url\$2 [L,QSA]
2221</IfModule>
2222
2223<IfModule !mod_rewrite.c>
2224  # if mod_rewrite is unavailable, we forward any missing page
2225  # or unresolved directory index requests to mtview
2226  # if mtview.php can resolve the request, it returns a 200
2227  # result code which prevents any 4xx error code from going
2228  # to the server's access logs. However, an error will be
2229  # reported in the error log file. If this is your only choice,
2230  # and you want to suppress these messages, adding a "LogLevel crit"
2231  # directive within your VirtualHost or root configuration for
2232  # Apache will turn them off.
2233  ErrorDocument 404 $mtview_server_url
2234  ErrorDocument 403 $mtview_server_url
2235</IfModule>
2236## ******* Movable Type generated this part; don't remove this line! *******
2237
2238HTACCESS
2239
2240                $blog->file_mgr->mkpath( $site_path );
2241
2242                open( HT, ">>$htaccess_path" )
2243                  || die "Couldn't open $htaccess_path for appending";
2244                print HT $htaccess || die "Couldn't write to $htaccess_path";
2245                close HT;
2246            }
2247        };
2248        if ($@) { print STDERR $@; }
2249    }
2250
2251    _create_mtview( $blog, $site_path, $cache, $conditional );
2252
2253    my $compiled_template_path =
2254      File::Spec->catfile( $site_path, 'templates_c' );
2255    my $fmgr        = $blog->file_mgr;
2256    my $cfg         = MT->config;
2257    my $saved_umask = $cfg->DirUmask;
2258    $cfg->DirUmask('0000');
2259    $fmgr->mkpath($compiled_template_path);
2260    $cfg->DirUmask($saved_umask);
2261    my $message = q();
2262
2263    if ( -d $compiled_template_path ) {
2264        $message = MT->translate(
2265'Error: Movable Type cannot write to the template cache directory. Please check the permissions for the directory called <code>[_1]</code> underneath your blog directory.',
2266            'templates_c'
2267        ) unless ( -w $compiled_template_path );
2268    }
2269    else {
2270        $message = MT->translate(
2271'Error: Movable Type was not able to create a directory to cache your dynamic templates. You should create a directory called <code>[_1]</code> underneath your blog directory.',
2272            'templates_c'
2273        ) unless ( -d $compiled_template_path );
2274    }
2275
2276    if ($cache) {
2277        _create_dynamiccache_dir( $blog, $site_path );
2278    }
2279}
2280
22811;
Note: See TracBrowser for help on using the browser.