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

Last change on this file since 10098 was 10098, checked in by patdenice, 13 years ago

feature:2250
Incompatible plugins and obsolete plugins may not be activated.

  • Property svn:eol-style set to LF
File size: 19.9 KB
RevLine 
[2263]1<?php
2// +-----------------------------------------------------------------------+
[8728]3// | Piwigo - a PHP based photo gallery                                    |
[2297]4// +-----------------------------------------------------------------------+
[8728]5// | Copyright(C) 2008-2011 Piwigo Team                  http://piwigo.org |
[2297]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// +-----------------------------------------------------------------------+
[2263]23
24class plugins
25{
26  var $fs_plugins = array();
27  var $db_plugins_by_id = array();
[2701]28  var $server_plugins = array();
[10098]29  var $default_plugins = array('LocalFilesEditor', 'language_switch', 'c13y_upgrade', 'admin_multi_view');
[2263]30
[2264]31  /**
32   * Initialize $fs_plugins and $db_plugins_by_id
33  */
34  function plugins()
[2263]35  {
[2264]36    $this->get_fs_plugins();
[2263]37
38    foreach (get_db_plugins() as $db_plugin)
39    {
40      $this->db_plugins_by_id[$db_plugin['id']] = $db_plugin;
41    }
42  }
43
[5367]44  /**
45   * Set tabsheet for plugins pages.
46   * @param string selected page.
47   */
48  function set_tabsheet($selected)
49  {
50    include_once(PHPWG_ROOT_PATH.'admin/include/tabsheet.class.php');
51
52    $link = get_root_url().'admin.php?page=';
53
54    $tabsheet = new tabsheet();
55    $tabsheet->add('plugins_list', l10n('Plugin list'), $link.'plugins_list');
56    $tabsheet->add('plugins_update', l10n('Check for updates'), $link.'plugins_update');
57    $tabsheet->add('plugins_new', l10n('Other plugins'), $link.'plugins_new');
58    $tabsheet->select($selected);
59    $tabsheet->assign();
60  }
61
[2263]62 /**
63   * Perform requested actions
64  *  @param string - action
65  * @param string - plugin id
[2264]66  * @param array - errors
[2263]67  */
[2272]68  function perform_action($action, $plugin_id)
[2263]69  {
70    if (isset($this->db_plugins_by_id[$plugin_id]))
71    {
72      $crt_db_plugin = $this->db_plugins_by_id[$plugin_id];
73    }
74    $file_to_include = PHPWG_PLUGINS_PATH . $plugin_id . '/maintain.inc.php';
75
[2272]76    $errors = array();
77
[2263]78    switch ($action)
79    {
80      case 'install':
81        if (!empty($crt_db_plugin))
82        {
83          array_push($errors, 'CANNOT INSTALL - ALREADY INSTALLED');
84          break;
85        }
86        if (!isset($this->fs_plugins[$plugin_id]))
87        {
88          array_push($errors, 'CANNOT INSTALL - NO SUCH PLUGIN');
89          break;
90        }
91        if (file_exists($file_to_include))
92        {
93          include_once($file_to_include);
94          if (function_exists('plugin_install'))
95          {
96            plugin_install($plugin_id, $this->fs_plugins[$plugin_id]['version'], $errors);
97          }
98        }
99        if (empty($errors))
100        {
101          $query = '
[4385]102INSERT INTO ' . PLUGINS_TABLE . ' (id,version) VALUES (\''
103. $plugin_id . '\',\'' . $this->fs_plugins[$plugin_id]['version'] . '\'
[2263]104)';
105          pwg_query($query);
106        }
107        break;
108
109      case 'activate':
110        if (!isset($crt_db_plugin))
111        {
112          array_push($errors, 'CANNOT ACTIVATE - NOT INSTALLED');
113          break;
114        }
115        if ($crt_db_plugin['state'] != 'inactive')
116        {
117          array_push($errors, 'invalid current state ' . $crt_db_plugin['state']);
118          break;
119        }
120        if (file_exists($file_to_include))
121        {
122          include_once($file_to_include);
123          if (function_exists('plugin_activate'))
124          {
125            plugin_activate($plugin_id, $crt_db_plugin['version'], $errors);
126          }
127        }
128        if (empty($errors))
129        {
130          $query = '
[3205]131UPDATE ' . PLUGINS_TABLE . '
[4385]132SET state=\'active\', version=\''.$this->fs_plugins[$plugin_id]['version'].'\'
133WHERE id=\'' . $plugin_id . '\'';
[2263]134          pwg_query($query);
135        }
136        break;
137
138      case 'deactivate':
139        if (!isset($crt_db_plugin))
140        {
141          die ('CANNOT DEACTIVATE - NOT INSTALLED');
142        }
143        if ($crt_db_plugin['state'] != 'active')
144        {
145          die('invalid current state ' . $crt_db_plugin['state']);
146        }
147        $query = '
[4385]148UPDATE ' . PLUGINS_TABLE . ' SET state=\'inactive\' WHERE id=\'' . $plugin_id . '\'';
[2263]149        pwg_query($query);
150        if (file_exists($file_to_include))
151        {
152          include_once($file_to_include);
153          if (function_exists('plugin_deactivate'))
154          {
155            plugin_deactivate($plugin_id);
156          }
157        }
158        break;
159
160      case 'uninstall':
161        if (!isset($crt_db_plugin))
162        {
163          die ('CANNOT UNINSTALL - NOT INSTALLED');
164        }
165        $query = '
[4385]166DELETE FROM ' . PLUGINS_TABLE . ' WHERE id=\'' . $plugin_id . '\'';
[2263]167        pwg_query($query);
168        if (file_exists($file_to_include))
169        {
170          include_once($file_to_include);
171          if (function_exists('plugin_uninstall'))
172          {
173            plugin_uninstall($plugin_id);
174          }
175        }
176        break;
177
178      case 'delete':
179        if (!empty($crt_db_plugin))
180        {
181          array_push($errors, 'CANNOT DELETE - PLUGIN IS INSTALLED');
182          break;
183        }
184        if (!isset($this->fs_plugins[$plugin_id]))
185        {
186          array_push($errors, 'CANNOT DELETE - NO SUCH PLUGIN');
187          break;
188        }
[10098]189        $query = '
190DELETE FROM ' . PLUGINS_TABLE . ' WHERE id=\'' . $plugin_id . '\'';
191        pwg_query($query);
[2263]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  /**
[2264]202  *  Get plugins defined in the plugin directory
[2263]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          }
[3716]238          if ($desc = load_language('description.txt', $path.'/', array('return' => true)))
[2263]239          {
[3716]240            $plugin['description'] = trim($desc);
241          }
242          elseif ( preg_match("|Description: (.*)|", $plg_data, $val) )
243          {
[2263]244            $plugin['description'] = trim($val[1]);
245          }
246          if ( preg_match("|Author: (.*)|", $plg_data, $val) )
247          {
248            $plugin['author'] = trim($val[1]);
249          }
250          if ( preg_match("|Author URI: (.*)|", $plg_data, $val) )
251          {
252            $plugin['author uri'] = trim($val[1]);
253          }
254          if (!empty($plugin['uri']) and strpos($plugin['uri'] , 'extension_view.php?eid='))
255          {
256            list( , $extension) = explode('extension_view.php?eid=', $plugin['uri']);
257            if (is_numeric($extension)) $plugin['extension'] = $extension;
258          }
259          // IMPORTANT SECURITY !
260          $plugin = array_map('htmlspecialchars', $plugin);
261          $this->fs_plugins[$file] = $plugin;
262        }
263      }
264    }
265    closedir($dir);
266  }
267
268  /**
[2264]269   * Sort fs_plugins
[2263]270   */
[2264]271  function sort_fs_plugins($order='name')
[2263]272  {
[2264]273    switch ($order)
[2263]274    {
[2264]275      case 'name':
276        uasort($this->fs_plugins, 'name_compare');
277        break;
[2263]278      case 'status':
279        $this->sort_plugins_by_state();
280        break;
281      case 'author':
282        uasort($this->fs_plugins, array($this, 'plugin_author_compare'));
283        break;
284      case 'id':
285        uksort($this->fs_plugins, 'strcasecmp');
286        break;
287    }
288  }
289
[10098]290  // Retrieve PEM versions
291  function get_versions_to_check($version=PHPWG_VERSION)
[2263]292  {
[2647]293    $versions_to_check = array();
[10098]294    $url = PEM_URL . '/api/get_version_list.php?category=12&format=php';
295    if (fetchRemote($url, $result) and $pem_versions = @unserialize($result))
[2647]296    {
297      if (!preg_match('/^\d+\.\d+\.\d+/', $version))
298      {
299        $version = $pem_versions[0]['name'];
300      }
301      $branch = substr($version, 0, strrpos($version, '.'));
302      foreach ($pem_versions as $pem_version)
303      {
304        if (strpos($pem_version['name'], $branch) === 0)
305        {
306          $versions_to_check[] = $pem_version['id'];
307        }
308      }
309    }
[10098]310    return $versions_to_check;
311  }
312
313  /**
314   * Retrieve PEM server datas to $server_plugins
315   */
316  function get_server_plugins($new=false)
317  {
318    global $user;
319
320    $versions_to_check = $this->get_versions_to_check();
[2647]321    if (empty($versions_to_check))
322    {
323      return false;
324    }
325
326    // Plugins to check
327    $plugins_to_check = array();
[2264]328    foreach($this->fs_plugins as $fs_plugin)
[2263]329    {
330      if (isset($fs_plugin['extension']))
331      {
332        $plugins_to_check[] = $fs_plugin['extension'];
333      }
334    }
335
[2647]336    // Retrieve PEM plugins infos
[8083]337    $url = PEM_URL . '/api/get_revision_list.php';
[10098]338    $get_data = array(
339      'category_id' => 12,
340      'format' => 'php',
[8083]341      'last_revision_only' => 'true',
342      'version' => implode(',', $versions_to_check),
343      'lang' => substr($user['language'], 0, 2),
344      'get_nb_downloads' => 'true',
345    );
[2701]346
[2647]347    if (!empty($plugins_to_check))
[2263]348    {
[8083]349      if ($new)
350      {
351        $get_data['extension_exclude'] = implode(',', $plugins_to_check);
352      }
353      else
354      {
355        $get_data['extension_include'] = implode(',', $plugins_to_check);
356      }
[2263]357    }
[8083]358    if (fetchRemote($url, $result, $get_data))
[2647]359    {
[2880]360      $pem_plugins = @unserialize($result);
[2701]361      if (!is_array($pem_plugins))
362      {
363        return false;
364      }
[2647]365      foreach ($pem_plugins as $plugin)
366      {
367        $this->server_plugins[$plugin['extension_id']] = $plugin;
368      }
369      return true;
370    }
[2880]371    return false;
[2263]372  }
[10098]373
374  function get_incompatible_plugins()
375  {
376    if (isset($_SESSION['incompatible_plugins']))
377    {
378      return $_SESSION['incompatible_plugins'];
379    }
380
381    $_SESSION['incompatible_plugins'] = array();
382
383    $versions_to_check = $this->get_versions_to_check();
384    if (empty($versions_to_check))
385    {
386      return false;
387    }
388
389    // Plugins to check
390    $plugins_to_check = array();
391    foreach($this->fs_plugins as $fs_plugin)
392    {
393      if (isset($fs_plugin['extension']))
394      {
395        $plugins_to_check[] = $fs_plugin['extension'];
396      }
397    }
398
399    // Retrieve PEM plugins infos
400    $url = PEM_URL . '/api/get_revision_list.php';
401    $get_data = array(
402      'category_id' => 12,
403      'format' => 'php',
404      'version' => implode(',', $versions_to_check),
405      'extension_include' => implode(',', $plugins_to_check),
406    );
407
408    if (fetchRemote($url, $result, $get_data))
409    {
410      $pem_plugins = @unserialize($result);
411      if (!is_array($pem_plugins))
412      {
413        return false;
414      }
415
416      $server_plugins = array();
417      foreach ($pem_plugins as $plugin)
418      {
419        if (!isset($server_plugins[$plugin['extension_id']]))
420        {
421          $server_plugins[$plugin['extension_id']] = array();
422        }
423        array_push($server_plugins[$plugin['extension_id']], $plugin['revision_name']);
424      }
425
426      foreach ($this->fs_plugins as $plugin_id => $fs_plugin)
427      {
428        if (isset($fs_plugin['extension'])
429          and !in_array($plugin_id, $this->default_plugins)
430          and $fs_plugin['version'] != 'auto'
431          and (!isset($server_plugins[$fs_plugin['extension']]) or !in_array($fs_plugin['version'], $server_plugins[$fs_plugin['extension']])))
432        {
433          $_SESSION['incompatible_plugins'][$plugin_id] = $fs_plugin['version'];
434        }
435      }
436      return $_SESSION['incompatible_plugins'];
437    }
438    return false;
439  }
[2264]440 
441  /**
442   * Sort $server_plugins
443   */
444  function sort_server_plugins($order='date')
[2263]445  {
[2264]446    switch ($order)
[2263]447    {
[2264]448      case 'date':
449        krsort($this->server_plugins);
450        break;
[2272]451      case 'revision':
452        usort($this->server_plugins, array($this, 'extension_revision_compare'));
453        break;
[2264]454      case 'name':
455        uasort($this->server_plugins, array($this, 'extension_name_compare'));
456        break;
457      case 'author':
458        uasort($this->server_plugins, array($this, 'extension_author_compare'));
459        break;
[3143]460      case 'downloads':
461        usort($this->server_plugins, array($this, 'extension_downloads_compare'));
462        break;
[2263]463    }
464  }
465
466  /**
467   * Extract plugin files from archive
468   * @param string - install or upgrade
469   *  @param string - archive URL
[2647]470    * @param string - plugin id or extension id
[2263]471   */
[5153]472  function extract_plugin_files($action, $revision, $dest)
[2263]473  {
[5153]474    if ($archive = tempnam( PHPWG_PLUGINS_PATH, 'zip'))
[2263]475    {
[8083]476      $url = PEM_URL . '/download.php';
477      $get_data = array(
478        'rid' => $revision,
479        'origin' => 'piwigo_'.$action,
480      );
[2880]481
[8083]482      if ($handle = @fopen($archive, 'wb') and fetchRemote($url, $handle, $get_data))
[2263]483      {
[2880]484        fclose($handle);
[2264]485        include(PHPWG_ROOT_PATH.'admin/include/pclzip.lib.php');
[2263]486        $zip = new PclZip($archive);
487        if ($list = $zip->listContent())
488        {
489          foreach ($list as $file)
490          {
491            // we search main.inc.php in archive
[5153]492            if (basename($file['filename']) == 'main.inc.php'
[2263]493              and (!isset($main_filepath)
494              or strlen($file['filename']) < strlen($main_filepath)))
495            {
496              $main_filepath = $file['filename'];
497            }
498          }
499          if (isset($main_filepath))
500          {
501            $root = dirname($main_filepath); // main.inc.php path in archive
502            if ($action == 'upgrade')
503            {
[5153]504              $extract_path = PHPWG_PLUGINS_PATH . $dest;
[2263]505            }
506            else
507            {
[5153]508              $extract_path = PHPWG_PLUGINS_PATH
[2263]509                  . ($root == '.' ? 'extension_' . $dest : basename($root));
510            }
511            if($result = $zip->extract(PCLZIP_OPT_PATH, $extract_path,
512                                       PCLZIP_OPT_REMOVE_PATH, $root,
513                                       PCLZIP_OPT_REPLACE_NEWER))
514            {
515              foreach ($result as $file)
516              {
517                if ($file['stored_filename'] == $main_filepath)
518                {
519                  $status = $file['status'];
520                  break;
521                }
522              }
[4034]523              if (file_exists($extract_path.'/obsolete.list')
524                and $old_files = file($extract_path.'/obsolete.list', FILE_IGNORE_NEW_LINES)
525                and !empty($old_files))
526              {
527                array_push($old_files, 'obsolete.list');
528                foreach($old_files as $old_file)
529                {
530                  $path = $extract_path.'/'.$old_file;
531                  if (is_file($path))
532                  {
533                    @unlink($path);
534                  }
535                  elseif (is_dir($path))
536                  {
537                    if (!$this->deltree($path))
538                    {
539                      $this->send_to_trash($path);
540                    }
541                  }
542                }
543              }
[2263]544            }
545            else $status = 'extract_error';
546          }
547          else $status = 'archive_error';
548        }
549        else $status = 'archive_error';
550      }
551      else $status = 'dl_archive_error';
552    }
553    else $status = 'temp_path_error';
554
555    @unlink($archive);
556    return $status;
557  }
[10098]558
559  function get_merged_extensions($version=PHPWG_VERSION)
560  {
561    if (!isset($_SESSION['merged_extensions']))
562    {
563      $_SESSION['merged_extensions'] = array();
564      if (fetchRemote(MERGED_EXTENSIONS_URL, $result))
565      {
566        $rows = explode("\n", $result);
567        foreach ($rows as $row)
568        {
569          if (preg_match('/^(\d+\.\d+): *(.*)$/', $row, $match))
570          {
571            if (version_compare($version, $match[1], '>='))
572            {
573              $extensions = explode(',', trim($match[2]));
574              $_SESSION['merged_extensions'] = array_merge($_SESSION['merged_extensions'], $extensions);
575            }
576          }
577        }
578      }
579    }
580    return $_SESSION['merged_extensions'];
581  }
[2263]582 
583  /**
584   * delete $path directory
585   * @param string - path
586   */
587  function deltree($path)
588  {
589    if (is_dir($path))
590    {
591      $fh = opendir($path);
592      while ($file = readdir($fh))
593      {
594        if ($file != '.' and $file != '..')
595        {
596          $pathfile = $path . '/' . $file;
597          if (is_dir($pathfile))
598          {
599            $this->deltree($pathfile);
600          }
601          else
602          {
603            @unlink($pathfile);
604          }
605        }
606      }
607      closedir($fh);
608      return @rmdir($path);
609    }
610  }
611
612  /**
613   * send $path to trash directory
[2264]614   * @param string - path
[2263]615   */
616  function send_to_trash($path)
617  {
618    $trash_path = PHPWG_PLUGINS_PATH . 'trash';
619    if (!is_dir($trash_path))
620    {
621      @mkdir($trash_path);
622      $file = @fopen($trash_path . '/.htaccess', 'w');
623      @fwrite($file, 'deny from all');
624      @fclose($file);
625    }
626    while ($r = $trash_path . '/' . md5(uniqid(rand(), true)))
627    {
628      if (!is_dir($r))
629      {
630        @rename($path, $r);
631        break;
632      }
633    }
634  }
635
636  /**
637   * Sort functions
638   */
639  function plugin_version_compare($a, $b)
640  {
[6725]641    if (strtolower($a) == 'auto') return false;
642
[2272]643    $pattern = array('/([a-z])/ei', '/\.+/', '/\.\Z|\A\./');
644    $replacement = array( "'.'.intval('\\1', 36).'.'", '.', '');
645
[2647]646    $array = preg_replace($pattern, $replacement, array($a, $b));
[2272]647
648    return version_compare($array[0], $array[1], '>=');
[2263]649  }
650
[2272]651  function extension_revision_compare($a, $b)
652  {
[2647]653    if ($a['revision_date'] < $b['revision_date']) return 1;
[2272]654    else return -1;
655  }
656
[2263]657  function extension_name_compare($a, $b)
658  {
[2647]659    return strcmp(strtolower($a['extension_name']), strtolower($b['extension_name']));
[2263]660  }
661
662  function extension_author_compare($a, $b)
663  {
[2647]664    $r = strcasecmp($a['author_name'], $b['author_name']);
[2263]665    if ($r == 0) return $this->extension_name_compare($a, $b);
666    else return $r;
667  }
668
669  function plugin_author_compare($a, $b)
670  {
671    $r = strcasecmp($a['author'], $b['author']);
672    if ($r == 0) return name_compare($a, $b);
673    else return $r;
674  }
675
[3143]676  function extension_downloads_compare($a, $b)
677  {
678    if ($a['extension_nb_downloads'] < $b['extension_nb_downloads']) return 1;
679    else return -1;
680  }
681
[2263]682  function sort_plugins_by_state()
683  {
684    uasort($this->fs_plugins, 'name_compare');
685
686    $active_plugins = array();
687    $inactive_plugins = array();
688    $not_installed = array();
689
690    foreach($this->fs_plugins as $plugin_id => $plugin)
691    {
692      if (isset($this->db_plugins_by_id[$plugin_id]))
693      {
694        $this->db_plugins_by_id[$plugin_id]['state'] == 'active' ?
695          $active_plugins[$plugin_id] = $plugin : $inactive_plugins[$plugin_id] = $plugin;
696      }
697      else
698      {
699        $not_installed[$plugin_id] = $plugin;
700      }
701    }
702    $this->fs_plugins = $active_plugins + $inactive_plugins + $not_installed;
703  }
704}
705?>
Note: See TracBrowser for help on using the repository browser.