source: trunk/include/functions_category.inc.php @ 1022

Last change on this file since 1022 was 1022, checked in by rvelices, 18 years ago
  • feature 280: code simplification
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 20.9 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | PhpWebGallery - a PHP based picture gallery                           |
4// | Copyright (C) 2002-2003 Pierrick LE GALL - pierrick@phpwebgallery.net |
5// | Copyright (C) 2003-2005 PhpWebGallery Team - http://phpwebgallery.net |
6// +-----------------------------------------------------------------------+
7// | branch        : BSF (Best So Far)
8// | file          : $RCSfile$
9// | last update   : $Date: 2006-02-01 22:56:17 +0000 (Wed, 01 Feb 2006) $
10// | last modifier : $Author: rvelices $
11// | revision      : $Revision: 1022 $
12// +-----------------------------------------------------------------------+
13// | This program is free software; you can redistribute it and/or modify  |
14// | it under the terms of the GNU General Public License as published by  |
15// | the Free Software Foundation                                          |
16// |                                                                       |
17// | This program is distributed in the hope that it will be useful, but   |
18// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
19// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
20// | General Public License for more details.                              |
21// |                                                                       |
22// | You should have received a copy of the GNU General Public License     |
23// | along with this program; if not, write to the Free Software           |
24// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
25// | USA.                                                                  |
26// +-----------------------------------------------------------------------+
27
28/**
29 * Provides functions to handle categories.
30 *
31 *
32 */
33
34/**
35 * Is the category accessible to the connected user ?
36 *
37 * Note : if the user is not authorized to see this category, page creation
38 * ends (exit command in this function)
39 *
40 * @param int category id to verify
41 * @return void
42 */
43function check_restrictions($category_id)
44{
45  global $user, $lang;
46
47  if (in_array($category_id, explode(',', $user['forbidden_categories'])))
48  {
49    echo '<div style="text-align:center;">'.$lang['access_forbiden'].'<br />';
50    echo '<a href="./category.php">';
51    echo $lang['thumbnails'].'</a></div>';
52    exit();
53  }
54}
55
56/**
57 * Checks whether the argument is a right parameter category id
58 *
59 * The argument is a right parameter if corresponds to one of these :
60 *
61 *  - is numeric and corresponds to a category in the database
62 *  - equals 'fav' (for favorites)
63 *  - equals 'search' (when the result of a search is displayed)
64 *  - equals 'most_visited'
65 *  - equals 'best_rated'
66 *  - equals 'recent_pics'
67 *  - equals 'recent_cats'
68 *  - equals 'calendar'
69 *  - equals 'list'
70 *
71 * The function fills the global var $page['cat'] and returns nothing
72 *
73 * @param mixed category id or special category name
74 * @return void
75 */
76function check_cat_id( $cat )
77{
78  global $page;
79
80  unset( $page['cat'] );
81  if ( isset( $cat ) )
82  {
83    if ( isset( $page['plain_structure'][$cat] ) )
84    {
85      $page['cat'] = $cat;
86    }
87    else if ( is_numeric( $cat ) )
88    {
89      $query = 'SELECT id';
90      $query.= ' FROM '.CATEGORIES_TABLE.' WHERE id = '.$cat.';';
91      $result = pwg_query( $query );
92      if ( mysql_num_rows( $result ) != 0 )
93      {
94        $page['cat'] = $cat;
95      }
96    }
97    if ( $cat == 'fav'
98         or $cat == 'most_visited'
99         or $cat == 'best_rated'
100         or $cat == 'recent_pics'
101         or $cat == 'recent_cats'
102         or $cat == 'calendar' )
103    {
104      $page['cat'] = $cat;
105    }
106    if ($cat == 'search'
107        and isset($_GET['search'])
108        and is_numeric($_GET['search']))
109    {
110      $page['cat'] = $cat;
111    }
112    if ($cat == 'list'
113        and isset($_GET['list'])
114        and preg_match('/^\d+(,\d+)*$/', $_GET['list']))
115    {
116      $page['cat'] = 'list';
117    }
118  }
119}
120
121function get_categories_menu()
122{
123  global $page,$user;
124 
125  $infos = array('');
126 
127  $query = '
128SELECT name,id,date_last,nb_images,global_rank
129  FROM '.CATEGORIES_TABLE.'
130  WHERE 1 = 1'; // stupid but permit using AND after it !
131  if (!$user['expand'])
132  {
133    $query.= '
134    AND (id_uppercat is NULL';
135    if (isset ($page['tab_expand']) and count($page['tab_expand']) > 0)
136    {
137      $query.= ' OR id_uppercat IN ('.implode(',',$page['tab_expand']).')';
138    }
139    $query.= ')';
140  }
141  if ($user['forbidden_categories'] != '')
142  {
143    $query.= '
144    AND id NOT IN ('.$user['forbidden_categories'].')';
145  }
146  $query.= '
147;';
148
149  $result = pwg_query($query);
150  $cats = array();
151  while ($row = mysql_fetch_array($result))
152  {
153    array_push($cats, $row);
154  }
155  usort($cats, 'global_rank_compare');
156
157  return get_html_menu_category($cats);
158}
159
160/**
161 * returns the total number of elements viewable in the gallery by the
162 * connected user
163 *
164 * @return int
165 */
166function count_user_total_images()
167{
168  global $user;
169
170  $query = '
171SELECT COUNT(DISTINCT(image_id)) as total
172  FROM '.IMAGE_CATEGORY_TABLE.'
173  WHERE category_id NOT IN ('.$user['forbidden_categories'].')
174;';
175  list($total) = mysql_fetch_array(pwg_query($query));
176 
177  return $total;
178}
179
180/**
181 * Retrieve informations about a category in the database
182 *
183 * Returns an array with following keys :
184 *
185 *  - comment
186 *  - dir : directory, might be empty for virtual categories
187 *  - name : an array with indexes from 0 (lowest cat name) to n (most
188 *           uppercat name findable)
189 *  - nb_images
190 *  - id_uppercat
191 *  - site_id
192 *  -
193 *
194 * @param int category id
195 * @return array
196 */
197function get_cat_info( $id )
198{
199  $infos = array('nb_images','id_uppercat','comment','site_id'
200                 ,'dir','date_last','uploadable','status','visible'
201                 ,'representative_picture_id','uppercats','commentable');
202 
203  $query = '
204SELECT '.implode(',', $infos).'
205  FROM '.CATEGORIES_TABLE.'
206  WHERE id = '.$id.'
207;';
208  $row = mysql_fetch_array(pwg_query($query));
209
210  $cat = array();
211  foreach ($infos as $info)
212  {
213    if (isset($row[$info]))
214    {
215      $cat[$info] = $row[$info];
216    }
217    else
218    {
219      $cat[$info] = '';
220    }
221    // If the field is true or false, the variable is transformed into a
222    // boolean value.
223    if ($cat[$info] == 'true' or $cat[$info] == 'false')
224    {
225      $cat[$info] = get_boolean( $cat[$info] );
226    }
227  }
228  $cat['comment'] = nl2br($cat['comment']);
229
230  $names = array();
231  $query = '
232SELECT name,id
233  FROM '.CATEGORIES_TABLE.'
234  WHERE id IN ('.$cat['uppercats'].')
235;';
236  $result = pwg_query($query);
237  while($row = mysql_fetch_array($result))
238  {
239    $names[$row['id']] = $row['name'];
240  }
241
242  // category names must be in the same order than uppercats list
243  $cat['name'] = array();
244  foreach (explode(',', $cat['uppercats']) as $cat_id)
245  {
246    $cat['name'][$cat_id] = $names[$cat_id];
247  }
248 
249  return $cat;
250}
251
252// get_complete_dir returns the concatenation of get_site_url and
253// get_local_dir
254// Example : "pets > rex > 1_year_old" is on the the same site as the
255// PhpWebGallery files and this category has 22 for identifier
256// get_complete_dir(22) returns "./galleries/pets/rex/1_year_old/"
257function get_complete_dir( $category_id )
258{
259  return get_site_url($category_id).get_local_dir($category_id);
260}
261
262// get_local_dir returns an array with complete path without the site url
263// Example : "pets > rex > 1_year_old" is on the the same site as the
264// PhpWebGallery files and this category has 22 for identifier
265// get_local_dir(22) returns "pets/rex/1_year_old/"
266function get_local_dir( $category_id )
267{
268  global $page;
269
270  $uppercats = '';
271  $local_dir = '';
272
273  if ( isset( $page['plain_structure'][$category_id]['uppercats'] ) )
274  {
275    $uppercats = $page['plain_structure'][$category_id]['uppercats'];
276  }
277  else
278  {
279    $query = 'SELECT uppercats';
280    $query.= ' FROM '.CATEGORIES_TABLE.' WHERE id = '.$category_id;
281    $query.= ';';
282    $row = mysql_fetch_array( pwg_query( $query ) );
283    $uppercats = $row['uppercats'];
284  }
285
286  $upper_array = explode( ',', $uppercats );
287
288  $database_dirs = array();
289  $query = 'SELECT id,dir';
290  $query.= ' FROM '.CATEGORIES_TABLE.' WHERE id IN ('.$uppercats.')';
291  $query.= ';';
292  $result = pwg_query( $query );
293  while( $row = mysql_fetch_array( $result ) )
294  {
295    $database_dirs[$row['id']] = $row['dir'];
296  }
297  foreach ($upper_array as $id)
298  {
299    $local_dir.= $database_dirs[$id].'/';
300  }
301
302  return $local_dir;
303}
304
305// retrieving the site url : "http://domain.com/gallery/" or
306// simply "./galleries/"
307function get_site_url($category_id)
308{
309  global $page;
310
311  $query = '
312SELECT galleries_url
313  FROM '.SITES_TABLE.' AS s,'.CATEGORIES_TABLE.' AS c
314  WHERE s.id = c.site_id
315    AND c.id = '.$category_id.'
316;';
317  $row = mysql_fetch_array(pwg_query($query));
318  return $row['galleries_url'];
319}
320
321// returns an array of image orders available for users/visitors
322function get_category_preferred_image_orders()
323{
324  global $lang, $conf;
325  return array(
326        array('Default', '', true),
327        array($lang['best_rated_cat'],   'average_rate DESC', $conf['rate']),
328        array($lang['most_visited_cat'], 'hit DESC', true),
329        array($lang['Creation date'], 'date_creation DESC', true),
330        array($lang['Availability date'], 'date_available DESC', true)
331  );
332}
333
334
335// initialize_category initializes ;-) the variables in relation
336// with category :
337// 1. calculation of the number of pictures in the category
338// 2. determination of the SQL query part to ask to find the right category
339//    $page['where'] is not the same if we are in
340//       - simple category
341//       - search result
342//       - favorites displaying
343//       - most visited pictures
344//       - best rated pictures
345//       - recent pictures
346//       - defined list (used for random)
347// 3. determination of the title of the page
348// 4. creation of the navigation bar
349function initialize_category( $calling_page = 'category' )
350{
351  pwg_debug( 'start initialize_category' );
352  global $page,$lang,$user,$conf;
353
354  if ( isset( $page['cat'] ) )
355  {
356    // $page['nb_image_page'] is the number of picture to display on this page
357    // By default, it is the same as the $user['nb_image_page']
358    $page['nb_image_page'] = $user['nb_image_page'];
359    // $url is used to create the navigation bar
360    $url = PHPWG_ROOT_PATH.'category.php?cat='.$page['cat'];
361    if ( isset($page['expand']) ) $url.= '&amp;expand='.$page['expand'];
362    // simple category
363    if ( is_numeric( $page['cat'] ) )
364    {
365      $result = get_cat_info( $page['cat'] );
366      $page['comment']        = $result['comment'];
367      $page['cat_dir']        = $result['dir'];
368      $page['cat_name']       = $result['name'];
369      $page['cat_nb_images']  = $result['nb_images'];
370      $page['cat_site_id']    = $result['site_id'];
371      $page['cat_uploadable'] = $result['uploadable'];
372      $page['cat_commentable'] = $result['commentable'];
373      $page['uppercats']      = $result['uppercats'];
374      $page['title'] =
375        get_cat_display_name($page['cat_name'],
376                             '',
377                             false);
378      $page['where'] = ' WHERE category_id = '.$page['cat'];
379    }
380    else
381    {
382      if ($page['cat'] == 'search'
383          or $page['cat'] == 'most_visited'
384          or $page['cat'] == 'recent_pics'
385          or $page['cat'] == 'recent_cats'
386          or $page['cat'] == 'best_rated'
387          or $page['cat'] == 'calendar'
388          or $page['cat'] == 'list')
389      {
390        // we must not show pictures of a forbidden category
391        if ( $user['forbidden_categories'] != '' )
392        {
393          $forbidden = ' category_id NOT IN ';
394          $forbidden.= '('.$user['forbidden_categories'].')';
395        }
396      }
397      // search result
398      if ( $page['cat'] == 'search' )
399      {
400        $page['title'] = $lang['search_result'];
401        if ( $calling_page == 'picture' )
402        {
403          $page['title'].= ' : <span style="font-style:italic;">';
404          $page['title'].= $_GET['search']."</span>";
405        }
406
407        $page['where'] = 'WHERE '.get_sql_search_clause($_GET['search']);
408       
409        if (isset($forbidden))
410        {
411          $page['where'].= "\n    AND ".$forbidden;
412        }
413
414        $query = '
415SELECT COUNT(DISTINCT(id)) AS nb_total_images
416  FROM '.IMAGES_TABLE.'
417    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
418  '.$page['where'].'
419;';
420        $url.= '&amp;search='.$_GET['search'];
421      }
422      // favorites displaying
423      else if ( $page['cat'] == 'fav' )
424      {
425        check_user_favorites();
426       
427        $page['title'] = $lang['favorites'];
428
429        $page['where'] = ', '.FAVORITES_TABLE.' AS fav';
430        $page['where'].= ' WHERE user_id = '.$user['id'];
431        $page['where'].= ' AND fav.image_id = id';
432     
433        $query = 'SELECT COUNT(*) AS nb_total_images';
434        $query.= ' FROM '.FAVORITES_TABLE;
435        $query.= ' WHERE user_id = '.$user['id'];
436        $query.= ';';
437      }
438      // pictures within the short period
439      else if ( $page['cat'] == 'recent_pics' )
440      {
441        $page['title'] = $lang['recent_pics_cat'];
442        // We must find the date corresponding to :
443        // today - $conf['periode_courte']
444        $date = time() - 60*60*24*$user['recent_period'];
445        $page['where'] = " WHERE date_available > '";
446        $page['where'].= date( 'Y-m-d', $date )."'";
447        if ( isset( $forbidden ) ) $page['where'].= ' AND '.$forbidden;
448
449        $query = '
450SELECT COUNT(DISTINCT(id)) AS nb_total_images
451  FROM '.IMAGES_TABLE.' INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic
452    ON id = ic.image_id
453  '.$page['where'].'
454;';
455      }
456      // categories containing recent pictures
457      else if ( $page['cat'] == 'recent_cats' )
458      {
459        $page['title'] = $lang['recent_cats_cat'];
460        $page['cat_nb_images'] = 0;
461      }
462      // most visited pictures
463      else if ( $page['cat'] == 'most_visited' )
464      {
465        $page['title'] = $conf['top_number'].' '.$lang['most_visited_cat'];
466
467        $page['where'] = 'WHERE hit > 0';
468        if (isset($forbidden))
469        {
470          $page['where'] = "\n".'    AND '.$forbidden;
471        }
472
473        $conf['order_by'] = ' ORDER BY hit DESC, file ASC';
474
475        // $page['cat_nb_images'] equals $conf['top_number'] unless there
476        // are less visited items
477        $query ='
478SELECT COUNT(DISTINCT(id)) AS count
479  FROM '.IMAGES_TABLE.'
480    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
481  '.$page['where'].'
482;';
483        $row = mysql_fetch_array(pwg_query($query));
484        if ($row['count'] < $conf['top_number'])
485        {
486          $page['cat_nb_images'] = $row['count'];
487        }
488        else
489        {
490          $page['cat_nb_images'] = $conf['top_number'];
491        }
492        unset($query);
493       
494        if ( isset( $page['start'] )
495             and ($page['start']+$user['nb_image_page']>=$conf['top_number']))
496        {
497          $page['nb_image_page'] = $conf['top_number'] - $page['start'];
498        }
499      }
500      else if ( $page['cat'] == 'calendar' )
501      {
502        $page['cat_nb_images'] = 0;
503        $page['title'] = $lang['calendar'];
504        if (isset($_GET['year'])
505            and preg_match('/^\d+$/', $_GET['year']))
506        {
507          $page['calendar_year'] = (int)$_GET['year'];
508        }
509        if (isset($_GET['month'])
510            and preg_match('/^(\d+)\.(\d{2})$/', $_GET['month'], $matches))
511        {
512          $page['calendar_year'] = (int)$matches[1];
513          $page['calendar_month'] = (int)$matches[2];
514        }
515        if (isset($_GET['day'])
516            and preg_match('/^(\d+)\.(\d{2})\.(\d{2})$/',
517                           $_GET['day'],
518                           $matches))
519        {
520          $page['calendar_year'] = (int)$matches[1];
521          $page['calendar_month'] = (int)$matches[2];
522          $page['calendar_day'] = (int)$matches[3];
523        }
524        if (isset($page['calendar_year']))
525        {
526          $page['title'] .= ' (';
527          if (isset($page['calendar_day']))
528          {
529            if ($page['calendar_year'] >= 1970)
530            {
531              $unixdate = mktime(0,0,0,
532                                 $page['calendar_month'],
533                                 $page['calendar_day'],
534                                 $page['calendar_year']);
535              $page['title'].= $lang['day'][date("w", $unixdate)];
536            }
537            $page['title'].= ' '.$page['calendar_day'].', ';
538          }
539          if (isset($page['calendar_month']))
540          {
541            $page['title'] .= $lang['month'][$page['calendar_month']].' ';
542          }
543          $page['title'] .= $page['calendar_year'];
544          $page['title'] .= ')';
545        }
546       
547        $page['where'] = 'WHERE '.$conf['calendar_datefield'].' IS NOT NULL';
548        if (isset($forbidden))
549        {
550          $page['where'].= ' AND '.$forbidden;
551        }
552      }
553      else if ($page['cat'] == 'best_rated')
554      {
555        $page['title'] = $conf['top_number'].' '.$lang['best_rated_cat'];
556
557        $page['where'] = ' WHERE average_rate IS NOT NULL';
558       
559        if (isset($forbidden))
560        {
561          $page['where'].= ' AND '.$forbidden;
562        }
563
564        $conf['order_by'] = ' ORDER BY average_rate DESC, id ASC';
565
566        // $page['cat_nb_images'] equals $conf['top_number'] unless there
567        // are less rated items
568        $query ='
569SELECT COUNT(DISTINCT(id)) AS count
570  FROM '.IMAGES_TABLE.'
571    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
572  '.$page['where'].'
573;';
574        $row = mysql_fetch_array(pwg_query($query));
575        if ($row['count'] < $conf['top_number'])
576        {
577          $page['cat_nb_images'] = $row['count'];
578        }
579        else
580        {
581          $page['cat_nb_images'] = $conf['top_number'];
582        }
583        unset($query);
584         
585
586        if (isset($page['start'])
587            and ($page['start']+$user['nb_image_page']>=$conf['top_number']))
588        {
589          $page['nb_image_page'] = $conf['top_number'] - $page['start'];
590        }
591      }
592      else if ($page['cat'] == 'list')
593      {
594        $page['title'] = $lang['random_cat'];
595         
596        $page['where'] = 'WHERE 1=1';
597        if (isset($forbidden))
598        {
599          $page['where'].= ' AND '.$forbidden;
600        }
601        $page['where'].= ' AND image_id IN ('.$_GET['list'].')';
602        $page['cat_nb_images'] = count(explode(',', $_GET['list']));
603
604        $url.= '&amp;list='.$_GET['list'];
605      }
606
607      if (isset($query))
608      {
609        $result = pwg_query( $query );
610        $row = mysql_fetch_array( $result );
611        $page['cat_nb_images'] = $row['nb_total_images'];
612      }
613    }
614    if ( $calling_page == 'category' )
615    {
616      $page['navigation_bar'] =
617        create_navigation_bar( $url, $page['cat_nb_images'], $page['start'],
618                               $user['nb_image_page'], 'back' );
619    }
620
621    if ($page['cat'] != 'most_visited' and $page['cat'] != 'best_rated')
622    {
623      $available_image_orders = get_category_preferred_image_orders();
624
625      $order_idx=0;
626      if ( isset($_COOKIE['pwg_image_order']) )
627      {
628        $order_idx = $_COOKIE['pwg_image_order'];
629      }
630
631      if ( $order_idx > 0 )
632      {
633        $order = $available_image_orders[$order_idx][1];
634        $conf['order_by'] = str_replace('ORDER BY ', 'ORDER BY '.$order.',', 
635                                          $conf['order_by'] );
636      }
637    }
638  }
639  else
640  {
641    $page['title'] = $lang['no_category'];
642  }
643  pwg_debug( 'end initialize_category' );
644}
645
646function display_select_categories($categories,
647                                   $selecteds,
648                                   $blockname,
649                                   $fullname = true)
650{
651  global $template;
652
653  foreach ($categories as $category)
654  {
655    $selected = '';
656    if (in_array($category['id'], $selecteds))
657    {
658      $selected = ' selected="selected"';
659    }
660
661    if ($fullname)
662    {
663      $option = get_cat_display_name_cache($category['uppercats'],
664                                           '',
665                                           false);
666    }
667    else
668    {
669      $option = str_repeat('&nbsp;',
670                           (3 * substr_count($category['global_rank'], '.')));
671      $option.= '- '.$category['name'];
672    }
673   
674    $template->assign_block_vars(
675      $blockname,
676      array('SELECTED'=>$selected,
677            'VALUE'=>$category['id'],
678            'OPTION'=>$option
679        ));
680  }
681}
682
683function display_select_cat_wrapper($query, $selecteds, $blockname,
684                                    $fullname = true)
685{
686  $result = pwg_query($query);
687  $categories = array();
688  if (!empty($result))
689  {
690    while ($row = mysql_fetch_array($result))
691    {
692      array_push($categories, $row);
693    }
694  }
695  usort($categories, 'global_rank_compare');
696  display_select_categories($categories, $selecteds, $blockname, $fullname);
697}
698
699/**
700 * returns all subcategory identifiers of given category ids
701 *
702 * @param array ids
703 * @return array
704 */
705function get_subcat_ids($ids)
706{
707  $query = '
708SELECT DISTINCT(id)
709  FROM '.CATEGORIES_TABLE.'
710  WHERE ';
711  foreach ($ids as $num => $category_id)
712  {
713    if ($num > 0)
714    {
715      $query.= '
716    OR ';
717    }
718    $query.= 'uppercats REGEXP \'(^|,)'.$category_id.'(,|$)\'';
719  }
720  $query.= '
721;';
722  $result = pwg_query($query);
723
724  $subcats = array();
725  while ($row = mysql_fetch_array($result))
726  {
727    array_push($subcats, $row['id']);
728  }
729  return $subcats;
730}
731
732function global_rank_compare($a, $b)
733{
734  return strnatcasecmp($a['global_rank'], $b['global_rank']);
735}
736?>
Note: See TracBrowser for help on using the repository browser.