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

Last change on this file since 25018 was 25018, checked in by mistic100, 11 years ago

remove all array_push (50% slower than []) + some changes missing for feature:2978

File size: 18.9 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based photo gallery                                    |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008-2013 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   * Perform requested actions
45   * @param string - action
46   * @param string - theme id
47   * @param array - errors
48   */
49  function perform_action($action, $theme_id)
50  {
51    global $conf;
52
53    if (isset($this->db_themes_by_id[$theme_id]))
54    {
55      $crt_db_theme = $this->db_themes_by_id[$theme_id];
56    }
57
58    $file_to_include = PHPWG_THEMES_PATH.'/'.$theme_id.'/admin/maintain.inc.php';
59
60    $errors = array();
61
62    switch ($action)
63    {
64      case 'activate':
65        if (isset($crt_db_theme))
66        {
67          // the theme is already active
68          break;
69        }
70
71        if ('default' == $theme_id)
72        {
73          // you can't activate the "default" theme
74          break;
75        }
76
77        $missing_parent = $this->missing_parent_theme($theme_id);
78        if (isset($missing_parent))
79        {
80          $errors[] = l10n(
81            'Impossible to activate this theme, the parent theme is missing: %s',
82            $missing_parent
83            );
84
85          break;
86        }
87
88
89        if ($this->fs_themes[$theme_id]['mobile']
90            and !empty($conf['mobile_theme'])
91            and $conf['mobile_theme'] != $theme_id)
92        {
93          $errors[] = l10n('You can activate only one mobile theme.');
94          break;
95        }
96
97        if (file_exists($file_to_include))
98        {
99          include($file_to_include);
100          if (function_exists('theme_activate'))
101          {
102            theme_activate($theme_id, $this->fs_themes[$theme_id]['version'], $errors);
103          }
104        }
105
106        if (empty($errors))
107        {
108          $query = '
109INSERT INTO '.THEMES_TABLE.'
110  (id, version, name)
111  VALUES(\''.$theme_id.'\',
112         \''.$this->fs_themes[$theme_id]['version'].'\',
113         \''.$this->fs_themes[$theme_id]['name'].'\')
114;';
115          pwg_query($query);
116
117          if ($this->fs_themes[$theme_id]['mobile'])
118          {
119            conf_update_param('mobile_theme', $theme_id);
120          }
121        }
122        break;
123
124      case 'deactivate':
125        if (!isset($crt_db_theme))
126        {
127          // the theme is already inactive
128          break;
129        }
130
131        // you can't deactivate the last theme
132        if (count($this->db_themes_by_id) <= 1)
133        {
134          $errors[] = l10n('Impossible to deactivate this theme, you need at least one theme.');
135          break;
136        }
137
138        if ($theme_id == get_default_theme())
139        {
140          // find a random theme to replace
141          $new_theme = null;
142
143          $query = '
144SELECT
145    id
146  FROM '.THEMES_TABLE.'
147  WHERE id != \''.$theme_id.'\'
148;';
149          $result = pwg_query($query);
150          if (pwg_db_num_rows($result) == 0)
151          {
152            $new_theme = 'default';
153          }
154          else
155          {
156            list($new_theme) = pwg_db_fetch_row($result);
157          }
158
159          $this->set_default_theme($new_theme);
160        }
161
162        if (file_exists($file_to_include))
163        {
164          include($file_to_include);
165          if (function_exists('theme_deactivate'))
166          {
167            theme_deactivate($theme_id);
168          }
169        }
170
171        $query = '
172DELETE
173  FROM '.THEMES_TABLE.'
174  WHERE id= \''.$theme_id.'\'
175;';
176        pwg_query($query);
177
178        if ($this->fs_themes[$theme_id]['mobile'])
179        {
180          conf_update_param('mobile_theme', '');
181        }
182        break;
183
184      case 'delete':
185        if (!empty($crt_db_theme))
186        {
187          $errors[] = 'CANNOT DELETE - THEME IS INSTALLED';
188          break;
189        }
190        if (!isset($this->fs_themes[$theme_id]))
191        {
192          // nothing to do here
193          break;
194        }
195
196        $children = $this->get_children_themes($theme_id);
197        if (count($children) > 0)
198        {
199          $errors[] = l10n(
200            'Impossible to delete this theme. Other themes depends on it: %s',
201            implode(', ', $children)
202            );
203          break;
204        }
205
206        if (file_exists($file_to_include))
207        {
208          include($file_to_include);
209          if (function_exists('theme_delete'))
210          {
211            theme_delete($theme_id);
212          }
213        }
214
215        deltree(PHPWG_THEMES_PATH.$theme_id, PHPWG_THEMES_PATH . 'trash');
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        $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      $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            'mobile' => false,
347            );
348          $theme_data = implode( '', file($path.'/themeconf.inc.php') );
349
350          if ( preg_match("|Theme Name: (.*)|", $theme_data, $val) )
351          {
352            $theme['name'] = trim( $val[1] );
353          }
354          if (preg_match("|Version: (.*)|", $theme_data, $val))
355          {
356            $theme['version'] = trim($val[1]);
357          }
358          if ( preg_match("|Theme URI: (.*)|", $theme_data, $val) )
359          {
360            $theme['uri'] = trim($val[1]);
361          }
362          if ($desc = load_language('description.txt', $path.'/', array('return' => true)))
363          {
364            $theme['description'] = trim($desc);
365          }
366          elseif ( preg_match("|Description: (.*)|", $theme_data, $val) )
367          {
368            $theme['description'] = trim($val[1]);
369          }
370          if ( preg_match("|Author: (.*)|", $theme_data, $val) )
371          {
372            $theme['author'] = trim($val[1]);
373          }
374          if ( preg_match("|Author URI: (.*)|", $theme_data, $val) )
375          {
376            $theme['author uri'] = trim($val[1]);
377          }
378          if (!empty($theme['uri']) and strpos($theme['uri'] , 'extension_view.php?eid='))
379          {
380            list( , $extension) = explode('extension_view.php?eid=', $theme['uri']);
381            if (is_numeric($extension)) $theme['extension'] = $extension;
382          }
383          if (preg_match('/["\']parent["\'][^"\']+["\']([^"\']+)["\']/', $theme_data, $val))
384          {
385            $theme['parent'] = $val[1];
386          }
387          if (preg_match('/["\']activable["\'].*?(true|false)/i', $theme_data, $val))
388          {
389            $theme['activable'] = get_boolean($val[1]);
390          }
391          if (preg_match('/["\']mobile["\'].*?(true|false)/i', $theme_data, $val))
392          {
393            $theme['mobile'] = get_boolean($val[1]);
394          }
395
396          // screenshot
397          $screenshot_path = $path.'/screenshot.png';
398          if (file_exists($screenshot_path))
399          {
400            $theme['screenshot'] = $screenshot_path;
401          }
402          else
403          {
404            global $conf;
405            $theme['screenshot'] =
406              PHPWG_ROOT_PATH.'admin/themes/'
407              .$conf['admin_theme']
408              .'/images/missing_screenshot.png'
409              ;
410          }
411
412          $admin_file = $path.'/admin/admin.inc.php';
413          if (file_exists($admin_file))
414          {
415            $theme['admin_uri'] = get_root_url().'admin.php?page=theme&theme='.$file;
416          }
417
418          // IMPORTANT SECURITY !
419          $theme = array_map('htmlspecialchars', $theme);
420          $this->fs_themes[$file] = $theme;
421        }
422      }
423    }
424    closedir($dir);
425  }
426
427  /**
428   * Sort fs_themes
429   */
430  function sort_fs_themes($order='name')
431  {
432    switch ($order)
433    {
434      case 'name':
435        uasort($this->fs_themes, 'name_compare');
436        break;
437      case 'status':
438        $this->sort_themes_by_state();
439        break;
440      case 'author':
441        uasort($this->fs_themes, array($this, 'theme_author_compare'));
442        break;
443      case 'id':
444        uksort($this->fs_themes, 'strcasecmp');
445        break;
446    }
447  }
448
449  /**
450   * Retrieve PEM server datas to $server_themes
451   */
452  function get_server_themes($new=false)
453  {
454    global $user, $conf;
455
456    $get_data = array(
457      'category_id' => $conf['pem_themes_category'],
458      'format' => 'php',
459    );
460
461    // Retrieve PEM versions
462    $version = PHPWG_VERSION;
463    $versions_to_check = array();
464    $url = PEM_URL . '/api/get_version_list.php';
465    if (fetchRemote($url, $result, $get_data) and $pem_versions = @unserialize($result))
466    {
467      if (!preg_match('/^\d+\.\d+\.\d+$/', $version))
468      {
469        $version = $pem_versions[0]['name'];
470      }
471      $branch = get_branch_from_version($version);
472      foreach ($pem_versions as $pem_version)
473      {
474        if (strpos($pem_version['name'], $branch) === 0)
475        {
476          $versions_to_check[] = $pem_version['id'];
477        }
478      }
479    }
480    if (empty($versions_to_check))
481    {
482      return false;
483    }
484
485    // Themes to check
486    $themes_to_check = array();
487    foreach($this->fs_themes as $fs_theme)
488    {
489      if (isset($fs_theme['extension']))
490      {
491        $themes_to_check[] = $fs_theme['extension'];
492      }
493    }
494
495    // Retrieve PEM themes infos
496    $url = PEM_URL . '/api/get_revision_list.php';
497    $get_data = array_merge($get_data, array(
498      'last_revision_only' => 'true',
499      'version' => implode(',', $versions_to_check),
500      'lang' => substr($user['language'], 0, 2),
501      'get_nb_downloads' => 'true',
502      )
503    );
504
505    if (!empty($themes_to_check))
506    {
507      if ($new)
508      {
509        $get_data['extension_exclude'] = implode(',', $themes_to_check);
510      }
511      else
512      {
513        $get_data['extension_include'] = implode(',', $themes_to_check);
514      }
515    }
516    if (fetchRemote($url, $result, $get_data))
517    {
518      $pem_themes = @unserialize($result);
519      if (!is_array($pem_themes))
520      {
521        return false;
522      }
523      foreach ($pem_themes as $theme)
524      {
525        $this->server_themes[$theme['extension_id']] = $theme;
526      }
527      return true;
528    }
529    return false;
530  }
531
532  /**
533   * Sort $server_themes
534   */
535  function sort_server_themes($order='date')
536  {
537    switch ($order)
538    {
539      case 'date':
540        krsort($this->server_themes);
541        break;
542      case 'revision':
543        usort($this->server_themes, array($this, 'extension_revision_compare'));
544        break;
545      case 'name':
546        uasort($this->server_themes, array($this, 'extension_name_compare'));
547        break;
548      case 'author':
549        uasort($this->server_themes, array($this, 'extension_author_compare'));
550        break;
551      case 'downloads':
552        usort($this->server_themes, array($this, 'extension_downloads_compare'));
553        break;
554    }
555  }
556
557  /**
558   * Extract theme files from archive
559   *
560   * @param string - install or upgrade
561   * @param string - remote revision identifier (numeric)
562   * @param string - theme id or extension id
563   */
564  function extract_theme_files($action, $revision, $dest)
565  {
566    if ($archive = tempnam( PHPWG_THEMES_PATH, 'zip'))
567    {
568      $url = PEM_URL . '/download.php';
569      $get_data = array(
570        'rid' => $revision,
571        'origin' => 'piwigo_'.$action,
572      );
573
574      if ($handle = @fopen($archive, 'wb') and fetchRemote($url, $handle, $get_data))
575      {
576        fclose($handle);
577        include_once(PHPWG_ROOT_PATH.'admin/include/pclzip.lib.php');
578        $zip = new PclZip($archive);
579        if ($list = $zip->listContent())
580        {
581          foreach ($list as $file)
582          {
583            // we search main.inc.php in archive
584            if (basename($file['filename']) == 'themeconf.inc.php'
585              and (!isset($main_filepath)
586              or strlen($file['filename']) < strlen($main_filepath)))
587            {
588              $main_filepath = $file['filename'];
589            }
590          }
591          if (isset($main_filepath))
592          {
593            $root = dirname($main_filepath); // main.inc.php path in archive
594            if ($action == 'upgrade')
595            {
596              $extract_path = PHPWG_THEMES_PATH . $dest;
597            }
598            else
599            {
600              $extract_path = PHPWG_THEMES_PATH . ($root == '.' ? 'extension_' . $dest : basename($root));
601            }
602            if (
603              $result = $zip->extract(
604                PCLZIP_OPT_PATH, $extract_path,
605                PCLZIP_OPT_REMOVE_PATH, $root,
606                PCLZIP_OPT_REPLACE_NEWER
607                )
608              )
609            {
610              foreach ($result as $file)
611              {
612                if ($file['stored_filename'] == $main_filepath)
613                {
614                  $status = $file['status'];
615                  break;
616                }
617              }
618              if (file_exists($extract_path.'/obsolete.list')
619                and $old_files = file($extract_path.'/obsolete.list', FILE_IGNORE_NEW_LINES)
620                and !empty($old_files))
621              {
622                $old_files[] = 'obsolete.list';
623                foreach($old_files as $old_file)
624                {
625                  $path = $extract_path.'/'.$old_file;
626                  if (is_file($path))
627                  {
628                    @unlink($path);
629                  }
630                  elseif (is_dir($path))
631                  {
632                    deltree($path, PHPWG_THEMES_PATH . 'trash');
633                  }
634                }
635              }
636            }
637            else $status = 'extract_error';
638          }
639          else $status = 'archive_error';
640        }
641        else $status = 'archive_error';
642      }
643      else $status = 'dl_archive_error';
644    }
645    else $status = 'temp_path_error';
646
647    @unlink($archive);
648    return $status;
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}
719?>
Note: See TracBrowser for help on using the repository browser.