Dotclear

source: inc/core/class.dc.modules.php @ 3109:7dab5455c29c

Revision 3109:7dab5455c29c, 18.6 KB checked in by franck <carnet.franck.paul@…>, 10 years ago (diff)

A step backward for admin URLs registration.

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
235          // Give opportunity to do something before loading context (admin,public,xmlrpc) files
236          $this->core->callBehavior('coreBeforeLoadingNsFiles',$this->core,$this,$lang);
237
238          foreach ($this->modules as $id => $m)
239          {
240               # If _prepend.php file returns null (ie. it has a void return statement)
241               if (in_array($id,$ignored)) {
242                    continue;
243               }
244               # Load ns_file
245               $this->loadNsFile($id,$ns);
246          }
247     }
248
249     public function requireDefine($dir,$id)
250     {
251          if (file_exists($dir.'/_define.php')) {
252               $this->id = $id;
253               require $dir.'/_define.php';
254               $this->id = null;
255          }
256     }
257
258     /**
259     This method registers a module in modules list. You should use this to
260     register a new module.
261
262     <var>$permissions</var> is a comma separated list of permissions for your
263     module. If <var>$permissions</var> is null, only super admin has access to
264     this module.
265
266     <var>$priority</var> is an integer. Modules are sorted by priority and name.
267     Lowest priority comes first.
268
269     @param    name           <b>string</b>       Module name
270     @param    desc           <b>string</b>       Module description
271     @param    author         <b>string</b>       Module author name
272     @param    version        <b>string</b>       Module version
273     @param    properties     <b>array</b>        extra properties
274     (currently available keys : permissions, priority, type)
275     */
276     public function registerModule($name,$desc,$author,$version, $properties = array())
277     {
278          if ($this->disabled_mode) {
279               $this->disabled_meta = array_merge(
280                         $properties,
281                         array(
282                              'root' => $this->mroot,
283                              'name' => $name,
284                              'desc' => $desc,
285                              'author' => $author,
286                              'version' => $version,
287                              'enabled' => false,
288                              'root_writable' => is_writable($this->mroot)
289                         )
290                    );
291               return;
292          }
293          # Fallback to legacy registerModule parameters
294          if (!is_array($properties)) {
295               $args = func_get_args();
296               $properties = array();
297               if (isset($args[4])) {
298                    $properties['permissions']=$args[4];
299               }
300               if (isset($args[5])) {
301                    $properties['priority']= (integer)$args[5];
302               }
303          }
304
305          # Default module properties
306          $properties = array_merge(
307               array(
308                    'permissions' => null,
309                    'priority' => 1000,
310                    'standalone_config' => false,
311                    'type' => null,
312                    'enabled' => true,
313                    'requires' => array()
314               ), $properties
315          );
316
317          # Check module type
318          if (self::$type !== null && $properties['type'] !== null && $properties['type'] != self::$type) {
319               $this->errors[] = sprintf(
320                    __('Module "%s" has type "%s" that mismatch required module type "%s".'),
321                    '<strong>'.html::escapeHTML($name).'</strong>',
322                    '<em>'.html::escapeHTML($properties['type']).'</em>',
323                    '<em>'.html::escapeHTML(self::$type).'</em>'
324               );
325               return;
326          }
327
328          # Check module perms on admin side
329          $permissions = $properties['permissions'];
330          if ($this->ns == 'admin') {
331               if ($permissions == '' && !$this->core->auth->isSuperAdmin()) {
332                    return;
333               } elseif (!$this->core->auth->check($permissions,$this->core->blog->id)) {
334                    return;
335               }
336          }
337
338          # Check module install on multiple path
339          if ($this->id) {
340               $module_exists = array_key_exists($name,$this->modules_names);
341               $module_overwrite = $module_exists ? version_compare($this->modules_names[$name],$version,'<') : false;
342               if (!$module_exists || ($module_exists && $module_overwrite)) {
343                    $this->modules_names[$name] = $version;
344                    $this->modules[$this->id] = array_merge(
345                         $properties,
346                         array(
347                              'root' => $this->mroot,
348                              'name' => $name,
349                              'desc' => $desc,
350                              'author' => $author,
351                              'version' => $version,
352                              'root_writable' => is_writable($this->mroot)
353                         )
354                    );
355               }
356               else {
357                    $path1 = path::real($this->moduleInfo($name,'root'));
358                    $path2 = path::real($this->mroot);
359                    $this->errors[] = sprintf(
360                         __('Module "%s" is installed twice in "%s" and "%s".'),
361                         '<strong>'.$name.'</strong>',
362                         '<em>'.$path1.'</em>',
363                         '<em>'.$path2.'</em>'
364                    );
365               }
366          }
367     }
368
369     public function resetModulesList()
370     {
371          $this->modules = array();
372          $this->modules_names = array();
373          $this->errors = array();
374     }
375
376     public static function installPackage($zip_file,dcModules &$modules)
377     {
378          $zip = new fileUnzip($zip_file);
379          $zip->getList(false,'#(^|/)(__MACOSX|\.svn|\.hg|\.git|\.DS_Store|\.directory|Thumbs\.db)(/|$)#');
380
381          $zip_root_dir = $zip->getRootDir();
382          $define = '';
383          if ($zip_root_dir != false) {
384               $target = dirname($zip_file);
385               $destination = $target.'/'.$zip_root_dir;
386               $define = $zip_root_dir.'/_define.php';
387               $has_define = $zip->hasFile($define);
388          } else {
389               $target = dirname($zip_file).'/'.preg_replace('/\.([^.]+)$/','',basename($zip_file));
390               $destination = $target;
391               $define = '_define.php';
392               $has_define = $zip->hasFile($define);
393          }
394
395          if ($zip->isEmpty()) {
396               $zip->close();
397               unlink($zip_file);
398               throw new Exception(__('Empty module zip file.'));
399          }
400
401          if (!$has_define) {
402               $zip->close();
403               unlink($zip_file);
404               throw new Exception(__('The zip file does not appear to be a valid Dotclear module.'));
405          }
406
407          $ret_code = 1;
408
409          if (!is_dir($destination))
410          {
411               try {
412                    files::makeDir($destination,true);
413
414                    $sandbox = clone $modules;
415                    $zip->unzip($define, $target.'/_define.php');
416
417                    $sandbox->resetModulesList();
418                    $sandbox->requireDefine($target,basename($destination));
419                    unlink($target.'/_define.php');
420
421                    $new_errors = $sandbox->getErrors();
422                    if (!empty($new_errors)) {
423                         $new_errors = is_array($new_errors) ? implode(" \n",$new_errors) : $new_errors;
424                         throw new Exception($new_errors);
425                    }
426
427                    files::deltree($destination);
428               }
429               catch(Exception $e)
430               {
431                    $zip->close();
432                    unlink($zip_file);
433                    files::deltree($destination);
434                    throw new Exception($e->getMessage());
435               }
436          }
437          else
438          {
439               # test for update
440               $sandbox = clone $modules;
441               $zip->unzip($define, $target.'/_define.php');
442
443               $sandbox->resetModulesList();
444               $sandbox->requireDefine($target,basename($destination));
445               unlink($target.'/_define.php');
446               $new_modules = $sandbox->getModules();
447
448               if (!empty($new_modules))
449               {
450                    $tmp = array_keys($new_modules);
451                    $id = $tmp[0];
452                    $cur_module = $modules->getModules($id);
453                    if (!empty($cur_module) && (defined('DC_DEV') && DC_DEV === true || dcUtils::versionsCompare($new_modules[$id]['version'], $cur_module['version'], '>', true)))
454                    {
455                         # delete old module
456                         if (!files::deltree($destination)) {
457                              throw new Exception(__('An error occurred during module deletion.'));
458                         }
459                         $ret_code = 2;
460                    }
461                    else
462                    {
463                         $zip->close();
464                         unlink($zip_file);
465                         throw new Exception(sprintf(__('Unable to upgrade "%s". (older or same version)'),basename($destination)));
466                    }
467               }
468               else
469               {
470                    $zip->close();
471                    unlink($zip_file);
472                    throw new Exception(sprintf(__('Unable to read new _define.php file')));
473               }
474          }
475          $zip->unzipAll($target);
476          $zip->close();
477          unlink($zip_file);
478          return $ret_code;
479     }
480
481     /**
482     This method installs all modules having a _install file.
483
484     @see dcModules::installModule
485     */
486     public function installModules()
487     {
488          $res = array('success'=>array(),'failure'=>array());
489          foreach ($this->modules as $id => &$m)
490          {
491               $i = $this->installModule($id,$msg);
492               if ($i === true) {
493                    $res['success'][$id] = true;
494               } elseif ($i === false) {
495                    $res['failure'][$id] = $msg;
496               }
497          }
498
499          return $res;
500     }
501
502     /**
503     This method installs module with ID <var>$id</var> and having a _install
504     file. This file should throw exception on failure or true if it installs
505     successfully.
506
507     <var>$msg</var> is an out parameter that handle installer message.
508
509     @param    id        <b>string</b>       Module ID
510     @param    msg       <b>string</b>       Module installer message
511     @return   <b>boolean</b>
512     */
513     public function installModule($id,&$msg)
514     {
515          try {
516               $i = $this->loadModuleFile($this->modules[$id]['root'].'/_install.php');
517               if ($i === true) {
518                    return true;
519               }
520          } catch (Exception $e) {
521               $msg = $e->getMessage();
522               return false;
523          }
524
525          return null;
526     }
527
528     public function deleteModule($id,$disabled=false)
529     {
530          if ($disabled) {
531               $p =& $this->disabled;
532          } else {
533               $p =& $this->modules;
534          }
535
536          if (!isset($p[$id])) {
537               throw new Exception(__('No such module.'));
538          }
539
540          if (!files::deltree($p[$id]['root'])) {
541               throw new Exception(__('Cannot remove module files'));
542          }
543     }
544
545     public function deactivateModule($id)
546     {
547          if (!isset($this->modules[$id])) {
548               throw new Exception(__('No such module.'));
549          }
550
551          if (!$this->modules[$id]['root_writable']) {
552               throw new Exception(__('Cannot deactivate plugin.'));
553          }
554
555          if (@file_put_contents($this->modules[$id]['root'].'/_disabled','')) {
556               throw new Exception(__('Cannot deactivate plugin.'));
557          }
558     }
559
560     public function activateModule($id)
561     {
562          if (!isset($this->disabled[$id])) {
563               throw new Exception(__('No such module.'));
564          }
565
566          if (!$this->disabled[$id]['root_writable']) {
567               throw new Exception(__('Cannot activate plugin.'));
568          }
569
570          if (@unlink($this->disabled[$id]['root'].'/_disabled') === false) {
571               throw new Exception(__('Cannot activate plugin.'));
572          }
573     }
574
575     /**
576     This method will search for file <var>$file</var> in language
577     <var>$lang</var> for module <var>$id</var>.
578
579     <var>$file</var> should not have any extension.
580
581     @param    id        <b>string</b>       Module ID
582     @param    lang      <b>string</b>       Language code
583     @param    file      <b>string</b>       File name (without extension)
584     */
585     public function loadModuleL10N($id,$lang,$file)
586     {
587          if (!$lang || !isset($this->modules[$id])) {
588               return;
589          }
590
591          $lfile = $this->modules[$id]['root'].'/locales/%s/%s';
592          if (l10n::set(sprintf($lfile,$lang,$file)) === false && $lang != 'en') {
593               l10n::set(sprintf($lfile,'en',$file));
594          }
595     }
596
597     public function loadModuleL10Nresources($id,$lang)
598     {
599          if (!$lang || !isset($this->modules[$id])) {
600               return;
601          }
602
603          $f = l10n::getFilePath($this->modules[$id]['root'].'/locales','resources.php',$lang);
604          if ($f) {
605               $this->loadModuleFile($f);
606          }
607     }
608
609     /**
610     Returns all modules associative array or only one module if <var>$id</var>
611     is present.
612
613     @param    id        <b>string</b>       Optionnal module ID
614     @return   <b>array</b>
615     */
616     public function getModules($id=null)
617     {
618          if ($id && isset($this->modules[$id])) {
619               return $this->modules[$id];
620          }
621          return $this->modules;
622     }
623
624     /**
625     Returns true if the module with ID <var>$id</var> exists.
626
627     @param    id        <b>string</b>       Module ID
628     @return   <b>boolean</b>
629     */
630     public function moduleExists($id)
631     {
632          return isset($this->modules[$id]);
633     }
634
635     /**
636     Returns all disabled modules in an array
637
638     @return   <b>array</b>
639     */
640     public function getDisabledModules()
641     {
642          return $this->disabled;
643     }
644
645     /**
646     Returns root path for module with ID <var>$id</var>.
647
648     @param    id        <b>string</b>       Module ID
649     @return   <b>string</b>
650     */
651     public function moduleRoot($id)
652     {
653          return $this->moduleInfo($id,'root');
654     }
655
656     /**
657     Returns a module information that could be:
658     - root
659     - name
660     - desc
661     - author
662     - version
663     - permissions
664     - priority
665
666     @param    id        <b>string</b>       Module ID
667     @param    info      <b>string</b>       Information to retrieve
668     @return   <b>string</b>
669     */
670     public function moduleInfo($id,$info)
671     {
672          return isset($this->modules[$id][$info]) ? $this->modules[$id][$info] : null;
673     }
674
675     /**
676     Loads namespace <var>$ns</var> specific files for all modules.
677
678     @param    ns        <b>string</b>       Namespace name
679     */
680     public function loadNsFiles($ns=null)
681     {
682          foreach ($this->modules as $k => $v) {
683               $this->loadNsFile($k,$ns);
684          }
685     }
686
687     /**
688     Loads namespace <var>$ns</var> specific file for module with ID
689     <var>$id</var>
690
691     @param    id        <b>string</b>       Module ID
692     @param    ns        <b>string</b>       Namespace name
693     */
694     public function loadNsFile($id,$ns=null)
695     {
696          switch ($ns) {
697               case 'admin':
698                    $this->loadModuleFile($this->modules[$id]['root'].'/_admin.php');
699                    break;
700               case 'public':
701                    $this->loadModuleFile($this->modules[$id]['root'].'/_public.php');
702                    break;
703               case 'xmlrpc':
704                    $this->loadModuleFile($this->modules[$id]['root'].'/_xmlrpc.php');
705                    break;
706          }
707     }
708
709     public function getErrors()
710     {
711          return $this->errors;
712     }
713
714     protected function loadModuleFile($________)
715     {
716          if (!file_exists($________)) {
717               return;
718          }
719
720          self::$_k = array_keys($GLOBALS);
721
722          foreach (self::$_k as self::$_n) {
723               if (!in_array(self::$_n,self::$superglobals)) {
724                    global ${self::$_n};
725               }
726          }
727
728          return require $________;
729     }
730
731     private function sortModules($a,$b)
732     {
733          if ($a['priority'] == $b['priority']) {
734               return strcasecmp($a['name'],$b['name']);
735          }
736
737          return ($a['priority'] < $b['priority']) ? -1 : 1;
738     }
739}
Note: See TracBrowser for help on using the repository browser.

Sites map