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

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

feature:2260
Keep only two states for plugins (active and inactive)

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