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

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

bug:2898 make some updates methods static + factorize code from plugins, themes & languages

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