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

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

improvement: dynamically activate all installed themes (with checks on
parent availability and so on).

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