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

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

final fix for plugins update ?

  • plugins.version is not updated in "activate" action
  • plugins.version is updated in "update" action and "load_plugin()" function (not only for plugins using maintain.class.php)

cases covered:

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