root/trunk/plugins/WidgetManager/lib/WidgetManager/App.pm @ 438

Revision 438, 14.7 kB (checked in by jallen, 3 years ago)

r1888@mt-master (orig r32441): sekine | 2006-06-27 00:50:35 -0700
BugzID:31219

  • fixed javascript.
  • The module of an old name was always deleted..
  • Property svn:keywords set to Id Revision
Line 
1# Widget Manager plugin for Movable Type
2# Author: Byrne Reese, Six Apart (http://www.sixapart.com)
3# Released under the Artistic License
4#
5# $Id$
6
7package WidgetManager::App;
8
9use strict;
10use Data::Dumper;
11use vars qw( $DEBUG );
12use MT::App;
13@WidgetManager::App::ISA = qw( MT::App );
14use WidgetManager::Util;
15
16sub init {
17    my $app = shift;
18    my %param = @_;
19    $app->SUPER::init(%param) or return;
20
21    WidgetManager::Util::debug('Initializing Widget Manager');
22    $app->add_methods(
23              'list'   => \&list,
24                      'edit'   => \&edit,
25                      'delete' => \&delete,
26                      'save'   => \&save,
27    );
28
29    $app->{default_mode}   = 'list';
30    $app->{user_class}     = 'MT::Author';
31    $app->{requires_login} = 1;
32
33    $app->{mtscript_url}   = ($app->{cfg}->AdminCGIPath ? $app->{cfg}->AdminCGIPath : $app->{cfg}->CGIPath) . $app->{cfg}->AdminScript;
34    $app->{mmscript_url}   = $app->path . $app->{cfg}->AdminScript;
35    $app->{script_url} = $app->{cfg}->CGIPath . 'plugins/WidgetManager/widget-manager.cgi';
36
37    WidgetManager::Util::debug('Finished initializing Widget Manager.');
38    return $app;
39}
40
41sub init_tmpl {
42    my $app = shift;
43    WidgetManager::Util::debug('Initializing template file.','  >');
44    WidgetManager::Util::debug('Calling MT::App::load_tmpl('.join(', ',@_).')','    >');
45    my $tmpl = $app->load_tmpl(@_);
46    if (!$tmpl) {
47        my $err = $app->plugin->translate("Loading template '[_1]' failed: [_2]", $_[0], $@);
48        WidgetManager::Util::debug($err,'    >');
49        return $app->error($err);
50    }
51    else {
52        WidgetManager::Util::debug('Template file successfully loaded.','    >');
53    }
54
55    require MT::App::CMS;
56    MT::App::CMS::is_authorized($app);
57    if (my $perms = $app->{perms}) {
58        $tmpl->param(can_post => $perms->can_post);
59        $tmpl->param(can_upload => $perms->can_upload);
60        $tmpl->param(can_edit_entries =>
61            $perms->can_post || $perms->can_edit_all_posts);
62        $tmpl->param(can_search_replace => $perms->can_edit_all_posts);
63        $tmpl->param(can_edit_templates => $perms->can_edit_templates);
64        $tmpl->param(can_edit_authors => $perms->can_administer_blog);
65        $tmpl->param(can_edit_config => $perms->can_edit_config);
66        # FIXME: once we have edit_commenters permission
67        $tmpl->param(can_edit_commenters => $perms->can_edit_config());
68        $tmpl->param(can_rebuild => $perms->can_rebuild);
69        $tmpl->param(can_edit_categories => $perms->can_edit_categories);
70        $tmpl->param(can_edit_notifications => $perms->can_edit_notifications);
71        $tmpl->param(has_manage_label =>
72            $perms->can_edit_templates  || $perms->can_administer_blog ||
73            $perms->can_edit_categories || $perms->can_edit_config);
74        $tmpl->param(has_posting_label =>
75            $perms->can_post  || $perms->can_edit_all_posts ||
76            $perms->can_upload);
77        $tmpl->param(has_community_label =>
78            $perms->can_post  || $perms->can_edit_config ||
79            $perms->can_edit_notifications || $perms->can_edit_all_posts);
80        $tmpl->param(can_view_log => $perms->can_view_blog_log);
81    }
82
83    my $apppath = $app->{__path} || '';
84
85    my $spath = $app->{cfg}->StaticWebPath || $app->path.'mt-static/';
86    $spath =~ s/\/*$/\//g;
87
88    my $enc = $app->{cfg}->PublishCharset || $app->language_handle->encoding;
89
90    $tmpl->param(plugin_name       => 'Widget Manager');
91    $tmpl->param(plugin_version    => $MT::Plugin::WidgetManager::VERSION);
92    $tmpl->param(plugin_author     => 'Six Apart');
93    $tmpl->param(mt_url            => $app->{mtscript_url});
94    $tmpl->param(mtscript_url      => $app->{mtscript_url});
95    $tmpl->param(mmscript_url      => $app->{mmscript_url});
96    $tmpl->param(static_uri        => $spath);
97    $tmpl->param(script_url        => File::Spec->catdir($apppath,'widget-manager.cgi'));
98    $tmpl->param(blog_url          => $app->blog->site_url);
99    if (my $lang_id = $app->current_language) {
100        $tmpl->param(local_lang_id => lc $lang_id) if $lang_id !~ m/^en/i;
101    }
102    $tmpl->param(page_titles       => [ reverse @{ $app->{breadcrumbs} } ]);
103    $tmpl->param(nav_widgetmanager => 1);
104
105    WidgetManager::Util::debug('MT Script URL: '.$tmpl->param('mtscript_url'),'    >');
106
107    WidgetManager::Util::debug('Finished initializing template file.','  >');
108    return $tmpl;
109}
110
111sub _permission_check {
112    my $app = shift;
113    require MT::App::CMS;
114    MT::App::CMS::is_authorized($app);
115    return ($app->{perms} && $app->{perms}->can_edit_templates);
116}
117
118sub save {
119    WidgetManager::Util::debug('Calling save...');
120    my $app = shift;
121
122    return $app->error($app->plugin->translate('Permission denied.'))
123        unless $app->_permission_check;
124
125    my $q = $app->{query};
126
127    my $blog_id = $q->param('blog_id');
128
129    my $str = build_module_list($q->param('modules'));
130    WidgetManager::Util::debug('Saving modules to blog #'.$blog_id.": $str");
131
132    # Load the current widgetmanager data
133    my $current = $q->param('widgetmanager');
134    $current = $q->param('name') if $current eq 'New Widget Manager';
135    require WidgetManager::Plugin;
136    my $modulesets = $app->plugin->load_selected_modules($blog_id);
137    # my $modulesets = WidgetManager::Plugin::load_selected_modules($blog_id);
138    $modulesets = {} unless $modulesets;
139
140    # delete old set
141    delete $modulesets->{$q->param('widgetmanager')};
142    # Handle renaming: Delete the entry that has changed names.
143    delete $modulesets->{$q->param('old_name')}; # unless $q->param('old_name') eq $q->param('name');
144    if(exists $modulesets->{$q->param('name')}) {
145        return $app->error($app->plugin->translate(
146            "Can't duplicate the existing '[_1]' Widget Manager. Please go back and enter a unique name.",
147            $q->param('name')))
148    }
149    # add it back with a potential new name
150    $modulesets->{$q->param('name')} = $str;
151
152    $app->plugin->set_config_value('modulesets',$modulesets,"blog:$blog_id");
153
154    $app->{rebuild} = 1;
155    return $app->list();
156}
157
158sub delete {
159    WidgetManager::Util::debug('Calling delete...');
160    my $app = shift;
161
162    return $app->error($app->plugin->translate('Permission denied.'))
163        unless $app->_permission_check;
164
165    my $q = $app->{query};
166    my $blog_id = $q->param('blog_id');
167
168    my $modulesets = $app->plugin->load_selected_modules($blog_id);
169    $modulesets = {} unless $modulesets;
170
171    my @ids = $q->param('id');
172    delete $modulesets->{$_} for @ids;
173
174    $app->plugin->set_config_value('modulesets',$modulesets,"blog:$blog_id");
175   
176    $app->{deleted} = 1;
177    return $app->list();
178}
179
180sub edit {
181    WidgetManager::Util::debug('Calling edit...');
182    my $app = shift;
183
184    return $app->error($app->plugin->translate('Permission denied.'))
185        unless $app->_permission_check;
186
187      $app->install_default_widgets(1);
188
189      my $q = $app->{query};
190      my $blog_id = $q->param('blog_id');
191
192      my $tmpl = $app->init_tmpl('edit.tmpl');
193      $tmpl->param('blog_id'  => $blog_id);
194      $app->add_breadcrumb($app->plugin->translate('Main Menu'),$app->{mtscript_url});
195      $app->add_breadcrumb($app->plugin->translate('Widget Manager'),'?__mode=list&blog_id='.$blog_id);
196      $app->add_breadcrumb($q->param('widgetmanager'));
197
198      my $modulesets = $app->plugin->load_selected_modules($blog_id);
199      $modulesets = {} unless $modulesets;
200
201      my @names = sort keys %$modulesets;
202      my $widgetmanager = $q->param('widgetmanager') || $names[0] || '';
203
204      my @selected = split(',',$modulesets->{$widgetmanager});
205
206      my %constraints;
207      $constraints{blog_id} = $blog_id;
208      $constraints{type}    = 'custom';
209      my %options;
210      $options{sort}      = 'name';
211      $options{direction} = 'ascend';
212      require MT::Template;
213      my $iter = MT::Template->load_iter( \%constraints, \%options );
214      my @avail_modules;
215      my @inst_modules;
216      while (my $m = $iter->()) {
217          my $name = $m->name();
218          if ($name =~ s/^(?:Widget|Sidebar): ?//) {
219              push @avail_modules, {
220                id => $m->id(),
221                name => $name,
222                selected => in_array($m->id,@selected),
223              };
224          }
225      }
226      foreach my $mid (@selected) {
227      for (my $i = 0; $i <= $#avail_modules; $i++) {
228          if ($avail_modules[$i]->{id} == $mid) {
229              WidgetManager::Util::debug($app->plugin->translate("Moving [_1] to list of installed modules", $mid));
230              push @inst_modules,$avail_modules[$i];
231              splice(@avail_modules,$i,1);
232          }
233      }
234      }
235
236      # Find non-conflicting name for new Widget Manager
237      if ($widgetmanager eq 'New Widget Manager') { 
238          $widgetmanager = $app->plugin->translate('Widget Manager');
239          if (grep(/^\Q$widgetmanager\E$/, @names)) {
240              my $i = 1;
241              while (grep(/^\Q$widgetmanager $i\E$/, @names)) {
242                  $i++;
243              }
244              $widgetmanager = "$widgetmanager $i";
245          }
246      }
247
248      my @widgetmanagers = map { { widgetmanager => $_ } } keys %$modulesets;
249      $tmpl->param(widgetmanagers => \@widgetmanagers);
250
251      $tmpl->param(available => \@avail_modules);
252      $tmpl->param(installed => \@inst_modules);
253      $tmpl->param(name      => $widgetmanager);
254
255      $app->{breadcrumbs}[-1]{is_last} = 1;
256      $tmpl->param(breadcrumbs       => $app->{breadcrumbs});
257      $tmpl->param(plugin_version    => $MT::Plugin::WidgetManager::VERSION);
258      $tmpl->param(rebuild           => $app->{rebuild});
259      return $app->plugin->l10n_filter($tmpl->output);
260}
261
262sub list {
263      WidgetManager::Util::debug('Calling list...');
264      my $app = shift;
265
266    return $app->error($app->plugin->translate('Permission denied.'))
267        unless $app->_permission_check;
268
269      my $q = $app->{query};
270      my $blog_id = $q->param('blog_id');
271
272      my $tmpl = $app->init_tmpl('list.tmpl');
273      $tmpl->param('blog_id'  => $blog_id);
274      $app->add_breadcrumb($app->plugin->translate("Main Menu"),$app->{mtscript_url});
275      $app->add_breadcrumb($app->plugin->translate("Widget Manager"));
276
277      $app->install_default_widgets() unless $app->installed;
278
279      my $modulesets = $app->plugin->load_selected_modules($blog_id) || {};
280
281      my (%constraints, %options);
282      $constraints{blog_id} = $blog_id;
283      $constraints{type}    = 'custom';
284      $options{sort}        = 'name';
285      $options{direction}   = 'ascend';
286      require MT::Template;
287      my $iter = MT::Template->load_iter( \%constraints, \%options );
288      my %avail;
289      while (my $m = $iter->()) {
290          my $name = $m->name();
291          if ($name =~ s/^(?:Widget|Sidebar): ?//) {
292              $avail{$m->id()} = $name;
293          }
294      }
295
296      my @names = sort keys %$modulesets;
297      my $widgetmanager = $q->param('widgetmanager') || $names[0] || '';
298
299      my @widgetmanagers;
300      my @keys = sort keys %$modulesets;
301
302      my $offset = $app->param('offset') || 0;
303      $tmpl->param( list_start => $offset + 1 );
304      $tmpl->param( list_end   => $offset + scalar @keys );
305
306      foreach my $key (@keys) {
307          # Collect the available widgets for this key.
308          my @w = ();
309          for my $w ( split /\s*,\s*/o, $modulesets->{$key} ) {
310              push @w, $avail{$w} if $avail{$w};
311          }
312          push @widgetmanagers,{
313            widgetmanager => $key,
314            names   => join(', ', @w),
315            widgets => $modulesets->{$key}
316          };
317      }
318      if ($widgetmanager eq 'New Widget Manager') { $widgetmanager = $q->param('name'); }
319
320      $tmpl->param(widgetmanagers => \@widgetmanagers);
321
322      $app->{breadcrumbs}[-1]{is_last} = 1;
323      $tmpl->param(breadcrumbs       => $app->{breadcrumbs});
324      $tmpl->param(plugin_version    => $MT::Plugin::WidgetManager::VERSION);
325      $tmpl->param(rebuild           => $app->{rebuild});
326      $tmpl->param(deleted           => $app->{deleted});
327      return $app->plugin->l10n_filter($tmpl->output);
328}
329
330sub build_module_list {
331    my $str = shift;
332    my @mods = split /;/, $str;
333    my @inst;
334    for (@mods) {
335        my ($id, $col) = /(\d+)=(\d+)\.(\d+)/;
336        push @inst, $id if $col == 1;
337    }
338    return join ',', @inst;
339}
340
341sub in_array {
342    my ($needle, @haystack) = @_;
343    for (@haystack) {
344        return 1 if $_ eq $needle;
345    }
346    return 0;
347}
348
349sub install_module {
350    my($app, $name, $text) = @_;
351    require MT::Template;
352    my $tmpl = MT::Template->new;
353    $tmpl->blog_id($app->blog->id);
354    $tmpl->type('custom');
355    $tmpl->name('Widget: ' . $app->plugin->translate($name));
356    $tmpl->text($app->plugin->translate_templatized($text));
357    $tmpl->save;
358    return $tmpl;   
359}
360
361
362sub install_default_widgets {
363    my $app = shift;
364    my $reinstall = shift;
365    my $blog_id = $app->blog->id;
366    my @preinstalled;
367    my ($tmpl,$default_widget_templates);
368
369    # Gather the existing modules.
370    my $modules = {};
371    require MT::Template;
372    for( MT::Template->load({ blog_id => $blog_id, type => 'custom' }) ) {
373        ( my $name = $_->name() ) =~ s/^(?:Widget|Sidebar):\s+(.*?)$/$1/;
374        $modules->{$name} = $_->linked_file();  # XXX The linked_file is undef for this plugin modules for some reason.
375    }
376
377    use File::Spec;
378    my $widgets_dir = File::Spec->catfile($app->app_dir, 'default_widgets');
379    my $cfg_file = File::Spec->catfile($widgets_dir, 'widgets.cfg');
380
381    local(*FH, $_, $/);
382    $/ = "\n";
383    open FH, $cfg_file or
384        return $app->error(MT->translate(
385            "Error opening file '[_1]': [_2]", $cfg_file, "$!" ));
386    my $cfg = join('',<FH>);
387    eval "$cfg;";
388    close FH;
389
390    foreach (@$default_widget_templates) {
391        next if exists $modules->{$app->plugin->translate($_->{name})};
392        open(TMPL, File::Spec->catfile($widgets_dir, $_->{template})) or die "Error: $!\n";
393        while (my $line = <TMPL>) {
394            $_->{text} .= $line;
395        }
396        close TMPL;
397        $tmpl = install_module($app, $_->{name}, $_->{text});
398        push @preinstalled, $tmpl->id;
399    }
400
401    unless( $reinstall ) {
402        # Set the 'installed' bit in the config
403        $app->installed(1);
404
405        # Now that the plugin is installed for this blog, create a first widgetmanager
406        # with all modules pre-installed.
407       
408        my $modulesets = {};
409        $modulesets->{$app->plugin->translate('First Widget Manager')} = join (',', @preinstalled);
410
411        $app->plugin->set_config_value('modulesets',$modulesets,"blog:$blog_id");
412    }
413}
414
415sub installed {
416    my $config = {};
417    my $app = shift;
418    my $blog_id = $app->{query}->param('blog_id');
419   
420    my $plugin = $app->plugin;
421    if (@_) {
422        # Set the installed bit, save and return
423        return $plugin->set_config_value('installed',1,"blog:$blog_id");
424    } else {
425        # Return early if status check
426        return $plugin->get_config_value('installed',"blog:$blog_id");
427    }
428}
429
430sub plugin {
431    return MT::Plugin::WidgetManager->instance;
432}
433
4341;
Note: See TracBrowser for help on using the browser.