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

Last change on this file since 1008 was 1008, checked in by plg, 18 years ago

Search engine redesign, first part :

  • new table #search to store search rules associated to a search id.
  • search rules are not passed through GET anymore, the search array build in search.php is serialized in #search table, so no need to rebuild it in function include/functions_category.inc.php::category_initialize
  • search array build code is improved (efficiency and layout) in search.php
  • SQL related to search is build in a dedicated function include/functions::get_sql_search_clause
  • direct search author:<...>, date_avalaible:<...>, date_creation:<...>, keywords:<...> from picture.php are not available anymore. They will come back later, with improvement (new design). Same for date_*:<> in calendar calendar category.
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 20.0 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-01-20 14:34:37 +0000 (Fri, 20 Jan 2006) $
10// | last modifier : $Author: plg $
11// | revision      : $Revision: 1008 $
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// initialize_category initializes ;-) the variables in relation
322// with category :
323// 1. calculation of the number of pictures in the category
324// 2. determination of the SQL query part to ask to find the right category
325//    $page['where'] is not the same if we are in
326//       - simple category
327//       - search result
328//       - favorites displaying
329//       - most visited pictures
330//       - best rated pictures
331//       - recent pictures
332//       - defined list (used for random)
333// 3. determination of the title of the page
334// 4. creation of the navigation bar
335function initialize_category( $calling_page = 'category' )
336{
337  pwg_debug( 'start initialize_category' );
338  global $page,$lang,$user,$conf;
339
340  if ( isset( $page['cat'] ) )
341  {
342    // $page['nb_image_page'] is the number of picture to display on this page
343    // By default, it is the same as the $user['nb_image_page']
344    $page['nb_image_page'] = $user['nb_image_page'];
345    // $url is used to create the navigation bar
346    $url = PHPWG_ROOT_PATH.'category.php?cat='.$page['cat'];
347    if ( isset($page['expand']) ) $url.= '&amp;expand='.$page['expand'];
348    // simple category
349    if ( is_numeric( $page['cat'] ) )
350    {
351      $result = get_cat_info( $page['cat'] );
352      $page['comment']        = $result['comment'];
353      $page['cat_dir']        = $result['dir'];
354      $page['cat_name']       = $result['name'];
355      $page['cat_nb_images']  = $result['nb_images'];
356      $page['cat_site_id']    = $result['site_id'];
357      $page['cat_uploadable'] = $result['uploadable'];
358      $page['cat_commentable'] = $result['commentable'];
359      $page['uppercats']      = $result['uppercats'];
360      $page['title'] =
361        get_cat_display_name($page['cat_name'],
362                             '',
363                             false);
364      $page['where'] = ' WHERE category_id = '.$page['cat'];
365    }
366    else
367    {
368      if ($page['cat'] == 'search'
369          or $page['cat'] == 'most_visited'
370          or $page['cat'] == 'recent_pics'
371          or $page['cat'] == 'recent_cats'
372          or $page['cat'] == 'best_rated'
373          or $page['cat'] == 'calendar'
374          or $page['cat'] == 'list')
375      {
376        // we must not show pictures of a forbidden category
377        if ( $user['forbidden_categories'] != '' )
378        {
379          $forbidden = ' category_id NOT IN ';
380          $forbidden.= '('.$user['forbidden_categories'].')';
381        }
382      }
383      // search result
384      if ( $page['cat'] == 'search' )
385      {
386        $page['title'] = $lang['search_result'];
387        if ( $calling_page == 'picture' )
388        {
389          $page['title'].= ' : <span style="font-style:italic;">';
390          $page['title'].= $_GET['search']."</span>";
391        }
392
393        $page['where'] = 'WHERE '.get_sql_search_clause($_GET['search']);
394       
395        if (isset($forbidden))
396        {
397          $page['where'].= "\n    AND ".$forbidden;
398        }
399
400        $query = '
401SELECT COUNT(DISTINCT(id)) AS nb_total_images
402  FROM '.IMAGES_TABLE.'
403    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
404  '.$page['where'].'
405;';
406        $url.= '&amp;search='.$_GET['search'];
407      }
408      // favorites displaying
409      else if ( $page['cat'] == 'fav' )
410      {
411        check_user_favorites();
412       
413        $page['title'] = $lang['favorites'];
414
415        $page['where'] = ', '.FAVORITES_TABLE.' AS fav';
416        $page['where'].= ' WHERE user_id = '.$user['id'];
417        $page['where'].= ' AND fav.image_id = id';
418     
419        $query = 'SELECT COUNT(*) AS nb_total_images';
420        $query.= ' FROM '.FAVORITES_TABLE;
421        $query.= ' WHERE user_id = '.$user['id'];
422        $query.= ';';
423      }
424      // pictures within the short period
425      else if ( $page['cat'] == 'recent_pics' )
426      {
427        $page['title'] = $lang['recent_pics_cat'];
428        // We must find the date corresponding to :
429        // today - $conf['periode_courte']
430        $date = time() - 60*60*24*$user['recent_period'];
431        $page['where'] = " WHERE date_available > '";
432        $page['where'].= date( 'Y-m-d', $date )."'";
433        if ( isset( $forbidden ) ) $page['where'].= ' AND '.$forbidden;
434
435        $query = '
436SELECT COUNT(DISTINCT(id)) AS nb_total_images
437  FROM '.IMAGES_TABLE.' INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic
438    ON id = ic.image_id
439  '.$page['where'].'
440;';
441      }
442      // categories containing recent pictures
443      else if ( $page['cat'] == 'recent_cats' )
444      {
445        $page['title'] = $lang['recent_cats_cat'];
446        $page['cat_nb_images'] = 0;
447      }
448      // most visited pictures
449      else if ( $page['cat'] == 'most_visited' )
450      {
451        $page['title'] = $conf['top_number'].' '.$lang['most_visited_cat'];
452
453        $page['where'] = 'WHERE hit > 0';
454        if (isset($forbidden))
455        {
456          $page['where'] = "\n".'    AND '.$forbidden;
457        }
458
459        $conf['order_by'] = ' ORDER BY hit DESC, file ASC';
460
461        // $page['cat_nb_images'] equals $conf['top_number'] unless there
462        // are less visited items
463        $query ='
464SELECT COUNT(DISTINCT(id)) AS count
465  FROM '.IMAGES_TABLE.'
466    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
467  '.$page['where'].'
468;';
469        $row = mysql_fetch_array(pwg_query($query));
470        if ($row['count'] < $conf['top_number'])
471        {
472          $page['cat_nb_images'] = $row['count'];
473        }
474        else
475        {
476          $page['cat_nb_images'] = $conf['top_number'];
477        }
478        unset($query);
479       
480        if ( isset( $page['start'] )
481             and ($page['start']+$user['nb_image_page']>=$conf['top_number']))
482        {
483          $page['nb_image_page'] = $conf['top_number'] - $page['start'];
484        }
485      }
486      else if ( $page['cat'] == 'calendar' )
487      {
488        $page['cat_nb_images'] = 0;
489        $page['title'] = $lang['calendar'];
490        if (isset($_GET['year'])
491            and preg_match('/^\d+$/', $_GET['year']))
492        {
493          $page['calendar_year'] = (int)$_GET['year'];
494        }
495        if (isset($_GET['month'])
496            and preg_match('/^(\d+)\.(\d{2})$/', $_GET['month'], $matches))
497        {
498          $page['calendar_year'] = (int)$matches[1];
499          $page['calendar_month'] = (int)$matches[2];
500        }
501        if (isset($_GET['day'])
502            and preg_match('/^(\d+)\.(\d{2})\.(\d{2})$/',
503                           $_GET['day'],
504                           $matches))
505        {
506          $page['calendar_year'] = (int)$matches[1];
507          $page['calendar_month'] = (int)$matches[2];
508          $page['calendar_day'] = (int)$matches[3];
509        }
510        if (isset($page['calendar_year']))
511        {
512          $page['title'] .= ' (';
513          if (isset($page['calendar_day']))
514          {
515            if ($page['calendar_year'] >= 1970)
516            {
517              $unixdate = mktime(0,0,0,
518                                 $page['calendar_month'],
519                                 $page['calendar_day'],
520                                 $page['calendar_year']);
521              $page['title'].= $lang['day'][date("w", $unixdate)];
522            }
523            $page['title'].= ' '.$page['calendar_day'].', ';
524          }
525          if (isset($page['calendar_month']))
526          {
527            $page['title'] .= $lang['month'][$page['calendar_month']].' ';
528          }
529          $page['title'] .= $page['calendar_year'];
530          $page['title'] .= ')';
531        }
532       
533        $page['where'] = 'WHERE '.$conf['calendar_datefield'].' IS NOT NULL';
534        if (isset($forbidden))
535        {
536          $page['where'].= ' AND '.$forbidden;
537        }
538      }
539      else if ($page['cat'] == 'best_rated')
540      {
541        $page['title'] = $conf['top_number'].' '.$lang['best_rated_cat'];
542
543        $page['where'] = ' WHERE average_rate IS NOT NULL';
544       
545        if (isset($forbidden))
546        {
547          $page['where'].= ' AND '.$forbidden;
548        }
549
550        $conf['order_by'] = ' ORDER BY average_rate DESC, id ASC';
551
552        // $page['cat_nb_images'] equals $conf['top_number'] unless there
553        // are less rated items
554        $query ='
555SELECT COUNT(DISTINCT(id)) AS count
556  FROM '.IMAGES_TABLE.'
557    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
558  '.$page['where'].'
559;';
560        $row = mysql_fetch_array(pwg_query($query));
561        if ($row['count'] < $conf['top_number'])
562        {
563          $page['cat_nb_images'] = $row['count'];
564        }
565        else
566        {
567          $page['cat_nb_images'] = $conf['top_number'];
568        }
569        unset($query);
570         
571
572        if (isset($page['start'])
573            and ($page['start']+$user['nb_image_page']>=$conf['top_number']))
574        {
575          $page['nb_image_page'] = $conf['top_number'] - $page['start'];
576        }
577      }
578      else if ($page['cat'] == 'list')
579      {
580        $page['title'] = $lang['random_cat'];
581         
582        $page['where'] = 'WHERE 1=1';
583        if (isset($forbidden))
584        {
585          $page['where'].= ' AND '.$forbidden;
586        }
587        $page['where'].= ' AND image_id IN ('.$_GET['list'].')';
588        $page['cat_nb_images'] = count(explode(',', $_GET['list']));
589
590        $url.= '&amp;list='.$_GET['list'];
591      }
592
593      if (isset($query))
594      {
595        $result = pwg_query( $query );
596        $row = mysql_fetch_array( $result );
597        $page['cat_nb_images'] = $row['nb_total_images'];
598      }
599    }
600    if ( $calling_page == 'category' )
601    {
602      $page['navigation_bar'] =
603        create_navigation_bar( $url, $page['cat_nb_images'], $page['start'],
604                               $user['nb_image_page'], 'back' );
605    }
606  }
607  else
608  {
609    $page['title'] = $lang['no_category'];
610  }
611  pwg_debug( 'end initialize_category' );
612}
613
614function display_select_categories($categories,
615                                   $selecteds,
616                                   $blockname,
617                                   $fullname = true)
618{
619  global $template;
620
621  foreach ($categories as $category)
622  {
623    $selected = '';
624    if (in_array($category['id'], $selecteds))
625    {
626      $selected = ' selected="selected"';
627    }
628
629    if ($fullname)
630    {
631      $option = get_cat_display_name_cache($category['uppercats'],
632                                           '',
633                                           false);
634    }
635    else
636    {
637      $option = str_repeat('&nbsp;',
638                           (3 * substr_count($category['global_rank'], '.')));
639      $option.= '- '.$category['name'];
640    }
641   
642    $template->assign_block_vars(
643      $blockname,
644      array('SELECTED'=>$selected,
645            'VALUE'=>$category['id'],
646            'OPTION'=>$option
647        ));
648  }
649}
650
651function display_select_cat_wrapper($query, $selecteds, $blockname,
652                                    $fullname = true)
653{
654  $result = pwg_query($query);
655  $categories = array();
656  if (!empty($result))
657  {
658    while ($row = mysql_fetch_array($result))
659    {
660      array_push($categories, $row);
661    }
662  }
663  usort($categories, 'global_rank_compare');
664  display_select_categories($categories, $selecteds, $blockname, $fullname);
665}
666
667/**
668 * returns all subcategory identifiers of given category ids
669 *
670 * @param array ids
671 * @return array
672 */
673function get_subcat_ids($ids)
674{
675  $query = '
676SELECT DISTINCT(id)
677  FROM '.CATEGORIES_TABLE.'
678  WHERE ';
679  foreach ($ids as $num => $category_id)
680  {
681    if ($num > 0)
682    {
683      $query.= '
684    OR ';
685    }
686    $query.= 'uppercats REGEXP \'(^|,)'.$category_id.'(,|$)\'';
687  }
688  $query.= '
689;';
690  $result = pwg_query($query);
691
692  $subcats = array();
693  while ($row = mysql_fetch_array($result))
694  {
695    array_push($subcats, $row['id']);
696  }
697  return $subcats;
698}
699
700function global_rank_compare($a, $b)
701{
702  return strnatcasecmp($a['global_rank'], $b['global_rank']);
703}
704?>
Note: See TracBrowser for help on using the repository browser.