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

Last change on this file since 11389 was 11389, checked in by mistic100, 13 years ago

reload DB config between plugin installation and plugin activation

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