source: trunk/admin/include/themes.class.php @ 25577

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

feature 2998: Warning: Parameter 3 to theme_activate() expected to be a reference, value given
unable to pass references through func_get_args and call_user_func_array

File size: 19.7 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
24/**
25 * class DummyTheme_maintain
26 * used when a theme uses the old procedural declaration of maintenance methods
27 */
28class DummyTheme_maintain extends ThemeMaintain
29{
30  function activate($theme_version, &$errors=array())
31  {
32    if (is_callable('theme_activate'))
33    {
34      return theme_activate($this->theme_id, $theme_version, $errors);
35    }
36  }
37  function deactivate()
38  {
39    if (is_callable('theme_deactivate'))
40    {
41      return theme_deactivate($this->theme_id);
42    }
43  }
44  function delete()
45  {
46    if (is_callable('theme_delete'))
47    {
48      return theme_delete($this->theme_id);
49    }
50  }
51}
52
53
54class themes
55{
56  var $fs_themes = array();
57  var $db_themes_by_id = array();
58  var $server_themes = array();
59
60  /**
61   * Initialize $fs_themes and $db_themes_by_id
62  */
63  function themes()
64  {
65    $this->get_fs_themes();
66
67    foreach ($this->get_db_themes() as $db_theme)
68    {
69      $this->db_themes_by_id[$db_theme['id']] = $db_theme;
70    }
71  }
72
73  /**
74   * Returns the maintain class of a theme
75   * or build a new class with the procedural methods
76   * @param string $theme_id
77   */
78  private static function build_maintain_class($theme_id)
79  {
80    $file_to_include = PHPWG_THEMES_PATH.'/'.$theme_id.'/admin/maintain.inc.php';
81    $classname = $theme_id.'_maintain';
82
83    if (file_exists($file_to_include))
84    {
85      include_once($file_to_include);
86
87      if (class_exists($classname))
88      {
89        $theme_maintain = new $classname($theme_id);
90      }
91      else
92      {
93        $theme_maintain = new DummyTheme_maintain($theme_id);
94      }
95    }
96    else
97    {
98      $theme_maintain = new DummyTheme_maintain($theme_id);
99    }
100
101    return $theme_maintain;
102  }
103
104  /**
105   * Perform requested actions
106   * @param string - action
107   * @param string - theme id
108   * @param array - errors
109   */
110  function perform_action($action, $theme_id)
111  {
112    global $conf;
113
114    if (isset($this->db_themes_by_id[$theme_id]))
115    {
116      $crt_db_theme = $this->db_themes_by_id[$theme_id];
117    }
118
119    $theme_maintain = self::build_maintain_class($theme_id);
120
121    $errors = array();
122
123    switch ($action)
124    {
125      case 'activate':
126        if (isset($crt_db_theme))
127        {
128          // the theme is already active
129          break;
130        }
131
132        if ('default' == $theme_id)
133        {
134          // you can't activate the "default" theme
135          break;
136        }
137
138        $missing_parent = $this->missing_parent_theme($theme_id);
139        if (isset($missing_parent))
140        {
141          $errors[] = l10n(
142            'Impossible to activate this theme, the parent theme is missing: %s',
143            $missing_parent
144            );
145
146          break;
147        }
148
149        if ($this->fs_themes[$theme_id]['mobile']
150            and !empty($conf['mobile_theme'])
151            and $conf['mobile_theme'] != $theme_id)
152        {
153          $errors[] = l10n('You can activate only one mobile theme.');
154          break;
155        }
156
157        $theme_maintain->activate($this->fs_themes[$theme_id]['version'], $errors);
158
159        if (empty($errors))
160        {
161          $query = '
162INSERT INTO '.THEMES_TABLE.'
163  (id, version, name)
164  VALUES(\''.$theme_id.'\',
165         \''.$this->fs_themes[$theme_id]['version'].'\',
166         \''.$this->fs_themes[$theme_id]['name'].'\')
167;';
168          pwg_query($query);
169
170          if ($this->fs_themes[$theme_id]['mobile'])
171          {
172            conf_update_param('mobile_theme', $theme_id);
173          }
174        }
175        break;
176
177      case 'deactivate':
178        if (!isset($crt_db_theme))
179        {
180          // the theme is already inactive
181          break;
182        }
183
184        // you can't deactivate the last theme
185        if (count($this->db_themes_by_id) <= 1)
186        {
187          $errors[] = l10n('Impossible to deactivate this theme, you need at least one theme.');
188          break;
189        }
190
191        if ($theme_id == get_default_theme())
192        {
193          // find a random theme to replace
194          $new_theme = null;
195
196          $query = '
197SELECT id
198  FROM '.THEMES_TABLE.'
199  WHERE id != \''.$theme_id.'\'
200;';
201          $result = pwg_query($query);
202          if (pwg_db_num_rows($result) == 0)
203          {
204            $new_theme = 'default';
205          }
206          else
207          {
208            list($new_theme) = pwg_db_fetch_row($result);
209          }
210
211          $this->set_default_theme($new_theme);
212        }
213
214        $theme_maintain->deactivate();
215
216        $query = '
217DELETE
218  FROM '.THEMES_TABLE.'
219  WHERE id= \''.$theme_id.'\'
220;';
221        pwg_query($query);
222
223        if ($this->fs_themes[$theme_id]['mobile'])
224        {
225          conf_update_param('mobile_theme', '');
226        }
227        break;
228
229      case 'delete':
230        if (!empty($crt_db_theme))
231        {
232          $errors[] = 'CANNOT DELETE - THEME IS INSTALLED';
233          break;
234        }
235        if (!isset($this->fs_themes[$theme_id]))
236        {
237          // nothing to do here
238          break;
239        }
240
241        $children = $this->get_children_themes($theme_id);
242        if (count($children) > 0)
243        {
244          $errors[] = l10n(
245            'Impossible to delete this theme. Other themes depends on it: %s',
246            implode(', ', $children)
247            );
248          break;
249        }
250
251        $theme_maintain->delete();
252
253        deltree(PHPWG_THEMES_PATH.$theme_id, PHPWG_THEMES_PATH . 'trash');
254        break;
255
256      case 'set_default':
257        // first we need to know which users are using the current default theme
258        $this->set_default_theme($theme_id);
259        break;
260    }
261    return $errors;
262  }
263
264  function missing_parent_theme($theme_id)
265  {
266    if (!isset($this->fs_themes[$theme_id]['parent']))
267    {
268      return null;
269    }
270
271    $parent = $this->fs_themes[$theme_id]['parent'];
272
273    if ('default' == $parent)
274    {
275      return null;
276    }
277
278    if (!isset($this->fs_themes[$parent]))
279    {
280      return $parent;
281    }
282
283    return $this->missing_parent_theme($parent);
284  }
285
286  function get_children_themes($theme_id)
287  {
288    $children = array();
289
290    foreach ($this->fs_themes as $test_child)
291    {
292      if (isset($test_child['parent']) and $test_child['parent'] == $theme_id)
293      {
294        $children[] = $test_child['name'];
295      }
296    }
297
298    return $children;
299  }
300
301  function set_default_theme($theme_id)
302  {
303    global $conf;
304
305    // first we need to know which users are using the current default theme
306    $default_theme = get_default_theme();
307
308    $query = '
309SELECT
310    user_id
311  FROM '.USER_INFOS_TABLE.'
312  WHERE theme = \''.$default_theme.'\'
313;';
314    $user_ids = array_unique(
315      array_merge(
316        array_from_query($query, 'user_id'),
317        array($conf['guest_id'], $conf['default_user_id'])
318        )
319      );
320
321    // $user_ids can't be empty, at least the default user has the default
322    // theme
323
324    $query = '
325UPDATE '.USER_INFOS_TABLE.'
326  SET theme = \''.$theme_id.'\'
327  WHERE user_id IN ('.implode(',', $user_ids).')
328;';
329    pwg_query($query);
330  }
331
332  function get_db_themes($id='')
333  {
334    $query = '
335SELECT
336    *
337  FROM '.THEMES_TABLE;
338
339    $clauses = array();
340    if (!empty($id))
341    {
342      $clauses[] = 'id = \''.$id.'\'';
343    }
344    if (count($clauses) > 0)
345    {
346      $query .= '
347  WHERE '. implode(' AND ', $clauses);
348    }
349
350    $result = pwg_query($query);
351    $themes = array();
352    while ($row = pwg_db_fetch_assoc($result))
353    {
354      $themes[] = $row;
355    }
356    return $themes;
357  }
358
359
360  /**
361  *  Get themes defined in the theme directory
362  */
363  function get_fs_themes()
364  {
365    $dir = opendir(PHPWG_THEMES_PATH);
366
367    while ($file = readdir($dir))
368    {
369      if ($file!='.' and $file!='..')
370      {
371        $path = PHPWG_THEMES_PATH.$file;
372        if (is_dir($path)
373            and preg_match('/^[a-zA-Z0-9-_]+$/', $file)
374            and file_exists($path.'/themeconf.inc.php')
375            )
376        {
377          $theme = array(
378            'id' => $file,
379            'name' => $file,
380            'version' => '0',
381            'uri' => '',
382            'description' => '',
383            'author' => '',
384            'mobile' => false,
385            );
386          $theme_data = implode( '', file($path.'/themeconf.inc.php') );
387
388          if ( preg_match("|Theme Name: (.*)|", $theme_data, $val) )
389          {
390            $theme['name'] = trim( $val[1] );
391          }
392          if (preg_match("|Version: (.*)|", $theme_data, $val))
393          {
394            $theme['version'] = trim($val[1]);
395          }
396          if ( preg_match("|Theme URI: (.*)|", $theme_data, $val) )
397          {
398            $theme['uri'] = trim($val[1]);
399          }
400          if ($desc = load_language('description.txt', $path.'/', array('return' => true)))
401          {
402            $theme['description'] = trim($desc);
403          }
404          elseif ( preg_match("|Description: (.*)|", $theme_data, $val) )
405          {
406            $theme['description'] = trim($val[1]);
407          }
408          if ( preg_match("|Author: (.*)|", $theme_data, $val) )
409          {
410            $theme['author'] = trim($val[1]);
411          }
412          if ( preg_match("|Author URI: (.*)|", $theme_data, $val) )
413          {
414            $theme['author uri'] = trim($val[1]);
415          }
416          if (!empty($theme['uri']) and strpos($theme['uri'] , 'extension_view.php?eid='))
417          {
418            list( , $extension) = explode('extension_view.php?eid=', $theme['uri']);
419            if (is_numeric($extension)) $theme['extension'] = $extension;
420          }
421          if (preg_match('/["\']parent["\'][^"\']+["\']([^"\']+)["\']/', $theme_data, $val))
422          {
423            $theme['parent'] = $val[1];
424          }
425          if (preg_match('/["\']activable["\'].*?(true|false)/i', $theme_data, $val))
426          {
427            $theme['activable'] = get_boolean($val[1]);
428          }
429          if (preg_match('/["\']mobile["\'].*?(true|false)/i', $theme_data, $val))
430          {
431            $theme['mobile'] = get_boolean($val[1]);
432          }
433
434          // screenshot
435          $screenshot_path = $path.'/screenshot.png';
436          if (file_exists($screenshot_path))
437          {
438            $theme['screenshot'] = $screenshot_path;
439          }
440          else
441          {
442            global $conf;
443            $theme['screenshot'] =
444              PHPWG_ROOT_PATH.'admin/themes/'
445              .$conf['admin_theme']
446              .'/images/missing_screenshot.png'
447              ;
448          }
449
450          $admin_file = $path.'/admin/admin.inc.php';
451          if (file_exists($admin_file))
452          {
453            $theme['admin_uri'] = get_root_url().'admin.php?page=theme&theme='.$file;
454          }
455
456          // IMPORTANT SECURITY !
457          $theme = array_map('htmlspecialchars', $theme);
458          $this->fs_themes[$file] = $theme;
459        }
460      }
461    }
462    closedir($dir);
463  }
464
465  /**
466   * Sort fs_themes
467   */
468  function sort_fs_themes($order='name')
469  {
470    switch ($order)
471    {
472      case 'name':
473        uasort($this->fs_themes, 'name_compare');
474        break;
475      case 'status':
476        $this->sort_themes_by_state();
477        break;
478      case 'author':
479        uasort($this->fs_themes, array($this, 'theme_author_compare'));
480        break;
481      case 'id':
482        uksort($this->fs_themes, 'strcasecmp');
483        break;
484    }
485  }
486
487  /**
488   * Retrieve PEM server datas to $server_themes
489   */
490  function get_server_themes($new=false)
491  {
492    global $user, $conf;
493
494    $get_data = array(
495      'category_id' => $conf['pem_themes_category'],
496      'format' => 'php',
497    );
498
499    // Retrieve PEM versions
500    $version = PHPWG_VERSION;
501    $versions_to_check = array();
502    $url = PEM_URL . '/api/get_version_list.php';
503    if (fetchRemote($url, $result, $get_data) and $pem_versions = @unserialize($result))
504    {
505      if (!preg_match('/^\d+\.\d+\.\d+$/', $version))
506      {
507        $version = $pem_versions[0]['name'];
508      }
509      $branch = get_branch_from_version($version);
510      foreach ($pem_versions as $pem_version)
511      {
512        if (strpos($pem_version['name'], $branch) === 0)
513        {
514          $versions_to_check[] = $pem_version['id'];
515        }
516      }
517    }
518    if (empty($versions_to_check))
519    {
520      return false;
521    }
522
523    // Themes to check
524    $themes_to_check = array();
525    foreach($this->fs_themes as $fs_theme)
526    {
527      if (isset($fs_theme['extension']))
528      {
529        $themes_to_check[] = $fs_theme['extension'];
530      }
531    }
532
533    // Retrieve PEM themes infos
534    $url = PEM_URL . '/api/get_revision_list.php';
535    $get_data = array_merge($get_data, array(
536      'last_revision_only' => 'true',
537      'version' => implode(',', $versions_to_check),
538      'lang' => substr($user['language'], 0, 2),
539      'get_nb_downloads' => 'true',
540      )
541    );
542
543    if (!empty($themes_to_check))
544    {
545      if ($new)
546      {
547        $get_data['extension_exclude'] = implode(',', $themes_to_check);
548      }
549      else
550      {
551        $get_data['extension_include'] = implode(',', $themes_to_check);
552      }
553    }
554    if (fetchRemote($url, $result, $get_data))
555    {
556      $pem_themes = @unserialize($result);
557      if (!is_array($pem_themes))
558      {
559        return false;
560      }
561      foreach ($pem_themes as $theme)
562      {
563        $this->server_themes[$theme['extension_id']] = $theme;
564      }
565      return true;
566    }
567    return false;
568  }
569
570  /**
571   * Sort $server_themes
572   */
573  function sort_server_themes($order='date')
574  {
575    switch ($order)
576    {
577      case 'date':
578        krsort($this->server_themes);
579        break;
580      case 'revision':
581        usort($this->server_themes, array($this, 'extension_revision_compare'));
582        break;
583      case 'name':
584        uasort($this->server_themes, array($this, 'extension_name_compare'));
585        break;
586      case 'author':
587        uasort($this->server_themes, array($this, 'extension_author_compare'));
588        break;
589      case 'downloads':
590        usort($this->server_themes, array($this, 'extension_downloads_compare'));
591        break;
592    }
593  }
594
595  /**
596   * Extract theme files from archive
597   *
598   * @param string - install or upgrade
599   * @param string - remote revision identifier (numeric)
600   * @param string - theme id or extension id
601   */
602  function extract_theme_files($action, $revision, $dest)
603  {
604    if ($archive = tempnam( PHPWG_THEMES_PATH, 'zip'))
605    {
606      $url = PEM_URL . '/download.php';
607      $get_data = array(
608        'rid' => $revision,
609        'origin' => 'piwigo_'.$action,
610      );
611
612      if ($handle = @fopen($archive, 'wb') and fetchRemote($url, $handle, $get_data))
613      {
614        fclose($handle);
615        include_once(PHPWG_ROOT_PATH.'admin/include/pclzip.lib.php');
616        $zip = new PclZip($archive);
617        if ($list = $zip->listContent())
618        {
619          foreach ($list as $file)
620          {
621            // we search main.inc.php in archive
622            if (basename($file['filename']) == 'themeconf.inc.php'
623              and (!isset($main_filepath)
624              or strlen($file['filename']) < strlen($main_filepath)))
625            {
626              $main_filepath = $file['filename'];
627            }
628          }
629          if (isset($main_filepath))
630          {
631            $root = dirname($main_filepath); // main.inc.php path in archive
632            if ($action == 'upgrade')
633            {
634              $extract_path = PHPWG_THEMES_PATH . $dest;
635            }
636            else
637            {
638              $extract_path = PHPWG_THEMES_PATH . ($root == '.' ? 'extension_' . $dest : basename($root));
639            }
640            if (
641              $result = $zip->extract(
642                PCLZIP_OPT_PATH, $extract_path,
643                PCLZIP_OPT_REMOVE_PATH, $root,
644                PCLZIP_OPT_REPLACE_NEWER
645                )
646              )
647            {
648              foreach ($result as $file)
649              {
650                if ($file['stored_filename'] == $main_filepath)
651                {
652                  $status = $file['status'];
653                  break;
654                }
655              }
656              if (file_exists($extract_path.'/obsolete.list')
657                and $old_files = file($extract_path.'/obsolete.list', FILE_IGNORE_NEW_LINES)
658                and !empty($old_files))
659              {
660                $old_files[] = 'obsolete.list';
661                foreach($old_files as $old_file)
662                {
663                  $path = $extract_path.'/'.$old_file;
664                  if (is_file($path))
665                  {
666                    @unlink($path);
667                  }
668                  elseif (is_dir($path))
669                  {
670                    deltree($path, PHPWG_THEMES_PATH . 'trash');
671                  }
672                }
673              }
674            }
675            else $status = 'extract_error';
676          }
677          else $status = 'archive_error';
678        }
679        else $status = 'archive_error';
680      }
681      else $status = 'dl_archive_error';
682    }
683    else $status = 'temp_path_error';
684
685    @unlink($archive);
686    return $status;
687  }
688
689  /**
690   * Sort functions
691   */
692  function theme_version_compare($a, $b)
693  {
694    $pattern = array('/([a-z])/ei', '/\.+/', '/\.\Z|\A\./');
695    $replacement = array( "'.'.intval('\\1', 36).'.'", '.', '');
696
697    $array = preg_replace($pattern, $replacement, array($a, $b));
698
699    return version_compare($array[0], $array[1], '>=');
700  }
701
702  function extension_revision_compare($a, $b)
703  {
704    if ($a['revision_date'] < $b['revision_date']) return 1;
705    else return -1;
706  }
707
708  function extension_name_compare($a, $b)
709  {
710    return strcmp(strtolower($a['extension_name']), strtolower($b['extension_name']));
711  }
712
713  function extension_author_compare($a, $b)
714  {
715    $r = strcasecmp($a['author_name'], $b['author_name']);
716    if ($r == 0) return $this->extension_name_compare($a, $b);
717    else return $r;
718  }
719
720  function theme_author_compare($a, $b)
721  {
722    $r = strcasecmp($a['author'], $b['author']);
723    if ($r == 0) return name_compare($a, $b);
724    else return $r;
725  }
726
727  function extension_downloads_compare($a, $b)
728  {
729    if ($a['extension_nb_downloads'] < $b['extension_nb_downloads']) return 1;
730    else return -1;
731  }
732
733  function sort_themes_by_state()
734  {
735    uasort($this->fs_themes, 'name_compare');
736
737    $active_themes = array();
738    $inactive_themes = array();
739    $not_installed = array();
740
741    foreach($this->fs_themes as $theme_id => $theme)
742    {
743      if (isset($this->db_themes_by_id[$theme_id]))
744      {
745        $this->db_themes_by_id[$theme_id]['state'] == 'active' ?
746          $active_themes[$theme_id] = $theme : $inactive_themes[$theme_id] = $theme;
747      }
748      else
749      {
750        $not_installed[$theme_id] = $theme;
751      }
752    }
753    $this->fs_themes = $active_themes + $inactive_themes + $not_installed;
754  }
755
756}
757?>
Note: See TracBrowser for help on using the repository browser.