root/branches/release-36/lib/MT/CMS/Blog.pm @ 2127

Revision 2127, 82.1 kB (checked in by takayama, 19 months ago)

Implemented BugId:71811
* When SSI was not PHP, and Dynamic Publishing is enabled, show alert message

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