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

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

feature 1514: improvement, impossible to delete a theme that is required
by another installed theme.

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