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

Last change on this file since 24159 was 24159, checked in by mistic100, 11 years ago

feature:2826 missing hardcoded PEM category id in r20449

  • Property svn:eol-style set to LF
File size: 18.1 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based photo gallery                                    |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008-2013 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          list($crt_db_plugin) = get_db_plugins(null, $plugin_id);
90          load_conf_from_db();
91        }
92        elseif ($crt_db_plugin['state'] == 'active')
93        {
94          break;
95        }
96        if (empty($errors) and file_exists($file_to_include))
97        {
98          include_once($file_to_include);
99          if (function_exists('plugin_activate'))
100          {
101            plugin_activate($plugin_id, $crt_db_plugin['version'], $errors);
102          }
103        }
104        if (empty($errors))
105        {
106          $query = '
107UPDATE ' . PLUGINS_TABLE . '
108SET state=\'active\', version=\''.$this->fs_plugins[$plugin_id]['version'].'\'
109WHERE id=\'' . $plugin_id . '\'';
110          pwg_query($query);
111        }
112        break;
113
114      case 'deactivate':
115        if (!isset($crt_db_plugin) or $crt_db_plugin['state'] != 'active')
116        {
117          break;
118        }
119        $query = '
120UPDATE ' . PLUGINS_TABLE . ' SET state=\'inactive\' WHERE id=\'' . $plugin_id . '\'';
121        pwg_query($query);
122        if (file_exists($file_to_include))
123        {
124          include_once($file_to_include);
125          if (function_exists('plugin_deactivate'))
126          {
127            plugin_deactivate($plugin_id);
128          }
129        }
130        break;
131
132      case 'uninstall':
133        if (!isset($crt_db_plugin))
134        {
135          break;
136        }
137        if ($crt_db_plugin['state'] == 'active')
138        {
139          $this->perform_action('deactivate', $plugin_id);
140        }
141        $query = '
142DELETE FROM ' . PLUGINS_TABLE . ' WHERE id=\'' . $plugin_id . '\'';
143        pwg_query($query);
144        if (file_exists($file_to_include))
145        {
146          include_once($file_to_include);
147          if (function_exists('plugin_uninstall'))
148          {
149            plugin_uninstall($plugin_id);
150          }
151        }
152        break;
153
154      case 'restore':
155        $this->perform_action('uninstall', $plugin_id);
156        unset($this->db_plugins_by_id[$plugin_id]);
157        $errors = $this->perform_action('activate', $plugin_id);
158        break;
159
160      case 'delete':
161        if (!empty($crt_db_plugin))
162        {
163          $this->perform_action('uninstall', $plugin_id);
164        }
165        if (!isset($this->fs_plugins[$plugin_id]))
166        {
167          break;
168        }
169        deltree(PHPWG_PLUGINS_PATH . $plugin_id, PHPWG_PLUGINS_PATH . 'trash');
170        break;
171    }
172    return $errors;
173  }
174
175  /**
176  *  Get plugins defined in the plugin directory
177  */ 
178  function get_fs_plugins()
179  {
180    $dir = opendir(PHPWG_PLUGINS_PATH);
181    while ($file = readdir($dir))
182    {
183      if ($file!='.' and $file!='..')
184      {
185        $path = PHPWG_PLUGINS_PATH.$file;
186        if (is_dir($path) and !is_link($path)
187            and preg_match('/^[a-zA-Z0-9-_]+$/', $file )
188            and file_exists($path.'/main.inc.php')
189            )
190        {
191          $plugin = array(
192              'name'=>$file,
193              'version'=>'0',
194              'uri'=>'',
195              'description'=>'',
196              'author'=>'',
197            );
198          $plg_data = implode( '', file($path.'/main.inc.php') );
199
200          if ( preg_match("|Plugin Name: (.*)|", $plg_data, $val) )
201          {
202            $plugin['name'] = trim( $val[1] );
203          }
204          if (preg_match("|Version: (.*)|", $plg_data, $val))
205          {
206            $plugin['version'] = trim($val[1]);
207          }
208          if ( preg_match("|Plugin URI: (.*)|", $plg_data, $val) )
209          {
210            $plugin['uri'] = trim($val[1]);
211          }
212          if ($desc = load_language('description.txt', $path.'/', array('return' => true)))
213          {
214            $plugin['description'] = trim($desc);
215          }
216          elseif ( preg_match("|Description: (.*)|", $plg_data, $val) )
217          {
218            $plugin['description'] = trim($val[1]);
219          }
220          if ( preg_match("|Author: (.*)|", $plg_data, $val) )
221          {
222            $plugin['author'] = trim($val[1]);
223          }
224          if ( preg_match("|Author URI: (.*)|", $plg_data, $val) )
225          {
226            $plugin['author uri'] = trim($val[1]);
227          }
228          if (!empty($plugin['uri']) and strpos($plugin['uri'] , 'extension_view.php?eid='))
229          {
230            list( , $extension) = explode('extension_view.php?eid=', $plugin['uri']);
231            if (is_numeric($extension)) $plugin['extension'] = $extension;
232          }
233          // IMPORTANT SECURITY !
234          $plugin = array_map('htmlspecialchars', $plugin);
235          $this->fs_plugins[$file] = $plugin;
236        }
237      }
238    }
239    closedir($dir);
240  }
241
242  /**
243   * Sort fs_plugins
244   */
245  function sort_fs_plugins($order='name')
246  {
247    switch ($order)
248    {
249      case 'name':
250        uasort($this->fs_plugins, 'name_compare');
251        break;
252      case 'status':
253        $this->sort_plugins_by_state();
254        break;
255      case 'author':
256        uasort($this->fs_plugins, array($this, 'plugin_author_compare'));
257        break;
258      case 'id':
259        uksort($this->fs_plugins, 'strcasecmp');
260        break;
261    }
262  }
263
264  // Retrieve PEM versions
265  function get_versions_to_check($version=PHPWG_VERSION)
266  {
267    global $conf;
268   
269    $versions_to_check = array();
270    $url = PEM_URL . '/api/get_version_list.php?category_id='. $conf['pem_plugins_category'] .'&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 = get_branch_from_version($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, $conf;
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' => $conf['pem_plugins_category'],
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    global $conf;
367
368    // Plugins to check
369    $plugins_to_check = array();
370    foreach($this->fs_plugins as $fs_plugin)
371    {
372      if (isset($fs_plugin['extension']))
373      {
374        $plugins_to_check[] = $fs_plugin['extension'];
375      }
376    }
377
378    // Retrieve PEM plugins infos
379    $url = PEM_URL . '/api/get_revision_list.php';
380    $get_data = array(
381      'category_id' => $conf['pem_plugins_category'],
382      'format' => 'php',
383      'version' => implode(',', $versions_to_check),
384      'extension_include' => implode(',', $plugins_to_check),
385    );
386
387    if (fetchRemote($url, $result, $get_data))
388    {
389      $pem_plugins = @unserialize($result);
390      if (!is_array($pem_plugins))
391      {
392        return false;
393      }
394
395      $server_plugins = array();
396      foreach ($pem_plugins as $plugin)
397      {
398        if (!isset($server_plugins[$plugin['extension_id']]))
399        {
400          $server_plugins[$plugin['extension_id']] = array();
401        }
402        array_push($server_plugins[$plugin['extension_id']], $plugin['revision_name']);
403      }
404
405      foreach ($this->fs_plugins as $plugin_id => $fs_plugin)
406      {
407        if (isset($fs_plugin['extension'])
408          and !in_array($plugin_id, $this->default_plugins)
409          and $fs_plugin['version'] != 'auto'
410          and (!isset($server_plugins[$fs_plugin['extension']]) or !in_array($fs_plugin['version'], $server_plugins[$fs_plugin['extension']])))
411        {
412          $_SESSION['incompatible_plugins'][$plugin_id] = $fs_plugin['version'];
413        }
414      }
415      return $_SESSION['incompatible_plugins'];
416    }
417    return false;
418  }
419 
420  /**
421   * Sort $server_plugins
422   */
423  function sort_server_plugins($order='date')
424  {
425    switch ($order)
426    {
427      case 'date':
428        krsort($this->server_plugins);
429        break;
430      case 'revision':
431        usort($this->server_plugins, array($this, 'extension_revision_compare'));
432        break;
433      case 'name':
434        uasort($this->server_plugins, array($this, 'extension_name_compare'));
435        break;
436      case 'author':
437        uasort($this->server_plugins, array($this, 'extension_author_compare'));
438        break;
439      case 'downloads':
440        usort($this->server_plugins, array($this, 'extension_downloads_compare'));
441        break;
442    }
443  }
444
445  /**
446   * Extract plugin files from archive
447   * @param string - install or upgrade
448   *  @param string - archive URL
449    * @param string - plugin id or extension id
450   */
451  function extract_plugin_files($action, $revision, $dest)
452  {
453    if ($archive = tempnam( PHPWG_PLUGINS_PATH, 'zip'))
454    {
455      $url = PEM_URL . '/download.php';
456      $get_data = array(
457        'rid' => $revision,
458        'origin' => 'piwigo_'.$action,
459      );
460
461      if ($handle = @fopen($archive, 'wb') and fetchRemote($url, $handle, $get_data))
462      {
463        fclose($handle);
464        include_once(PHPWG_ROOT_PATH.'admin/include/pclzip.lib.php');
465        $zip = new PclZip($archive);
466        if ($list = $zip->listContent())
467        {
468          foreach ($list as $file)
469          {
470            // we search main.inc.php in archive
471            if (basename($file['filename']) == 'main.inc.php'
472              and (!isset($main_filepath)
473              or strlen($file['filename']) < strlen($main_filepath)))
474            {
475              $main_filepath = $file['filename'];
476            }
477          }
478          if (isset($main_filepath))
479          {
480            $root = dirname($main_filepath); // main.inc.php path in archive
481            if ($action == 'upgrade')
482            {
483              $extract_path = PHPWG_PLUGINS_PATH . $dest;
484            }
485            else
486            {
487              $extract_path = PHPWG_PLUGINS_PATH
488                  . ($root == '.' ? 'extension_' . $dest : basename($root));
489            }
490            if($result = $zip->extract(PCLZIP_OPT_PATH, $extract_path,
491                                       PCLZIP_OPT_REMOVE_PATH, $root,
492                                       PCLZIP_OPT_REPLACE_NEWER))
493            {
494              foreach ($result as $file)
495              {
496                if ($file['stored_filename'] == $main_filepath)
497                {
498                  $status = $file['status'];
499                  break;
500                }
501              }
502              if (file_exists($extract_path.'/obsolete.list')
503                and $old_files = file($extract_path.'/obsolete.list', FILE_IGNORE_NEW_LINES)
504                and !empty($old_files))
505              {
506                array_push($old_files, 'obsolete.list');
507                foreach($old_files as $old_file)
508                {
509                  $path = $extract_path.'/'.$old_file;
510                  if (is_file($path))
511                  {
512                    @unlink($path);
513                  }
514                  elseif (is_dir($path))
515                  {
516                    deltree($path, PHPWG_PLUGINS_PATH . 'trash');
517                  }
518                }
519              }
520            }
521            else $status = 'extract_error';
522          }
523          else $status = 'archive_error';
524        }
525        else $status = 'archive_error';
526      }
527      else $status = 'dl_archive_error';
528    }
529    else $status = 'temp_path_error';
530
531    @unlink($archive);
532    return $status;
533  }
534
535  function get_merged_extensions($version=PHPWG_VERSION)
536  {
537    $file = PHPWG_ROOT_PATH.'install/obsolete_extensions.list';
538    $merged_extensions = array();
539
540    if (file_exists($file) and $obsolete_ext = file($file, FILE_IGNORE_NEW_LINES) and !empty($obsolete_ext))
541    {
542      foreach ($obsolete_ext as $ext)
543      {
544        if (preg_match('/^(\d+) ?: ?(.*?)$/', $ext, $matches))
545        {
546          $merged_extensions[$matches[1]] = $matches[2];
547        }
548      }
549    }
550    return $merged_extensions;
551  }
552
553  /**
554   * Sort functions
555   */
556  function plugin_version_compare($a, $b)
557  {
558    if (strtolower($a) == 'auto') return false;
559
560    $pattern = array('/([a-z])/ei', '/\.+/', '/\.\Z|\A\./');
561    $replacement = array( "'.'.intval('\\1', 36).'.'", '.', '');
562
563    $array = preg_replace($pattern, $replacement, array($a, $b));
564
565    return version_compare($array[0], $array[1], '>=');
566  }
567
568  function extension_revision_compare($a, $b)
569  {
570    if ($a['revision_date'] < $b['revision_date']) return 1;
571    else return -1;
572  }
573
574  function extension_name_compare($a, $b)
575  {
576    return strcmp(strtolower($a['extension_name']), strtolower($b['extension_name']));
577  }
578
579  function extension_author_compare($a, $b)
580  {
581    $r = strcasecmp($a['author_name'], $b['author_name']);
582    if ($r == 0) return $this->extension_name_compare($a, $b);
583    else return $r;
584  }
585
586  function plugin_author_compare($a, $b)
587  {
588    $r = strcasecmp($a['author'], $b['author']);
589    if ($r == 0) return name_compare($a, $b);
590    else return $r;
591  }
592
593  function extension_downloads_compare($a, $b)
594  {
595    if ($a['extension_nb_downloads'] < $b['extension_nb_downloads']) return 1;
596    else return -1;
597  }
598
599  function sort_plugins_by_state()
600  {
601    uasort($this->fs_plugins, 'name_compare');
602
603    $active_plugins = array();
604    $inactive_plugins = array();
605    $not_installed = array();
606
607    foreach($this->fs_plugins as $plugin_id => $plugin)
608    {
609      if (isset($this->db_plugins_by_id[$plugin_id]))
610      {
611        $this->db_plugins_by_id[$plugin_id]['state'] == 'active' ?
612          $active_plugins[$plugin_id] = $plugin : $inactive_plugins[$plugin_id] = $plugin;
613      }
614      else
615      {
616        $not_installed[$plugin_id] = $plugin;
617      }
618    }
619    $this->fs_plugins = $active_plugins + $inactive_plugins + $not_installed;
620  }
621}
622?>
Note: See TracBrowser for help on using the repository browser.