root/branches/release-33/lib/MT/CMS/Blog.pm @ 1779

Revision 1779, 76.5 kB (checked in by bchoate, 20 months ago)

Avoid rebuilding files within the same build operation (particularly helps for date-based archive rebuilds). BugId:69032

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