Index: /trunk/admin.php
===================================================================
--- /trunk/admin.php	(revision 5152)
+++ /trunk/admin.php	(revision 5153)
@@ -124,5 +124,5 @@
     'U_CONFIG_EXTENTS'=> $link_start.'extend_for_templates',
     'U_CONFIG_MENUBAR'=> $link_start.'menubar',
-    'U_CONFIG_THEMES'=> $link_start.'themes_new',
+    'U_CONFIG_THEMES'=> $link_start.'themes_installed',
     'U_CATEGORIES'=> $link_start.'cat_list',
     'U_MOVE'=> $link_start.'cat_move',
Index: /trunk/admin/include/plugins.class.php
===================================================================
--- /trunk/admin/include/plugins.class.php	(revision 5152)
+++ /trunk/admin/include/plugins.class.php	(revision 5153)
@@ -269,18 +269,12 @@
    * Retrieve PEM server datas to $server_plugins
    */
-  function get_server_plugins($new=false, $ext_type='plugin')
+  function get_server_plugins($new=false)
   {
     global $user;
-
-    $pem_category_id = 12;
-    if ('theme' == $ext_type)
-    {
-      $pem_category_id = 10;
-    }
 
     // Retrieve PEM versions
     $version = PHPWG_VERSION;
     $versions_to_check = array();
-    $url = PEM_URL . '/api/get_version_list.php?category_id='.$pem_category_id.'&format=php';
+    $url = PEM_URL . '/api/get_version_list.php?category_id=12&format=php';
     if (fetchRemote($url, $result) and $pem_versions = @unserialize($result))
     {
@@ -314,5 +308,5 @@
 
     // Retrieve PEM plugins infos
-    $url = PEM_URL . '/api/get_revision_list.php?category_id='.$pem_category_id.'&format=php&last_revision_only=true';
+    $url = PEM_URL . '/api/get_revision_list.php?category_id=12&format=php&last_revision_only=true';
     $url .= '&version=' . implode(',', $versions_to_check);
     $url .= '&lang=' . substr($user['language'], 0, 2);
@@ -371,22 +365,7 @@
     * @param string - plugin id or extension id
    */
-  function extract_plugin_files($action, $revision, $dest, $ext_type = 'plugin')
-  {
-    if ('plugin' == $ext_type)
-    {
-      $install_basedir = PHPWG_PLUGINS_PATH;
-      $main_filename = 'main.inc.php';
-    }
-    elseif ('theme' == $ext_type)
-    {
-      $install_basedir = PHPWG_ROOT_PATH.'themes/';
-      $main_filename = 'themeconf.inc.php';
-    }
-    else
-    {
-      fatal_error('unknown extension type "'.$ext_type.'"');
-    }
-    
-    if ($archive = tempnam( $install_basedir, 'zip'))
+  function extract_plugin_files($action, $revision, $dest)
+  {
+    if ($archive = tempnam( PHPWG_PLUGINS_PATH, 'zip'))
     {
       $url = PEM_URL . '/download.php?rid=' . $revision;
@@ -403,5 +382,5 @@
           {
             // we search main.inc.php in archive
-            if (basename($file['filename']) == $main_filename
+            if (basename($file['filename']) == 'main.inc.php'
               and (!isset($main_filepath)
               or strlen($file['filename']) < strlen($main_filepath)))
@@ -415,9 +394,9 @@
             if ($action == 'upgrade')
             {
-              $extract_path = $install_basedir . $dest;
+              $extract_path = PHPWG_PLUGINS_PATH . $dest;
             }
             else
             {
-              $extract_path = $install_basedir
+              $extract_path = PHPWG_PLUGINS_PATH
                   . ($root == '.' ? 'extension_' . $dest : basename($root));
             }
Index: /trunk/admin/include/themes.class.php
===================================================================
--- /trunk/admin/include/themes.class.php	(revision 5153)
+++ /trunk/admin/include/themes.class.php	(revision 5153)
@@ -0,0 +1,662 @@
+<?php
+// +-----------------------------------------------------------------------+
+// | Piwigo - a PHP based picture gallery                                  |
+// +-----------------------------------------------------------------------+
+// | Copyright(C) 2008-2009 Piwigo Team                  http://piwigo.org |
+// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
+// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
+// +-----------------------------------------------------------------------+
+// | This program is free software; you can redistribute it and/or modify  |
+// | it under the terms of the GNU General Public License as published by  |
+// | the Free Software Foundation                                          |
+// |                                                                       |
+// | This program is distributed in the hope that it will be useful, but   |
+// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
+// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
+// | General Public License for more details.                              |
+// |                                                                       |
+// | You should have received a copy of the GNU General Public License     |
+// | along with this program; if not, write to the Free Software           |
+// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
+// | USA.                                                                  |
+// +-----------------------------------------------------------------------+
+
+class themes
+{
+  var $fs_themes = array();
+  var $db_themes_by_id = array();
+  var $server_themes = array();
+
+  /**
+   * Initialize $fs_themes and $db_themes_by_id
+  */
+  function themes()
+  {
+    $this->get_fs_themes();
+
+    foreach ($this->get_db_themes() as $db_theme)
+    {
+      $this->db_themes_by_id[$db_theme['id']] = $db_theme;
+    }
+  }
+
+  /**
+   * Set tabsheet for themes pages.
+   * @param string selected page.
+   */
+  function set_tabsheet($selected)
+  {
+    include_once(PHPWG_ROOT_PATH.'admin/include/tabsheet.class.php');
+
+    $link = get_root_url().'admin.php?page=';
+
+    $tabsheet = new tabsheet();
+    $tabsheet->add('themes_installed', l10n('Installed Themes'), $link.'themes_installed');
+    $tabsheet->add('themes_new', l10n('Add New Theme'), $link.'themes_new');
+    $tabsheet->select($selected);
+    $tabsheet->assign();
+  }
+
+  /**
+   * Perform requested actions
+   * @param string - action
+   * @param string - theme id
+   * @param array - errors
+   */
+  function perform_action($action, $theme_id)
+  {
+    if (isset($this->db_themes_by_id[$theme_id]))
+    {
+      $crt_db_theme = $this->db_themes_by_id[$theme_id];
+    }
+
+    $errors = array();
+
+    switch ($action)
+    {
+      case 'activate':
+        if (isset($crt_db_theme))
+        {
+          // the theme is already active
+          break;
+        }
+        
+        $query = "
+INSERT INTO ".THEMES_TABLE."
+  SET id = '".$theme_id."'
+    , version = '".$this->fs_themes[$theme_id]['version']."'
+    , name = '".$this->fs_themes[$theme_id]['name']."'
+;";
+        pwg_query($query);
+        break;
+
+      case 'deactivate':
+        if (!isset($crt_db_theme))
+        {
+          // the theme is already inactive
+          break;
+        }
+
+        if ($theme_id == get_default_theme())
+        {
+          // find a random theme to replace
+          $new_theme = null;
+
+          $query = '
+SELECT
+    id
+  FROM '.THEMES_TABLE.'
+  WHERE id != "'.$theme_id.'"
+;';
+          $result = pwg_query($query);
+          if (pwg_db_num_rows($result) == 0)
+          {
+            $new_theme = 'default';
+          }
+          else
+          {
+            list($new_theme) = pwg_db_fetch_row($result);
+          }
+
+          $this->set_default_theme($new_theme);
+        }
+        
+        $query = "
+DELETE
+  FROM ".THEMES_TABLE."
+  WHERE id= '".$theme_id."'
+;";
+        pwg_query($query);
+        break;
+
+      case 'delete':
+        if (!empty($crt_db_theme))
+        {
+          array_push($errors, 'CANNOT DELETE - THEME IS INSTALLED');
+          break;
+        }
+        if (!isset($this->fs_themes[$theme_id]))
+        {
+          // nothing to do here
+          break;
+        }
+        
+        if (!$this->deltree(PHPWG_THEMES_PATH.$theme_id))
+        {
+          $this->send_to_trash(PHPWG_THEMES_PATH.$theme_id);
+        }
+        break;
+
+      case 'set_default':
+        // first we need to know which users are using the current default theme
+        $this->set_default_theme($theme_id);        
+        break;
+    }
+    return $errors;
+  }
+
+  function set_default_theme($theme_id)
+  {
+    // first we need to know which users are using the current default theme
+    $default_theme = get_default_theme();
+    
+    $query = '
+SELECT
+    user_id
+  FROM '.USER_INFOS_TABLE.'
+  WHERE theme = "'.$default_theme.'"
+;';
+    $user_ids = array_from_query($query, 'user_id');
+
+    // $user_ids can't be empty, at least the default user has the default
+    // theme
+
+    $query = '
+UPDATE '.USER_INFOS_TABLE.'
+  SET theme = "'.$theme_id.'"
+  WHERE user_id IN ('.implode(',', $user_ids).')
+;';
+    pwg_query($query);
+  }
+
+  function get_db_themes($id='')
+  {
+    $query = '
+SELECT
+    *
+  FROM '.THEMES_TABLE;
+    
+    $clauses = array();
+    if (!empty($id))
+    {
+      $clauses[] = "id = '".$id."'";
+    }
+    if (count($clauses) > 0)
+    {
+      $query .= '
+  WHERE '. implode(' AND ', $clauses);
+    }
+
+    $result = pwg_query($query);
+    $themes = array();
+    while ($row = pwg_db_fetch_assoc($result))
+    {
+      array_push($themes, $row);
+    }
+    return $themes;
+  }
+
+  
+  /**
+  *  Get themes defined in the theme directory
+  */  
+  function get_fs_themes()
+  {
+    $dir = opendir(PHPWG_THEMES_PATH);
+    
+    while ($file = readdir($dir))
+    {
+      if ($file!='.' and $file!='..')
+      {
+        $path = PHPWG_THEMES_PATH.$file;
+        if (is_dir($path)
+            and preg_match('/^[a-zA-Z0-9-_]+$/', $file)
+            and file_exists($path.'/themeconf.inc.php')
+            )
+        {
+          $theme = array(
+            'id' => $file,
+            'name' => $file,
+            'version' => '0',
+            'uri' => '',
+            'description' => '',
+            'author' => '',
+            );
+          $theme_data = implode( '', file($path.'/themeconf.inc.php') );
+
+          if ( preg_match("|Theme Name: (.*)|", $theme_data, $val) )
+          {
+            $theme['name'] = trim( $val[1] );
+          }
+          if (preg_match("|Version: (.*)|", $theme_data, $val))
+          {
+            $theme['version'] = trim($val[1]);
+          }
+          if ( preg_match("|Theme URI: (.*)|", $theme_data, $val) )
+          {
+            $theme['uri'] = trim($val[1]);
+          }
+          if ($desc = load_language('description.txt', $path.'/', array('return' => true)))
+          {
+            $theme['description'] = trim($desc);
+          }
+          elseif ( preg_match("|Description: (.*)|", $theme_data, $val) )
+          {
+            $theme['description'] = trim($val[1]);
+          }
+          if ( preg_match("|Author: (.*)|", $theme_data, $val) )
+          {
+            $theme['author'] = trim($val[1]);
+          }
+          if ( preg_match("|Author URI: (.*)|", $theme_data, $val) )
+          {
+            $theme['author uri'] = trim($val[1]);
+          }
+          if (!empty($theme['uri']) and strpos($theme['uri'] , 'extension_view.php?eid='))
+          {
+            list( , $extension) = explode('extension_view.php?eid=', $theme['uri']);
+            if (is_numeric($extension)) $theme['extension'] = $extension;
+          }
+
+          // screenshot
+          $screenshot_path = $path.'/screenshot.png';
+          if (file_exists($screenshot_path))
+          {
+            $theme['screenshot'] = $screenshot_path;
+          }
+          else
+          {
+            global $conf;
+            $theme['screenshot'] =
+              PHPWG_ROOT_PATH.'admin/themes/'
+              .$conf['admin_theme']
+              .'/images/missing_screenshot.png'
+              ;
+          }
+          
+          // IMPORTANT SECURITY !
+          $theme = array_map('htmlspecialchars', $theme);
+          $this->fs_themes[$file] = $theme;
+        }
+      }
+    }
+    closedir($dir);
+  }
+
+  /**
+   * Sort fs_themes
+   */
+  function sort_fs_themes($order='name')
+  {
+    switch ($order)
+    {
+      case 'name':
+        uasort($this->fs_themes, 'name_compare');
+        break;
+      case 'status':
+        $this->sort_themes_by_state();
+        break;
+      case 'author':
+        uasort($this->fs_themes, array($this, 'theme_author_compare'));
+        break;
+      case 'id':
+        uksort($this->fs_themes, 'strcasecmp');
+        break;
+    }
+  }
+
+  /**
+   * Retrieve PEM server datas to $server_themes
+   */
+  function get_server_themes($new=false)
+  {
+    global $user;
+
+    $pem_category_id = 10;
+
+    // Retrieve PEM versions
+    $version = PHPWG_VERSION;
+    $versions_to_check = array();
+    $url = PEM_URL . '/api/get_version_list.php?category_id='.$pem_category_id.'&format=php';
+    if (fetchRemote($url, $result) and $pem_versions = @unserialize($result))
+    {
+      if (!preg_match('/^\d+\.\d+\.\d+/', $version))
+      {
+        $version = $pem_versions[0]['name'];
+      }
+      $branch = substr($version, 0, strrpos($version, '.'));
+      foreach ($pem_versions as $pem_version)
+      {
+        if (strpos($pem_version['name'], $branch) === 0)
+        {
+          $versions_to_check[] = $pem_version['id'];
+        }
+      }
+    }
+    if (empty($versions_to_check))
+    {
+      return false;
+    }
+
+    // Themes to check
+    $themes_to_check = array();
+    foreach($this->fs_themes as $fs_theme)
+    {
+      if (isset($fs_theme['extension']))
+      {
+        $themes_to_check[] = $fs_theme['extension'];
+      }
+    }
+
+    // Retrieve PEM themes infos
+    $url = PEM_URL . '/api/get_revision_list.php?category_id='.$pem_category_id.'&format=php&last_revision_only=true';
+    $url .= '&version=' . implode(',', $versions_to_check);
+    $url .= '&lang=' . substr($user['language'], 0, 2);
+    $url .= '&get_nb_downloads=true';
+
+    if (!empty($themes_to_check))
+    {
+      $url .= $new ? '&extension_exclude=' : '&extension_include=';
+      $url .= implode(',', $themes_to_check);
+    }
+    if (fetchRemote($url, $result))
+    {
+      $pem_themes = @unserialize($result);
+      if (!is_array($pem_themes))
+      {
+        return false;
+      }
+      foreach ($pem_themes as $theme)
+      {
+        $this->server_themes[$theme['extension_id']] = $theme;
+      }
+      return true;
+    }
+    return false;
+  }
+  
+  /**
+   * Sort $server_themes
+   */
+  function sort_server_themes($order='date')
+  {
+    switch ($order)
+    {
+      case 'date':
+        krsort($this->server_themes);
+        break;
+      case 'revision':
+        usort($this->server_themes, array($this, 'extension_revision_compare'));
+        break;
+      case 'name':
+        uasort($this->server_themes, array($this, 'extension_name_compare'));
+        break;
+      case 'author':
+        uasort($this->server_themes, array($this, 'extension_author_compare'));
+        break;
+      case 'downloads':
+        usort($this->server_themes, array($this, 'extension_downloads_compare'));
+        break;
+    }
+  }
+
+  /**
+   * Extract theme files from archive
+   *
+   * @param string - install or upgrade
+   * @param string - remote revision identifier (numeric)
+   * @param string - theme id or extension id
+   */
+  function extract_theme_files($action, $revision, $dest)
+  {
+    if ($archive = tempnam( PHPWG_THEMES_PATH, 'zip'))
+    {
+      $url = PEM_URL . '/download.php?rid=' . $revision;
+      $url .= '&origin=piwigo_' . $action;
+
+      if ($handle = @fopen($archive, 'wb') and fetchRemote($url, $handle))
+      {
+        fclose($handle);
+        include(PHPWG_ROOT_PATH.'admin/include/pclzip.lib.php');
+        $zip = new PclZip($archive);
+        if ($list = $zip->listContent())
+        {
+          foreach ($list as $file)
+          {
+            // we search main.inc.php in archive
+            if (basename($file['filename']) == 'themeconf.inc.php'
+              and (!isset($main_filepath)
+              or strlen($file['filename']) < strlen($main_filepath)))
+            {
+              $main_filepath = $file['filename'];
+            }
+          }
+          if (isset($main_filepath))
+          {
+            $root = dirname($main_filepath); // main.inc.php path in archive
+            if ($action == 'upgrade')
+            {
+              $extract_path = PHPWG_THEMES_PATH . $dest;
+            }
+            else
+            {
+              $extract_path = PHPWG_THEMES_PATH . ($root == '.' ? 'extension_' . $dest : basename($root));
+            }
+            if (
+              $result = $zip->extract(
+                PCLZIP_OPT_PATH, $extract_path,
+                PCLZIP_OPT_REMOVE_PATH, $root,
+                PCLZIP_OPT_REPLACE_NEWER
+                )
+              )
+            {
+              foreach ($result as $file)
+              {
+                if ($file['stored_filename'] == $main_filepath)
+                {
+                  $status = $file['status'];
+                  break;
+                }
+              }
+              if (file_exists($extract_path.'/obsolete.list')
+                and $old_files = file($extract_path.'/obsolete.list', FILE_IGNORE_NEW_LINES)
+                and !empty($old_files))
+              {
+                array_push($old_files, 'obsolete.list');
+                foreach($old_files as $old_file)
+                {
+                  $path = $extract_path.'/'.$old_file;
+                  if (is_file($path))
+                  {
+                    @unlink($path);
+                  }
+                  elseif (is_dir($path))
+                  {
+                    if (!$this->deltree($path))
+                    {
+                      $this->send_to_trash($path);
+                    }
+                  }
+                }
+              }
+            }
+            else $status = 'extract_error';
+          }
+          else $status = 'archive_error';
+        }
+        else $status = 'archive_error';
+      }
+      else $status = 'dl_archive_error';
+    }
+    else $status = 'temp_path_error';
+
+    @unlink($archive);
+    return $status;
+  }
+  
+  /**
+   * delete $path directory
+   * @param string - path
+   */
+  function deltree($path)
+  {
+    if (is_dir($path))
+    {
+      $fh = opendir($path);
+      while ($file = readdir($fh))
+      {
+        if ($file != '.' and $file != '..')
+        {
+          $pathfile = $path . '/' . $file;
+          if (is_dir($pathfile))
+          {
+            $this->deltree($pathfile);
+          }
+          else
+          {
+            @unlink($pathfile);
+          }
+        }
+      }
+      closedir($fh);
+      return @rmdir($path);
+    }
+  }
+
+  /**
+   * send $path to trash directory
+   * @param string - path
+   */
+  function send_to_trash($path)
+  {
+    $trash_path = PHPWG_THEMES_PATH . 'trash';
+    if (!is_dir($trash_path))
+    {
+      @mkdir($trash_path);
+      $file = @fopen($trash_path . '/.htaccess', 'w');
+      @fwrite($file, 'deny from all');
+      @fclose($file);
+    }
+    while ($r = $trash_path . '/' . md5(uniqid(rand(), true)))
+    {
+      if (!is_dir($r))
+      {
+        @rename($path, $r);
+        break;
+      }
+    }
+  }
+
+  /**
+   * Sort functions
+   */
+  function theme_version_compare($a, $b)
+  {
+    $pattern = array('/([a-z])/ei', '/\.+/', '/\.\Z|\A\./');
+    $replacement = array( "'.'.intval('\\1', 36).'.'", '.', '');
+
+    $array = preg_replace($pattern, $replacement, array($a, $b));
+
+    return version_compare($array[0], $array[1], '>=');
+  }
+
+  function extension_revision_compare($a, $b)
+  {
+    if ($a['revision_date'] < $b['revision_date']) return 1;
+    else return -1;
+  }
+
+  function extension_name_compare($a, $b)
+  {
+    return strcmp(strtolower($a['extension_name']), strtolower($b['extension_name']));
+  }
+
+  function extension_author_compare($a, $b)
+  {
+    $r = strcasecmp($a['author_name'], $b['author_name']);
+    if ($r == 0) return $this->extension_name_compare($a, $b);
+    else return $r;
+  }
+
+  function theme_author_compare($a, $b)
+  {
+    $r = strcasecmp($a['author'], $b['author']);
+    if ($r == 0) return name_compare($a, $b);
+    else return $r;
+  }
+
+  function extension_downloads_compare($a, $b)
+  {
+    if ($a['extension_nb_downloads'] < $b['extension_nb_downloads']) return 1;
+    else return -1;
+  }
+
+  function sort_themes_by_state()
+  {
+    uasort($this->fs_themes, 'name_compare');
+
+    $active_themes = array();
+    $inactive_themes = array();
+    $not_installed = array();
+
+    foreach($this->fs_themes as $theme_id => $theme)
+    {
+      if (isset($this->db_themes_by_id[$theme_id]))
+      {
+        $this->db_themes_by_id[$theme_id]['state'] == 'active' ?
+          $active_themes[$theme_id] = $theme : $inactive_themes[$theme_id] = $theme;
+      }
+      else
+      {
+        $not_installed[$theme_id] = $theme;
+      }
+    }
+    $this->fs_themes = $active_themes + $inactive_themes + $not_installed;
+  }
+
+  // themes specific methods
+  function get_fs_themes_with_ini()
+  {
+    $themes_dir = PHPWG_ROOT_PATH.'themes';
+
+    $fs_themes = array();
+
+    foreach (get_dirs($themes_dir) as $theme)
+    {
+      $conf_file = $themes_dir.'/'.$theme.'/themeconf.inc.php';
+      if (file_exists($conf_file))
+      {
+        $theme_data = array(
+          'name' => $theme,
+          );
+        
+        $ini_file = $themes_dir.'/'.$theme.'/theme.ini';
+        if (file_exists($ini_file))
+        {
+          $theme_ini = parse_ini_file($ini_file);
+          if (isset($theme_ini['extension_id']))
+          {
+            $theme_data['extension_id'] = $theme_ini['extension_id'];
+          }
+        }
+
+        array_push($fs_themes, $theme_data);
+      }
+    }
+
+    echo '<pre>'; print_r($fs_themes); echo '</pre>';
+  }
+
+  
+}
+?>
Index: /trunk/admin/themes/default/default-layout.css
===================================================================
--- /trunk/admin/themes/default/default-layout.css	(revision 5152)
+++ /trunk/admin/themes/default/default-layout.css	(revision 5153)
@@ -738,7 +738,12 @@
 }
 
-.themeBox {float:left; text-align:center; height:170px; background-color:#eee; margin:5px; -moz-border-radius:5px;}
+.themeBox {float:left; text-align:center; height:180px; background-color:#eee; margin:5px; -moz-border-radius:5px;}
 .themeBox IMG {border:1px solid white; margin:0 15px;}
 .themeName {font-size:1.1em; margin:5px 0;}
-.themeActions {margin:5px 0;}
-.themeActions A {display:block;}
+.themeActions {margin:5px 0; font-size:12px;}
+.themeActions A {}
+
+#themesContent .themeBox IMG {width:150px; height:120px;}
+#themesContent H3 {font-size:16px; text-align:left; border-bottom:1px solid #444; letter-spacing:1px; margin:5px;}
+
+.themeBoxes {min-height:300px;}
Index: /trunk/admin/themes/default/template/footer.tpl
===================================================================
--- /trunk/admin/themes/default/template/footer.tpl	(revision 5152)
+++ /trunk/admin/themes/default/template/footer.tpl	(revision 5153)
@@ -46,5 +46,5 @@
 <script type='text/javascript'>
   $(function() {
-    $('#pwgHead A, #footer A').tipTip({
+    $('#pwgHead A, #footer A, .themeActions A').tipTip({
         'delay' : 0,
         'fadeIn' : 200,
Index: /trunk/admin/themes/default/template/themes_installed.tpl
===================================================================
--- /trunk/admin/themes/default/template/themes_installed.tpl	(revision 5153)
+++ /trunk/admin/themes/default/template/themes_installed.tpl	(revision 5153)
@@ -0,0 +1,42 @@
+<div class="titrePage">
+  <h2>{'Installed Themes'|@translate}</h2>
+</div>
+
+<div id="themesContent">
+
+<h3>Active Themes</h3>
+{if isset($active_themes)}
+<div class="themeBoxes">
+{foreach from=$active_themes item=theme}
+  <div class="themeBox{if $theme.is_default} themeDefault{/if}">
+    <div class="themeName">{$theme.name}{if $theme.is_default} <em>(default)</em>{/if}</div>
+    <div class="themeShot"><img src="{$theme.screenshot}"></div>
+    <div class="themeActions">
+      <a href="{$deactivate_baseurl}{$theme.id}" title="{'Forbid this theme to users'|@translate}">{'Deactivate'|@translate}</a>
+{if not $theme.is_default}
+      | <a href="{$set_default_baseurl}{$theme.id}" title="{'Set as default theme for unregistered and new users'|@translate}">{'Default'|@translate}</a>
+{/if}
+    </div> <!-- themeActions -->
+  </div>
+{/foreach}
+</div> <!-- themeBoxes -->
+{/if}
+
+{if isset($inactive_themes)}
+<h3>Inactive Themes</h3>
+<div class="themeBoxes">
+{foreach from=$inactive_themes item=theme}
+  <div class="themeBox">
+    <div class="themeName">{$theme.name}</div>
+    <div class="themeShot"><img src="{$theme.screenshot}"></div>
+    <div class="themeActions">
+      <a href="{$activate_baseurl}{$theme.id}" title="{'Make this theme available to users'|@translate}">{'Activate'|@translate}</a>
+      | <a href="{$delete_baseurl}{$theme.id}" title="{'Delete this theme'|@translate}">{'Delete'|@translate}</a>
+    </div>
+    
+  </div>
+{/foreach}
+</div> <!-- themeBoxes -->
+{/if}
+
+</div> <!-- themesContent -->
Index: /trunk/admin/themes/default/template/themes_new.tpl
===================================================================
--- /trunk/admin/themes/default/template/themes_new.tpl	(revision 5152)
+++ /trunk/admin/themes/default/template/themes_new.tpl	(revision 5153)
@@ -1,15 +1,15 @@
 <div class="titrePage">
-  <h2>{'Install New Theme'|@translate}</h2>
+  <h2>{'Add New Theme'|@translate}</h2>
 </div>
 
 {if isset($themes)}
-<div id="themesBox">
+<div id="themeBoxes">
 {foreach from=$new_themes item=theme name=themes_loop}
   <div class="themeBox">
     <div class="themeName">{$theme.name}</div>
-    <div class="themeShot"><img src="{$theme.src}"></div>
-    <div class="themeActions"><a href="{$theme.install_url}">Install</a></div>
+    <div class="themeShot"><img src="{$theme.screenshot}"></div>
+    <div class="themeActions"><a href="{$theme.install_url}">{'Install'|@translate}</a></div>
   </div>
 {/foreach}
-</div> <!-- themesBox -->
+</div> <!-- themeBoxes -->
 {/if}
Index: /trunk/admin/themes/roma/theme.css
===================================================================
--- /trunk/admin/themes/roma/theme.css	(revision 5152)
+++ /trunk/admin/themes/roma/theme.css	(revision 5153)
@@ -223,2 +223,4 @@
 .themeName {color:white;}
 .themeActions A {border-bottom:none;}
+
+.themeDefault {background-color:#555;}
Index: /trunk/admin/themes_installed.php
===================================================================
--- /trunk/admin/themes_installed.php	(revision 5153)
+++ /trunk/admin/themes_installed.php	(revision 5153)
@@ -0,0 +1,112 @@
+<?php
+// +-----------------------------------------------------------------------+
+// | Piwigo - a PHP based picture gallery                                  |
+// +-----------------------------------------------------------------------+
+// | Copyright(C) 2008-2009 Piwigo Team                  http://piwigo.org |
+// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
+// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
+// +-----------------------------------------------------------------------+
+// | This program is free software; you can redistribute it and/or modify  |
+// | it under the terms of the GNU General Public License as published by  |
+// | the Free Software Foundation                                          |
+// |                                                                       |
+// | This program is distributed in the hope that it will be useful, but   |
+// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
+// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
+// | General Public License for more details.                              |
+// |                                                                       |
+// | You should have received a copy of the GNU General Public License     |
+// | along with this program; if not, write to the Free Software           |
+// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
+// | USA.                                                                  |
+// +-----------------------------------------------------------------------+
+
+if( !defined("PHPWG_ROOT_PATH") )
+{
+  die ("Hacking attempt!");
+}
+
+include_once(PHPWG_ROOT_PATH.'admin/include/themes.class.php');
+
+$base_url = get_root_url().'admin.php?page='.$page['page'];
+
+$themes = new themes();
+
+// +-----------------------------------------------------------------------+
+// |                          perform actions                              |
+// +-----------------------------------------------------------------------+
+
+if (isset($_GET['action']) and isset($_GET['theme']) and !is_adviser())
+{
+  $page['errors'] = $themes->perform_action($_GET['action'], $_GET['theme']);
+
+  if (empty($page['errors']))
+  {
+    if ($_GET['action'] == 'activate' or $_GET['action'] == 'deactivate')
+    {
+      $template->delete_compiled_templates();
+    }
+    redirect($base_url);
+  }
+}
+
+// +-----------------------------------------------------------------------+
+// |                     start template output                             |
+// +-----------------------------------------------------------------------+
+
+$themes->sort_fs_themes();
+
+$default_theme = get_default_theme();
+
+$db_themes = $themes->get_db_themes();
+$db_theme_ids = array();
+foreach ($db_themes as $db_theme)
+{
+  array_push($db_theme_ids, $db_theme['id']);
+}
+
+$active_themes = array();
+$inactive_themes = array();
+
+foreach($themes->fs_themes as $theme_id => $fs_theme)
+{
+  if ($theme_id == 'default')
+  {
+    continue;
+  }
+
+  if (in_array($theme_id, $db_theme_ids))
+  {
+    if ($theme_id == $default_theme)
+    {
+      $fs_theme['is_default'] = true;
+      array_unshift($active_themes, $fs_theme);
+    }
+    else
+    {
+      array_push($active_themes, $fs_theme);
+    }
+  }
+  else
+  {
+    array_push($inactive_themes, $fs_theme);
+  }
+}
+
+$template->assign(
+    array(
+      'activate_baseurl' => $base_url.'&action=activate&theme=',
+      'deactivate_baseurl' => $base_url.'&action=deactivate&theme=',
+      'set_default_baseurl' => $base_url.'&action=set_default&theme=',
+      'delete_baseurl' => $base_url.'&action=delete&theme=',
+
+      'active_themes' => $active_themes,
+      'inactive_themes' => $inactive_themes,
+    )
+  );
+
+
+$themes->set_tabsheet($page['page']);
+$template->set_filenames(array('themes' => 'themes_installed.tpl'));
+$template->assign_var_from_handle('ADMIN_CONTENT', 'themes');
+?>
Index: /trunk/admin/themes_new.php
===================================================================
--- /trunk/admin/themes_new.php	(revision 5152)
+++ /trunk/admin/themes_new.php	(revision 5153)
@@ -3,5 +3,5 @@
 // | Piwigo - a PHP based picture gallery                                  |
 // +-----------------------------------------------------------------------+
-// | Copyright(C) 2008-2009 Piwigo Team                  http://piwigo.org |
+// | Copyright(C) 2008-2010 Piwigo Team                  http://piwigo.org |
 // | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
 // | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
@@ -27,9 +27,10 @@
 }
 
-include_once(PHPWG_ROOT_PATH.'admin/include/plugins.class.php');
+include_once(PHPWG_ROOT_PATH.'admin/include/themes.class.php');
 
 $base_url = get_root_url().'admin.php?page='.$page['page'];
 
-$themes = new plugins();
+$themes = new themes();
+$themes->set_tabsheet('themes_new');
 
 // +-----------------------------------------------------------------------+
@@ -55,9 +56,8 @@
 if (isset($_GET['revision']) and isset($_GET['extension']) and !is_adviser())
 {
-  $install_status = $themes->extract_plugin_files(
+  $install_status = $themes->extract_theme_files(
     'install',
     $_GET['revision'],
-    $_GET['extension'],
-    'theme'
+    $_GET['extension']
     );
   
@@ -106,7 +106,7 @@
 $template->set_filenames(array('themes' => 'themes_new.tpl'));
 
-if ($themes->get_server_plugins(true, 'theme'))
+if ($themes->get_server_themes(true)) // only new themes
 {
-  foreach($themes->server_plugins as $theme)
+  foreach($themes->server_themes as $theme)
   {
     $url_auto_install = htmlentities($base_url)
@@ -119,5 +119,5 @@
       array(
         'name' => $theme['extension_name'],
-        'src' => PEM_URL.'/upload/extension-'.$theme['extension_id'].'/thumbnail.jpg',
+        'screenshot' => PEM_URL.'/upload/extension-'.$theme['extension_id'].'/thumbnail.jpg',
         'install_url' => $url_auto_install,
         )
Index: /trunk/include/config_default.inc.php
===================================================================
--- /trunk/include/config_default.inc.php	(revision 5152)
+++ /trunk/include/config_default.inc.php	(revision 5153)
@@ -769,3 +769,6 @@
 // where should the user be guided when there is no photo in his gallery yet?
 $conf['no_photo_yet_url'] = 'admin.php?page=photos_add';
+
+// directory with themes inside
+$conf['themes_dir'] = PHPWG_ROOT_PATH.'themes';
 ?>
Index: /trunk/include/constants.php
===================================================================
--- /trunk/include/constants.php	(revision 5152)
+++ /trunk/include/constants.php	(revision 5153)
@@ -25,5 +25,7 @@
 define('PHPWG_VERSION', 'Colibri');
 define('PHPWG_DEFAULT_LANGUAGE', 'en_UK');
-define('PHPWG_DEFAULT_TEMPLATE', 'yoga/Sylvia');
+define('PHPWG_DEFAULT_TEMPLATE', 'Sylvia');
+
+define('PHPWG_THEMES_PATH', $conf['themes_dir'].'/');
 
 // Required versions
@@ -98,4 +100,6 @@
 if (!defined('OLD_PERMALINKS_TABLE'))
   define('OLD_PERMALINKS_TABLE', $prefixeTable.'old_permalinks');
+if (!defined('THEMES_TABLE'))
+  define('THEMES_TABLE', $prefixeTable.'themes');
 
 ?>
Index: /trunk/include/functions.inc.php
===================================================================
--- /trunk/include/functions.inc.php	(revision 5152)
+++ /trunk/include/functions.inc.php	(revision 5153)
@@ -714,19 +714,22 @@
 function get_pwg_themes()
 {
-  global $conf;
   $themes = array();
 
-  $template_dir = PHPWG_ROOT_PATH.'themes';
-
-  foreach (get_dirs($template_dir) as $theme)
-  {
-    if ( $theme != 'default' )
-	  {
-      array_push($themes, $theme);
-	  }
+  $query = '
+SELECT
+    id,
+    name
+  FROM '.THEMES_TABLE.'
+  ORDER BY name ASC
+;';
+  $result = pwg_query($query);
+  while ($row = pwg_db_fetch_assoc($result))
+  {
+    $themes[ $row['id'] ] = $row['name'];
   }
 
   // plugins want remove some themes based on user status maybe?
   $themes = trigger_event('get_pwg_themes', $themes);
+  
   return $themes;
 }
Index: /trunk/install/db/85-database.php
===================================================================
--- /trunk/install/db/85-database.php	(revision 5153)
+++ /trunk/install/db/85-database.php	(revision 5153)
@@ -0,0 +1,46 @@
+<?php
+// +-----------------------------------------------------------------------+
+// | Piwigo - a PHP based picture gallery                                  |
+// +-----------------------------------------------------------------------+
+// | Copyright(C) 2008-2009 Piwigo Team                  http://piwigo.org |
+// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
+// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
+// +-----------------------------------------------------------------------+
+// | This program is free software; you can redistribute it and/or modify  |
+// | it under the terms of the GNU General Public License as published by  |
+// | the Free Software Foundation                                          |
+// |                                                                       |
+// | This program is distributed in the hope that it will be useful, but   |
+// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
+// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
+// | General Public License for more details.                              |
+// |                                                                       |
+// | You should have received a copy of the GNU General Public License     |
+// | along with this program; if not, write to the Free Software           |
+// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
+// | USA.                                                                  |
+// +-----------------------------------------------------------------------+
+
+if (!defined('PHPWG_ROOT_PATH'))
+{
+  die('Hacking attempt!');
+}
+
+$upgrade_description = 'Add a table to manage themes.';
+
+$query = "
+CREATE TABLE ".PREFIX_TABLE."themes (
+  `id` varchar(64) NOT NULL default '',
+  `version` varchar(64) NOT NULL default '0',
+  `name` varchar(64) default NULL,
+  PRIMARY KEY  (`id`)
+)";
+
+pwg_query($query);
+
+echo
+"\n"
+. $upgrade_description
+."\n"
+;
+?>
Index: /trunk/install/piwigo_structure-mysql.sql
===================================================================
--- /trunk/install/piwigo_structure-mysql.sql	(revision 5152)
+++ /trunk/install/piwigo_structure-mysql.sql	(revision 5153)
@@ -294,4 +294,16 @@
 
 --
+-- Table structure for table `piwigo_themes`
+--
+
+DROP TABLE IF EXISTS `piwigo_themes`;
+CREATE TABLE `piwigo_themes` (
+  `id` varchar(64) NOT NULL default '',
+  `version` varchar(64) NOT NULL default '0',
+  `name` varchar(64) default NULL,
+  PRIMARY KEY  (`id`)
+) TYPE=MyISAM;
+
+--
 -- Table structure for table `piwigo_upgrade`
 --
Index: /trunk/profile.php
===================================================================
--- /trunk/profile.php	(revision 5152)
+++ /trunk/profile.php	(revision 5153)
@@ -258,13 +258,6 @@
       ));
 
-  foreach (get_pwg_themes() as $pwg_theme)
-  {
-    if (isset($_POST['submit']) or $userdata['theme'] == $pwg_theme)
-    {
-      $template->assign('template_selection', $pwg_theme);
-    }
-    $template_options[$pwg_theme] = $pwg_theme;
-  }
-  $template->assign('template_options', $template_options);
+  $template->assign('template_selection', $userdata['theme']);
+  $template->assign('template_options', get_pwg_themes());
 
   foreach (get_languages() as $language_code => $language_name)
