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

Last change on this file since 9472 was 9472, checked in by patdenice, 13 years ago

Add themes autmatic update functionality.

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