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

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

feature:2250
Add expire parameter.
Clean code.

  • Property svn:eol-style set to LF
File size: 20.2 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based photo gallery                                    |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008-2011 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  var $default_plugins = array('LocalFilesEditor', 'language_switch', 'c13y_upgrade', 'admin_multi_view');
30
31  /**
32   * Initialize $fs_plugins and $db_plugins_by_id
33  */
34  function plugins()
35  {
36    $this->get_fs_plugins();
37
38    foreach (get_db_plugins() as $db_plugin)
39    {
40      $this->db_plugins_by_id[$db_plugin['id']] = $db_plugin;
41    }
42  }
43
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
62 /**
63   * Perform requested actions
64  *  @param string - action
65  * @param string - plugin id
66  * @param array - errors
67  */
68  function perform_action($action, $plugin_id)
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
76    $errors = array();
77
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 = '
102INSERT INTO ' . PLUGINS_TABLE . ' (id,version) VALUES (\''
103. $plugin_id . '\',\'' . $this->fs_plugins[$plugin_id]['version'] . '\'
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 = '
131UPDATE ' . PLUGINS_TABLE . '
132SET state=\'active\', version=\''.$this->fs_plugins[$plugin_id]['version'].'\'
133WHERE id=\'' . $plugin_id . '\'';
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 = '
148UPDATE ' . PLUGINS_TABLE . ' SET state=\'inactive\' WHERE id=\'' . $plugin_id . '\'';
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 = '
166DELETE FROM ' . PLUGINS_TABLE . ' WHERE id=\'' . $plugin_id . '\'';
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        }
189        $query = '
190DELETE FROM ' . PLUGINS_TABLE . ' WHERE id=\'' . $plugin_id . '\'';
191        pwg_query($query);
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  /**
202  *  Get plugins defined in the plugin directory
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          }
238          if ($desc = load_language('description.txt', $path.'/', array('return' => true)))
239          {
240            $plugin['description'] = trim($desc);
241          }
242          elseif ( preg_match("|Description: (.*)|", $plg_data, $val) )
243          {
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  /**
269   * Sort fs_plugins
270   */
271  function sort_fs_plugins($order='name')
272  {
273    switch ($order)
274    {
275      case 'name':
276        uasort($this->fs_plugins, 'name_compare');
277        break;
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
290  // Retrieve PEM versions
291  function get_versions_to_check($version=PHPWG_VERSION)
292  {
293    $versions_to_check = array();
294    $url = PEM_URL . '/api/get_version_list.php?category=12&format=php';
295    if (fetchRemote($url, $result) and $pem_versions = @unserialize($result))
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    }
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();
321    if (empty($versions_to_check))
322    {
323      return false;
324    }
325
326    // Plugins to check
327    $plugins_to_check = array();
328    foreach($this->fs_plugins as $fs_plugin)
329    {
330      if (isset($fs_plugin['extension']))
331      {
332        $plugins_to_check[] = $fs_plugin['extension'];
333      }
334    }
335
336    // Retrieve PEM plugins infos
337    $url = PEM_URL . '/api/get_revision_list.php';
338    $get_data = array(
339      'category_id' => 12,
340      'format' => 'php',
341      'last_revision_only' => 'true',
342      'version' => implode(',', $versions_to_check),
343      'lang' => substr($user['language'], 0, 2),
344      'get_nb_downloads' => 'true',
345    );
346
347    if (!empty($plugins_to_check))
348    {
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      }
357    }
358    if (fetchRemote($url, $result, $get_data))
359    {
360      $pem_plugins = @unserialize($result);
361      if (!is_array($pem_plugins))
362      {
363        return false;
364      }
365      foreach ($pem_plugins as $plugin)
366      {
367        $this->server_plugins[$plugin['extension_id']] = $plugin;
368      }
369      return true;
370    }
371    return false;
372  }
373
374  function get_incompatible_plugins($actualize=false)
375  {
376    if (isset($_SESSION['incompatible_plugins']) and !$actualize
377      and $_SESSION['incompatible_plugins']['~~expire~~'] > time())
378    {
379      return $_SESSION['incompatible_plugins'];
380    }
381
382    $_SESSION['incompatible_plugins'] = array('~~expire~~' => time() + 300);
383
384    $versions_to_check = $this->get_versions_to_check();
385    if (empty($versions_to_check))
386    {
387      return false;
388    }
389
390    // Plugins to check
391    $plugins_to_check = array();
392    foreach($this->fs_plugins as $fs_plugin)
393    {
394      if (isset($fs_plugin['extension']))
395      {
396        $plugins_to_check[] = $fs_plugin['extension'];
397      }
398    }
399
400    // Retrieve PEM plugins infos
401    $url = PEM_URL . '/api/get_revision_list.php';
402    $get_data = array(
403      'category_id' => 12,
404      'format' => 'php',
405      'version' => implode(',', $versions_to_check),
406      'extension_include' => implode(',', $plugins_to_check),
407    );
408
409    if (fetchRemote($url, $result, $get_data))
410    {
411      $pem_plugins = @unserialize($result);
412      if (!is_array($pem_plugins))
413      {
414        return false;
415      }
416
417      $server_plugins = array();
418      foreach ($pem_plugins as $plugin)
419      {
420        if (!isset($server_plugins[$plugin['extension_id']]))
421        {
422          $server_plugins[$plugin['extension_id']] = array();
423        }
424        array_push($server_plugins[$plugin['extension_id']], $plugin['revision_name']);
425      }
426
427      foreach ($this->fs_plugins as $plugin_id => $fs_plugin)
428      {
429        if (isset($fs_plugin['extension'])
430          and !in_array($plugin_id, $this->default_plugins)
431          and $fs_plugin['version'] != 'auto'
432          and (!isset($server_plugins[$fs_plugin['extension']]) or !in_array($fs_plugin['version'], $server_plugins[$fs_plugin['extension']])))
433        {
434          $_SESSION['incompatible_plugins'][$plugin_id] = $fs_plugin['version'];
435        }
436      }
437      return $_SESSION['incompatible_plugins'];
438    }
439    return false;
440  }
441 
442  /**
443   * Sort $server_plugins
444   */
445  function sort_server_plugins($order='date')
446  {
447    switch ($order)
448    {
449      case 'date':
450        krsort($this->server_plugins);
451        break;
452      case 'revision':
453        usort($this->server_plugins, array($this, 'extension_revision_compare'));
454        break;
455      case 'name':
456        uasort($this->server_plugins, array($this, 'extension_name_compare'));
457        break;
458      case 'author':
459        uasort($this->server_plugins, array($this, 'extension_author_compare'));
460        break;
461      case 'downloads':
462        usort($this->server_plugins, array($this, 'extension_downloads_compare'));
463        break;
464    }
465  }
466
467  /**
468   * Extract plugin files from archive
469   * @param string - install or upgrade
470   *  @param string - archive URL
471    * @param string - plugin id or extension id
472   */
473  function extract_plugin_files($action, $revision, $dest)
474  {
475    if ($archive = tempnam( PHPWG_PLUGINS_PATH, 'zip'))
476    {
477      $url = PEM_URL . '/download.php';
478      $get_data = array(
479        'rid' => $revision,
480        'origin' => 'piwigo_'.$action,
481      );
482
483      if ($handle = @fopen($archive, 'wb') and fetchRemote($url, $handle, $get_data))
484      {
485        fclose($handle);
486        include(PHPWG_ROOT_PATH.'admin/include/pclzip.lib.php');
487        $zip = new PclZip($archive);
488        if ($list = $zip->listContent())
489        {
490          foreach ($list as $file)
491          {
492            // we search main.inc.php in archive
493            if (basename($file['filename']) == 'main.inc.php'
494              and (!isset($main_filepath)
495              or strlen($file['filename']) < strlen($main_filepath)))
496            {
497              $main_filepath = $file['filename'];
498            }
499          }
500          if (isset($main_filepath))
501          {
502            $root = dirname($main_filepath); // main.inc.php path in archive
503            if ($action == 'upgrade')
504            {
505              $extract_path = PHPWG_PLUGINS_PATH . $dest;
506            }
507            else
508            {
509              $extract_path = PHPWG_PLUGINS_PATH
510                  . ($root == '.' ? 'extension_' . $dest : basename($root));
511            }
512            if($result = $zip->extract(PCLZIP_OPT_PATH, $extract_path,
513                                       PCLZIP_OPT_REMOVE_PATH, $root,
514                                       PCLZIP_OPT_REPLACE_NEWER))
515            {
516              foreach ($result as $file)
517              {
518                if ($file['stored_filename'] == $main_filepath)
519                {
520                  $status = $file['status'];
521                  break;
522                }
523              }
524              if (file_exists($extract_path.'/obsolete.list')
525                and $old_files = file($extract_path.'/obsolete.list', FILE_IGNORE_NEW_LINES)
526                and !empty($old_files))
527              {
528                array_push($old_files, 'obsolete.list');
529                foreach($old_files as $old_file)
530                {
531                  $path = $extract_path.'/'.$old_file;
532                  if (is_file($path))
533                  {
534                    @unlink($path);
535                  }
536                  elseif (is_dir($path))
537                  {
538                    if (!$this->deltree($path))
539                    {
540                      $this->send_to_trash($path);
541                    }
542                  }
543                }
544              }
545            }
546            else $status = 'extract_error';
547          }
548          else $status = 'archive_error';
549        }
550        else $status = 'archive_error';
551      }
552      else $status = 'dl_archive_error';
553    }
554    else $status = 'temp_path_error';
555
556    @unlink($archive);
557    return $status;
558  }
559
560  function get_merged_extensions($version=PHPWG_VERSION)
561  {
562    if (isset($_SESSION['merged_extensions']) and $_SESSION['merged_extensions']['~~expire~~'] > time())
563    {
564      return $_SESSION['merged_extensions'];
565    }
566
567    $_SESSION['merged_extensions'] = array('~~expire~~' => time() + 600);
568
569    if (fetchRemote(PHPWG_URL.'/download/merged_extensions.txt', $result))
570    {
571      $rows = explode("\n", $result);
572      foreach ($rows as $row)
573      {
574        if (preg_match('/^(\d+\.\d+): *(.*)$/', $row, $match))
575        {
576          if (version_compare($version, $match[1], '>='))
577          {
578            $extensions = explode(',', trim($match[2]));
579            $_SESSION['merged_extensions'] = array_merge($_SESSION['merged_extensions'], $extensions);
580          }
581        }
582      }
583    }
584
585    return $_SESSION['merged_extensions'];
586  }
587 
588  /**
589   * delete $path directory
590   * @param string - path
591   */
592  function deltree($path)
593  {
594    if (is_dir($path))
595    {
596      $fh = opendir($path);
597      while ($file = readdir($fh))
598      {
599        if ($file != '.' and $file != '..')
600        {
601          $pathfile = $path . '/' . $file;
602          if (is_dir($pathfile))
603          {
604            $this->deltree($pathfile);
605          }
606          else
607          {
608            @unlink($pathfile);
609          }
610        }
611      }
612      closedir($fh);
613      return @rmdir($path);
614    }
615  }
616
617  /**
618   * send $path to trash directory
619   * @param string - path
620   */
621  function send_to_trash($path)
622  {
623    $trash_path = PHPWG_PLUGINS_PATH . 'trash';
624    if (!is_dir($trash_path))
625    {
626      @mkdir($trash_path);
627      $file = @fopen($trash_path . '/.htaccess', 'w');
628      @fwrite($file, 'deny from all');
629      @fclose($file);
630    }
631    while ($r = $trash_path . '/' . md5(uniqid(rand(), true)))
632    {
633      if (!is_dir($r))
634      {
635        @rename($path, $r);
636        break;
637      }
638    }
639  }
640
641  /**
642   * Sort functions
643   */
644  function plugin_version_compare($a, $b)
645  {
646    if (strtolower($a) == 'auto') return false;
647
648    $pattern = array('/([a-z])/ei', '/\.+/', '/\.\Z|\A\./');
649    $replacement = array( "'.'.intval('\\1', 36).'.'", '.', '');
650
651    $array = preg_replace($pattern, $replacement, array($a, $b));
652
653    return version_compare($array[0], $array[1], '>=');
654  }
655
656  function extension_revision_compare($a, $b)
657  {
658    if ($a['revision_date'] < $b['revision_date']) return 1;
659    else return -1;
660  }
661
662  function extension_name_compare($a, $b)
663  {
664    return strcmp(strtolower($a['extension_name']), strtolower($b['extension_name']));
665  }
666
667  function extension_author_compare($a, $b)
668  {
669    $r = strcasecmp($a['author_name'], $b['author_name']);
670    if ($r == 0) return $this->extension_name_compare($a, $b);
671    else return $r;
672  }
673
674  function plugin_author_compare($a, $b)
675  {
676    $r = strcasecmp($a['author'], $b['author']);
677    if ($r == 0) return name_compare($a, $b);
678    else return $r;
679  }
680
681  function extension_downloads_compare($a, $b)
682  {
683    if ($a['extension_nb_downloads'] < $b['extension_nb_downloads']) return 1;
684    else return -1;
685  }
686
687  function sort_plugins_by_state()
688  {
689    uasort($this->fs_plugins, 'name_compare');
690
691    $active_plugins = array();
692    $inactive_plugins = array();
693    $not_installed = array();
694
695    foreach($this->fs_plugins as $plugin_id => $plugin)
696    {
697      if (isset($this->db_plugins_by_id[$plugin_id]))
698      {
699        $this->db_plugins_by_id[$plugin_id]['state'] == 'active' ?
700          $active_plugins[$plugin_id] = $plugin : $inactive_plugins[$plugin_id] = $plugin;
701      }
702      else
703      {
704        $not_installed[$plugin_id] = $plugin;
705      }
706    }
707    $this->fs_plugins = $active_plugins + $inactive_plugins + $not_installed;
708  }
709}
710?>
Note: See TracBrowser for help on using the repository browser.