Dotclear

source: inc/core/class.dc.modules.php @ 0:54703be25dd6

Revision 0:54703be25dd6, 12.9 KB checked in by Dsls <dsls@…>, 14 years ago (diff)

2.3 branch (trunk) first checkin

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

Sites map