Dotclear

source: inc/admin/lib.moduleslist.php @ 2270:cd5dc1b0aca1

Revision 2270:cd5dc1b0aca1, 35.1 KB checked in by Denis Jean-Chirstian <contact@…>, 12 years ago (diff)

Fix redirection on last module update and fix user agent on repository query

Line 
1<?php
2# -- BEGIN LICENSE BLOCK ---------------------------------------
3#
4# This file is part of Dotclear 2.
5#
6# Copyright (c) 2003-2013 Olivier Meunier & Association Dotclear
7# Licensed under the GPL version 2.0 license.
8# See LICENSE file or
9# http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
10#
11# -- END LICENSE BLOCK -----------------------------------------
12if (!defined('DC_ADMIN_CONTEXT')) { return; }
13
14/**
15 * @ingroup DC_CORE
16 * @brief Helper for admin list of modules.
17 * @since 2.6
18
19 * Provides an object to parse XML feed of modules from a repository.
20 */
21class adminModulesList
22{
23     public $core;       /**< @var object    dcCore instance */
24     public $modules;    /**< @var object    dcModules instance */
25     public $store;      /**< @var object    dcStore instance */
26
27     public static $allow_multi_install = false;       /**< @var boolean   Work with multiple root directories */
28     public static $distributed_modules = array();     /**< @var array     List of modules distributed with Dotclear */
29
30     protected $list_id = 'unknow';     /**< @var string    Current list ID */
31     protected $data = array();         /**< @var array     Current modules */
32
33     protected $config_module = '';     /**< @var string    Module ID to configure */
34     protected $config_file = '';  /**< @var string    Module path to configure */
35     protected $config_content = '';    /**< @var string    Module configuration page content */
36
37     protected $path = false;           /**< @var string    Modules root directory */
38     protected $path_writable = false;  /**< @var boolean   Indicate if modules root directory is writable */
39     protected $path_pattern = false;   /**< @var string    Directory pattern to work on */
40
41     protected $page_url = 'plugins.php';    /**< @var string    Page URL */
42     protected $page_qs = '?';                    /**< @var string    Page query string */
43     protected $page_tab = '';                    /**< @var string    Page tab */
44     protected $page_redir = '';                  /**< @var string    Page redirection */
45
46     public static $nav_indexes = 'abcdefghijklmnopqrstuvwxyz0123456789'; /**< @var  string    Index list */
47     protected $nav_list = array();          /**< @var array     Index list with special index */
48     protected $nav_special = 'other';  /**< @var string    Text for other special index */
49
50     protected $sort_field = 'sname';   /**< @var string    Field used to sort modules */
51     protected $sort_asc = true;             /**< @var boolean   Sort order asc */
52
53     /**
54      * Constructor.
55      *
56      * Note that this creates dcStore instance.
57      *
58      * @param object    $modules       dcModules instance
59      * @param string    $modules_root  Modules root directories
60      * @param string    $xml_url       URL of modules feed from repository
61      */
62     public function __construct(dcModules $modules, $modules_root, $xml_url)
63     {
64          $this->core = $modules->core;
65          $this->modules = $modules;
66          $this->store = new dcStore($modules, $xml_url);
67
68          $this->setPath($modules_root);
69          $this->setIndex(__('other'));
70     }
71
72     /**
73      * Begin a new list.
74      *
75      * @param string    $id       New list ID
76      * @return     adminModulesList self instance
77      */
78     public function setList($id)
79     {
80          $this->data = array();
81          $this->page_tab = '';
82          $this->list_id = $id;
83
84          return $this;
85     }
86
87     /**
88      * Get list ID.
89      *
90      * @return     List ID
91      */
92     public function getList()
93     {
94          return $this->list_id;
95     }
96
97     /// @name Modules root directory methods
98     //@{
99     /**
100      * Set path info.
101      *
102      * @param string    $root          Modules root directories
103      * @return     adminModulesList self instance
104      */
105     protected function setPath($root)
106     {
107          $paths = explode(PATH_SEPARATOR, $root);
108          $path = array_pop($paths);
109          unset($paths);
110
111          $this->path = $path;
112          if (is_dir($path) && is_writeable($path)) {
113               $this->path_writable = true;
114               $this->path_pattern = preg_quote($path,'!');
115          }
116
117          return $this;
118     }
119
120     /**
121      * Get modules root directory.
122      *
123      * @return     Path to work on
124      */
125     public function getPath()
126     {
127          return $this->path;
128     }
129
130     /**
131      * Check if modules root directory is writable.
132      *
133      * @return     True if directory is writable
134      */
135     public function isWritablePath()
136     {
137          return $this->path_writable;
138     }
139
140     /**
141      * Check if root directory of a module is deletable.
142      *
143      * @param string    $root          Module root directory
144      * @return     True if directory is delatable
145      */
146     public function isDeletablePath($root)
147     {
148          return $this->path_writable 
149               && (preg_match('!^'.$this->path_pattern.'!', $root) || defined('DC_DEV') && DC_DEV) 
150               && $this->core->auth->isSuperAdmin();
151     }
152     //@}
153
154     /// @name Page methods
155     //@{
156     /**
157      * Set page base URL.
158      *
159      * @param string    $url      Page base URL
160      * @return     adminModulesList self instance
161      */
162     public function setURL($url)
163     {
164          $this->page_qs = strpos('?', $url) ? '&' : '?';
165          $this->page_url = $url;
166
167          return $this;
168     }
169
170     /**
171      * Get page URL.
172      *
173      * @param string|array   $queries  Additionnal query string
174      * @param booleany  $with_tab      Add current tab to URL end
175      * @return     Clean page URL
176      */
177     public function getURL($queries='', $with_tab=true)
178     {
179          return $this->page_url.
180               (!empty($queries) ? $this->page_qs : '').
181               (is_array($queries) ? http_build_query($queries) : $queries).
182               ($with_tab && !empty($this->page_tab) ? '#'.$this->page_tab : '');
183     }
184
185     /**
186      * Set page tab.
187      *
188      * @param string    $tab      Page tab
189      * @return     adminModulesList self instance
190      */
191     public function setTab($tab)
192     {
193          $this->page_tab = $tab;
194
195          return $this;
196     }
197
198     /**
199      * Get page tab.
200      *
201      * @return     Page tab
202      */
203     public function getTab()
204     {
205          return $this->page_tab;
206     }
207
208     /**
209      * Set page redirection.
210      *
211      * @param string    $default       Default redirection
212      * @return     adminModulesList self instance
213      */
214     public function setRedir($default='')
215     {
216          $this->page_redir = empty($_REQUEST['redir']) ? $default : $_REQUEST['redir'];
217
218          return $this;
219     }
220
221     /**
222      * Get page redirection.
223      *
224      * @return     Page redirection
225      */
226     public function getRedir()
227     {
228          return empty($this->page_redir) ? $this->getURL() : $this->page_redir;
229     }
230     //@}
231
232     /// @name Search methods
233     //@{
234     /**
235      * Get search query.
236      *
237      * @return     Search query
238      */
239     public function getSearch()
240     {
241          $query = !empty($_REQUEST['m_search']) ? trim($_REQUEST['m_search']) : null;
242          return strlen($query) > 2 ? $query : null;
243     }
244
245     /**
246      * Display searh form.
247      *
248      * @return     adminModulesList self instance
249      */
250     public function displaySearch()
251     {
252          $query = $this->getSearch();
253
254          if (empty($this->data) && $query === null) {
255               return $this;
256          }
257
258          echo 
259          '<form action="'.$this->getURL().'" method="get" class="fieldset">'.
260          '<p><label for="m_search" class="classic">'.__('Search in repository:').'&nbsp;</label><br />'.
261          form::field(array('m_search','m_search'), 30, 255, html::escapeHTML($query)).
262          '<input type="submit" value="'.__('Search').'" /> ';
263          if ($query) { echo ' <a href="'.$this->getURL().'" class="button">'.__('Reset search').'</a>'; }
264          echo '</p>'.
265          '</form>';
266
267          if ($query) {
268               echo 
269               '<p class="message">'.sprintf(
270                    __('Found %d result for search "%s":', 'Found %d results for search "%s":', count($this->data)), 
271                    count($this->data), html::escapeHTML($query)
272                    ).
273               '</p>';
274          }
275          return $this;
276     }
277     //@}
278
279     /// @name Navigation menu methods
280     //@{
281     /**
282      * Set navigation special index.
283      *
284      * @return     adminModulesList self instance
285      */
286     public function setIndex($str)
287     {
288          $this->nav_special = (string) $str;
289          $this->nav_list = array_merge(str_split(self::$nav_indexes), array($this->nav_special));
290
291          return $this;
292     }
293
294     /**
295      * Get index from query.
296      *
297      * @return     Query index or default one
298      */
299     public function getIndex()
300     {
301          return isset($_REQUEST['m_nav']) && in_array($_REQUEST['m_nav'], $this->nav_list) ? $_REQUEST['m_nav'] : $this->nav_list[0];
302     }
303
304     /**
305      * Display navigation by index menu.
306      *
307      * @return     adminModulesList self instance
308      */
309     public function displayIndex()
310     {
311          if (empty($this->data) || $this->getSearch() !== null) {
312               return $this;
313          }
314
315          # Fetch modules required field
316          $indexes = array();
317          foreach ($this->data as $id => $module) {
318               if (!isset($module[$this->sort_field])) {
319                    continue;
320               }
321               $char = substr($module[$this->sort_field], 0, 1);
322               if (!in_array($char, $this->nav_list)) {
323                    $char = $this->nav_special;
324               }
325               if (!isset($indexes[$char])) {
326                    $indexes[$char] = 0;
327               }
328               $indexes[$char]++;
329          }
330
331          $buttons = array();
332          foreach($this->nav_list as $char) {
333               # Selected letter
334               if ($this->getIndex() == $char) {
335                    $buttons[] = '<li class="active" title="'.__('current selection').'"><strong> '.$char.' </strong></li>';
336               }
337               # Letter having modules
338               elseif (!empty($indexes[$char])) {
339                    $title = sprintf(__('%d module', '%d modules', $indexes[$char]), $indexes[$char]);
340                    $buttons[] = '<li class="btn" title="'.$title.'"><a href="'.$this->getURL('m_nav='.$char).'" title="'.$title.'"> '.$char.' </a></li>';
341               }
342               # Letter without modules
343               else {
344                    $buttons[] = '<li class="btn no-link" title="'.__('no module').'"> '.$char.' </li>';
345               }
346          }
347          # Parse navigation menu
348          echo '<div class="pager">'.__('Browse index:').' <ul>'.implode('',$buttons).'</ul></div>';
349
350          return $this;
351     }
352     //@}
353
354     /// @name Sort methods
355     //@{
356     /**
357      * Set default sort field.
358      *
359      * @return     adminModulesList self instance
360      */
361     public function setSort($field, $asc=true)
362     {
363          $this->sort_field = $field;
364          $this->sort_asc = (boolean) $asc;
365
366          return $this;
367     }
368
369     /**
370      * Get sort field from query.
371      *
372      * @return     Query sort field or default one
373      */
374     public function getSort()
375     {
376          return !empty($_REQUEST['m_sort']) ? $_REQUEST['m_sort'] : $this->sort_field;
377     }
378
379     /**
380      * Display sort field form.
381      *
382      * @note  This method is not implemented yet
383      * @return     adminModulesList self instance
384      */
385     public function displaySort()
386     {
387          //
388
389          return $this;
390     }
391     //@}
392
393     /// @name Modules methods
394     //@{
395     /**
396      * Set modules and sanitize them.
397      *
398      * @return     adminModulesList self instance
399      */
400     public function setModules($modules)
401     {
402          $this->data = array();
403          if (!empty($modules) && is_array($modules)) {
404               foreach($modules as $id => $module) {
405                    $this->data[$id] = self::sanitizeModule($id, $module);
406               }
407          }
408          return $this;
409     }
410
411     /**
412      * Get modules currently set.
413      *
414      * @return     Array of modules
415      */
416     public function getModules()
417     {
418          return $this->data;
419     }
420
421     /**
422      * Sanitize a module.
423      *
424      * This clean infos of a module by adding default keys
425      * and clean some of them, sanitize module can safely
426      * be used in lists.
427      *
428      * @return     Array of the module informations
429      */
430     public static function sanitizeModule($id, $module)
431     {
432          $label = empty($module['label']) ? $id : $module['label'];
433          $name = __(empty($module['name']) ? $label : $module['name']);
434         
435          return array_merge(
436               # Default values
437               array(
438                    'desc'                   => '',
439                    'author'            => '',
440                    'version'                => 0,
441                    'current_version'   => 0,
442                    'root'                   => '',
443                    'root_writable'     => false,
444                    'permissions'       => null,
445                    'parent'            => null,
446                    'priority'               => 1000,
447                    'standalone_config' => false,
448                    'support'                => '',
449                    'section'                => '',
450                    'tags'                   => '',
451                    'details'                => '',
452                    'sshot'             => '',
453                    'score'                  => 0
454               ),
455               # Module's values
456               $module,
457               # Clean up values
458               array(
459                    'id'                     => $id,
460                    'sid'                    => self::sanitizeString($id),
461                    'label'             => $label,
462                    'name'                   => $name,
463                    'sname'             => self::sanitizeString($name)
464               )
465          );
466     }
467
468     /**
469      * Check if a module is part of the distribution.
470      *
471      * @param string    $id       Module root directory
472      * @return     True if module is part of the distribution
473      */
474     public static function isDistributedModule($id)
475     {
476          $distributed_modules = self::$distributed_modules;
477
478          return is_array($distributed_modules) && in_array($id, $distributed_modules);
479     }
480
481     /**
482      * Sort modules list by specific field.
483      *
484      * @param string    $module        Array of modules
485      * @param string    $field         Field to sort from
486      * @param bollean   $asc      Sort asc if true, else decs
487      * @return     Array of sorted modules
488      */
489     public static function sortModules($modules, $field, $asc=true)
490     {
491          $sorter = array();
492          foreach($modules as $id => $module) {
493               $sorter[$id] = isset($module[$field]) ? $module[$field] : $field;
494          }
495          array_multisort($sorter, $asc ? SORT_ASC : SORT_DESC, $modules);
496
497          return $modules;
498     }
499
500     /**
501      * Display list of modules.
502      *
503      * @param array     $cols          List of colones (module field) to display
504      * @param array     $actions  List of predefined actions to show on form
505      * @param boolean   $nav_limit     Limit list to previously selected index
506      * @return     adminModulesList self instance
507      */
508     public function displayModules($cols=array('name', 'version', 'desc'), $actions=array(), $nav_limit=false)
509     {
510          echo 
511          '<div class="table-outer">'.
512          '<table id="'.html::escapeHTML($this->list_id).'" class="modules'.(in_array('expander', $cols) ? ' expandable' : '').'">'.
513          '<caption class="hidden">'.html::escapeHTML(__('Modules list')).'</caption><tr>';
514
515          if (in_array('name', $cols)) {
516               echo 
517               '<th class="first nowrap"'.(in_array('icon', $cols) ? ' colspan="2"' : '').'>'.__('Name').'</th>';
518          }
519
520          if (in_array('score', $cols) && $this->getSearch() !== null && defined('DC_DEBUG') && DC_DEBUG) {
521               echo 
522               '<th class="nowrap">'.__('Score').'</th>';
523          }
524
525          if (in_array('version', $cols)) {
526               echo 
527               '<th class="nowrap count" scope="col">'.__('Version').'</th>';
528          }
529
530          if (in_array('current_version', $cols)) {
531               echo 
532               '<th class="nowrap count" scope="col">'.__('Current version').'</th>';
533          }
534
535          if (in_array('desc', $cols)) {
536               echo 
537               '<th class="nowrap" scope="col">'.__('Details').'</th>';
538          }
539
540          if (in_array('distrib', $cols)) {
541               echo '<th'.(in_array('desc', $cols) ? '' : ' class="maximal"').'></th>';
542          }
543
544          if (!empty($actions) && $this->core->auth->isSuperAdmin()) {
545               echo 
546               '<th class="minimal nowrap">'.__('Action').'</th>';
547          }
548
549          echo 
550          '</tr>';
551
552          $sort_field = $this->getSort();
553
554          # Sort modules by $sort_field (default sname)
555          $modules = $this->getSearch() === null ?
556               self::sortModules($this->data, $sort_field, $this->sort_asc) :
557               $this->data;
558
559          $count = 0;
560          foreach ($modules as $id => $module)
561          {
562               # Show only requested modules
563               if ($nav_limit && $this->getSearch() === null) {
564                    $char = substr($module[$sort_field], 0, 1);
565                    if (!in_array($char, $this->nav_list)) {
566                         $char = $this->nav_special;
567                    }
568                    if ($this->getIndex() != $char) {
569                         continue;
570                    }
571               }
572
573               echo 
574               '<tr class="line" id="'.html::escapeHTML($this->list_id).'_m_'.html::escapeHTML($id).'">';
575
576               if (in_array('icon', $cols)) {
577                    echo 
578                    '<td class="module-icon nowrap">'.sprintf(
579                         '<img alt="%1$s" title="%1$s" src="%2$s" />', 
580                         html::escapeHTML($id), file_exists($module['root'].'/icon.png') ? 'index.php?pf='.$id.'/icon.png' : 'images/module.png'
581                    ).'</td>';
582               }
583
584               # Link to config file
585               $config = in_array('config', $cols) && !empty($module['root']) && file_exists(path::real($module['root'].'/_config.php'));
586
587               echo 
588               '<td class="module-name nowrap" scope="row">'.($config ? 
589                    '<a href="'.$this->getURL('module='.$id.'&conf=1').'" title"'.sprintf(__('Configure module "%s"'), html::escapeHTML($module['name'])).'">'.html::escapeHTML($module['name']).'</a>' : 
590                    html::escapeHTML($module['name'])
591               ).'</td>';
592
593               # Display score only for debug purpose
594               if (in_array('score', $cols) && $this->getSearch() !== null && defined('DC_DEBUG') && DC_DEBUG) {
595                    echo 
596                    '<td class="module-version nowrap count"><span class="debug">'.$module['score'].'</span></td>';
597               }
598
599               if (in_array('version', $cols)) {
600                    echo 
601                    '<td class="module-version nowrap count">'.html::escapeHTML($module['version']).'</td>';
602               }
603
604               if (in_array('current_version', $cols)) {
605                    echo 
606                    '<td class="module-current-version nowrap count">'.html::escapeHTML($module['current_version']).'</td>';
607               }
608
609               if (in_array('desc', $cols)) {
610                    echo 
611                    '<td class="module-desc maximal">'.html::escapeHTML($module['desc']).'</td>';
612               }
613
614               if (in_array('distrib', $cols)) {
615                    echo 
616                    '<td class="module-distrib">'.(self::isDistributedModule($id) ? 
617                         '<img src="images/dotclear_pw.png" alt="'.
618                         __('Module from official distribution').'" title="'.
619                         __('module from official distribution').'" />' 
620                    : '').'</td>';
621               }
622
623               if (!empty($actions) && $this->core->auth->isSuperAdmin()) {
624                    $buttons = $this->getActions($id, $module, $actions);
625
626                    echo 
627                    '<td class="module-actions nowrap">'.
628
629                    '<form action="'.$this->getURL().'" method="post">'.
630                    '<div>'.
631                    $this->core->formNonce().
632                    form::hidden(array('module'), html::escapeHTML($id)).
633
634                    implode(' ', $buttons).
635
636                    '</div>'.
637                    '</form>'.
638
639                    '</td>';
640               }
641
642               echo 
643               '</tr>';
644
645               $count++;
646          }
647          echo 
648          '</table></div>';
649
650          if(!$count && $this->getSearch() === null) {
651               echo 
652               '<p class="message">'.__('No module matches your search.').'</p>';
653          }
654
655          return $this;
656     }
657
658     /**
659      * Get action buttons to add to modules list.
660      *
661      * @param string    $id            Module ID
662      * @param array     $module        Module info
663      * @param array     $actions  Actions keys
664      * @return     Array of actions buttons
665      */
666     protected function getActions($id, $module, $actions)
667     {
668          $submits = array();
669
670          # Use loop to keep requested order
671          foreach($actions as $action) {
672               switch($action) {
673
674                    # Deactivate
675                    case 'activate': if ($module['root_writable']) {
676                         $submits[] = 
677                         '<input type="submit" name="activate" value="'.__('Activate').'" />';
678                    } break;
679
680                    # Activate
681                    case 'deactivate': if ($module['root_writable']) {
682                         $submits[] = 
683                         '<input type="submit" name="deactivate" value="'.__('Deactivate').'" class="reset" />';
684                    } break;
685
686                    # Delete
687                    case 'delete': if ($this->isDeletablePath($module['root'])) {
688                         $dev = !preg_match('!^'.$this->path_pattern.'!', $module['root']) && defined('DC_DEV') && DC_DEV ? ' debug' : '';
689                         $submits[] = 
690                         '<input type="submit" class="delete '.$dev.'" name="delete" value="'.__('Delete').'" />';
691                    } break;
692
693                    # Install (from store)
694                    case 'install': if ($this->path_writable) {
695                         $submits[] = 
696                         '<input type="submit" name="install" value="'.__('Install').'" />';
697                    } break;
698
699                    # Update (from store)
700                    case 'update': if ($this->path_writable) {
701                         $submits[] = 
702                         '<input type="submit" name="update" value="'.__('Update').'" />';
703                    } break;
704
705                    # Behavior
706                    case 'behavior':
707
708                         # --BEHAVIOR-- adminModulesListGetActions
709                         $tmp = $this->core->callBehavior('adminModulesListGetActions', $this, $id, $module);
710
711                         if (!empty($tmp)) {
712                              $submits[] = $tmp;
713                         }
714                    break;
715               }
716          }
717
718
719          return $submits;
720     }
721
722     /**
723      * Execute POST action.
724      *
725      * @note  Set a notice on success through dcPage::addSuccessNotice
726      * @throw Exception Module not find or command failed
727      * @param string    $prefix        Prefix used on behaviors
728      * @return     Null
729      */
730     public function doActions($prefix)
731     {
732          if (empty($_POST) || !empty($_REQUEST['conf']) 
733          || !$this->core->auth->isSuperAdmin() || !$this->isWritablePath()) {
734               return null;
735          }
736
737          # List actions
738          if (!empty($_POST['module'])) {
739
740               $id = $_POST['module'];
741
742               if (!empty($_POST['activate'])) {
743
744                    $enabled = $this->modules->getDisabledModules();
745                    if (!isset($enabled[$id])) {
746                         throw new Exception(__('No such module.'));
747                    }
748
749                    # --BEHAVIOR-- moduleBeforeActivate
750                    $this->core->callBehavior($prefix.'BeforeActivate', $id);
751
752                    $this->modules->activateModule($id);
753
754                    # --BEHAVIOR-- moduleAfterActivate
755                    $this->core->callBehavior($prefix.'AfterActivate', $id);
756
757                    dcPage::addSuccessNotice(__('Module has been successfully activated.'));
758                    http::redirect($this->getURL());
759               }
760
761               elseif (!empty($_POST['deactivate'])) {
762
763                    if (!$this->modules->moduleExists($id)) {
764                         throw new Exception(__('No such module.'));
765                    }
766
767                    $module = $this->modules->getModules($id);
768                    $module['id'] = $id;
769
770                    if (!$module['root_writable']) {
771                         throw new Exception(__('You don\'t have permissions to deactivate this module.'));
772                    }
773
774                    # --BEHAVIOR-- moduleBeforeDeactivate
775                    $this->core->callBehavior($prefix.'BeforeDeactivate', $module);
776
777                    $this->modules->deactivateModule($id);
778
779                    # --BEHAVIOR-- moduleAfterDeactivate
780                    $this->core->callBehavior($prefix.'AfterDeactivate', $module);
781
782                    dcPage::addSuccessNotice(__('Module has been successfully deactivated.'));
783                    http::redirect($this->getURL());
784               }
785
786               elseif (!empty($_POST['delete'])) {
787
788                    $disabled = $this->modules->getDisabledModules();
789                    if (!isset($disabled[$id])) {
790
791                         if (!$this->modules->moduleExists($id)) {
792                              throw new Exception(__('No such module.'));
793                         }
794
795                         $module = $this->modules->getModules($id);
796                         $module['id'] = $id;
797
798                         if (!$this->isDeletablePath($module['root'])) {
799                              throw new Exception(__("You don't have permissions to delete this module."));
800                         }
801
802                         # --BEHAVIOR-- moduleBeforeDelete
803                         $this->core->callBehavior($prefix.'BeforeDelete', $module);
804
805                         $this->modules->deleteModule($id);
806
807                         # --BEHAVIOR-- moduleAfterDelete
808                         $this->core->callBehavior($prefix.'AfterDelete', $module);
809                    }
810                    else {
811                         $this->modules->deleteModule($id, true);
812                    }
813
814                    dcPage::addSuccessNotice(__('Module has been successfully deleted.'));
815                    http::redirect($this->getURL());
816               }
817
818               elseif (!empty($_POST['install'])) {
819
820                    $updated = $this->store->get();
821                    if (!isset($updated[$id])) {
822                         throw new Exception(__('No such module.'));
823                    }
824
825                    $module = $updated[$id];
826                    $module['id'] = $id;
827
828                    $dest = $this->getPath().'/'.basename($module['file']);
829
830                    # --BEHAVIOR-- moduleBeforeAdd
831                    $this->core->callBehavior($prefix.'BeforeAdd', $module);
832
833                    $ret_code = $this->store->process($module['file'], $dest);
834
835                    # --BEHAVIOR-- moduleAfterAdd
836                    $this->core->callBehavior($prefix.'AfterAdd', $module);
837
838                    dcPage::addSuccessNotice($ret_code == 2 ?
839                         __('Module has been successfully updated.') :
840                         __('Module has been successfully installed.')
841                    );
842                    http::redirect($this->getURL());
843               }
844
845               elseif (!empty($_POST['update'])) {
846
847                    $updated = $this->store->get(true);
848                    if (!isset($updated[$id])) {
849                         throw new Exception(__('No such module.'));
850                    }
851
852                    if (!$this->modules->moduleExists($id)) {
853                         throw new Exception(__('No such module.'));
854                    }
855
856                    $tab = count($updated) > 1 ? '' : '#'.$prefix;
857
858                    $module = $updated[$id];
859                    $module['id'] = $id;
860
861                    if (!self::$allow_multi_install) {
862                         $dest = $module['root'].'/../'.basename($module['file']);
863                    }
864                    else {
865                         $dest = $this->getPath().'/'.basename($module['file']);
866                         if ($module['root'] != $dest) {
867                              @file_put_contents($module['root'].'/_disabled', '');
868                         }
869                    }
870
871                    # --BEHAVIOR-- moduleBeforeUpdate
872                    $this->core->callBehavior($prefix.'BeforeUpdate', $module);
873
874                    $this->store->process($module['file'], $dest);
875
876                    # --BEHAVIOR-- moduleAfterUpdate
877                    $this->core->callBehavior($prefix.'AfterUpdate', $module);
878
879                    dcPage::addSuccessNotice(__('Module has been successfully updated.'));
880                    http::redirect($this->getURL().$tab);
881               }
882               else {
883
884                    # --BEHAVIOR-- adminModulesListDoActions
885                    $this->core->callBehavior('adminModulesListDoActions', $this, $id, $prefix);
886
887               }
888          }
889          # Manual actions
890          elseif (!empty($_POST['upload_pkg']) && !empty($_FILES['pkg_file']) 
891               || !empty($_POST['fetch_pkg']) && !empty($_POST['pkg_url']))
892          {
893               if (empty($_POST['your_pwd']) || !$this->core->auth->checkPassword(crypt::hmac(DC_MASTER_KEY, $_POST['your_pwd']))) {
894                    throw new Exception(__('Password verification failed'));
895               }
896
897               if (!empty($_POST['upload_pkg'])) {
898                    files::uploadStatus($_FILES['pkg_file']);
899                   
900                    $dest = $this->getPath().'/'.$_FILES['pkg_file']['name'];
901                    if (!move_uploaded_file($_FILES['pkg_file']['tmp_name'], $dest)) {
902                         throw new Exception(__('Unable to move uploaded file.'));
903                    }
904               }
905               else {
906                    $url = urldecode($_POST['pkg_url']);
907                    $dest = $this->getPath().'/'.basename($url);
908                    $this->store->download($url, $dest);
909               }
910
911               # --BEHAVIOR-- moduleBeforeAdd
912               $this->core->callBehavior($prefix.'BeforeAdd', null);
913
914               $ret_code = $this->store->install($dest);
915
916               # --BEHAVIOR-- moduleAfterAdd
917               $this->core->callBehavior($prefix.'AfterAdd', null);
918
919               dcPage::addSuccessNotice($ret_code == 2 ?
920                    __('Module has been successfully updated.') :
921                    __('Module has been successfully installed.')
922               );
923               http::redirect($this->getURL().'#'.$prefix);
924          }
925
926          return null;
927     }
928
929     /**
930      * Display tab for manual installation.
931      *
932      * @return     adminModulesList self instance
933      */
934     public function displayManualForm()
935     {
936          if (!$this->core->auth->isSuperAdmin() || !$this->isWritablePath()) {
937               return null;
938          }
939
940          # 'Upload module' form
941          echo
942          '<form method="post" action="'.$this->getURL().'" id="uploadpkg" enctype="multipart/form-data" class="fieldset">'.
943          '<h4>'.__('Upload a zip file').'</h4>'.
944          '<p class="field"><label for="pkg_file" class="classic required"><abbr title="'.__('Required field').'">*</abbr> '.__('Zip file path:').'</label> '.
945          '<input type="file" name="pkg_file" id="pkg_file" /></p>'.
946          '<p class="field"><label for="your_pwd1" class="classic required"><abbr title="'.__('Required field').'">*</abbr> '.__('Your password:').'</label> '.
947          form::password(array('your_pwd','your_pwd1'),20,255).'</p>'.
948          '<p><input type="submit" name="upload_pkg" value="'.__('Upload').'" />'.
949          $this->core->formNonce().'</p>'.
950          '</form>';
951
952          # 'Fetch module' form
953          echo
954          '<form method="post" action="'.$this->getURL().'" id="fetchpkg" class="fieldset">'.
955          '<h4>'.__('Download a zip file').'</h4>'.
956          '<p class="field"><label for="pkg_url" class="classic required"><abbr title="'.__('Required field').'">*</abbr> '.__('Zip file URL:').'</label> '.
957          form::field(array('pkg_url','pkg_url'),40,255).'</p>'.
958          '<p class="field"><label for="your_pwd2" class="classic required"><abbr title="'.__('Required field').'">*</abbr> '.__('Your password:').'</label> '.
959          form::password(array('your_pwd','your_pwd2'),20,255).'</p>'.
960          '<p><input type="submit" name="fetch_pkg" value="'.__('Download').'" />'.
961          $this->core->formNonce().'</p>'.
962          '</form>';
963
964          return $this;
965     }
966     //@}
967
968     /// @name Module configuration methods
969     //@{
970     /**
971      * Prepare module configuration.
972      *
973      * We need to get configuration content in three steps
974      * and out of this class to keep backward compatibility.
975      *
976      * if ($xxx->setConfiguration()) {
977      *   include $xxx->includeConfiguration();
978      * }
979      * $xxx->getConfiguration();
980      * ... [put here page headers and other stuff]
981      * $xxx->displayConfiguration();
982      *
983      * @param string    $id       Module to work on or it gather through REQUEST
984      * @return     True if config set
985      */
986     public function setConfiguration($id=null)
987     {
988          if (empty($_REQUEST['conf']) || empty($_REQUEST['module']) && !$id) {
989               return false;
990          }
991         
992          if (!empty($_REQUEST['module']) && empty($id)) {
993               $id = $_REQUEST['module'];
994          }
995
996          if (!$this->modules->moduleExists($id)) {
997               $core->error->add(__('Unknow module ID'));
998               return false;
999          }
1000
1001          $module = $this->modules->getModules($id);
1002          $module = self::sanitizeModule($id, $module);
1003          $file = path::real($module['root'].'/_config.php');
1004
1005          if (!file_exists($file)) {
1006               $core->error->add(__('This module has no configuration file.'));
1007               return false;
1008          }
1009
1010          $this->config_module = $module;
1011          $this->config_file = $file;
1012          $this->config_content = '';
1013
1014          if (!defined('DC_CONTEXT_MODULE')) {
1015               define('DC_CONTEXT_MODULE', true);
1016          }
1017
1018          return true;
1019     }
1020
1021     /**
1022      * Get path of module configuration file.
1023      *
1024      * @note Required previously set file info
1025      * @return Full path of config file or null
1026      */
1027     public function includeConfiguration()
1028     {
1029          if (!$this->config_file) {
1030               return null;
1031          }
1032          $this->setRedir($this->getURL().'#plugins');
1033
1034          ob_start();
1035
1036          return $this->config_file;
1037     }
1038
1039     /**
1040      * Gather module configuration file content.
1041      *
1042      * @note Required previously file inclusion
1043      * @return True if content has been captured
1044      */
1045     public function getConfiguration()
1046     {
1047          if ($this->config_file) {
1048               $this->config_content = ob_get_contents();
1049          }
1050
1051          ob_end_clean();
1052
1053          return !empty($this->file_content);
1054     }
1055
1056     /**
1057      * Display module configuration form.
1058      *
1059      * @note Required previously gathered content
1060      * @return     adminModulesList self instance
1061      */
1062     public function displayConfiguration()
1063     {
1064          if ($this->config_file) {
1065
1066               if (!$this->config_module['standalone_config']) {
1067                    echo
1068                    '<form id="module_config" action="'.$this->getURL('conf=1').'" method="post" enctype="multipart/form-data">'.
1069                    '<h3>'.sprintf(__('Configure plugin "%s"'), html::escapeHTML($this->config_module['name'])).'</h3>'.
1070                    '<p><a class="back" href="'.$this->getRedir().'">'.__('Back').'</a></p>';
1071               }
1072
1073               echo $this->config_content;
1074
1075               if (!$this->config_module['standalone_config']) {
1076                    echo
1077                    '<p class="clear"><input type="submit" name="save" value="'.__('Save').'" />'.
1078                    form::hidden('module', $this->config_module['id']).
1079                    form::hidden('redir', $this->getRedir()).
1080                    $this->core->formNonce().'</p>'.
1081                    '</form>';
1082               }
1083          }
1084
1085          return $this;
1086     }
1087     //@}
1088
1089     /**
1090      * Helper to sanitize a string.
1091      *
1092      * Used for search or id.
1093      *
1094      * @param string    $str      String to sanitize
1095      * @return     Sanitized string
1096      */
1097     public static function sanitizeString($str)
1098     {
1099          return preg_replace('/[^A-Za-z0-9\@\#+_-]/', '', strtolower($str));
1100     }
1101}
1102
1103/**
1104 * @ingroup DC_CORE
1105 * @brief Helper to manage list of themes.
1106 * @since 2.6
1107 */
1108class adminThemesList extends adminModulesList
1109{
1110     protected $page_url = 'blog_theme.php';
1111
1112     public function displayModules($cols=array('name', 'config', 'version', 'desc'), $actions=array(), $nav_limit=false)
1113     {
1114          echo 
1115          '<div id="'.html::escapeHTML($this->list_id).'" class="modules'.(in_array('expander', $cols) ? ' expandable' : '').' one-box">';
1116
1117          $sort_field = $this->getSort();
1118
1119          # Sort modules by id
1120          $modules = $this->getSearch() === null ?
1121               self::sortModules($this->data, $sort_field, $this->sort_asc) :
1122               $this->data;
1123
1124          $res = '';
1125          $count = 0;
1126          foreach ($modules as $id => $module)
1127          {
1128               # Show only requested modules
1129               if ($nav_limit && $this->getSearch() === null) {
1130                    $char = substr($module[$sort_field], 0, 1);
1131                    if (!in_array($char, $this->nav_list)) {
1132                         $char = $this->nav_special;
1133                    }
1134                    if ($this->getIndex() != $char) {
1135                         continue;
1136                    }
1137               }
1138
1139               $current = $this->core->blog->settings->system->theme == $id && $this->modules->moduleExists($id);
1140               $distrib = self::isDistributedModule($id) ? ' dc-box' : '';
1141
1142               $line = 
1143               '<div class="box '.($current ? 'medium current-theme' : 'small theme').$distrib.'">';
1144
1145               if (in_array('name', $cols)) {
1146                    $line .= 
1147                    '<h4 class="module-name">'.html::escapeHTML($module['name']).'</h4>';
1148               }
1149
1150               # Display score only for debug purpose
1151               if (in_array('score', $cols) && $this->getSearch() !== null && defined('DC_DEBUG') && DC_DEBUG) {
1152                    $line .= 
1153                    '<p class="module-score debug">'.sprintf(__('Score: %s'), $module['score']).'</p>';
1154               }
1155
1156               if (in_array('sshot', $cols)) {
1157                    # Screenshot from url
1158                    if (preg_match('#^http(s)?://#', $module['sshot'])) {
1159                         $sshot = $module['sshot'];
1160                    }
1161                    # Screenshot from installed module
1162                    elseif (file_exists($this->core->blog->themes_path.'/'.$id.'/screenshot.jpg')) {
1163                         $sshot = $this->getURL('shot='.rawurlencode($id));
1164                    }
1165                    # Default screenshot
1166                    else {
1167                         $sshot = 'images/noscreenshot.png';
1168                    }
1169
1170                    $line .= 
1171                    '<div class="module-sshot"><img src="'.$sshot.'" alt="'.
1172                    sprintf(__('%s screenshot.'), html::escapeHTML($module['name'])).'" /></div>';
1173               }
1174
1175               $line .= 
1176               '<div class="module-infos toggle-bloc">'.
1177               '<p>';
1178
1179               if (in_array('desc', $cols)) {
1180                    $line .= 
1181                    '<span class="module-desc">'.html::escapeHTML($module['desc']).'</span> ';
1182               }
1183
1184               if (in_array('author', $cols)) {
1185                    $line .= 
1186                    '<span class="module-author">'.sprintf(__('by %s'),html::escapeHTML($module['author'])).'</span> ';
1187               }
1188
1189               if (in_array('version', $cols)) {
1190                    $line .= 
1191                    '<span class="module-version">'.sprintf(__('version %s'),html::escapeHTML($module['version'])).'</span> ';
1192               }
1193
1194               if (in_array('current_version', $cols)) {
1195                    $line .= 
1196                    '<span class="module-current-version">'.sprintf(__('(current version %s)'),html::escapeHTML($module['current_version'])).'</span> ';
1197               }
1198
1199               if (in_array('parent', $cols) && !empty($module['parent'])) {
1200                    if ($this->modules->moduleExists($module['parent'])) {
1201                         $line .= 
1202                         '<span class="module-parent-ok">'.sprintf(__('(built on "%s")'),html::escapeHTML($module['parent'])).'</span> ';
1203                    }
1204                    else {
1205                         $line .= 
1206                         '<span class="module-parent-missing">'.sprintf(__('(requires "%s")'),html::escapeHTML($module['parent'])).'</span> ';
1207                    }
1208               }
1209
1210               $has_details = in_array('details', $cols) && !empty($module['details']);
1211               $has_support = in_array('support', $cols) && !empty($module['support']);
1212               if ($has_details || $has_support) {
1213                    $line .=
1214                    '<span class="mod-more">';
1215
1216                    if ($has_details) {
1217                         $line .= 
1218                         '<a class="module-details" href="'.$module['details'].'">'.__('Details').'</a>';
1219                    }
1220
1221                    if ($has_support) {
1222                         $line .= 
1223                         ' - <a class="module-support" href="'.$module['support'].'">'.__('Support').'</a>';
1224                    }
1225
1226                    $line .=
1227                    '</span>';
1228               }
1229
1230               $line .= 
1231               '</p>'.
1232               '</div>';
1233
1234               $line .= 
1235               '<div class="module-actions toggle-bloc">';
1236               
1237               # Plugins actions
1238               if ($current) {
1239
1240                    # _GET actions
1241                    if (file_exists(path::real($this->core->blog->themes_path.'/'.$id).'/style.css')) {
1242                         $theme_url = preg_match('#^http(s)?://#', $this->core->blog->settings->system->themes_url) ?
1243                              http::concatURL($this->core->blog->settings->system->themes_url, '/'.$id) :
1244                              http::concatURL($this->core->blog->url, $this->core->blog->settings->system->themes_url.'/'.$id);
1245                         $line .= 
1246                         '<p><a href="'.$theme_url.'/style.css">'.__('View stylesheet').'</a></p>';
1247                    }
1248
1249                    $line .= '<div class="current-actions">';
1250
1251                    if (file_exists(path::real($this->core->blog->themes_path.'/'.$id).'/_config.php')) {
1252                         $line .= 
1253                         '<p><a href="'.$this->getURL('module='.$id.'&conf=1', false).'" class="button">'.__('Configure theme').'</a></p>';
1254                    }
1255
1256                    # --BEHAVIOR-- adminCurrentThemeDetails
1257                    $line .= 
1258                    $this->core->callBehavior('adminCurrentThemeDetails', $this->core, $id, $module);
1259
1260                    $line .= '</div>';
1261               }
1262
1263               # _POST actions
1264               if (!empty($actions)) {
1265                    $line .=
1266                    '<form action="'.$this->getURL().'" method="post">'.
1267                    '<div>'.
1268                    $this->core->formNonce().
1269                    form::hidden(array('module'), html::escapeHTML($id)).
1270
1271                    implode(' ', $this->getActions($id, $module, $actions)).
1272 
1273                    '</div>'.
1274                    '</form>';
1275               }
1276
1277               $line .= 
1278               '</div>';
1279
1280               $line .=
1281               '</div>';
1282
1283               $count++;
1284
1285               $res = $current ? $line.$res : $res.$line;
1286          }
1287          echo 
1288          $res.
1289          '</div>';
1290
1291          if(!$count && $this->getSearch() === null) {
1292               echo 
1293               '<p class="message">'.__('No module matches your search.').'</p>';
1294          }
1295     }
1296
1297     protected function getActions($id, $module, $actions)
1298     {
1299          $submits = array();
1300
1301          $this->core->blog->settings->addNamespace('system');
1302          if ($id != $this->core->blog->settings->system->theme) {
1303
1304               # Select theme to use on curent blog
1305               if (in_array('select', $actions) && $this->path_writable) {
1306                    $submits[] = 
1307                    '<input type="submit" name="select" value="'.__('Use this one').'" />';
1308               }
1309          }
1310
1311          return array_merge(
1312               $submits,
1313               parent::getActions($id, $module, $actions)
1314          );
1315     }
1316
1317     public function doActions($prefix)
1318     {
1319          if (!empty($_POST) && empty($_REQUEST['conf']) && $this->isWritablePath()) {
1320
1321               # Select theme to use on curent blog
1322               if (!empty($_POST['module']) && !empty($_POST['select'])) {
1323                    $id = $_POST['module'];
1324
1325                    if (!$this->modules->moduleExists($id)) {
1326                         throw new Exception(__('No such module.'));
1327                    }
1328
1329                    $this->core->blog->settings->addNamespace('system');
1330                    $this->core->blog->settings->system->put('theme',$id);
1331                    $this->core->blog->triggerBlog();
1332
1333                    dcPage::addSuccessNotice(__('Module has been successfully selected.'));
1334                    http::redirect($this->getURL().'#themes');
1335               }
1336          }
1337
1338          return parent::doActions($prefix);
1339     }
1340}
Note: See TracBrowser for help on using the repository browser.

Sites map