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

Last change on this file since 29393 was 28969, checked in by mistic100, 10 years ago

improves regexes parsing plugins metadata

  • Property svn:eol-style set to LF
File size: 18.7 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based photo gallery                                    |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008-2014 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/**
25 * class DummyPlugin_maintain
26 * used when a plugin uses the old procedural declaration of maintenance methods
27 */
28class DummyPlugin_maintain extends PluginMaintain
29{
30  function install($plugin_version, &$errors=array())
31  {
32    if (is_callable('plugin_install'))
33    {
34      return plugin_install($this->plugin_id, $plugin_version, $errors);
35    }
36  }
37  function activate($plugin_version, &$errors=array())
38  {
39    if (is_callable('plugin_activate'))
40    {
41      return plugin_activate($this->plugin_id, $plugin_version, $errors);
42    }
43  }
44  function deactivate()
45  {
46    if (is_callable('plugin_deactivate'))
47    {
48      return plugin_deactivate($this->plugin_id);
49    }
50  }
51  function uninstall()
52  {
53    if (is_callable('plugin_uninstall'))
54    {
55      return plugin_uninstall($this->plugin_id);
56    }
57  }
58  function update($old_version, $new_version, &$errors=array()) {}
59}
60
61
62class plugins
63{
64  var $fs_plugins = array();
65  var $db_plugins_by_id = array();
66  var $server_plugins = array();
67  var $default_plugins = array('LocalFilesEditor', 'language_switch', 'TakeATour', 'AdminTools');
68
69  /**
70   * Initialize $fs_plugins and $db_plugins_by_id
71   */
72  function plugins()
73  {
74    $this->get_fs_plugins();
75
76    foreach (get_db_plugins() as $db_plugin)
77    {
78      $this->db_plugins_by_id[$db_plugin['id']] = $db_plugin;
79    }
80  }
81
82  /**
83   * Returns the maintain class of a plugin
84   * or build a new class with the procedural methods
85   * @param string $plugin_id
86   */
87  private static function build_maintain_class($plugin_id)
88  {
89    $file_to_include = PHPWG_PLUGINS_PATH . $plugin_id . '/maintain';
90    $classname = $plugin_id.'_maintain';
91
92    if (file_exists($file_to_include.'.class.php'))
93    {
94      include_once($file_to_include.'.class.php');
95      return new $classname($plugin_id);
96    }
97
98    if (file_exists($file_to_include.'.inc.php'))
99    {
100      include_once($file_to_include.'.inc.php');
101
102      if (class_exists($classname))
103      {
104        return new $classname($plugin_id);
105      }
106    }
107
108    return new DummyPlugin_maintain($plugin_id);
109  }
110
111  /**
112   * Perform requested actions
113   * @param string - action
114   * @param string - plugin id
115   * @param array - errors
116   */
117  function perform_action($action, $plugin_id)
118  {
119    if (isset($this->db_plugins_by_id[$plugin_id]))
120    {
121      $crt_db_plugin = $this->db_plugins_by_id[$plugin_id];
122    }
123
124    $plugin_maintain = self::build_maintain_class($plugin_id);
125
126    $errors = array();
127
128    switch ($action)
129    {
130      case 'install':
131        if (!empty($crt_db_plugin) or !isset($this->fs_plugins[$plugin_id]))
132        {
133          break;
134        }
135
136        $plugin_maintain->install($this->fs_plugins[$plugin_id]['version'], $errors);
137
138        if (empty($errors))
139        {
140          $query = '
141INSERT INTO '. PLUGINS_TABLE .' (id,version)
142  VALUES (\''. $plugin_id .'\', \''. $this->fs_plugins[$plugin_id]['version'] .'\')
143;';
144          pwg_query($query);
145        }
146        break;
147
148      case 'activate':
149        if (!isset($crt_db_plugin))
150        {
151          $errors = $this->perform_action('install', $plugin_id);
152          list($crt_db_plugin) = get_db_plugins(null, $plugin_id);
153          load_conf_from_db();
154        }
155        elseif ($crt_db_plugin['state'] == 'active')
156        {
157          break;
158        }
159
160        if (empty($errors))
161        {
162          $plugin_maintain->activate($crt_db_plugin['version'], $errors);
163        }
164
165        if (empty($errors))
166        {
167          $query = '
168UPDATE '. PLUGINS_TABLE .'
169  SET state=\'active\',
170    version=\''. $this->fs_plugins[$plugin_id]['version'] .'\'
171  WHERE id=\''. $plugin_id .'\'
172;';
173          pwg_query($query);
174        }
175        break;
176
177      case 'deactivate':
178        if (!isset($crt_db_plugin) or $crt_db_plugin['state'] != 'active')
179        {
180          break;
181        }
182
183        $query = '
184UPDATE '. PLUGINS_TABLE .'
185  SET state=\'inactive\'
186  WHERE id=\''. $plugin_id .'\'
187;';
188        pwg_query($query);
189
190        $plugin_maintain->deactivate();
191        break;
192
193      case 'uninstall':
194        if (!isset($crt_db_plugin))
195        {
196          break;
197        }
198        if ($crt_db_plugin['state'] == 'active')
199        {
200          $this->perform_action('deactivate', $plugin_id);
201        }
202
203        $query = '
204DELETE FROM '. PLUGINS_TABLE .'
205  WHERE id=\''. $plugin_id .'\'
206;';
207        pwg_query($query);
208
209        $plugin_maintain->uninstall();
210        break;
211
212      case 'restore':
213        $this->perform_action('uninstall', $plugin_id);
214        unset($this->db_plugins_by_id[$plugin_id]);
215        $errors = $this->perform_action('activate', $plugin_id);
216        break;
217
218      case 'delete':
219        if (!empty($crt_db_plugin))
220        {
221          $this->perform_action('uninstall', $plugin_id);
222        }
223        if (!isset($this->fs_plugins[$plugin_id]))
224        {
225          break;
226        }
227
228        deltree(PHPWG_PLUGINS_PATH . $plugin_id, PHPWG_PLUGINS_PATH . 'trash');
229        break;
230    }
231
232    return $errors;
233  }
234
235  /**
236   * Get plugins defined in the plugin directory
237   */
238  function get_fs_plugins()
239  {
240    $dir = opendir(PHPWG_PLUGINS_PATH);
241    while ($file = readdir($dir))
242    {
243      if ($file!='.' and $file!='..')
244      {
245        $path = PHPWG_PLUGINS_PATH.$file;
246        if (is_dir($path) and !is_link($path)
247            and preg_match('/^[a-zA-Z0-9-_]+$/', $file )
248            and file_exists($path.'/main.inc.php')
249            )
250        {
251          $plugin = array(
252              'name'=>$file,
253              'version'=>'0',
254              'uri'=>'',
255              'description'=>'',
256              'author'=>'',
257            );
258          $plg_data = file_get_contents($path.'/main.inc.php', null, null, 0, 2048);
259
260          if (preg_match("|Plugin Name:\\s*(.+)|", $plg_data, $val))
261          {
262            $plugin['name'] = trim( $val[1] );
263          }
264          if (preg_match("|Version:\\s*([\\w.-]+)|", $plg_data, $val))
265          {
266            $plugin['version'] = trim($val[1]);
267          }
268          if (preg_match("|Plugin URI:\\s*(https?:\\/\\/.+)|", $plg_data, $val))
269          {
270            $plugin['uri'] = trim($val[1]);
271          }
272          if ($desc = load_language('description.txt', $path.'/', array('return' => true)))
273          {
274            $plugin['description'] = trim($desc);
275          }
276          elseif (preg_match("|Description:\\s*(.+)|", $plg_data, $val))
277          {
278            $plugin['description'] = trim($val[1]);
279          }
280          if (preg_match("|Author:\\s*(.+)|", $plg_data, $val))
281          {
282            $plugin['author'] = trim($val[1]);
283          }
284          if (preg_match("|Author URI:\\s*(https?:\\/\\/.+)|", $plg_data, $val))
285          {
286            $plugin['author uri'] = trim($val[1]);
287          }
288          if (!empty($plugin['uri']) and strpos($plugin['uri'] , 'extension_view.php?eid='))
289          {
290            list( , $extension) = explode('extension_view.php?eid=', $plugin['uri']);
291            if (is_numeric($extension)) $plugin['extension'] = $extension;
292          }
293
294          // IMPORTANT SECURITY !
295          $plugin = array_map('htmlspecialchars', $plugin);
296          $this->fs_plugins[$file] = $plugin;
297        }
298      }
299    }
300    closedir($dir);
301  }
302
303  /**
304   * Sort fs_plugins
305   */
306  function sort_fs_plugins($order='name')
307  {
308    switch ($order)
309    {
310      case 'name':
311        uasort($this->fs_plugins, 'name_compare');
312        break;
313      case 'status':
314        $this->sort_plugins_by_state();
315        break;
316      case 'author':
317        uasort($this->fs_plugins, array($this, 'plugin_author_compare'));
318        break;
319      case 'id':
320        uksort($this->fs_plugins, 'strcasecmp');
321        break;
322    }
323  }
324
325  // Retrieve PEM versions
326  function get_versions_to_check($version=PHPWG_VERSION)
327  {
328    global $conf;
329
330    $versions_to_check = array();
331    $url = PEM_URL . '/api/get_version_list.php?category_id='. $conf['pem_plugins_category'] .'&format=php';
332    if (fetchRemote($url, $result) and $pem_versions = @unserialize($result))
333    {
334      if (!preg_match('/^\d+\.\d+\.\d+$/', $version))
335      {
336        $version = $pem_versions[0]['name'];
337      }
338      $branch = get_branch_from_version($version);
339      foreach ($pem_versions as $pem_version)
340      {
341        if (strpos($pem_version['name'], $branch) === 0)
342        {
343          $versions_to_check[] = $pem_version['id'];
344        }
345      }
346    }
347    return $versions_to_check;
348  }
349
350  /**
351   * Retrieve PEM server datas to $server_plugins
352   */
353  function get_server_plugins($new=false)
354  {
355    global $user, $conf;
356
357    $versions_to_check = $this->get_versions_to_check();
358    if (empty($versions_to_check))
359    {
360      return false;
361    }
362
363    // Plugins to check
364    $plugins_to_check = array();
365    foreach($this->fs_plugins as $fs_plugin)
366    {
367      if (isset($fs_plugin['extension']))
368      {
369        $plugins_to_check[] = $fs_plugin['extension'];
370      }
371    }
372
373    // Retrieve PEM plugins infos
374    $url = PEM_URL . '/api/get_revision_list.php';
375    $get_data = array(
376      'category_id' => $conf['pem_plugins_category'],
377      'format' => 'php',
378      'last_revision_only' => 'true',
379      'version' => implode(',', $versions_to_check),
380      'lang' => substr($user['language'], 0, 2),
381      'get_nb_downloads' => 'true',
382    );
383
384    if (!empty($plugins_to_check))
385    {
386      if ($new)
387      {
388        $get_data['extension_exclude'] = implode(',', $plugins_to_check);
389      }
390      else
391      {
392        $get_data['extension_include'] = implode(',', $plugins_to_check);
393      }
394    }
395    if (fetchRemote($url, $result, $get_data))
396    {
397      $pem_plugins = @unserialize($result);
398      if (!is_array($pem_plugins))
399      {
400        return false;
401      }
402      foreach ($pem_plugins as $plugin)
403      {
404        $this->server_plugins[$plugin['extension_id']] = $plugin;
405      }
406      return true;
407    }
408    return false;
409  }
410
411  function get_incompatible_plugins($actualize=false)
412  {
413    if (isset($_SESSION['incompatible_plugins']) and !$actualize
414      and $_SESSION['incompatible_plugins']['~~expire~~'] > time())
415    {
416      return $_SESSION['incompatible_plugins'];
417    }
418
419    $_SESSION['incompatible_plugins'] = array('~~expire~~' => time() + 300);
420
421    $versions_to_check = $this->get_versions_to_check();
422    if (empty($versions_to_check))
423    {
424      return false;
425    }
426
427    global $conf;
428
429    // Plugins to check
430    $plugins_to_check = array();
431    foreach($this->fs_plugins as $fs_plugin)
432    {
433      if (isset($fs_plugin['extension']))
434      {
435        $plugins_to_check[] = $fs_plugin['extension'];
436      }
437    }
438
439    // Retrieve PEM plugins infos
440    $url = PEM_URL . '/api/get_revision_list.php';
441    $get_data = array(
442      'category_id' => $conf['pem_plugins_category'],
443      'format' => 'php',
444      'version' => implode(',', $versions_to_check),
445      'extension_include' => implode(',', $plugins_to_check),
446    );
447
448    if (fetchRemote($url, $result, $get_data))
449    {
450      $pem_plugins = @unserialize($result);
451      if (!is_array($pem_plugins))
452      {
453        return false;
454      }
455
456      $server_plugins = array();
457      foreach ($pem_plugins as $plugin)
458      {
459        if (!isset($server_plugins[$plugin['extension_id']]))
460        {
461          $server_plugins[$plugin['extension_id']] = array();
462        }
463        $server_plugins[$plugin['extension_id']][] = $plugin['revision_name'];
464      }
465
466      foreach ($this->fs_plugins as $plugin_id => $fs_plugin)
467      {
468        if (isset($fs_plugin['extension'])
469          and !in_array($plugin_id, $this->default_plugins)
470          and $fs_plugin['version'] != 'auto'
471          and (!isset($server_plugins[$fs_plugin['extension']]) or !in_array($fs_plugin['version'], $server_plugins[$fs_plugin['extension']])))
472        {
473          $_SESSION['incompatible_plugins'][$plugin_id] = $fs_plugin['version'];
474        }
475      }
476      return $_SESSION['incompatible_plugins'];
477    }
478    return false;
479  }
480
481  /**
482   * Sort $server_plugins
483   */
484  function sort_server_plugins($order='date')
485  {
486    switch ($order)
487    {
488      case 'date':
489        krsort($this->server_plugins);
490        break;
491      case 'revision':
492        usort($this->server_plugins, array($this, 'extension_revision_compare'));
493        break;
494      case 'name':
495        uasort($this->server_plugins, array($this, 'extension_name_compare'));
496        break;
497      case 'author':
498        uasort($this->server_plugins, array($this, 'extension_author_compare'));
499        break;
500      case 'downloads':
501        usort($this->server_plugins, array($this, 'extension_downloads_compare'));
502        break;
503    }
504  }
505
506  /**
507   * Extract plugin files from archive
508   * @param string - install or upgrade
509   *  @param string - archive URL
510    * @param string - plugin id or extension id
511   */
512  function extract_plugin_files($action, $revision, $dest, &$plugin_id=null)
513  {
514    if ($archive = tempnam( PHPWG_PLUGINS_PATH, 'zip'))
515    {
516      $url = PEM_URL . '/download.php';
517      $get_data = array(
518        'rid' => $revision,
519        'origin' => 'piwigo_'.$action,
520      );
521
522      if ($handle = @fopen($archive, 'wb') and fetchRemote($url, $handle, $get_data))
523      {
524        fclose($handle);
525        include_once(PHPWG_ROOT_PATH.'admin/include/pclzip.lib.php');
526        $zip = new PclZip($archive);
527        if ($list = $zip->listContent())
528        {
529          foreach ($list as $file)
530          {
531            // we search main.inc.php in archive
532            if (basename($file['filename']) == 'main.inc.php'
533              and (!isset($main_filepath)
534              or strlen($file['filename']) < strlen($main_filepath)))
535            {
536              $main_filepath = $file['filename'];
537            }
538          }
539          if (isset($main_filepath))
540          {
541            $root = dirname($main_filepath); // main.inc.php path in archive
542            if ($action == 'upgrade')
543            {
544              $plugin_id = $dest;
545            }
546            else
547            {
548              $plugin_id = ($root == '.' ? 'extension_' . $dest : basename($root));
549            }
550            $extract_path = PHPWG_PLUGINS_PATH . $plugin_id;
551
552            if($result = $zip->extract(PCLZIP_OPT_PATH, $extract_path,
553                                       PCLZIP_OPT_REMOVE_PATH, $root,
554                                       PCLZIP_OPT_REPLACE_NEWER))
555            {
556              foreach ($result as $file)
557              {
558                if ($file['stored_filename'] == $main_filepath)
559                {
560                  $status = $file['status'];
561                  break;
562                }
563              }
564              if (file_exists($extract_path.'/obsolete.list')
565                and $old_files = file($extract_path.'/obsolete.list', FILE_IGNORE_NEW_LINES)
566                and !empty($old_files))
567              {
568                $old_files[] = 'obsolete.list';
569                foreach($old_files as $old_file)
570                {
571                  $path = $extract_path.'/'.$old_file;
572                  if (is_file($path))
573                  {
574                    @unlink($path);
575                  }
576                  elseif (is_dir($path))
577                  {
578                    deltree($path, PHPWG_PLUGINS_PATH . 'trash');
579                  }
580                }
581              }
582            }
583            else $status = 'extract_error';
584          }
585          else $status = 'archive_error';
586        }
587        else $status = 'archive_error';
588      }
589      else $status = 'dl_archive_error';
590    }
591    else $status = 'temp_path_error';
592
593    @unlink($archive);
594    return $status;
595  }
596
597  function get_merged_extensions($version=PHPWG_VERSION)
598  {
599    $file = PHPWG_ROOT_PATH.'install/obsolete_extensions.list';
600    $merged_extensions = array();
601
602    if (file_exists($file) and $obsolete_ext = file($file, FILE_IGNORE_NEW_LINES) and !empty($obsolete_ext))
603    {
604      foreach ($obsolete_ext as $ext)
605      {
606        if (preg_match('/^(\d+) ?: ?(.*?)$/', $ext, $matches))
607        {
608          $merged_extensions[$matches[1]] = $matches[2];
609        }
610      }
611    }
612    return $merged_extensions;
613  }
614
615  /**
616   * Sort functions
617   */
618  function extension_revision_compare($a, $b)
619  {
620    if ($a['revision_date'] < $b['revision_date']) return 1;
621    else return -1;
622  }
623
624  function extension_name_compare($a, $b)
625  {
626    return strcmp(strtolower($a['extension_name']), strtolower($b['extension_name']));
627  }
628
629  function extension_author_compare($a, $b)
630  {
631    $r = strcasecmp($a['author_name'], $b['author_name']);
632    if ($r == 0) return $this->extension_name_compare($a, $b);
633    else return $r;
634  }
635
636  function plugin_author_compare($a, $b)
637  {
638    $r = strcasecmp($a['author'], $b['author']);
639    if ($r == 0) return name_compare($a, $b);
640    else return $r;
641  }
642
643  function extension_downloads_compare($a, $b)
644  {
645    if ($a['extension_nb_downloads'] < $b['extension_nb_downloads']) return 1;
646    else return -1;
647  }
648
649  function sort_plugins_by_state()
650  {
651    uasort($this->fs_plugins, 'name_compare');
652
653    $active_plugins = array();
654    $inactive_plugins = array();
655    $not_installed = array();
656
657    foreach($this->fs_plugins as $plugin_id => $plugin)
658    {
659      if (isset($this->db_plugins_by_id[$plugin_id]))
660      {
661        $this->db_plugins_by_id[$plugin_id]['state'] == 'active' ?
662          $active_plugins[$plugin_id] = $plugin : $inactive_plugins[$plugin_id] = $plugin;
663      }
664      else
665      {
666        $not_installed[$plugin_id] = $plugin;
667      }
668    }
669    $this->fs_plugins = $active_plugins + $inactive_plugins + $not_installed;
670  }
671}
672?>
Note: See TracBrowser for help on using the repository browser.