Dotclear

source: inc/core/class.dc.modules.php @ 3067:42a2dc49b08f

Revision 3067:42a2dc49b08f, 18.4 KB checked in by franck <carnet.franck.paul@…>, 10 years ago (diff)

2.8 Changelog

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_RC_PATH')) { return; }
13
14/**
15@ingroup DC_CORE
16@brief Modules handler
17
18Provides an object to handle modules (themes or plugins).
19*/
20class dcModules
21{
22     protected $path;
23     protected $ns;
24     protected $modules = array();
25     protected $disabled = array();
26     protected $errors = array();
27     protected $modules_names = array();
28     protected $all_modules = array();
29     protected $disabled_mode = false;
30     protected $disabled_meta = array();
31     protected $to_disable = array();
32
33     protected $id;
34     protected $mroot;
35
36     # Inclusion variables
37     protected static $superglobals = array('GLOBALS','_SERVER','_GET','_POST','_COOKIE','_FILES','_ENV','_REQUEST','_SESSION');
38     protected static $_k;
39     protected static $_n;
40
41     protected static $type = null;
42
43     public $core;  ///< <b>dcCore</b>  dcCore instance
44
45     /**
46     Object constructor.
47
48     @param    core      <b>dcCore</b>  dcCore instance
49     */
50     public function __construct($core)
51     {
52          $this->core =& $core;
53     }
54
55     /**
56      * Checks all modules dependencies
57      *   Fills in the following information in module :
58      *     * cannot_enable : list reasons why module cannot be enabled. Not set if module can be enabled
59      *     * cannot_disable : list reasons why module cannot be disabled. Not set if module can be disabled
60      *     * implies : reverse dependencies
61      * @return array list of enabled modules with unmet dependencies, and that must be disabled.
62      */
63     public function checkDependencies()
64     {
65          $this->to_disable = array();
66          foreach ($this->all_modules as $k => &$m) {
67               if (isset($m['requires'])) {
68                    $missing = array();
69                    foreach ($m['requires'] as &$dep) {
70                         if (!is_array($dep)) {
71                              $dep = array($dep);
72                         }
73                         // grab missing dependencies
74                         if (!isset($this->all_modules[$dep[0]])) {
75                              // module not present
76                              $missing[$dep[0]] = sprintf(__("Requires module %s which is not installed"), $dep[0]);
77                         } elseif ((count($dep)>1) && version_compare($this->all_modules[$dep[0]]['version'],$dep[1])==-1) {
78                              // module present, but version missing
79                              $missing[$dep[0]] = sprintf(__("Requires module %s version %s, but version %s is installed"), $dep[0],$dep[1],$m['version']);
80                         } elseif (!$this->all_modules[$dep[0]]['enabled']) {
81                              // module disabled
82                              $missing[$dep[0]] = sprintf(__("Requires module %s which is disabled"), $dep[0]);
83                         }
84                         $this->all_modules[$dep[0]]['implies'][]=$k;
85                    }
86                    if (count($missing)) {
87                         $m['cannot_enable']=$missing;
88                         if ($m['enabled']) {
89                              $this->to_disable[]=array('name' => $k,'reason'=> $missing);
90                         }
91                    }
92               }
93          }
94          // Check modules that cannot be disabled
95          foreach ($this->modules as $k => &$m) {
96               if (isset($m['implies']) && $m['enabled']) {
97                    foreach ($m['implies'] as $im) {
98                         if (isset($this->all_modules[$im]) && $this->all_modules[$im]['enabled']) {
99                              $m['cannot_disable'][]=$im;
100                         }
101                    }
102               }
103          }
104     }
105
106     /**
107      * Checks all modules dependencies, and disable unmet dependencies
108      * @param  string $redir_url URL to redirect if modules are to disable
109      * @return boolean, true if a redirection has been performed
110      */
111     public function disableDepModules($redir_url)
112     {
113          if (isset($_GET['dep'])) {
114               // Avoid infinite redirects
115               return false;
116          }
117          $reason = array();
118          foreach ($this->to_disable as $module) {
119               try{
120                    $this->deactivateModule($module['name']);
121                    $reason[] = sprintf("<li>%s : %s</li>",$module['name'],join(',',$module['reason']));
122               } catch (Exception $e) {
123               }
124          }
125          if (count($reason)) {
126               $message = sprintf ("<p>%s</p><ul>%s</ul>",
127                    __('The following extensions have been disabled :'),
128                    join('',$reason)
129               );
130               dcPage::addWarningNotice($message,array('divtag' => true,'with_ts' => false));
131               $url = $redir_url.(strpos($redir_url,"?") ? '&' : '?').'dep=1';
132               http::redirect($url);
133               return true;
134          }
135          return false;
136     }
137
138     /**
139     Loads modules. <var>$path</var> could be a separated list of paths
140     (path separator depends on your OS).
141
142     <var>$ns</var> indicates if an additionnal file needs to be loaded on plugin
143     load, value could be:
144     - admin (loads module's _admin.php)
145     - public (loads module's _public.php)
146     - xmlrpc (loads module's _xmlrpc.php)
147
148     <var>$lang</var> indicates if we need to load a lang file on plugin
149     loading.
150     */
151     public function loadModules($path,$ns=null,$lang=null)
152     {
153          $this->path = explode(PATH_SEPARATOR,$path);
154          $this->ns = $ns;
155
156          $disabled = isset($_SESSION['sess_safe_mode']) && $_SESSION['sess_safe_mode'];
157          $disabled = $disabled && !get_parent_class($this) ? true : false;
158
159          $ignored = array();
160
161          foreach ($this->path as $root)
162          {
163               if (!is_dir($root) || !is_readable($root)) {
164                    continue;
165               }
166
167               if (substr($root,-1) != '/') {
168                    $root .= '/';
169               }
170
171               if (($d = @dir($root)) === false) {
172                    continue;
173               }
174
175               while (($entry = $d->read()) !== false)
176               {
177                    $full_entry = $root.$entry;
178
179                    if ($entry != '.' && $entry != '..' && is_dir($full_entry)
180                    && file_exists($full_entry.'/_define.php'))
181                    {
182                         if (!file_exists($full_entry.'/_disabled') && !$disabled)
183                         {
184                              $this->id = $entry;
185                              $this->mroot = $full_entry;
186                              require $full_entry.'/_define.php';
187                              $this->all_modules[$entry] =& $this->modules[$entry];
188                              $this->id = null;
189                              $this->mroot = null;
190                         }
191                         else
192                         {
193                              if (file_exists($full_entry.'/_define.php')) {
194                                   $this->id = $entry;
195                                   $this->mroot = $full_entry;
196                                   $this->disabled_mode=true;
197                                   require $full_entry.'/_define.php';
198                                   $this->disabled_mode=false;
199                                   $this->disabled[$entry] =  $this->disabled_meta;
200                                   $this->all_modules[$entry] =& $this->disabled[$entry];
201                                   $this->id = null;
202                                   $this->mroot = null;
203                              }
204                         }
205                    }
206               }
207               $d->close();
208          }
209          $this->checkDependencies();
210          # Sort plugins
211          uasort($this->modules,array($this,'sortModules'));
212
213          foreach ($this->modules as $id => $m)
214          {
215               # Load translation and _prepend
216               if (file_exists($m['root'].'/_prepend.php'))
217               {
218                    $r = $this->loadModuleFile($m['root'].'/_prepend.php');
219
220                    # If _prepend.php file returns null (ie. it has a void return statement)
221                    if (is_null($r)) {
222                         $ignored[] = $id;
223                         continue;
224                    }
225                    unset($r);
226               }
227
228               $this->loadModuleL10N($id,$lang,'main');
229               if ($ns == 'admin') {
230                    $this->loadModuleL10Nresources($id,$lang);
231                    $this->core->adminurl->register('admin.plugin.'.$id,'plugin.php',array('p'=>$id));
232               }
233          }
234          foreach ($this->modules as $id => $m)
235          {
236               # If _prepend.php file returns null (ie. it has a void return statement)
237               if (in_array($id,$ignored)) {
238                    continue;
239               }
240               # Load ns_file
241               $this->loadNsFile($id,$ns);
242          }
243     }
244
245     public function requireDefine($dir,$id)
246     {
247          if (file_exists($dir.'/_define.php')) {
248               $this->id = $id;
249               require $dir.'/_define.php';
250               $this->id = null;
251          }
252     }
253
254     /**
255     This method registers a module in modules list. You should use this to
256     register a new module.
257
258     <var>$permissions</var> is a comma separated list of permissions for your
259     module. If <var>$permissions</var> is null, only super admin has access to
260     this module.
261
262     <var>$priority</var> is an integer. Modules are sorted by priority and name.
263     Lowest priority comes first.
264
265     @param    name           <b>string</b>       Module name
266     @param    desc           <b>string</b>       Module description
267     @param    author         <b>string</b>       Module author name
268     @param    version        <b>string</b>       Module version
269     @param    properties     <b>array</b>        extra properties
270     (currently available keys : permissions, priority, type)
271     */
272     public function registerModule($name,$desc,$author,$version, $properties = array())
273     {
274          if ($this->disabled_mode) {
275               $this->disabled_meta = array_merge(
276                         $properties,
277                         array(
278                              'root' => $this->mroot,
279                              'name' => $name,
280                              'desc' => $desc,
281                              'author' => $author,
282                              'version' => $version,
283                              'enabled' => false,
284                              'root_writable' => is_writable($this->mroot)
285                         )
286                    );
287               return;
288          }
289          # Fallback to legacy registerModule parameters
290          if (!is_array($properties)) {
291               $args = func_get_args();
292               $properties = array();
293               if (isset($args[4])) {
294                    $properties['permissions']=$args[4];
295               }
296               if (isset($args[5])) {
297                    $properties['priority']= (integer)$args[5];
298               }
299          }
300
301          # Default module properties
302          $properties = array_merge(
303               array(
304                    'permissions' => null,
305                    'priority' => 1000,
306                    'standalone_config' => false,
307                    'type' => null,
308                    'enabled' => true,
309                    'requires' => array()
310               ), $properties
311          );
312
313          # Check module type
314          if (self::$type !== null && $properties['type'] !== null && $properties['type'] != self::$type) {
315               $this->errors[] = sprintf(
316                    __('Module "%s" has type "%s" that mismatch required module type "%s".'),
317                    '<strong>'.html::escapeHTML($name).'</strong>',
318                    '<em>'.html::escapeHTML($properties['type']).'</em>',
319                    '<em>'.html::escapeHTML(self::$type).'</em>'
320               );
321               return;
322          }
323
324          # Check module perms on admin side
325          $permissions = $properties['permissions'];
326          if ($this->ns == 'admin') {
327               if ($permissions == '' && !$this->core->auth->isSuperAdmin()) {
328                    return;
329               } elseif (!$this->core->auth->check($permissions,$this->core->blog->id)) {
330                    return;
331               }
332          }
333
334          # Check module install on multiple path
335          if ($this->id) {
336               $module_exists = array_key_exists($name,$this->modules_names);
337               $module_overwrite = $module_exists ? version_compare($this->modules_names[$name],$version,'<') : false;
338               if (!$module_exists || ($module_exists && $module_overwrite)) {
339                    $this->modules_names[$name] = $version;
340                    $this->modules[$this->id] = array_merge(
341                         $properties,
342                         array(
343                              'root' => $this->mroot,
344                              'name' => $name,
345                              'desc' => $desc,
346                              'author' => $author,
347                              'version' => $version,
348                              'root_writable' => is_writable($this->mroot)
349                         )
350                    );
351               }
352               else {
353                    $path1 = path::real($this->moduleInfo($name,'root'));
354                    $path2 = path::real($this->mroot);
355                    $this->errors[] = sprintf(
356                         __('Module "%s" is installed twice in "%s" and "%s".'),
357                         '<strong>'.$name.'</strong>',
358                         '<em>'.$path1.'</em>',
359                         '<em>'.$path2.'</em>'
360                    );
361               }
362          }
363     }
364
365     public function resetModulesList()
366     {
367          $this->modules = array();
368          $this->modules_names = array();
369          $this->errors = array();
370     }
371
372     public static function installPackage($zip_file,dcModules &$modules)
373     {
374          $zip = new fileUnzip($zip_file);
375          $zip->getList(false,'#(^|/)(__MACOSX|\.svn|\.hg|\.git|\.DS_Store|\.directory|Thumbs\.db)(/|$)#');
376
377          $zip_root_dir = $zip->getRootDir();
378          $define = '';
379          if ($zip_root_dir != false) {
380               $target = dirname($zip_file);
381               $destination = $target.'/'.$zip_root_dir;
382               $define = $zip_root_dir.'/_define.php';
383               $has_define = $zip->hasFile($define);
384          } else {
385               $target = dirname($zip_file).'/'.preg_replace('/\.([^.]+)$/','',basename($zip_file));
386               $destination = $target;
387               $define = '_define.php';
388               $has_define = $zip->hasFile($define);
389          }
390
391          if ($zip->isEmpty()) {
392               $zip->close();
393               unlink($zip_file);
394               throw new Exception(__('Empty module zip file.'));
395          }
396
397          if (!$has_define) {
398               $zip->close();
399               unlink($zip_file);
400               throw new Exception(__('The zip file does not appear to be a valid Dotclear module.'));
401          }
402
403          $ret_code = 1;
404
405          if (!is_dir($destination))
406          {
407               try {
408                    files::makeDir($destination,true);
409
410                    $sandbox = clone $modules;
411                    $zip->unzip($define, $target.'/_define.php');
412
413                    $sandbox->resetModulesList();
414                    $sandbox->requireDefine($target,basename($destination));
415                    unlink($target.'/_define.php');
416
417                    $new_errors = $sandbox->getErrors();
418                    if (!empty($new_errors)) {
419                         $new_errors = is_array($new_errors) ? implode(" \n",$new_errors) : $new_errors;
420                         throw new Exception($new_errors);
421                    }
422
423                    files::deltree($destination);
424               }
425               catch(Exception $e)
426               {
427                    $zip->close();
428                    unlink($zip_file);
429                    files::deltree($destination);
430                    throw new Exception($e->getMessage());
431               }
432          }
433          else
434          {
435               # test for update
436               $sandbox = clone $modules;
437               $zip->unzip($define, $target.'/_define.php');
438
439               $sandbox->resetModulesList();
440               $sandbox->requireDefine($target,basename($destination));
441               unlink($target.'/_define.php');
442               $new_modules = $sandbox->getModules();
443
444               if (!empty($new_modules))
445               {
446                    $tmp = array_keys($new_modules);
447                    $id = $tmp[0];
448                    $cur_module = $modules->getModules($id);
449                    if (!empty($cur_module) && (defined('DC_DEV') && DC_DEV === true || dcUtils::versionsCompare($new_modules[$id]['version'], $cur_module['version'], '>', true)))
450                    {
451                         # delete old module
452                         if (!files::deltree($destination)) {
453                              throw new Exception(__('An error occurred during module deletion.'));
454                         }
455                         $ret_code = 2;
456                    }
457                    else
458                    {
459                         $zip->close();
460                         unlink($zip_file);
461                         throw new Exception(sprintf(__('Unable to upgrade "%s". (older or same version)'),basename($destination)));
462                    }
463               }
464               else
465               {
466                    $zip->close();
467                    unlink($zip_file);
468                    throw new Exception(sprintf(__('Unable to read new _define.php file')));
469               }
470          }
471          $zip->unzipAll($target);
472          $zip->close();
473          unlink($zip_file);
474          return $ret_code;
475     }
476
477     /**
478     This method installs all modules having a _install file.
479
480     @see dcModules::installModule
481     */
482     public function installModules()
483     {
484          $res = array('success'=>array(),'failure'=>array());
485          foreach ($this->modules as $id => &$m)
486          {
487               $i = $this->installModule($id,$msg);
488               if ($i === true) {
489                    $res['success'][$id] = true;
490               } elseif ($i === false) {
491                    $res['failure'][$id] = $msg;
492               }
493          }
494
495          return $res;
496     }
497
498     /**
499     This method installs module with ID <var>$id</var> and having a _install
500     file. This file should throw exception on failure or true if it installs
501     successfully.
502
503     <var>$msg</var> is an out parameter that handle installer message.
504
505     @param    id        <b>string</b>       Module ID
506     @param    msg       <b>string</b>       Module installer message
507     @return   <b>boolean</b>
508     */
509     public function installModule($id,&$msg)
510     {
511          try {
512               $i = $this->loadModuleFile($this->modules[$id]['root'].'/_install.php');
513               if ($i === true) {
514                    return true;
515               }
516          } catch (Exception $e) {
517               $msg = $e->getMessage();
518               return false;
519          }
520
521          return null;
522     }
523
524     public function deleteModule($id,$disabled=false)
525     {
526          if ($disabled) {
527               $p =& $this->disabled;
528          } else {
529               $p =& $this->modules;
530          }
531
532          if (!isset($p[$id])) {
533               throw new Exception(__('No such module.'));
534          }
535
536          if (!files::deltree($p[$id]['root'])) {
537               throw new Exception(__('Cannot remove module files'));
538          }
539     }
540
541     public function deactivateModule($id)
542     {
543          if (!isset($this->modules[$id])) {
544               throw new Exception(__('No such module.'));
545          }
546
547          if (!$this->modules[$id]['root_writable']) {
548               throw new Exception(__('Cannot deactivate plugin.'));
549          }
550
551          if (@file_put_contents($this->modules[$id]['root'].'/_disabled','')) {
552               throw new Exception(__('Cannot deactivate plugin.'));
553          }
554     }
555
556     public function activateModule($id)
557     {
558          if (!isset($this->disabled[$id])) {
559               throw new Exception(__('No such module.'));
560          }
561
562          if (!$this->disabled[$id]['root_writable']) {
563               throw new Exception(__('Cannot activate plugin.'));
564          }
565
566          if (@unlink($this->disabled[$id]['root'].'/_disabled') === false) {
567               throw new Exception(__('Cannot activate plugin.'));
568          }
569     }
570
571     /**
572     This method will search for file <var>$file</var> in language
573     <var>$lang</var> for module <var>$id</var>.
574
575     <var>$file</var> should not have any extension.
576
577     @param    id        <b>string</b>       Module ID
578     @param    lang      <b>string</b>       Language code
579     @param    file      <b>string</b>       File name (without extension)
580     */
581     public function loadModuleL10N($id,$lang,$file)
582     {
583          if (!$lang || !isset($this->modules[$id])) {
584               return;
585          }
586
587          $lfile = $this->modules[$id]['root'].'/locales/%s/%s';
588          if (l10n::set(sprintf($lfile,$lang,$file)) === false && $lang != 'en') {
589               l10n::set(sprintf($lfile,'en',$file));
590          }
591     }
592
593     public function loadModuleL10Nresources($id,$lang)
594     {
595          if (!$lang || !isset($this->modules[$id])) {
596               return;
597          }
598
599          $f = l10n::getFilePath($this->modules[$id]['root'].'/locales','resources.php',$lang);
600          if ($f) {
601               $this->loadModuleFile($f);
602          }
603     }
604
605     /**
606     Returns all modules associative array or only one module if <var>$id</var>
607     is present.
608
609     @param    id        <b>string</b>       Optionnal module ID
610     @return   <b>array</b>
611     */
612     public function getModules($id=null)
613     {
614          if ($id && isset($this->modules[$id])) {
615               return $this->modules[$id];
616          }
617          return $this->modules;
618     }
619
620     /**
621     Returns true if the module with ID <var>$id</var> exists.
622
623     @param    id        <b>string</b>       Module ID
624     @return   <b>boolean</b>
625     */
626     public function moduleExists($id)
627     {
628          return isset($this->modules[$id]);
629     }
630
631     /**
632     Returns all disabled modules in an array
633
634     @return   <b>array</b>
635     */
636     public function getDisabledModules()
637     {
638          return $this->disabled;
639     }
640
641     /**
642     Returns root path for module with ID <var>$id</var>.
643
644     @param    id        <b>string</b>       Module ID
645     @return   <b>string</b>
646     */
647     public function moduleRoot($id)
648     {
649          return $this->moduleInfo($id,'root');
650     }
651
652     /**
653     Returns a module information that could be:
654     - root
655     - name
656     - desc
657     - author
658     - version
659     - permissions
660     - priority
661
662     @param    id        <b>string</b>       Module ID
663     @param    info      <b>string</b>       Information to retrieve
664     @return   <b>string</b>
665     */
666     public function moduleInfo($id,$info)
667     {
668          return isset($this->modules[$id][$info]) ? $this->modules[$id][$info] : null;
669     }
670
671     /**
672     Loads namespace <var>$ns</var> specific files for all modules.
673
674     @param    ns        <b>string</b>       Namespace name
675     */
676     public function loadNsFiles($ns=null)
677     {
678          foreach ($this->modules as $k => $v) {
679               $this->loadNsFile($k,$ns);
680          }
681     }
682
683     /**
684     Loads namespace <var>$ns</var> specific file for module with ID
685     <var>$id</var>
686
687     @param    id        <b>string</b>       Module ID
688     @param    ns        <b>string</b>       Namespace name
689     */
690     public function loadNsFile($id,$ns=null)
691     {
692          switch ($ns) {
693               case 'admin':
694                    $this->loadModuleFile($this->modules[$id]['root'].'/_admin.php');
695                    break;
696               case 'public':
697                    $this->loadModuleFile($this->modules[$id]['root'].'/_public.php');
698                    break;
699               case 'xmlrpc':
700                    $this->loadModuleFile($this->modules[$id]['root'].'/_xmlrpc.php');
701                    break;
702          }
703     }
704
705     public function getErrors()
706     {
707          return $this->errors;
708     }
709
710     protected function loadModuleFile($________)
711     {
712          if (!file_exists($________)) {
713               return;
714          }
715
716          self::$_k = array_keys($GLOBALS);
717
718          foreach (self::$_k as self::$_n) {
719               if (!in_array(self::$_n,self::$superglobals)) {
720                    global ${self::$_n};
721               }
722          }
723
724          return require $________;
725     }
726
727     private function sortModules($a,$b)
728     {
729          if ($a['priority'] == $b['priority']) {
730               return strcasecmp($a['name'],$b['name']);
731          }
732
733          return ($a['priority'] < $b['priority']) ? -1 : 1;
734     }
735}
Note: See TracBrowser for help on using the repository browser.

Sites map