aboutsummaryrefslogtreecommitdiffstats
path: root/admin/include/plugins.class.php
blob: 9862bccd463aa3343726d9f197aac417feddc3e8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
<?php
// +-----------------------------------------------------------------------+
// | Piwigo - a PHP based photo gallery                                    |
// +-----------------------------------------------------------------------+
// | Copyright(C) 2008-2014 Piwigo Team                  http://piwigo.org |
// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
// +-----------------------------------------------------------------------+
// | This program is free software; you can redistribute it and/or modify  |
// | it under the terms of the GNU General Public License as published by  |
// | the Free Software Foundation                                          |
// |                                                                       |
// | This program is distributed in the hope that it will be useful, but   |
// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
// | General Public License for more details.                              |
// |                                                                       |
// | You should have received a copy of the GNU General Public License     |
// | along with this program; if not, write to the Free Software           |
// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
// | USA.                                                                  |
// +-----------------------------------------------------------------------+

/**
 * class DummyPlugin_maintain
 * used when a plugin uses the old procedural declaration of maintenance methods
 */
class DummyPlugin_maintain extends PluginMaintain
{
  function install($plugin_version, &$errors=array())
  {
    if (is_callable('plugin_install'))
    {
      return plugin_install($this->plugin_id, $plugin_version, $errors);
    }
  }
  function activate($plugin_version, &$errors=array())
  {
    if (is_callable('plugin_activate'))
    {
      return plugin_activate($this->plugin_id, $plugin_version, $errors);
    }
  }
  function deactivate()
  {
    if (is_callable('plugin_deactivate'))
    {
      return plugin_deactivate($this->plugin_id);
    }
  }
  function uninstall()
  {
    if (is_callable('plugin_uninstall'))
    {
      return plugin_uninstall($this->plugin_id);
    }
  }
}


class plugins
{
  var $fs_plugins = array();
  var $db_plugins_by_id = array();
  var $server_plugins = array();
  var $default_plugins = array('LocalFilesEditor', 'language_switch', 'c13y_upgrade', 'admin_multi_view');

  /**
   * Initialize $fs_plugins and $db_plugins_by_id
   */
  function plugins()
  {
    $this->get_fs_plugins();

    foreach (get_db_plugins() as $db_plugin)
    {
      $this->db_plugins_by_id[$db_plugin['id']] = $db_plugin;
    }
  }

  /**
   * Returns the maintain class of a plugin
   * or build a new class with the procedural methods
   * @param string $plugin_id
   */
  private static function build_maintain_class($plugin_id)
  {
    $file_to_include = PHPWG_PLUGINS_PATH . $plugin_id . '/maintain.inc.php';
    $classname = $plugin_id.'_maintain';

    if (file_exists($file_to_include))
    {
      include_once($file_to_include);

      if (class_exists($classname))
      {
        $plugin_maintain = new $classname($plugin_id);
      }
      else
      {
        $plugin_maintain = new DummyPlugin_maintain($plugin_id);
      }
    }
    else
    {
      $plugin_maintain = new DummyPlugin_maintain($plugin_id);
    }

    return $plugin_maintain;
  }

  /**
   * Perform requested actions
   * @param string - action
   * @param string - plugin id
   * @param array - errors
   */
  function perform_action($action, $plugin_id)
  {
    if (isset($this->db_plugins_by_id[$plugin_id]))
    {
      $crt_db_plugin = $this->db_plugins_by_id[$plugin_id];
    }
    
    $plugin_maintain = self::build_maintain_class($plugin_id);

    $errors = array();

    switch ($action)
    {
      case 'install':
        if (!empty($crt_db_plugin) or !isset($this->fs_plugins[$plugin_id]))
        {
          break;
        }

        $plugin_maintain->install($this->fs_plugins[$plugin_id]['version'], $errors);

        if (empty($errors))
        {
          $query = '
INSERT INTO '. PLUGINS_TABLE .' (id,version)
  VALUES (\''. $plugin_id .'\', \''. $this->fs_plugins[$plugin_id]['version'] .'\')
;';
          pwg_query($query);
        }
        break;

      case 'activate':
        if (!isset($crt_db_plugin))
        {
          $errors = $this->perform_action('install', $plugin_id);
          list($crt_db_plugin) = get_db_plugins(null, $plugin_id);
          load_conf_from_db();
        }
        elseif ($crt_db_plugin['state'] == 'active')
        {
          break;
        }

        if (empty($errors))
        {
          $plugin_maintain->activate($crt_db_plugin['version'], $errors);
        }

        if (empty($errors))
        {
          $query = '
UPDATE '. PLUGINS_TABLE .'
  SET state=\'active\',
    version=\''. $this->fs_plugins[$plugin_id]['version'] .'\'
  WHERE id=\''. $plugin_id .'\'
;';
          pwg_query($query);
        }
        break;

      case 'deactivate':
        if (!isset($crt_db_plugin) or $crt_db_plugin['state'] != 'active')
        {
          break;
        }

        $query = '
UPDATE '. PLUGINS_TABLE .'
  SET state=\'inactive\'
  WHERE id=\''. $plugin_id .'\'
;';
        pwg_query($query);
        
        $plugin_maintain->deactivate();
        break;

      case 'uninstall':
        if (!isset($crt_db_plugin))
        {
          break;
        }
        if ($crt_db_plugin['state'] == 'active')
        {
          $this->perform_action('deactivate', $plugin_id);
        }

        $query = '
DELETE FROM '. PLUGINS_TABLE .'
  WHERE id=\''. $plugin_id .'\'
;';
        pwg_query($query);
        
        $plugin_maintain->uninstall();
        break;

      case 'restore':
        $this->perform_action('uninstall', $plugin_id);
        unset($this->db_plugins_by_id[$plugin_id]);
        $errors = $this->perform_action('activate', $plugin_id);
        break;

      case 'delete':
        if (!empty($crt_db_plugin))
        {
          $this->perform_action('uninstall', $plugin_id);
        }
        if (!isset($this->fs_plugins[$plugin_id]))
        {
          break;
        }

        deltree(PHPWG_PLUGINS_PATH . $plugin_id, PHPWG_PLUGINS_PATH . 'trash');
        break;
    }

    return $errors;
  }

  /**
   * Get plugins defined in the plugin directory
   */  
  function get_fs_plugins()
  {
    $dir = opendir(PHPWG_PLUGINS_PATH);
    while ($file = readdir($dir))
    {
      if ($file!='.' and $file!='..')
      {
        $path = PHPWG_PLUGINS_PATH.$file;
        if (is_dir($path) and !is_link($path)
            and preg_match('/^[a-zA-Z0-9-_]+$/', $file )
            and file_exists($path.'/main.inc.php')
            )
        {
          $plugin = array(
              'name'=>$file,
              'version'=>'0',
              'uri'=>'',
              'description'=>'',
              'author'=>'',
            );
          $plg_data = implode( '', file($path.'/main.inc.php') );

          if ( preg_match("|Plugin Name: (.*)|", $plg_data, $val) )
          {
            $plugin['name'] = trim( $val[1] );
          }
          if (preg_match("|Version: (.*)|", $plg_data, $val))
          {
            $plugin['version'] = trim($val[1]);
          }
          if ( preg_match("|Plugin URI: (.*)|", $plg_data, $val) )
          {
            $plugin['uri'] = trim($val[1]);
          }
          if ($desc = load_language('description.txt', $path.'/', array('return' => true)))
          {
            $plugin['description'] = trim($desc);
          }
          elseif ( preg_match("|Description: (.*)|", $plg_data, $val) )
          {
            $plugin['description'] = trim($val[1]);
          }
          if ( preg_match("|Author: (.*)|", $plg_data, $val) )
          {
            $plugin['author'] = trim($val[1]);
          }
          if ( preg_match("|Author URI: (.*)|", $plg_data, $val) )
          {
            $plugin['author uri'] = trim($val[1]);
          }
          if (!empty($plugin['uri']) and strpos($plugin['uri'] , 'extension_view.php?eid='))
          {
            list( , $extension) = explode('extension_view.php?eid=', $plugin['uri']);
            if (is_numeric($extension)) $plugin['extension'] = $extension;
          }
          // IMPORTANT SECURITY !
          $plugin = array_map('htmlspecialchars', $plugin);
          $this->fs_plugins[$file] = $plugin;
        }
      }
    }
    closedir($dir);
  }

  /**
   * Sort fs_plugins
   */
  function sort_fs_plugins($order='name')
  {
    switch ($order)
    {
      case 'name':
        uasort($this->fs_plugins, 'name_compare');
        break;
      case 'status':
        $this->sort_plugins_by_state();
        break;
      case 'author':
        uasort($this->fs_plugins, array($this, 'plugin_author_compare'));
        break;
      case 'id':
        uksort($this->fs_plugins, 'strcasecmp');
        break;
    }
  }

  // Retrieve PEM versions
  function get_versions_to_check($version=PHPWG_VERSION)
  {
    global $conf;
    
    $versions_to_check = array();
    $url = PEM_URL . '/api/get_version_list.php?category_id='. $conf['pem_plugins_category'] .'&format=php';
    if (fetchRemote($url, $result) and $pem_versions = @unserialize($result))
    {
      if (!preg_match('/^\d+\.\d+\.\d+$/', $version))
      {
        $version = $pem_versions[0]['name'];
      }
      $branch = get_branch_from_version($version);
      foreach ($pem_versions as $pem_version)
      {
        if (strpos($pem_version['name'], $branch) === 0)
        {
          $versions_to_check[] = $pem_version['id'];
        }
      }
    }
    return $versions_to_check;
  }

  /**
   * Retrieve PEM server datas to $server_plugins
   */
  function get_server_plugins($new=false)
  {
    global $user, $conf;

    $versions_to_check = $this->get_versions_to_check();
    if (empty($versions_to_check))
    {
      return false;
    }

    // Plugins to check
    $plugins_to_check = array();
    foreach($this->fs_plugins as $fs_plugin)
    {
      if (isset($fs_plugin['extension']))
      {
        $plugins_to_check[] = $fs_plugin['extension'];
      }
    }

    // Retrieve PEM plugins infos
    $url = PEM_URL . '/api/get_revision_list.php';
    $get_data = array(
      'category_id' => $conf['pem_plugins_category'],
      'format' => 'php',
      'last_revision_only' => 'true',
      'version' => implode(',', $versions_to_check),
      'lang' => substr($user['language'], 0, 2),
      'get_nb_downloads' => 'true',
    );

    if (!empty($plugins_to_check))
    {
      if ($new)
      {
        $get_data['extension_exclude'] = implode(',', $plugins_to_check);
      }
      else
      {
        $get_data['extension_include'] = implode(',', $plugins_to_check);
      }
    }
    if (fetchRemote($url, $result, $get_data))
    {
      $pem_plugins = @unserialize($result);
      if (!is_array($pem_plugins))
      {
        return false;
      }
      foreach ($pem_plugins as $plugin)
      {
        $this->server_plugins[$plugin['extension_id']] = $plugin;
      }
      return true;
    }
    return false;
  }

  function get_incompatible_plugins($actualize=false)
  {
    if (isset($_SESSION['incompatible_plugins']) and !$actualize
      and $_SESSION['incompatible_plugins']['~~expire~~'] > time())
    {
      return $_SESSION['incompatible_plugins'];
    }

    $_SESSION['incompatible_plugins'] = array('~~expire~~' => time() + 300);

    $versions_to_check = $this->get_versions_to_check();
    if (empty($versions_to_check))
    {
      return false;
    }
    
    global $conf;

    // Plugins to check
    $plugins_to_check = array();
    foreach($this->fs_plugins as $fs_plugin)
    {
      if (isset($fs_plugin['extension']))
      {
        $plugins_to_check[] = $fs_plugin['extension'];
      }
    }

    // Retrieve PEM plugins infos
    $url = PEM_URL . '/api/get_revision_list.php';
    $get_data = array(
      'category_id' => $conf['pem_plugins_category'],
      'format' => 'php',
      'version' => implode(',', $versions_to_check),
      'extension_include' => implode(',', $plugins_to_check),
    );

    if (fetchRemote($url, $result, $get_data))
    {
      $pem_plugins = @unserialize($result);
      if (!is_array($pem_plugins))
      {
        return false;
      }

      $server_plugins = array();
      foreach ($pem_plugins as $plugin)
      {
        if (!isset($server_plugins[$plugin['extension_id']]))
        {
          $server_plugins[$plugin['extension_id']] = array();
        }
        $server_plugins[$plugin['extension_id']][] = $plugin['revision_name'];
      }

      foreach ($this->fs_plugins as $plugin_id => $fs_plugin)
      {
        if (isset($fs_plugin['extension'])
          and !in_array($plugin_id, $this->default_plugins)
          and $fs_plugin['version'] != 'auto'
          and (!isset($server_plugins[$fs_plugin['extension']]) or !in_array($fs_plugin['version'], $server_plugins[$fs_plugin['extension']])))
        {
          $_SESSION['incompatible_plugins'][$plugin_id] = $fs_plugin['version'];
        }
      }
      return $_SESSION['incompatible_plugins'];
    }
    return false;
  }
  
  /**
   * Sort $server_plugins
   */
  function sort_server_plugins($order='date')
  {
    switch ($order)
    {
      case 'date':
        krsort($this->server_plugins);
        break;
      case 'revision':
        usort($this->server_plugins, array($this, 'extension_revision_compare'));
        break;
      case 'name':
        uasort($this->server_plugins, array($this, 'extension_name_compare'));
        break;
      case 'author':
        uasort($this->server_plugins, array($this, 'extension_author_compare'));
        break;
      case 'downloads':
        usort($this->server_plugins, array($this, 'extension_downloads_compare'));
        break;
    }
  }

  /**
   * Extract plugin files from archive
   * @param string - install or upgrade
   *  @param string - archive URL
    * @param string - plugin id or extension id
   */
  function extract_plugin_files($action, $revision, $dest)
  {
    if ($archive = tempnam( PHPWG_PLUGINS_PATH, 'zip'))
    {
      $url = PEM_URL . '/download.php';
      $get_data = array(
        'rid' => $revision,
        'origin' => 'piwigo_'.$action,
      );

      if ($handle = @fopen($archive, 'wb') and fetchRemote($url, $handle, $get_data))
      {
        fclose($handle);
        include_once(PHPWG_ROOT_PATH.'admin/include/pclzip.lib.php');
        $zip = new PclZip($archive);
        if ($list = $zip->listContent())
        {
          foreach ($list as $file)
          {
            // we search main.inc.php in archive
            if (basename($file['filename']) == 'main.inc.php'
              and (!isset($main_filepath)
              or strlen($file['filename']) < strlen($main_filepath)))
            {
              $main_filepath = $file['filename'];
            }
          }
          if (isset($main_filepath))
          {
            $root = dirname($main_filepath); // main.inc.php path in archive
            if ($action == 'upgrade')
            {
              $extract_path = PHPWG_PLUGINS_PATH . $dest;
            }
            else
            {
              $extract_path = PHPWG_PLUGINS_PATH
                  . ($root == '.' ? 'extension_' . $dest : basename($root));
            }
            if($result = $zip->extract(PCLZIP_OPT_PATH, $extract_path,
                                       PCLZIP_OPT_REMOVE_PATH, $root,
                                       PCLZIP_OPT_REPLACE_NEWER))
            {
              foreach ($result as $file)
              {
                if ($file['stored_filename'] == $main_filepath)
                {
                  $status = $file['status'];
                  break;
                }
              }
              if (file_exists($extract_path.'/obsolete.list')
                and $old_files = file($extract_path.'/obsolete.list', FILE_IGNORE_NEW_LINES)
                and !empty($old_files))
              {
                $old_files[] = 'obsolete.list';
                foreach($old_files as $old_file)
                {
                  $path = $extract_path.'/'.$old_file;
                  if (is_file($path))
                  {
                    @unlink($path);
                  }
                  elseif (is_dir($path))
                  {
                    deltree($path, PHPWG_PLUGINS_PATH . 'trash');
                  }
                }
              }
            }
            else $status = 'extract_error';
          }
          else $status = 'archive_error';
        }
        else $status = 'archive_error';
      }
      else $status = 'dl_archive_error';
    }
    else $status = 'temp_path_error';

    @unlink($archive);
    return $status;
  }

  function get_merged_extensions($version=PHPWG_VERSION)
  {
    $file = PHPWG_ROOT_PATH.'install/obsolete_extensions.list';
    $merged_extensions = array();

    if (file_exists($file) and $obsolete_ext = file($file, FILE_IGNORE_NEW_LINES) and !empty($obsolete_ext))
    {
      foreach ($obsolete_ext as $ext)
      {
        if (preg_match('/^(\d+) ?: ?(.*?)$/', $ext, $matches))
        {
          $merged_extensions[$matches[1]] = $matches[2];
        }
      }
    }
    return $merged_extensions;
  }

  /**
   * Sort functions
   */
  function extension_revision_compare($a, $b)
  {
    if ($a['revision_date'] < $b['revision_date']) return 1;
    else return -1;
  }

  function extension_name_compare($a, $b)
  {
    return strcmp(strtolower($a['extension_name']), strtolower($b['extension_name']));
  }

  function extension_author_compare($a, $b)
  {
    $r = strcasecmp($a['author_name'], $b['author_name']);
    if ($r == 0) return $this->extension_name_compare($a, $b);
    else return $r;
  }

  function plugin_author_compare($a, $b)
  {
    $r = strcasecmp($a['author'], $b['author']);
    if ($r == 0) return name_compare($a, $b);
    else return $r;
  }

  function extension_downloads_compare($a, $b)
  {
    if ($a['extension_nb_downloads'] < $b['extension_nb_downloads']) return 1;
    else return -1;
  }

  function sort_plugins_by_state()
  {
    uasort($this->fs_plugins, 'name_compare');

    $active_plugins = array();
    $inactive_plugins = array();
    $not_installed = array();

    foreach($this->fs_plugins as $plugin_id => $plugin)
    {
      if (isset($this->db_plugins_by_id[$plugin_id]))
      {
        $this->db_plugins_by_id[$plugin_id]['state'] == 'active' ?
          $active_plugins[$plugin_id] = $plugin : $inactive_plugins[$plugin_id] = $plugin;
      }
      else
      {
        $not_installed[$plugin_id] = $plugin;
      }
    }
    $this->fs_plugins = $active_plugins + $inactive_plugins + $not_installed;
  }
}
?>