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

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

Update headers to 2014. Happy new year!!

  • Property svn:eol-style set to LF
File size: 19.0 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}
59
60
61class plugins
62{
63  var $fs_plugins = array();
64  var $db_plugins_by_id = array();
65  var $server_plugins = array();
66  var $default_plugins = array('LocalFilesEditor', 'language_switch', 'c13y_upgrade', 'admin_multi_view');
67
68  /**
69   * Initialize $fs_plugins and $db_plugins_by_id
70   */
71  function plugins()
72  {
73    $this->get_fs_plugins();
74
75    foreach (get_db_plugins() as $db_plugin)
76    {
77      $this->db_plugins_by_id[$db_plugin['id']] = $db_plugin;
78    }
79  }
80
81  /**
82   * Returns the maintain class of a plugin
83   * or build a new class with the procedural methods
84   * @param string $plugin_id
85   */
86  private static function build_maintain_class($plugin_id)
87  {
88    $file_to_include = PHPWG_PLUGINS_PATH . $plugin_id . '/maintain.inc.php';
89    $classname = $plugin_id.'_maintain';
90
91    if (file_exists($file_to_include))
92    {
93      include_once($file_to_include);
94
95      if (class_exists($classname))
96      {
97        $plugin_maintain = new $classname($plugin_id);
98      }
99      else
100      {
101        $plugin_maintain = new DummyPlugin_maintain($plugin_id);
102      }
103    }
104    else
105    {
106      $plugin_maintain = new DummyPlugin_maintain($plugin_id);
107    }
108
109    return $plugin_maintain;
110  }
111
112  /**
113   * Perform requested actions
114   * @param string - action
115   * @param string - plugin id
116   * @param array - errors
117   */
118  function perform_action($action, $plugin_id)
119  {
120    if (isset($this->db_plugins_by_id[$plugin_id]))
121    {
122      $crt_db_plugin = $this->db_plugins_by_id[$plugin_id];
123    }
124   
125    $plugin_maintain = self::build_maintain_class($plugin_id);
126
127    $errors = array();
128
129    switch ($action)
130    {
131      case 'install':
132        if (!empty($crt_db_plugin) or !isset($this->fs_plugins[$plugin_id]))
133        {
134          break;
135        }
136
137        $plugin_maintain->install($this->fs_plugins[$plugin_id]['version'], $errors);
138
139        if (empty($errors))
140        {
141          $query = '
142INSERT INTO '. PLUGINS_TABLE .' (id,version)
143  VALUES (\''. $plugin_id .'\', \''. $this->fs_plugins[$plugin_id]['version'] .'\')
144;';
145          pwg_query($query);
146        }
147        break;
148
149      case 'activate':
150        if (!isset($crt_db_plugin))
151        {
152          $errors = $this->perform_action('install', $plugin_id);
153          list($crt_db_plugin) = get_db_plugins(null, $plugin_id);
154          load_conf_from_db();
155        }
156        elseif ($crt_db_plugin['state'] == 'active')
157        {
158          break;
159        }
160
161        if (empty($errors))
162        {
163          $plugin_maintain->activate($crt_db_plugin['version'], $errors);
164        }
165
166        if (empty($errors))
167        {
168          $query = '
169UPDATE '. PLUGINS_TABLE .'
170  SET state=\'active\',
171    version=\''. $this->fs_plugins[$plugin_id]['version'] .'\'
172  WHERE id=\''. $plugin_id .'\'
173;';
174          pwg_query($query);
175        }
176        break;
177
178      case 'deactivate':
179        if (!isset($crt_db_plugin) or $crt_db_plugin['state'] != 'active')
180        {
181          break;
182        }
183
184        $query = '
185UPDATE '. PLUGINS_TABLE .'
186  SET state=\'inactive\'
187  WHERE id=\''. $plugin_id .'\'
188;';
189        pwg_query($query);
190       
191        $plugin_maintain->deactivate();
192        break;
193
194      case 'uninstall':
195        if (!isset($crt_db_plugin))
196        {
197          break;
198        }
199        if ($crt_db_plugin['state'] == 'active')
200        {
201          $this->perform_action('deactivate', $plugin_id);
202        }
203
204        $query = '
205DELETE FROM '. PLUGINS_TABLE .'
206  WHERE id=\''. $plugin_id .'\'
207;';
208        pwg_query($query);
209       
210        $plugin_maintain->uninstall();
211        break;
212
213      case 'restore':
214        $this->perform_action('uninstall', $plugin_id);
215        unset($this->db_plugins_by_id[$plugin_id]);
216        $errors = $this->perform_action('activate', $plugin_id);
217        break;
218
219      case 'delete':
220        if (!empty($crt_db_plugin))
221        {
222          $this->perform_action('uninstall', $plugin_id);
223        }
224        if (!isset($this->fs_plugins[$plugin_id]))
225        {
226          break;
227        }
228
229        deltree(PHPWG_PLUGINS_PATH . $plugin_id, PHPWG_PLUGINS_PATH . 'trash');
230        break;
231    }
232
233    return $errors;
234  }
235
236  /**
237   * Get plugins defined in the plugin directory
238   */ 
239  function get_fs_plugins()
240  {
241    $dir = opendir(PHPWG_PLUGINS_PATH);
242    while ($file = readdir($dir))
243    {
244      if ($file!='.' and $file!='..')
245      {
246        $path = PHPWG_PLUGINS_PATH.$file;
247        if (is_dir($path) and !is_link($path)
248            and preg_match('/^[a-zA-Z0-9-_]+$/', $file )
249            and file_exists($path.'/main.inc.php')
250            )
251        {
252          $plugin = array(
253              'name'=>$file,
254              'version'=>'0',
255              'uri'=>'',
256              'description'=>'',
257              'author'=>'',
258            );
259          $plg_data = implode( '', file($path.'/main.inc.php') );
260
261          if ( preg_match("|Plugin Name: (.*)|", $plg_data, $val) )
262          {
263            $plugin['name'] = trim( $val[1] );
264          }
265          if (preg_match("|Version: (.*)|", $plg_data, $val))
266          {
267            $plugin['version'] = trim($val[1]);
268          }
269          if ( preg_match("|Plugin URI: (.*)|", $plg_data, $val) )
270          {
271            $plugin['uri'] = trim($val[1]);
272          }
273          if ($desc = load_language('description.txt', $path.'/', array('return' => true)))
274          {
275            $plugin['description'] = trim($desc);
276          }
277          elseif ( preg_match("|Description: (.*)|", $plg_data, $val) )
278          {
279            $plugin['description'] = trim($val[1]);
280          }
281          if ( preg_match("|Author: (.*)|", $plg_data, $val) )
282          {
283            $plugin['author'] = trim($val[1]);
284          }
285          if ( preg_match("|Author URI: (.*)|", $plg_data, $val) )
286          {
287            $plugin['author uri'] = trim($val[1]);
288          }
289          if (!empty($plugin['uri']) and strpos($plugin['uri'] , 'extension_view.php?eid='))
290          {
291            list( , $extension) = explode('extension_view.php?eid=', $plugin['uri']);
292            if (is_numeric($extension)) $plugin['extension'] = $extension;
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)
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              $extract_path = PHPWG_PLUGINS_PATH . $dest;
545            }
546            else
547            {
548              $extract_path = PHPWG_PLUGINS_PATH
549                  . ($root == '.' ? 'extension_' . $dest : basename($root));
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 plugin_version_compare($a, $b)
618  {
619    if (strtolower($a) == 'auto') return false;
620   
621    $array = preg_replace(
622      array('/\.+/', '/\.\Z|\A\./'),
623      array('.', ''),
624      array($a, $b)
625      );
626     
627    $array = preg_replace_callback(
628      '/([a-z])/i',
629      create_function('$m', 'return intval($m[1], 36);'),
630      $array
631      );
632   
633    return version_compare($array[0], $array[1], '>=');
634  }
635
636  function extension_revision_compare($a, $b)
637  {
638    if ($a['revision_date'] < $b['revision_date']) return 1;
639    else return -1;
640  }
641
642  function extension_name_compare($a, $b)
643  {
644    return strcmp(strtolower($a['extension_name']), strtolower($b['extension_name']));
645  }
646
647  function extension_author_compare($a, $b)
648  {
649    $r = strcasecmp($a['author_name'], $b['author_name']);
650    if ($r == 0) return $this->extension_name_compare($a, $b);
651    else return $r;
652  }
653
654  function plugin_author_compare($a, $b)
655  {
656    $r = strcasecmp($a['author'], $b['author']);
657    if ($r == 0) return name_compare($a, $b);
658    else return $r;
659  }
660
661  function extension_downloads_compare($a, $b)
662  {
663    if ($a['extension_nb_downloads'] < $b['extension_nb_downloads']) return 1;
664    else return -1;
665  }
666
667  function sort_plugins_by_state()
668  {
669    uasort($this->fs_plugins, 'name_compare');
670
671    $active_plugins = array();
672    $inactive_plugins = array();
673    $not_installed = array();
674
675    foreach($this->fs_plugins as $plugin_id => $plugin)
676    {
677      if (isset($this->db_plugins_by_id[$plugin_id]))
678      {
679        $this->db_plugins_by_id[$plugin_id]['state'] == 'active' ?
680          $active_plugins[$plugin_id] = $plugin : $inactive_plugins[$plugin_id] = $plugin;
681      }
682      else
683      {
684        $not_installed[$plugin_id] = $plugin;
685      }
686    }
687    $this->fs_plugins = $active_plugins + $inactive_plugins + $not_installed;
688  }
689}
690?>
Note: See TracBrowser for help on using the repository browser.