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

Last change on this file since 5382 was 5382, checked in by plg, 14 years ago

feature 1514: make the "deactivate" action inactive if there is no active
theme left.

bug fixed: when setting the default theme, make sure at least one user will
be updated.

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