source: trunk/admin/include/plugins.class.php @ 2297

Last change on this file since 2297 was 2297, checked in by plg, 16 years ago

Modification: new header on PHP files, PhpWebGallery renamed Piwigo.

  • Property svn:eol-style set to LF
  • Property svn:keywords set to Author Date Id Revision
File size: 15.2 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based picture gallery                                  |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008      Piwigo Team                  http://piwigo.org |
6// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
7// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
8// +-----------------------------------------------------------------------+
9// | This program is free software; you can redistribute it and/or modify  |
10// | it under the terms of the GNU General Public License as published by  |
11// | the Free Software Foundation                                          |
12// |                                                                       |
13// | This program is distributed in the hope that it will be useful, but   |
14// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
15// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
16// | General Public License for more details.                              |
17// |                                                                       |
18// | You should have received a copy of the GNU General Public License     |
19// | along with this program; if not, write to the Free Software           |
20// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
21// | USA.                                                                  |
22// +-----------------------------------------------------------------------+
23// +-----------------------------------------------------------------------+
24// | PhpWebGallery - a PHP based picture gallery                           |
25// | Copyright (C) 2002-2003 Pierrick LE GALL - pierrick@phpwebgallery.net |
26// | Copyright (C) 2003-2008 PhpWebGallery Team - http://phpwebgallery.net |
27// +-----------------------------------------------------------------------+
28// | file          : $Id: plugins.class.php 2297 2008-04-04 22:57:23Z plg $
29// | last update   : $Date: 2008-04-04 22:57:23 +0000 (Fri, 04 Apr 2008) $
30// | last modifier : $Author: plg $
31// | revision      : $Revision: 2297 $
32// +-----------------------------------------------------------------------+
33// | This program is free software; you can redistribute it and/or modify  |
34// | it under the terms of the GNU General Public License as published by  |
35// | the Free Software Foundation                                          |
36// |                                                                       |
37// | This program is distributed in the hope that it will be useful, but   |
38// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
39// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
40// | General Public License for more details.                              |
41// |                                                                       |
42// | You should have received a copy of the GNU General Public License     |
43// | along with this program; if not, write to the Free Software           |
44// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
45// | USA.                                                                  |
46// +-----------------------------------------------------------------------+
47
48class plugins
49{
50  var $fs_plugins = array();
51  var $db_plugins_by_id = array();
52  var $server_plugins;
53
54  /**
55   * Initialize $fs_plugins and $db_plugins_by_id
56  */
57  function plugins()
58  {
59    $this->get_fs_plugins();
60
61    foreach (get_db_plugins() as $db_plugin)
62    {
63      $this->db_plugins_by_id[$db_plugin['id']] = $db_plugin;
64    }
65  }
66
67 /**
68   * Perform requested actions
69  *  @param string - action
70  * @param string - plugin id
71  * @param array - errors
72  */
73  function perform_action($action, $plugin_id)
74  {
75    if (isset($this->db_plugins_by_id[$plugin_id]))
76    {
77      $crt_db_plugin = $this->db_plugins_by_id[$plugin_id];
78    }
79    $file_to_include = PHPWG_PLUGINS_PATH . $plugin_id . '/maintain.inc.php';
80
81    $errors = array();
82
83    switch ($action)
84    {
85      case 'install':
86        if (!empty($crt_db_plugin))
87        {
88          array_push($errors, 'CANNOT INSTALL - ALREADY INSTALLED');
89          break;
90        }
91        if (!isset($this->fs_plugins[$plugin_id]))
92        {
93          array_push($errors, 'CANNOT INSTALL - NO SUCH PLUGIN');
94          break;
95        }
96        if (file_exists($file_to_include))
97        {
98          include_once($file_to_include);
99          if (function_exists('plugin_install'))
100          {
101            plugin_install($plugin_id, $this->fs_plugins[$plugin_id]['version'], $errors);
102          }
103        }
104        if (empty($errors))
105        {
106          $query = '
107INSERT INTO ' . PLUGINS_TABLE . ' (id,version) VALUES ("'
108. $plugin_id . '","' . $this->fs_plugins[$plugin_id]['version'] . '"
109)';
110          pwg_query($query);
111        }
112        break;
113
114      case 'activate':
115        if (!isset($crt_db_plugin))
116        {
117          array_push($errors, 'CANNOT ACTIVATE - NOT INSTALLED');
118          break;
119        }
120        if ($crt_db_plugin['state'] != 'inactive')
121        {
122          array_push($errors, 'invalid current state ' . $crt_db_plugin['state']);
123          break;
124        }
125        if (file_exists($file_to_include))
126        {
127          include_once($file_to_include);
128          if (function_exists('plugin_activate'))
129          {
130            plugin_activate($plugin_id, $crt_db_plugin['version'], $errors);
131          }
132        }
133        if (empty($errors))
134        {
135          $query = '
136UPDATE ' . PLUGINS_TABLE . ' SET state="active" WHERE id="' . $plugin_id . '"';
137          pwg_query($query);
138        }
139        break;
140
141      case 'deactivate':
142        if (!isset($crt_db_plugin))
143        {
144          die ('CANNOT DEACTIVATE - NOT INSTALLED');
145        }
146        if ($crt_db_plugin['state'] != 'active')
147        {
148          die('invalid current state ' . $crt_db_plugin['state']);
149        }
150        $query = '
151UPDATE ' . PLUGINS_TABLE . ' SET state="inactive" WHERE id="' . $plugin_id . '"';
152        pwg_query($query);
153        if (file_exists($file_to_include))
154        {
155          include_once($file_to_include);
156          if (function_exists('plugin_deactivate'))
157          {
158            plugin_deactivate($plugin_id);
159          }
160        }
161        break;
162
163      case 'uninstall':
164        if (!isset($crt_db_plugin))
165        {
166          die ('CANNOT UNINSTALL - NOT INSTALLED');
167        }
168        $query = '
169DELETE FROM ' . PLUGINS_TABLE . ' WHERE id="' . $plugin_id . '"';
170        pwg_query($query);
171        if (file_exists($file_to_include))
172        {
173          include_once($file_to_include);
174          if (function_exists('plugin_uninstall'))
175          {
176            plugin_uninstall($plugin_id);
177          }
178        }
179        break;
180
181      case 'delete':
182        if (!empty($crt_db_plugin))
183        {
184          array_push($errors, 'CANNOT DELETE - PLUGIN IS INSTALLED');
185          break;
186        }
187        if (!isset($this->fs_plugins[$plugin_id]))
188        {
189          array_push($errors, 'CANNOT DELETE - NO SUCH PLUGIN');
190          break;
191        }
192        if (!$this->deltree(PHPWG_PLUGINS_PATH . $plugin_id))
193        {
194          $this->send_to_trash(PHPWG_PLUGINS_PATH . $plugin_id);
195        }
196        break;
197    }
198    return $errors;
199  }
200
201  /**
202  *  Get plugins defined in the plugin directory
203  */ 
204  function get_fs_plugins()
205  {
206    $dir = opendir(PHPWG_PLUGINS_PATH);
207    while ($file = readdir($dir))
208    {
209      if ($file!='.' and $file!='..')
210      {
211        $path = PHPWG_PLUGINS_PATH.$file;
212        if (is_dir($path) and !is_link($path)
213            and preg_match('/^[a-zA-Z0-9-_]+$/', $file )
214            and file_exists($path.'/main.inc.php')
215            )
216        {
217          $plugin = array(
218              'name'=>$file,
219              'version'=>'0',
220              'uri'=>'',
221              'description'=>'',
222              'author'=>'',
223            );
224          $plg_data = implode( '', file($path.'/main.inc.php') );
225
226          if ( preg_match("|Plugin Name: (.*)|", $plg_data, $val) )
227          {
228            $plugin['name'] = trim( $val[1] );
229          }
230          if (preg_match("|Version: (.*)|", $plg_data, $val))
231          {
232            $plugin['version'] = trim($val[1]);
233          }
234          if ( preg_match("|Plugin URI: (.*)|", $plg_data, $val) )
235          {
236            $plugin['uri'] = trim($val[1]);
237          }
238          if ( preg_match("|Description: (.*)|", $plg_data, $val) )
239          {
240            $plugin['description'] = trim($val[1]);
241          }
242          if ( preg_match("|Author: (.*)|", $plg_data, $val) )
243          {
244            $plugin['author'] = trim($val[1]);
245          }
246          if ( preg_match("|Author URI: (.*)|", $plg_data, $val) )
247          {
248            $plugin['author uri'] = trim($val[1]);
249          }
250          if (!empty($plugin['uri']) and strpos($plugin['uri'] , 'extension_view.php?eid='))
251          {
252            list( , $extension) = explode('extension_view.php?eid=', $plugin['uri']);
253            if (is_numeric($extension)) $plugin['extension'] = $extension;
254          }
255          // IMPORTANT SECURITY !
256          $plugin = array_map('htmlspecialchars', $plugin);
257          $this->fs_plugins[$file] = $plugin;
258        }
259      }
260    }
261    closedir($dir);
262  }
263
264  /**
265   * Sort fs_plugins
266   */
267  function sort_fs_plugins($order='name')
268  {
269    switch ($order)
270    {
271      case 'name':
272        uasort($this->fs_plugins, 'name_compare');
273        break;
274      case 'status':
275        $this->sort_plugins_by_state();
276        break;
277      case 'author':
278        uasort($this->fs_plugins, array($this, 'plugin_author_compare'));
279        break;
280      case 'id':
281        uksort($this->fs_plugins, 'strcasecmp');
282        break;
283    }
284  }
285
286  /**
287   * Retrieve PEM server datas to $server_plugins
288   */
289  function get_server_plugins($new=false)
290  {
291    foreach($this->fs_plugins as $fs_plugin)
292    {
293      if (isset($fs_plugin['extension']))
294      {
295        $plugins_to_check[] = $fs_plugin['extension'];
296      }
297    }
298    $url = PEM_URL . '/uptodate.php?version=' . rawurlencode(PHPWG_VERSION) . '&extensions=' . implode(',', $plugins_to_check);
299    $url .= $new ? '&newext=Plugin' : '';
300
301    if (!empty($plugins_to_check) and $source = @file_get_contents($url))
302    {
303      $this->server_plugins = @unserialize($source);
304    }
305  }
306 
307  /**
308   * Sort $server_plugins
309   */
310  function sort_server_plugins($order='date')
311  {
312    switch ($order)
313    {
314      case 'date':
315        krsort($this->server_plugins);
316        break;
317      case 'revision':
318        usort($this->server_plugins, array($this, 'extension_revision_compare'));
319        break;
320      case 'name':
321        uasort($this->server_plugins, array($this, 'extension_name_compare'));
322        break;
323      case 'author':
324        uasort($this->server_plugins, array($this, 'extension_author_compare'));
325        break;
326    }
327  }
328
329  /**
330   * Extract plugin files from archive
331   * @param string - install or upgrade
332   *  @param string - archive URL
333    * @param string - destination path
334   */
335  function extract_plugin_files($action, $source, $dest)
336  {
337    if ($archive = tempnam( PHPWG_PLUGINS_PATH, 'zip'))
338    {
339      if (@copy(PEM_URL . str_replace(' ', '%20', $source), $archive))
340      {
341        include(PHPWG_ROOT_PATH.'admin/include/pclzip.lib.php');
342        $zip = new PclZip($archive);
343        if ($list = $zip->listContent())
344        {
345          foreach ($list as $file)
346          {
347            // we search main.inc.php in archive
348            if (basename($file['filename']) == 'main.inc.php'
349              and (!isset($main_filepath)
350              or strlen($file['filename']) < strlen($main_filepath)))
351            {
352              $main_filepath = $file['filename'];
353            }
354          }
355          if (isset($main_filepath))
356          {
357            $root = dirname($main_filepath); // main.inc.php path in archive
358            if ($action == 'upgrade')
359            {
360              $extract_path = PHPWG_PLUGINS_PATH.$dest;
361            }
362            else
363            {
364              $extract_path = PHPWG_PLUGINS_PATH
365                  . ($root == '.' ? 'extension_' . $dest : basename($root));
366            }
367            if($result = $zip->extract(PCLZIP_OPT_PATH, $extract_path,
368                                       PCLZIP_OPT_REMOVE_PATH, $root,
369                                       PCLZIP_OPT_REPLACE_NEWER))
370            {
371              foreach ($result as $file)
372              {
373                if ($file['stored_filename'] == $main_filepath)
374                {
375                  $status = $file['status'];
376                  break;
377                }
378              }
379            }
380            else $status = 'extract_error';
381          }
382          else $status = 'archive_error';
383        }
384        else $status = 'archive_error';
385      }
386      else $status = 'dl_archive_error';
387    }
388    else $status = 'temp_path_error';
389
390    @unlink($archive);
391    return $status;
392  }
393 
394  /**
395   * delete $path directory
396   * @param string - path
397   */
398  function deltree($path)
399  {
400    if (is_dir($path))
401    {
402      $fh = opendir($path);
403      while ($file = readdir($fh))
404      {
405        if ($file != '.' and $file != '..')
406        {
407          $pathfile = $path . '/' . $file;
408          if (is_dir($pathfile))
409          {
410            $this->deltree($pathfile);
411          }
412          else
413          {
414            @unlink($pathfile);
415          }
416        }
417      }
418      closedir($fh);
419      return @rmdir($path);
420    }
421  }
422
423  /**
424   * send $path to trash directory
425   * @param string - path
426   */
427  function send_to_trash($path)
428  {
429    $trash_path = PHPWG_PLUGINS_PATH . 'trash';
430    if (!is_dir($trash_path))
431    {
432      @mkdir($trash_path);
433      $file = @fopen($trash_path . '/.htaccess', 'w');
434      @fwrite($file, 'deny from all');
435      @fclose($file);
436    }
437    while ($r = $trash_path . '/' . md5(uniqid(rand(), true)))
438    {
439      if (!is_dir($r))
440      {
441        @rename($path, $r);
442        break;
443      }
444    }
445  }
446
447  /**
448   * Sort functions
449   */
450  function plugin_version_compare($a, $b)
451  {
452    $pattern = array('/([a-z])/ei', '/\.+/', '/\.\Z|\A\./');
453    $replacement = array( "'.'.intval('\\1', 36).'.'", '.', '');
454
455    $array = preg_replace($pattern, $replacement, array($a['version'], $b['version']));
456
457    return version_compare($array[0], $array[1], '>=');
458  }
459
460  function extension_revision_compare($a, $b)
461  {
462    if ($a['date'] < $b['date']) return 1;
463    else return -1;
464  }
465
466  function extension_name_compare($a, $b)
467  {
468    return strcmp(strtolower($a['ext_name']), strtolower($b['ext_name']));
469  }
470
471  function extension_author_compare($a, $b)
472  {
473    $r = strcasecmp($a['author'], $b['author']);
474    if ($r == 0) return $this->extension_name_compare($a, $b);
475    else return $r;
476  }
477
478  function plugin_author_compare($a, $b)
479  {
480    $r = strcasecmp($a['author'], $b['author']);
481    if ($r == 0) return name_compare($a, $b);
482    else return $r;
483  }
484
485  function sort_plugins_by_state()
486  {
487    uasort($this->fs_plugins, 'name_compare');
488
489    $active_plugins = array();
490    $inactive_plugins = array();
491    $not_installed = array();
492
493    foreach($this->fs_plugins as $plugin_id => $plugin)
494    {
495      if (isset($this->db_plugins_by_id[$plugin_id]))
496      {
497        $this->db_plugins_by_id[$plugin_id]['state'] == 'active' ?
498          $active_plugins[$plugin_id] = $plugin : $inactive_plugins[$plugin_id] = $plugin;
499      }
500      else
501      {
502        $not_installed[$plugin_id] = $plugin;
503      }
504    }
505    $this->fs_plugins = $active_plugins + $inactive_plugins + $not_installed;
506  }
507}
508?>
Note: See TracBrowser for help on using the repository browser.