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

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

feature 3088: set AdminTools as default plugin, set admin_multi_view as obsolete

  • Property svn:eol-style set to LF
File size: 18.6 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: (.*)|", $plg_data, $val) )
261          {
262            $plugin['name'] = trim( $val[1] );
263          }
264          if (preg_match("|Version: (.*)|", $plg_data, $val))
265          {
266            $plugin['version'] = trim($val[1]);
267          }
268          if ( preg_match("|Plugin URI: (.*)|", $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: (.*)|", $plg_data, $val) )
277          {
278            $plugin['description'] = trim($val[1]);
279          }
280          if ( preg_match("|Author: (.*)|", $plg_data, $val) )
281          {
282            $plugin['author'] = trim($val[1]);
283          }
284          if ( preg_match("|Author URI: (.*)|", $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          // IMPORTANT SECURITY !
294          $plugin = array_map('htmlspecialchars', $plugin);
295          $this->fs_plugins[$file] = $plugin;
296        }
297      }
298    }
299    closedir($dir);
300  }
301
302  /**
303   * Sort fs_plugins
304   */
305  function sort_fs_plugins($order='name')
306  {
307    switch ($order)
308    {
309      case 'name':
310        uasort($this->fs_plugins, 'name_compare');
311        break;
312      case 'status':
313        $this->sort_plugins_by_state();
314        break;
315      case 'author':
316        uasort($this->fs_plugins, array($this, 'plugin_author_compare'));
317        break;
318      case 'id':
319        uksort($this->fs_plugins, 'strcasecmp');
320        break;
321    }
322  }
323
324  // Retrieve PEM versions
325  function get_versions_to_check($version=PHPWG_VERSION)
326  {
327    global $conf;
328
329    $versions_to_check = array();
330    $url = PEM_URL . '/api/get_version_list.php?category_id='. $conf['pem_plugins_category'] .'&format=php';
331    if (fetchRemote($url, $result) and $pem_versions = @unserialize($result))
332    {
333      if (!preg_match('/^\d+\.\d+\.\d+$/', $version))
334      {
335        $version = $pem_versions[0]['name'];
336      }
337      $branch = get_branch_from_version($version);
338      foreach ($pem_versions as $pem_version)
339      {
340        if (strpos($pem_version['name'], $branch) === 0)
341        {
342          $versions_to_check[] = $pem_version['id'];
343        }
344      }
345    }
346    return $versions_to_check;
347  }
348
349  /**
350   * Retrieve PEM server datas to $server_plugins
351   */
352  function get_server_plugins($new=false)
353  {
354    global $user, $conf;
355
356    $versions_to_check = $this->get_versions_to_check();
357    if (empty($versions_to_check))
358    {
359      return false;
360    }
361
362    // Plugins to check
363    $plugins_to_check = array();
364    foreach($this->fs_plugins as $fs_plugin)
365    {
366      if (isset($fs_plugin['extension']))
367      {
368        $plugins_to_check[] = $fs_plugin['extension'];
369      }
370    }
371
372    // Retrieve PEM plugins infos
373    $url = PEM_URL . '/api/get_revision_list.php';
374    $get_data = array(
375      'category_id' => $conf['pem_plugins_category'],
376      'format' => 'php',
377      'last_revision_only' => 'true',
378      'version' => implode(',', $versions_to_check),
379      'lang' => substr($user['language'], 0, 2),
380      'get_nb_downloads' => 'true',
381    );
382
383    if (!empty($plugins_to_check))
384    {
385      if ($new)
386      {
387        $get_data['extension_exclude'] = implode(',', $plugins_to_check);
388      }
389      else
390      {
391        $get_data['extension_include'] = implode(',', $plugins_to_check);
392      }
393    }
394    if (fetchRemote($url, $result, $get_data))
395    {
396      $pem_plugins = @unserialize($result);
397      if (!is_array($pem_plugins))
398      {
399        return false;
400      }
401      foreach ($pem_plugins as $plugin)
402      {
403        $this->server_plugins[$plugin['extension_id']] = $plugin;
404      }
405      return true;
406    }
407    return false;
408  }
409
410  function get_incompatible_plugins($actualize=false)
411  {
412    if (isset($_SESSION['incompatible_plugins']) and !$actualize
413      and $_SESSION['incompatible_plugins']['~~expire~~'] > time())
414    {
415      return $_SESSION['incompatible_plugins'];
416    }
417
418    $_SESSION['incompatible_plugins'] = array('~~expire~~' => time() + 300);
419
420    $versions_to_check = $this->get_versions_to_check();
421    if (empty($versions_to_check))
422    {
423      return false;
424    }
425
426    global $conf;
427
428    // Plugins to check
429    $plugins_to_check = array();
430    foreach($this->fs_plugins as $fs_plugin)
431    {
432      if (isset($fs_plugin['extension']))
433      {
434        $plugins_to_check[] = $fs_plugin['extension'];
435      }
436    }
437
438    // Retrieve PEM plugins infos
439    $url = PEM_URL . '/api/get_revision_list.php';
440    $get_data = array(
441      'category_id' => $conf['pem_plugins_category'],
442      'format' => 'php',
443      'version' => implode(',', $versions_to_check),
444      'extension_include' => implode(',', $plugins_to_check),
445    );
446
447    if (fetchRemote($url, $result, $get_data))
448    {
449      $pem_plugins = @unserialize($result);
450      if (!is_array($pem_plugins))
451      {
452        return false;
453      }
454
455      $server_plugins = array();
456      foreach ($pem_plugins as $plugin)
457      {
458        if (!isset($server_plugins[$plugin['extension_id']]))
459        {
460          $server_plugins[$plugin['extension_id']] = array();
461        }
462        $server_plugins[$plugin['extension_id']][] = $plugin['revision_name'];
463      }
464
465      foreach ($this->fs_plugins as $plugin_id => $fs_plugin)
466      {
467        if (isset($fs_plugin['extension'])
468          and !in_array($plugin_id, $this->default_plugins)
469          and $fs_plugin['version'] != 'auto'
470          and (!isset($server_plugins[$fs_plugin['extension']]) or !in_array($fs_plugin['version'], $server_plugins[$fs_plugin['extension']])))
471        {
472          $_SESSION['incompatible_plugins'][$plugin_id] = $fs_plugin['version'];
473        }
474      }
475      return $_SESSION['incompatible_plugins'];
476    }
477    return false;
478  }
479
480  /**
481   * Sort $server_plugins
482   */
483  function sort_server_plugins($order='date')
484  {
485    switch ($order)
486    {
487      case 'date':
488        krsort($this->server_plugins);
489        break;
490      case 'revision':
491        usort($this->server_plugins, array($this, 'extension_revision_compare'));
492        break;
493      case 'name':
494        uasort($this->server_plugins, array($this, 'extension_name_compare'));
495        break;
496      case 'author':
497        uasort($this->server_plugins, array($this, 'extension_author_compare'));
498        break;
499      case 'downloads':
500        usort($this->server_plugins, array($this, 'extension_downloads_compare'));
501        break;
502    }
503  }
504
505  /**
506   * Extract plugin files from archive
507   * @param string - install or upgrade
508   *  @param string - archive URL
509    * @param string - plugin id or extension id
510   */
511  function extract_plugin_files($action, $revision, $dest, &$plugin_id=null)
512  {
513    if ($archive = tempnam( PHPWG_PLUGINS_PATH, 'zip'))
514    {
515      $url = PEM_URL . '/download.php';
516      $get_data = array(
517        'rid' => $revision,
518        'origin' => 'piwigo_'.$action,
519      );
520
521      if ($handle = @fopen($archive, 'wb') and fetchRemote($url, $handle, $get_data))
522      {
523        fclose($handle);
524        include_once(PHPWG_ROOT_PATH.'admin/include/pclzip.lib.php');
525        $zip = new PclZip($archive);
526        if ($list = $zip->listContent())
527        {
528          foreach ($list as $file)
529          {
530            // we search main.inc.php in archive
531            if (basename($file['filename']) == 'main.inc.php'
532              and (!isset($main_filepath)
533              or strlen($file['filename']) < strlen($main_filepath)))
534            {
535              $main_filepath = $file['filename'];
536            }
537          }
538          if (isset($main_filepath))
539          {
540            $root = dirname($main_filepath); // main.inc.php path in archive
541            if ($action == 'upgrade')
542            {
543              $plugin_id = $dest;
544            }
545            else
546            {
547              $plugin_id = ($root == '.' ? 'extension_' . $dest : basename($root));
548            }
549            $extract_path = PHPWG_PLUGINS_PATH . $plugin_id;
550
551            if($result = $zip->extract(PCLZIP_OPT_PATH, $extract_path,
552                                       PCLZIP_OPT_REMOVE_PATH, $root,
553                                       PCLZIP_OPT_REPLACE_NEWER))
554            {
555              foreach ($result as $file)
556              {
557                if ($file['stored_filename'] == $main_filepath)
558                {
559                  $status = $file['status'];
560                  break;
561                }
562              }
563              if (file_exists($extract_path.'/obsolete.list')
564                and $old_files = file($extract_path.'/obsolete.list', FILE_IGNORE_NEW_LINES)
565                and !empty($old_files))
566              {
567                $old_files[] = 'obsolete.list';
568                foreach($old_files as $old_file)
569                {
570                  $path = $extract_path.'/'.$old_file;
571                  if (is_file($path))
572                  {
573                    @unlink($path);
574                  }
575                  elseif (is_dir($path))
576                  {
577                    deltree($path, PHPWG_PLUGINS_PATH . 'trash');
578                  }
579                }
580              }
581            }
582            else $status = 'extract_error';
583          }
584          else $status = 'archive_error';
585        }
586        else $status = 'archive_error';
587      }
588      else $status = 'dl_archive_error';
589    }
590    else $status = 'temp_path_error';
591
592    @unlink($archive);
593    return $status;
594  }
595
596  function get_merged_extensions($version=PHPWG_VERSION)
597  {
598    $file = PHPWG_ROOT_PATH.'install/obsolete_extensions.list';
599    $merged_extensions = array();
600
601    if (file_exists($file) and $obsolete_ext = file($file, FILE_IGNORE_NEW_LINES) and !empty($obsolete_ext))
602    {
603      foreach ($obsolete_ext as $ext)
604      {
605        if (preg_match('/^(\d+) ?: ?(.*?)$/', $ext, $matches))
606        {
607          $merged_extensions[$matches[1]] = $matches[2];
608        }
609      }
610    }
611    return $merged_extensions;
612  }
613
614  /**
615   * Sort functions
616   */
617  function extension_revision_compare($a, $b)
618  {
619    if ($a['revision_date'] < $b['revision_date']) return 1;
620    else return -1;
621  }
622
623  function extension_name_compare($a, $b)
624  {
625    return strcmp(strtolower($a['extension_name']), strtolower($b['extension_name']));
626  }
627
628  function extension_author_compare($a, $b)
629  {
630    $r = strcasecmp($a['author_name'], $b['author_name']);
631    if ($r == 0) return $this->extension_name_compare($a, $b);
632    else return $r;
633  }
634
635  function plugin_author_compare($a, $b)
636  {
637    $r = strcasecmp($a['author'], $b['author']);
638    if ($r == 0) return name_compare($a, $b);
639    else return $r;
640  }
641
642  function extension_downloads_compare($a, $b)
643  {
644    if ($a['extension_nb_downloads'] < $b['extension_nb_downloads']) return 1;
645    else return -1;
646  }
647
648  function sort_plugins_by_state()
649  {
650    uasort($this->fs_plugins, 'name_compare');
651
652    $active_plugins = array();
653    $inactive_plugins = array();
654    $not_installed = array();
655
656    foreach($this->fs_plugins as $plugin_id => $plugin)
657    {
658      if (isset($this->db_plugins_by_id[$plugin_id]))
659      {
660        $this->db_plugins_by_id[$plugin_id]['state'] == 'active' ?
661          $active_plugins[$plugin_id] = $plugin : $inactive_plugins[$plugin_id] = $plugin;
662      }
663      else
664      {
665        $not_installed[$plugin_id] = $plugin;
666      }
667    }
668    $this->fs_plugins = $active_plugins + $inactive_plugins + $not_installed;
669  }
670}
671?>
Note: See TracBrowser for help on using the repository browser.