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

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

increase copyright year to 2010

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