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

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