Index: trunk/category.php
===================================================================
--- trunk/category.php	(revision 1035)
+++ trunk/category.php	(revision 1036)
@@ -42,21 +42,18 @@
   redirect( $url );
 }
-//-------------------------------------------------- access authorization check
-if (isset($_GET['cat']))
-{
-  check_cat_id($_GET['cat']);
-}
-check_login_authorization();
-if (isset($page['cat']) and is_numeric($page['cat']))
-{
-  check_restrictions($page['cat']);
-}
-//----------------------------------------------- change of image dispaly order 
-if ( isset($_GET['image_order']) )
-{
-  setcookie( 'pwg_image_order', 
-    $_GET['image_order']>0 ? $_GET['image_order'] : '', 0 );
-  redirect( PHPWG_ROOT_PATH.'category.php'.
-    get_query_string_diff(array('image_order')) );
+//---------------------------------------------- change of image display order 
+if (isset($_GET['image_order']))
+{
+  setcookie(
+    'pwg_image_order', 
+    $_GET['image_order'] > 0 ? $_GET['image_order'] : '',
+    0
+    );
+  
+  redirect(
+    PHPWG_ROOT_PATH
+    .'category.php'
+    .get_query_string_diff(array('image_order'))
+    );
 }
 //-------------------------------------------------------------- initialization
@@ -73,18 +70,49 @@
 }
 
-initialize_category();
+include(PHPWG_ROOT_PATH.'include/section_init.inc.php');
+
+// access authorization check
+if (isset($page['cat']) and is_numeric($page['cat']))
+{
+  check_restrictions($page['cat']);
+}
+
+if (isset($page['cat'])
+    and $page['cat_nb_images'] > $user['nb_image_page'])
+{
+  // $nav_url is used to create the navigation bar
+  $nav_url = PHPWG_ROOT_PATH.'category.php?cat='.$page['cat'];
+
+  switch ($page['cat'])
+  {
+    case 'search':
+    {
+      $nav_url.= '&amp;search='.$_GET['search'];
+      break;
+    }
+    case 'list':
+    {
+      $nav_url.= '&amp;list='.$_GET['list'];
+      break;
+    }
+  }
+  
+  $page['navigation_bar'] = create_navigation_bar(
+    $nav_url,
+    $page['cat_nb_images'],
+    $page['start'],
+    $user['nb_image_page'],
+    'back'
+    );
+}
+else
+{
+  $page['navigation_bar'] = '';
+}
 
 // caddie filling :-)
 if (isset($_GET['caddie']))
 {
-//  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
-  
-  $query = '
-SELECT DISTINCT(id)
-  FROM '.IMAGES_TABLE.' AS i
-    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
-  '.$page['where'].'
-;';
-  fill_caddie(array_from_query($query, 'id'));
+  fill_caddie($page['items']);
 }
 
@@ -325,40 +353,5 @@
 
 //------------------------------------------------------ main part : thumbnails
-if (isset($page['cat'])
-    and ((is_numeric($page['cat']) and $page['cat_nb_images'] != 0)
-         or in_array($page['cat'],
-                     array('search'
-                           ,'most_visited'
-                           ,'recent_pics'
-                           ,'best_rated'
-                           ,'list'
-                           ,'fav'
-                       ))))
-{
-  include(PHPWG_ROOT_PATH.'include/category_default.inc.php');
-
-  if ('admin' == $user['status'])
-  {
-    $template->assign_block_vars(
-      'caddie',
-      array(
-        'URL' =>
-            PHPWG_ROOT_PATH.'category.php'
-            .get_query_string_diff(array('caddie')).'&amp;caddie=1')
-      );
-  }
-}
-elseif (isset($page['cat']) and $page['cat'] == 'calendar')
-{
-  include(PHPWG_ROOT_PATH.'include/category_calendar.inc.php');
-}
-elseif (isset($page['cat']) and $page['cat'] == 'recent_cats')
-{
-  include(PHPWG_ROOT_PATH.'include/category_recent_cats.inc.php');
-}
-else
-{
-  include(PHPWG_ROOT_PATH.'include/category_subcats.inc.php');
-}
+include(PHPWG_ROOT_PATH.$page['thumbnails_include']);
 //------------------------------------------------------- category informations
 if ( isset ( $page['cat'] ) )
Index: trunk/include/category_default.inc.php
===================================================================
--- trunk/include/category_default.inc.php	(revision 1035)
+++ trunk/include/category_default.inc.php	(revision 1036)
@@ -32,24 +32,34 @@
  */
 
-/**
- * $array_cat_directories is a cache hash associating category id with their
- * complete directory
- */
-$array_cat_directories = array();
-  
-$query = '
-SELECT DISTINCT(id),path,file,date_available
-       ,tn_ext,name,filesize,storage_category_id,average_rate,hit
-  FROM '.IMAGES_TABLE.' AS i
-    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id=ic.image_id
-  '.$page['where'].'
-  '.$conf['order_by'].'
-  LIMIT '.$page['start'].','.$page['nb_image_page'].'
+$page['rank_of'] = array_flip($page['items']);
+
+$pictures = array();
+
+$selection = array_slice(
+  $page['items'],
+  $page['start'],
+  $page['nb_image_page']
+  );
+
+if (count($selection) > 0)
+{
+  $query = '
+SELECT *
+  FROM '.IMAGES_TABLE.'
+  WHERE id IN ('.implode(',', $selection).')
 ;';
-//echo '<pre>'.$query.'</pre>';
-$result = pwg_query($query);
+  $result = pwg_query($query);
+  while ($row = mysql_fetch_array($result))
+  {
+    $row['rank'] = $page['rank_of'][ $row['id'] ];
+    
+    array_push($pictures, $row);
+  }
+
+  usort($pictures, 'rank_compare');
+}
 
 // template thumbnail initialization
-if ( mysql_num_rows($result) > 0 )
+if (count($pictures) > 0)
 {
   $template->assign_block_vars('thumbnails', array());
@@ -60,5 +70,5 @@
 }
 
-while ($row = mysql_fetch_array($result))
+foreach ($pictures as $row)
 {
   $thumbnail_url = get_thumbnail_src($row['path'], @$row['tn_ext']);
@@ -151,3 +161,5 @@
   }
 }
+
+pwg_debug('end include/category_default.inc.php');
 ?>
Index: trunk/include/common.inc.php
===================================================================
--- trunk/include/common.inc.php	(revision 1035)
+++ trunk/include/common.inc.php	(revision 1036)
@@ -199,4 +199,17 @@
 }
 
+if ($conf['gallery_locked'])
+{
+  echo
+    '<div style="text-align:center;">'
+    .$lang['gallery_locked_message']
+    .'</div>';
+
+  if ($user['status'] != 'admin')
+  {
+    exit();
+  }
+}
+
 // only now we can set the localized username of the guest user (and not in
 // include/user.inc.php)
@@ -210,5 +223,10 @@
 // TODO : replace initial $user['template'] by $user['layout']
 
-include(PHPWG_ROOT_PATH.'template/'.$user['template'].'/theme/'.$user['theme'].'/themeconf.inc.php');
+include(
+  PHPWG_ROOT_PATH
+  .'template/'.$user['template']
+  .'/theme/'.$user['theme']
+  .'/themeconf.inc.php'
+  );
 
 // template instance
Index: trunk/include/functions_category.inc.php
===================================================================
--- trunk/include/functions_category.inc.php	(revision 1035)
+++ trunk/include/functions_category.inc.php	(revision 1036)
@@ -54,69 +54,4 @@
 }
 
-/**
- * Checks whether the argument is a right parameter category id
- *
- * The argument is a right parameter if corresponds to one of these :
- *
- *  - is numeric and corresponds to a category in the database
- *  - equals 'fav' (for favorites)
- *  - equals 'search' (when the result of a search is displayed)
- *  - equals 'most_visited'
- *  - equals 'best_rated'
- *  - equals 'recent_pics'
- *  - equals 'recent_cats'
- *  - equals 'calendar'
- *  - equals 'list'
- *
- * The function fills the global var $page['cat'] and returns nothing
- *
- * @param mixed category id or special category name
- * @return void
- */
-function check_cat_id( $cat )
-{
-  global $page;
-
-  unset( $page['cat'] );
-  if ( isset( $cat ) )
-  {
-    if ( isset( $page['plain_structure'][$cat] ) )
-    {
-      $page['cat'] = $cat;
-    }
-    else if ( is_numeric( $cat ) )
-    {
-      $query = 'SELECT id';
-      $query.= ' FROM '.CATEGORIES_TABLE.' WHERE id = '.$cat.';';
-      $result = pwg_query( $query );
-      if ( mysql_num_rows( $result ) != 0 )
-      {
-        $page['cat'] = $cat;
-      }
-    }
-    if ( $cat == 'fav'
-         or $cat == 'most_visited'
-         or $cat == 'best_rated'
-         or $cat == 'recent_pics'
-         or $cat == 'recent_cats'
-         or $cat == 'calendar' )
-    {
-      $page['cat'] = $cat;
-    }
-    if ($cat == 'search'
-        and isset($_GET['search'])
-        and is_numeric($_GET['search']))
-    {
-      $page['cat'] = $cat;
-    }
-    if ($cat == 'list'
-        and isset($_GET['list'])
-        and preg_match('/^\d+(,\d+)*$/', $_GET['list']))
-    {
-      $page['cat'] = 'list';
-    }
-  }
-}
-
 function get_categories_menu()
 {
@@ -333,317 +268,4 @@
 }
 
-
-// initialize_category initializes ;-) the variables in relation
-// with category :
-// 1. calculation of the number of pictures in the category
-// 2. determination of the SQL query part to ask to find the right category
-//    $page['where'] is not the same if we are in
-//       - simple category
-//       - search result
-//       - favorites displaying
-//       - most visited pictures
-//       - best rated pictures
-//       - recent pictures
-//       - defined list (used for random)
-// 3. determination of the title of the page
-// 4. creation of the navigation bar
-function initialize_category( $calling_page = 'category' )
-{
-  pwg_debug( 'start initialize_category' );
-  global $page,$lang,$user,$conf;
-
-  if ( isset( $page['cat'] ) )
-  {
-    // $page['nb_image_page'] is the number of picture to display on this page
-    // By default, it is the same as the $user['nb_image_page']
-    $page['nb_image_page'] = $user['nb_image_page'];
-    // $url is used to create the navigation bar
-    $url = PHPWG_ROOT_PATH.'category.php?cat='.$page['cat'];
-    if ( isset($page['expand']) ) $url.= '&amp;expand='.$page['expand'];
-    // simple category
-    if ( is_numeric( $page['cat'] ) )
-    {
-      $result = get_cat_info( $page['cat'] );
-      $page['comment']        = $result['comment'];
-      $page['cat_dir']        = $result['dir'];
-      $page['cat_name']       = $result['name'];
-      $page['cat_nb_images']  = $result['nb_images'];
-      $page['cat_site_id']    = $result['site_id'];
-      $page['cat_uploadable'] = $result['uploadable'];
-      $page['cat_commentable'] = $result['commentable'];
-      $page['cat_id_uppercat'] = $result['id_uppercat'];
-      $page['uppercats']      = $result['uppercats'];
-      $page['title'] =
-        get_cat_display_name($page['cat_name'],
-                             '',
-                             false);
-      $page['where'] = ' WHERE category_id = '.$page['cat'];
-    }
-    else
-    {
-      if ($page['cat'] == 'search'
-          or $page['cat'] == 'most_visited'
-          or $page['cat'] == 'recent_pics'
-          or $page['cat'] == 'recent_cats'
-          or $page['cat'] == 'best_rated'
-          or $page['cat'] == 'calendar'
-          or $page['cat'] == 'list')
-      {
-        // we must not show pictures of a forbidden category
-        if ( $user['forbidden_categories'] != '' )
-        {
-          $forbidden = ' category_id NOT IN ';
-          $forbidden.= '('.$user['forbidden_categories'].')';
-        }
-      }
-      // search result
-      if ( $page['cat'] == 'search' )
-      {
-        $page['title'] = $lang['search_result'];
-        if ( $calling_page == 'picture' )
-        {
-          $page['title'].= ' : <span style="font-style:italic;">';
-          $page['title'].= $_GET['search']."</span>";
-        }
-
-        $page['where'] = 'WHERE '.get_sql_search_clause($_GET['search']);
-        
-        if (isset($forbidden))
-        {
-          $page['where'].= "\n    AND ".$forbidden;
-        }
-
-        $query = '
-SELECT COUNT(DISTINCT(id)) AS nb_total_images
-  FROM '.IMAGES_TABLE.'
-    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
-  '.$page['where'].'
-;';
-        $url.= '&amp;search='.$_GET['search'];
-      }
-      // favorites displaying
-      else if ( $page['cat'] == 'fav' )
-      {
-        check_user_favorites();
-        
-        $page['title'] = $lang['favorites'];
-
-        $page['where'] = ', '.FAVORITES_TABLE.' AS fav';
-        $page['where'].= ' WHERE user_id = '.$user['id'];
-        $page['where'].= ' AND fav.image_id = id';
-      
-        $query = 'SELECT COUNT(*) AS nb_total_images';
-        $query.= ' FROM '.FAVORITES_TABLE;
-        $query.= ' WHERE user_id = '.$user['id'];
-        $query.= ';';
-      }
-      // pictures within the short period
-      else if ( $page['cat'] == 'recent_pics' )
-      {
-        $page['title'] = $lang['recent_pics_cat'];
-        // We must find the date corresponding to :
-        // today - $conf['periode_courte']
-        $date = time() - 60*60*24*$user['recent_period'];
-        $page['where'] = " WHERE date_available > '";
-        $page['where'].= date( 'Y-m-d', $date )."'";
-        if ( isset( $forbidden ) ) $page['where'].= ' AND '.$forbidden;
-
-        $query = '
-SELECT COUNT(DISTINCT(id)) AS nb_total_images
-  FROM '.IMAGES_TABLE.' INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic
-    ON id = ic.image_id
-  '.$page['where'].'
-;';
-      }
-      // categories containing recent pictures
-      else if ( $page['cat'] == 'recent_cats' )
-      {
-        $page['title'] = $lang['recent_cats_cat'];
-        $page['cat_nb_images'] = 0;
-      }
-      // most visited pictures
-      else if ( $page['cat'] == 'most_visited' )
-      {
-        $page['title'] = $conf['top_number'].' '.$lang['most_visited_cat'];
-
-        $page['where'] = 'WHERE hit > 0';
-        if (isset($forbidden))
-        {
-          $page['where'] .= "\n".'    AND '.$forbidden;
-        }
-
-        $conf['order_by'] = ' ORDER BY hit DESC, file ASC';
-
-        // $page['cat_nb_images'] equals $conf['top_number'] unless there
-        // are less visited items
-        $query ='
-SELECT COUNT(DISTINCT(id)) AS count
-  FROM '.IMAGES_TABLE.'
-    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
-  '.$page['where'].'
-;';
-        $row = mysql_fetch_array(pwg_query($query));
-        if ($row['count'] < $conf['top_number'])
-        {
-          $page['cat_nb_images'] = $row['count'];
-        }
-        else
-        {
-          $page['cat_nb_images'] = $conf['top_number'];
-        }
-        unset($query);
-        
-        if ( isset( $page['start'] )
-             and ($page['start']+$user['nb_image_page']>=$conf['top_number']))
-        {
-          $page['nb_image_page'] = $conf['top_number'] - $page['start'];
-        }
-      }
-      else if ( $page['cat'] == 'calendar' )
-      {
-        $page['cat_nb_images'] = 0;
-        $page['title'] = $lang['calendar'];
-        if (isset($_GET['year'])
-            and preg_match('/^\d+$/', $_GET['year']))
-        {
-          $page['calendar_year'] = (int)$_GET['year'];
-        }
-        if (isset($_GET['month'])
-            and preg_match('/^(\d+)\.(\d{2})$/', $_GET['month'], $matches))
-        {
-          $page['calendar_year'] = (int)$matches[1];
-          $page['calendar_month'] = (int)$matches[2];
-        }
-        if (isset($_GET['day'])
-            and preg_match('/^(\d+)\.(\d{2})\.(\d{2})$/',
-                           $_GET['day'],
-                           $matches))
-        {
-          $page['calendar_year'] = (int)$matches[1];
-          $page['calendar_month'] = (int)$matches[2];
-          $page['calendar_day'] = (int)$matches[3];
-        }
-        if (isset($page['calendar_year']))
-        {
-          $page['title'] .= ' (';
-          if (isset($page['calendar_day']))
-          {
-            if ($page['calendar_year'] >= 1970)
-            {
-              $unixdate = mktime(0,0,0,
-                                 $page['calendar_month'],
-                                 $page['calendar_day'],
-                                 $page['calendar_year']);
-              $page['title'].= $lang['day'][date("w", $unixdate)];
-            }
-            $page['title'].= ' '.$page['calendar_day'].', ';
-          }
-          if (isset($page['calendar_month']))
-          {
-            $page['title'] .= $lang['month'][$page['calendar_month']].' ';
-          }
-          $page['title'] .= $page['calendar_year'];
-          $page['title'] .= ')';
-        }
-        
-        $page['where'] = 'WHERE '.$conf['calendar_datefield'].' IS NOT NULL';
-        if (isset($forbidden))
-        {
-          $page['where'].= ' AND '.$forbidden;
-        }
-      }
-      else if ($page['cat'] == 'best_rated')
-      {
-        $page['title'] = $conf['top_number'].' '.$lang['best_rated_cat'];
-
-        $page['where'] = ' WHERE average_rate IS NOT NULL';
-        
-        if (isset($forbidden))
-        {
-          $page['where'].= ' AND '.$forbidden;
-        }
-
-        $conf['order_by'] = ' ORDER BY average_rate DESC, id ASC';
-
-        // $page['cat_nb_images'] equals $conf['top_number'] unless there
-        // are less rated items
-        $query ='
-SELECT COUNT(DISTINCT(id)) AS count
-  FROM '.IMAGES_TABLE.'
-    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
-  '.$page['where'].'
-;';
-        $row = mysql_fetch_array(pwg_query($query));
-        if ($row['count'] < $conf['top_number'])
-        {
-          $page['cat_nb_images'] = $row['count'];
-        }
-        else
-        {
-          $page['cat_nb_images'] = $conf['top_number'];
-        }
-        unset($query);
-          
-
-        if (isset($page['start'])
-            and ($page['start']+$user['nb_image_page']>=$conf['top_number']))
-        {
-          $page['nb_image_page'] = $conf['top_number'] - $page['start'];
-        }
-      }
-      else if ($page['cat'] == 'list')
-      {
-        $page['title'] = $lang['random_cat'];
-          
-        $page['where'] = 'WHERE 1=1';
-        if (isset($forbidden))
-        {
-          $page['where'].= ' AND '.$forbidden;
-        }
-        $page['where'].= ' AND image_id IN ('.$_GET['list'].')';
-        $page['cat_nb_images'] = count(explode(',', $_GET['list']));
-
-        $url.= '&amp;list='.$_GET['list'];
-      }
-
-      if (isset($query))
-      {
-        $result = pwg_query( $query );
-        $row = mysql_fetch_array( $result );
-        $page['cat_nb_images'] = $row['nb_total_images'];
-      }
-    }
-    if ( $calling_page == 'category' )
-    {
-      $page['navigation_bar'] =
-        create_navigation_bar( $url, $page['cat_nb_images'], $page['start'],
-                               $user['nb_image_page'], 'back' );
-    }
-
-    if ($page['cat'] != 'most_visited' and $page['cat'] != 'best_rated')
-    {
-      $available_image_orders = get_category_preferred_image_orders();
-
-      $order_idx=0;
-      if ( isset($_COOKIE['pwg_image_order']) )
-      {
-        $order_idx = $_COOKIE['pwg_image_order'];
-      }
-
-      if ( $order_idx > 0 )
-      {
-        $order = $available_image_orders[$order_idx][1];
-        $conf['order_by'] = str_replace('ORDER BY ', 'ORDER BY '.$order.',', 
-                                          $conf['order_by'] );
-      }
-    }
-  }
-  else
-  {
-    $page['title'] = $lang['no_category'];
-  }
-  pwg_debug( 'end initialize_category' );
-}
-
 function display_select_categories($categories,
                                    $selecteds,
@@ -736,3 +358,13 @@
   return strnatcasecmp($a['global_rank'], $b['global_rank']);
 }
+
+function rank_compare($a, $b)
+{
+  if ($a['rank'] == $b['rank'])
+  {
+    return 0;
+  }
+
+  return ($a['rank'] < $b['rank']) ? -1 : 1;
+}
 ?>
Index: trunk/include/functions_html.inc.php
===================================================================
--- trunk/include/functions_html.inc.php	(revision 1035)
+++ trunk/include/functions_html.inc.php	(revision 1036)
@@ -350,5 +350,6 @@
   $level = 0;
   $menu = '';
-  
+
+  // $page_cat value remains 0 for special sections
   $page_cat = 0;
   if (isset($page['cat']) and is_numeric($page['cat']) )
@@ -384,5 +385,6 @@
     $url = PHPWG_ROOT_PATH.'category.php?cat='.$category['id'];
     $menu.= "\n".'<a href="'.$url.'"';
-    if ($category['id'] == $page['cat_id_uppercat'])
+    if ($page_cat != 0
+        and $category['id'] == $page['cat_id_uppercat'])
     {
       $menu.= ' rel="up"';
Index: trunk/include/functions_user.inc.php
===================================================================
--- trunk/include/functions_user.inc.php	(revision 1035)
+++ trunk/include/functions_user.inc.php	(revision 1036)
@@ -101,27 +101,4 @@
 }
 
-function check_login_authorization($guest_allowed = true)
-{
-  global $user,$lang,$conf,$template;
-
-  if ($user['is_the_guest'] and !$guest_allowed)
-  {
-    echo '<div style="text-align:center;">'.$lang['only_members'].'<br />';
-    echo '<a href="./identification.php">'.$lang['ident_title'].'</a></div>';
-    exit();
-  }
-
-  if ($conf['gallery_locked'])
-  {
-    echo '<div style="text-align:center;">';
-    echo $lang['gallery_locked_message'];
-    echo '</div>';
-    if ($user['status'] != 'admin')
-    {
-      exit();
-    }
-  }
-}
-
 function setup_style($style)
 {
Index: trunk/include/section_init.inc.php
===================================================================
--- trunk/include/section_init.inc.php	(revision 1036)
+++ trunk/include/section_init.inc.php	(revision 1036)
@@ -0,0 +1,400 @@
+<?php
+// +-----------------------------------------------------------------------+
+// | PhpWebGallery - a PHP based picture gallery                           |
+// | Copyright (C) 2002-2003 Pierrick LE GALL - pierrick@phpwebgallery.net |
+// | Copyright (C) 2003-2005 PhpWebGallery Team - http://phpwebgallery.net |
+// +-----------------------------------------------------------------------+
+// | branch        : BSF (Best So Far)
+// | file          : $RCSfile$
+// | last update   : $Date: 2006-01-27 02:11:43 +0100 (ven, 27 jan 2006) $
+// | last modifier : $Author: rvelices $
+// | revision      : $Revision: 1014 $
+// +-----------------------------------------------------------------------+
+// | 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.                                                                  |
+// +-----------------------------------------------------------------------+
+
+/**
+ * This included page checks section related parameter and provides
+ * following informations:
+ *
+ * - $page['title']
+ *
+ * - $page['items']: ordered list of items to display
+ *
+ * - $page['cat_nb_images']: number of items in the section (should be equal
+ * to count($page['items']))
+ *
+ * - $page['thumbnails_include']: include page managing thumbnails to
+ * display
+ */
+
+unset($page['cat']);
+
+if (isset($_GET['cat']))
+{
+  if (is_numeric($_GET['cat']))
+  {
+    $page['cat'] = $_GET['cat'];
+  }
+  else if ($_GET['cat'] == 'fav'
+           or $_GET['cat'] == 'most_visited'
+           or $_GET['cat'] == 'best_rated'
+           or $_GET['cat'] == 'recent_pics'
+           or $_GET['cat'] == 'recent_cats'
+           or $_GET['cat'] == 'calendar')
+  {
+    $page['cat'] = $_GET['cat'];
+  }
+  else if ($_GET['cat'] == 'search')
+  {
+    if (!isset($_GET['search']))
+    {
+      die('search GET parameter is missing');
+    }
+    else if (!is_numeric($_GET['search']))
+    {
+      die('wrong format on search GET parameter');
+    }
+    else
+    {
+      $page['cat'] = 'search';
+    }
+  }
+  else if ($_GET['cat'] == 'list')
+  {
+    if (!isset($_GET['list']))
+    {
+      die('list GET parameter is missing');
+    }
+    else if (!preg_match('/^\d+(,\d+)*$/', $_GET['list']))
+    {
+      die('wrong format on list GET parameter');
+    }
+    else
+    {
+      $page['cat'] = 'list';
+    }
+  }
+  else
+  {
+    die('unknown cat GET parameter value');
+  }
+}
+
+
+if (isset($page['cat']))
+{
+  // $page['nb_image_page'] is the number of picture to display on this page
+  // By default, it is the same as the $user['nb_image_page']
+  $page['nb_image_page'] = $user['nb_image_page'];
+
+  if ($page['cat'] != 'most_visited' and $page['cat'] != 'best_rated')
+  {
+    if (isset($_COOKIE['pwg_image_order'])
+        and is_numeric($_COOKIE['pwg_image_order'])
+        and $_COOKIE['pwg_image_order'] > 0)
+    {
+      $orders = get_category_preferred_image_orders();
+
+      $conf['order_by'] = str_replace(
+        'ORDER BY ',
+        'ORDER BY '.$orders[ $_COOKIE['pwg_image_order'] ][1].',', 
+        $conf['order_by']
+        );
+    }
+  }
+  
+// +-----------------------------------------------------------------------+
+// |                              category                                 |
+// +-----------------------------------------------------------------------+
+  if (is_numeric($page['cat']))
+  {
+    $query = '
+SELECT image_id
+  FROM '.IMAGE_CATEGORY_TABLE.'
+    INNER JOIN '.IMAGES_TABLE.' ON id = image_id
+  WHERE category_id = '.$page['cat'].'
+  '.$conf['order_by'].'
+;';
+
+    $result = get_cat_info($page['cat']);
+    
+    $page = array_merge(
+      $page,
+      array(
+        'comment'          => $result['comment'],
+        'cat_dir'          => $result['dir'],
+        'cat_name'         => $result['name'],
+        'cat_nb_images'    => $result['nb_images'],
+        'cat_site_id'      => $result['site_id'],
+        'cat_uploadable'   => $result['uploadable'],
+        'cat_commentable'  => $result['commentable'],
+        'cat_id_uppercat'  => $result['id_uppercat'],
+        'uppercats'        => $result['uppercats'],
+                
+        'title' => get_cat_display_name($result['name'], '', false),
+        'items' => array_from_query($query, 'image_id'),
+        'thumbnails_include' =>
+          $result['nb_images'] > 0
+          ? 'include/category_default.inc.php'
+          : 'include/category_subcats.inc.php',
+        )
+      );
+  }
+  // special section
+  else
+  {
+    if (!empty($user['forbidden_categories']))
+    {
+      $forbidden =
+        ' category_id NOT IN ('.$user['forbidden_categories'].')';
+    }
+    else
+    {
+      $forbidden = ' 1=1';
+    }
+          
+// +-----------------------------------------------------------------------+
+// |                           search section                              |
+// +-----------------------------------------------------------------------+
+    if ( $page['cat'] == 'search' )
+    {
+      $query = '
+SELECT DISTINCT(id)
+  FROM '.IMAGES_TABLE.'
+    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
+  WHERE '.get_sql_search_clause($_GET['search']).'
+    AND '.$forbidden.'
+  '.$conf['order_by'].'
+;';
+
+      $page = array_merge(
+        $page,
+        array(
+          'title' => $lang['search_result'],
+          'items' => array_from_query($query, 'id'),
+          'thumbnails_include' => 'include/category_default.inc.php',
+          )
+        );
+    }
+// +-----------------------------------------------------------------------+
+// |                           favorite section                            |
+// +-----------------------------------------------------------------------+
+    else if ($page['cat'] == 'fav')
+    {
+      check_user_favorites();
+
+      $query = '
+SELECT image_id
+  FROM '.FAVORITES_TABLE.'
+    INNER JOIN '.IMAGES_TABLE.' ON image_id = id
+  WHERE user_id = '.$user['id'].'
+  '.$conf['order_by'].'
+;';
+
+      $page = array_merge(
+        $page,
+        array(
+          'title' => $lang['favorites'],
+          'items' => array_from_query($query, 'id'),
+          'thumbnails_include' => 'include/category_default.inc.php',
+          )
+        );
+    }
+// +-----------------------------------------------------------------------+
+// |                       recent pictures section                         |
+// +-----------------------------------------------------------------------+
+    else if ($page['cat'] == 'recent_pics')
+    {
+      $query = '
+SELECT DISTINCT(id)
+  FROM '.IMAGES_TABLE.'
+    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
+  WHERE date_available > \''.
+        date('Y-m-d', time() - 60*60*24*$user['recent_period']).'\'
+    AND '.$forbidden.'
+  '.$conf['order_by'].'
+;';
+
+      $page = array_merge(
+        $page,
+        array(
+          'title' => $lang['recent_pics_cat'],
+          'items' => array_from_query($query, 'id'),
+          'thumbnails_include' => 'include/category_default.inc.php',
+          )
+        );
+    }
+// +-----------------------------------------------------------------------+
+// |                 recently updated categories section                   |
+// +-----------------------------------------------------------------------+
+    else if ($page['cat'] == 'recent_cats')
+    {
+      $page = array_merge(
+        $page,
+        array(
+          'title' => $lang['recent_cats_cat'],
+          'cat_nb_images' => 0,
+          'thumbnails_include' => 'include/category_recent_cats.inc.php',
+          )
+        );
+    }
+// +-----------------------------------------------------------------------+
+// |                        most visited section                           |
+// +-----------------------------------------------------------------------+
+    else if ($page['cat'] == 'most_visited')
+    {
+      $query = '
+SELECT DISTINCT(id)
+  FROM '.IMAGES_TABLE.'
+    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
+  WHERE hit > 0
+    AND '.$forbidden.'
+  ORDER BY hit DESC, file ASC
+  LIMIT 0, '.$conf['top_number'].'
+;';
+
+      $page = array_merge(
+        $page,
+        array(
+          'title' => $conf['top_number'].' '.$lang['most_visited_cat'],
+          'items' => array_from_query($query, 'id'),
+          'thumbnails_include' => 'include/category_default.inc.php',
+          )
+        );
+    }
+// +-----------------------------------------------------------------------+
+// |                           calendar section                            |
+// +-----------------------------------------------------------------------+
+    else if ($page['cat'] == 'calendar')
+    {
+      $page['cat_nb_images'] = 0;
+      $page['title'] = $lang['calendar'];
+      if (isset($_GET['year'])
+          and preg_match('/^\d+$/', $_GET['year']))
+      {
+        $page['calendar_year'] = (int)$_GET['year'];
+      }
+      if (isset($_GET['month'])
+          and preg_match('/^(\d+)\.(\d{2})$/', $_GET['month'], $matches))
+      {
+        $page['calendar_year'] = (int)$matches[1];
+        $page['calendar_month'] = (int)$matches[2];
+      }
+      if (isset($_GET['day'])
+          and preg_match('/^(\d+)\.(\d{2})\.(\d{2})$/',
+                         $_GET['day'],
+                         $matches))
+      {
+        $page['calendar_year'] = (int)$matches[1];
+        $page['calendar_month'] = (int)$matches[2];
+        $page['calendar_day'] = (int)$matches[3];
+      }
+      if (isset($page['calendar_year']))
+      {
+        $page['title'] .= ' (';
+        if (isset($page['calendar_day']))
+        {
+          if ($page['calendar_year'] >= 1970)
+          {
+            $unixdate = mktime(
+              0,
+              0,
+              0,
+              $page['calendar_month'],
+              $page['calendar_day'],
+              $page['calendar_year']
+              );
+            $page['title'].= $lang['day'][date("w", $unixdate)];
+          }
+          $page['title'].= ' '.$page['calendar_day'].', ';
+        }
+        if (isset($page['calendar_month']))
+        {
+          $page['title'] .= $lang['month'][$page['calendar_month']].' ';
+        }
+        $page['title'] .= $page['calendar_year'];
+        $page['title'] .= ')';
+      }
+        
+      $page['where'] = 'WHERE '.$conf['calendar_datefield'].' IS NOT NULL';
+      if (isset($forbidden))
+      {
+        $page['where'].= ' AND '.$forbidden;
+      }
+
+      $page['thumbnails_include'] = 'include/category_calendar.inc.php';
+    }
+// +-----------------------------------------------------------------------+
+// |                          best rated section                           |
+// +-----------------------------------------------------------------------+
+    else if ($page['cat'] == 'best_rated')
+    {
+      $query ='
+SELECT DISTINCT(id)
+  FROM '.IMAGES_TABLE.'
+    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
+  WHERE average_rate IS NOT NULL
+    AND '.$forbidden.'
+  ORDER BY average_rate DESC, id ASC
+  LIMIT 0, '.$conf['top_number'].'
+;';
+      $page = array_merge(
+        $page,
+        array(
+          'title' => $conf['top_number'].' '.$lang['best_rated_cat'],
+          'items' => array_from_query($query, 'id'),
+          'thumbnails_include' => 'include/category_default.inc.php',
+          )
+        );
+    }
+// +-----------------------------------------------------------------------+
+// |                             list section                              |
+// +-----------------------------------------------------------------------+
+    else if ($page['cat'] == 'list')
+    {
+      $query ='
+SELECT DISTINCT(id)
+  FROM '.IMAGES_TABLE.'
+    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
+  WHERE image_id IN ('.$_GET['list'].')
+    AND '.$forbidden.'
+  '.$conf['order_by'].'
+;';
+      $page = array_merge(
+        $page,
+        array(
+          'title' => $lang['random_cat'],
+          'items' => array_from_query($query, 'id'),
+          'thumbnails_include' => 'include/category_default.inc.php',
+          )
+        );
+    }
+
+    if (!isset($page['cat_nb_images']))
+    {
+      $page['cat_nb_images'] = count($page['items']);
+    }
+  }
+}
+// +-----------------------------------------------------------------------+
+// |                            root category                              |
+// +-----------------------------------------------------------------------+
+else
+{
+  $page['title'] = $lang['no_category'];
+  $page['thumbnails_include'] = 'include/category_subcats.inc.php';
+}
+?>
Index: trunk/include/user.inc.php
===================================================================
--- trunk/include/user.inc.php	(revision 1035)
+++ trunk/include/user.inc.php	(revision 1036)
@@ -60,6 +60,11 @@
 }
 
-$use_cache = (defined('IN_ADMIN') and IN_ADMIN) ? false : true;
-$user = array_merge($user, getuserdata($user['id'], $use_cache));
+$user = array_merge(
+  $user,
+  getuserdata(
+    $user['id'],
+    defined('IN_ADMIN') and IN_ADMIN ? false : true // use cache ?
+    )
+  );
 
 // properties of user guest are found in the configuration
Index: trunk/picture.php
===================================================================
--- trunk/picture.php	(revision 1035)
+++ trunk/picture.php	(revision 1036)
@@ -31,16 +31,73 @@
 include_once(PHPWG_ROOT_PATH.'include/common.inc.php');
 //-------------------------------------------------- access authorization check
-check_cat_id( $_GET['cat'] );
-
-if (!isset($page['cat']))
-{
-  die($lang['access_forbiden']);
-}
-
-check_login_authorization();
-if ( isset( $page['cat'] ) and is_numeric( $page['cat'] ) )
-{
-  check_restrictions( $page['cat'] );
-}
+if (isset($page['cat']) and is_numeric($page['cat']))
+{
+  check_restrictions($page['cat']);
+}
+//-------------------------------------------------------------- initialization
+include(PHPWG_ROOT_PATH.'include/section_init.inc.php');
+
+// if this image_id doesn't correspond to this category, an error message is
+// displayed, and execution is stopped
+if (!in_array($_GET['image_id'], $page['items']))
+{
+  echo '
+<div style="text-align:center;">'.$lang['access_forbiden'].'<br />
+  <a href="'.PHPWG_ROOT_PATH.'category.php'.'">'.$lang['thumbnails'].'</a>
+</div>';
+  exit();
+}
+
+$page['rank_of'] = array_flip($page['items']);
+
+// caching first_rank, last_rank, current_rank in the displayed
+// section. This should also help in readability.
+$page['first_rank']   = 0;
+$page['last_rank']    = count($page['items']) - 1;
+$page['current_rank'] = $page['rank_of'][ $_GET['image_id'] ];
+
+// caching current item : readability purpose
+$page['current_item'] = $_GET['image_id'];
+
+if ($page['current_rank'] != $page['first_rank'])
+{
+  // "go to first picture of this section" link is displayed only if the
+  // displayed item is not the first.
+  $template->assign_block_vars(
+    'first',
+    array(
+      'U_IMG' =>
+        PHPWG_ROOT_PATH.'picture.php'.
+        get_query_string_diff(
+          array('image_id', 'add_fav', 'slideshow', 'rate')
+          ).
+        '&amp;image_id='.$page['items'][ $page['first_rank'] ],
+      )
+    );
+
+  // caching previous item : readability purpose
+  $page['previous_item'] = $page['items'][ $page['current_rank'] - 1 ];
+}
+
+if ($page['current_rank'] != $page['last_rank'])
+{
+  // "go to last picture of this section" link is displayed only if the
+  // displayed item is not the last.
+  $template->assign_block_vars(
+    'last',
+    array(
+      'U_IMG' =>
+        PHPWG_ROOT_PATH.'picture.php'.
+        get_query_string_diff(
+          array('image_id', 'add_fav', 'slideshow', 'rate')
+          ).
+        '&amp;image_id='.$page['items'][ $page['last_rank'] ],
+      )
+    );
+
+  // caching next item : readability purpose
+  $page['next_item'] = $page['items'][ $page['current_rank'] + 1 ];
+}
+
 //---------------------------------------- incrementation of the number of hits
 if ( count(array_intersect(
@@ -56,62 +113,5 @@
   @pwg_query( $query );
 }
-//-------------------------------------------------------------- initialization
-initialize_category( 'picture' );
-// retrieving the number of the picture in its category (in order)
-$query = '
-SELECT DISTINCT(id)
-  FROM '.IMAGES_TABLE.'
-    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
-  '.$page['where'].'
-  '.$conf['order_by'].'
-;';
-$result = pwg_query( $query );
-$page['num'] = 0;
-$belongs = false;
-while ($row = mysql_fetch_array($result))
-{
-  if ($row['id'] == $_GET['image_id'])
-  {
-    $belongs = true;
-    break;
-  }
-  if ($page['num']==0)
-  {
-    $url_first_last = PHPWG_ROOT_PATH.'picture.php';
-    $url_first_last.= get_query_string_diff(array('image_id','add_fav',
-                                                    'slideshow','rate'));
-    $url_first_last.= '&amp;image_id=';
-    $template->assign_block_vars(
-      'first',
-      array(
-        'U_IMG' => $url_first_last . $row['id'],
-        ));
-  }
-  $page['num']++;
-}
-if ($page['cat_nb_images']>0 and $page['num'] < $page['cat_nb_images'] - 1)
-{
-  mysql_data_seek($result, $page['cat_nb_images'] - 1);
-  $row = mysql_fetch_array($result);
-  $url_first_last = PHPWG_ROOT_PATH.'picture.php';
-  $url_first_last.= get_query_string_diff(array('image_id','add_fav',
-                                                  'slideshow','rate'));
-  $url_first_last.= '&amp;image_id=';
-  $template->assign_block_vars(
-    'last',
-    array(
-      'U_IMG' => $url_first_last . $row['id'],
-      ));
-}
-
-// if this image_id doesn't correspond to this category, an error message is
-// displayed, and execution is stopped
-if (!$belongs)
-{
-  echo '<div style="text-align:center;">'.$lang['access_forbiden'].'<br />';
-  echo '<a href="'.PHPWG_ROOT_PATH.'category.php'.'">';
-  echo $lang['thumbnails'].'</a></div>';
-  exit();
-}
+
 //-------------------------------------------------------------- representative
 if ('admin' == $user['status'] and isset($_GET['representative']))
@@ -162,55 +162,37 @@
 $picture = array();
 
-if ($page['num'] == 0)
-{
-  $has_prev = false;
-}
-else
-{
-  $has_prev = true;
-}
-
-if ($page['num'] == $page['cat_nb_images'] - 1)
-{
-  $has_next = false;
-}
-else
-{
-  $has_next = true;
+$ids = array($_GET['image_id']);
+if (isset($page['previous_item']))
+{
+  array_push($ids, $page['previous_item']);
+}
+if (isset($page['next_item']))
+{
+  array_push($ids, $page['next_item']);
 }
 
 $query = '
-SELECT DISTINCT(i.id), i.*
-  FROM '.IMAGES_TABLE.' AS i
-    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON i.id = ic.image_id
-  '.$page['where'].'
-  '.$conf['order_by'].'
-  ';
-
-if ( !$has_prev )
-{
-  $query.= ' LIMIT 0,2';
-}
-else
-{
-  $query.= ' LIMIT '.($page['num'] - 1).',3';
-}
-$query.= ';';
-
-$result = pwg_query( $query );
-$indexes = array('prev', 'current', 'next');
-
-foreach (array('prev', 'current', 'next') as $i)
-{
-  if ($i == 'prev' and !$has_prev)
-  {
-    continue;
-  }
-  if ($i == 'next' and !$has_next)
-  {
-    break;
-  }
-
-  $row = mysql_fetch_array($result);
+SELECT *
+  FROM '.IMAGES_TABLE.'
+  WHERE id IN ('.implode(',', $ids).')
+;';
+
+$result = pwg_query($query);
+
+while ($row = mysql_fetch_array($result))
+{
+  if (isset($page['previous_item']) and $row['id'] == $page['previous_item'])
+  {
+    $i = 'prev';
+  }
+  else if (isset($page['next_item']) and $row['id'] == $page['next_item'])
+  {
+    $i = 'next';
+  }
+  else
+  {
+    $i = 'current';
+  }
+  
   foreach (array_keys($row) as $key)
   {
@@ -235,6 +217,7 @@
   if (isset($row['representative_ext']) and $row['representative_ext'] != '')
   {
-    $picture[$i]['src'] = $cat_directory.'/pwg_representative/';
-    $picture[$i]['src'].= $file_wo_ext.'.'.$row['representative_ext'];
+    $picture[$i]['src'] =
+      $cat_directory.'/pwg_representative/'
+      .$file_wo_ext.'.'.$row['representative_ext'];
   }
   else
@@ -275,12 +258,13 @@
   }
 
-  $picture[$i]['url'] = PHPWG_ROOT_PATH.'picture.php';
-  $picture[$i]['url'].= get_query_string_diff(array('image_id','add_fav',
-                                                    'slideshow','rate'));
-  $picture[$i]['url'].= '&amp;image_id='.$row['id'];
+  $picture[$i]['url'] =
+    PHPWG_ROOT_PATH.'picture.php'
+    .get_query_string_diff(array('image_id', 'add_fav', 'slideshow', 'rate'))
+    .'&amp;image_id='.$row['id'];
 }
 
 $url_up = PHPWG_ROOT_PATH.'category.php?cat='.$page['cat'];
-$url_up_start = floor( $page['num'] / $user['nb_image_page'] );
+
+$url_up_start = floor( $page['current_rank'] / $user['nb_image_page'] );
 $url_up_start *= $user['nb_image_page'];
 if ($url_up_start>0)
@@ -298,10 +282,11 @@
 }
 
-$url_admin = PHPWG_ROOT_PATH.'admin.php?page=picture_modify';
-$url_admin.= '&amp;cat_id='.$page['cat'];
-$url_admin.= '&amp;image_id='.$_GET['image_id'];
-
-$url_slide = $picture['current']['url'];
-$url_slide.= '&amp;slideshow='.$conf['slideshow_period'];
+$url_admin =
+  PHPWG_ROOT_PATH.'admin.php?page=picture_modify'
+  .'&amp;cat_id='.$page['cat']
+  .'&amp;image_id='.$_GET['image_id'];
+
+$url_slide =
+  $picture['current']['url'].'&amp;slideshow='.$conf['slideshow_period'];
 
 //----------------------------------------------------------- rate registration
@@ -485,5 +470,5 @@
 {
   $title_img = replace_space(get_cat_display_name($page['cat_name']));
-  $n = $page['num'] + 1;
+  $n = $page['current_rank'] + 1;
   $title_nb = $n.'/'.$page['cat_nb_images'];
 }
@@ -527,6 +512,6 @@
 
 $page['body_id'] = 'thePicturePage';
-//-------------------------------------------------------- navigation management
-if ($has_prev)
+//------------------------------------------------------- navigation management
+if (isset($page['previous_item']))
 {
   $template->assign_block_vars(
@@ -537,8 +522,9 @@
       'U_IMG' => $picture['prev']['url'],
       'U_IMG_SRC' => $picture['prev']['src']
-      ));
-}
-
-if ($has_next)
+      )
+    );
+}
+
+if (isset($page['next_item']))
 {
   $template->assign_block_vars(
@@ -549,5 +535,6 @@
       'U_IMG' => $picture['next']['url'],
       'U_IMG_SRC' => $picture['next']['src'] // allow navigator to preload
-      ));
+      )
+    );
 }
 
Index: trunk/profile.php
===================================================================
--- trunk/profile.php	(revision 1035)
+++ trunk/profile.php	(revision 1036)
@@ -33,5 +33,12 @@
 define('PHPWG_ROOT_PATH','./');
 include_once(PHPWG_ROOT_PATH.'include/common.inc.php');
-check_login_authorization(false);
+
+if ($user['is_the_guest'] and !$guest_allowed)
+{
+  echo '<div style="text-align:center;">'.$lang['only_members'].'<br />';
+  echo '<a href="./identification.php">'.$lang['ident_title'].'</a></div>';
+  exit();
+}
+
 $userdata = $user;
 
Index: trunk/search.php
===================================================================
--- trunk/search.php	(revision 1035)
+++ trunk/search.php	(revision 1036)
@@ -29,6 +29,4 @@
 define('PHPWG_ROOT_PATH','./');
 include_once( PHPWG_ROOT_PATH.'include/common.inc.php' );
-//-------------------------------------------------- access authorization check
-check_login_authorization();
 //------------------------------------------------------------------ form check
 $errors = array();
Index: trunk/upload.php
===================================================================
--- trunk/upload.php	(revision 1035)
+++ trunk/upload.php	(revision 1036)
@@ -113,7 +113,10 @@
 
 //-------------------------------------------------- access authorization check
-check_login_authorization();
-check_cat_id( $_GET['cat'] );
-if ( isset( $page['cat'] ) and is_numeric( $page['cat'] ) )
+if (is_numeric($_GET['cat']))
+{
+  $page['cat'] = $_GET['cat'];
+}
+
+if (isset($page['cat']))
 {
   check_restrictions( $page['cat'] );
