Dotclear

source: inc/core/class.dc.modules.php @ 2492:8a25f7bf147d

Revision 2492:8a25f7bf147d, 14.6 KB checked in by Denis Jean-Chirstian <contact@…>, 12 years ago (diff)

New class dcPlugins, fix backward compatibility with generic dcModules class and un-type modules

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

Sites map