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

Last change on this file since 507 was 507, checked in by z0rglub, 20 years ago

add rating feature

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 27.0 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// |                      functions_category.inc.php                       |
4// +-----------------------------------------------------------------------+
5// | application   : PhpWebGallery <http://phpwebgallery.net>              |
6// | branch        : BSF (Best So Far)                                     |
7// +-----------------------------------------------------------------------+
8// | file          : $RCSfile$
9// | last update   : $Date: 2004-08-30 22:00:46 +0000 (Mon, 30 Aug 2004) $
10// | last modifier : $Author: z0rglub $
11// | revision      : $Revision: 507 $
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, $user['restrictions'] ) )
48  {
49    echo '<div style="text-align:center;">'.$lang['access_forbiden'].'<br />';
50    echo '<a href="'.add_session_id( './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 *
70 * The function fills the global var $page['cat'] and returns nothing
71 *
72 * @param mixed category id or special category name
73 * @return void
74 */
75function check_cat_id( $cat )
76{
77  global $page;
78
79  unset( $page['cat'] );
80  if ( isset( $cat ) )
81  {
82    if ( isset( $page['plain_structure'][$cat] ) )
83    {
84      $page['cat'] = $cat;
85    }
86    else if ( is_numeric( $cat ) )
87    {
88      $query = 'SELECT id';
89      $query.= ' FROM '.CATEGORIES_TABLE.' WHERE id = '.$cat.';';
90      $result = mysql_query( $query );
91      if ( mysql_num_rows( $result ) != 0 )
92      {
93        $page['cat'] = $cat;
94      }
95    }
96    if ( $cat == 'fav'
97         or $cat == 'most_visited'
98         or $cat == 'best_rated'
99         or $cat == 'recent_pics'
100         or $cat == 'recent_cats'
101         or $cat == 'calendar' )
102    {
103      $page['cat'] = $cat;
104    }
105    if ($cat == 'search' and isset($_GET['search']))
106    {
107      $page['cat'] = $cat;
108    }
109  }
110}
111
112function get_user_plain_structure()
113{
114  global $page,$user;
115 
116  $infos = array( 'name','id','date_last','nb_images','dir','id_uppercat',
117                  'rank','site_id','uppercats');
118 
119  $query = 'SELECT '.implode( ',', $infos );
120  $query.= ' FROM '.CATEGORIES_TABLE;
121  $query.= ' WHERE 1 = 1'; // stupid but permit using AND after it !
122  if ( !$user['expand'] )
123  {
124    $query.= ' AND (id_uppercat is NULL';
125    if ( isset ($page['tab_expand']) && count( $page['tab_expand'] ) > 0 )
126    {
127      $query.= ' OR id_uppercat IN ('.implode(',',$page['tab_expand']).')';
128    }
129    $query.= ')';
130  }
131  if ( $user['forbidden_categories'] != '' )
132  {
133    $query.= ' AND id NOT IN ';
134    $query.= '('.$user['forbidden_categories'].')';
135  }
136  $query.= ' ORDER BY id_uppercat ASC, rank ASC';
137  $query.= ';';
138
139  $plain_structure = array();
140  $result = mysql_query( $query );
141  while ( $row = mysql_fetch_array( $result ) )
142  {
143    $category = array();
144    foreach ( $infos as $info ) {
145      if ( $info == 'uc.date_last')
146      {
147        if ( empty( $row['date_last'] ) )
148        {
149          $category['date_last'] = 0;
150        }
151        else
152        {
153          list($year,$month,$day) = explode( '-', $row['date_last'] );
154          $category['date_last'] = mktime(0,0,0,$month,$day,$year);
155        }
156      }
157      else if ( isset( $row[$info] ) ) $category[$info] = $row[$info];
158      else                             $category[$info] = '';
159    }
160    $plain_structure[$row['id']] = $category;
161  }
162
163  return $plain_structure;
164}
165
166function create_user_structure( $id_uppercat )
167{
168  global $page;
169
170  if ( !isset( $page['plain_structure'] ) )
171    $page['plain_structure'] = get_user_plain_structure();
172
173  $structure = array();
174  $ids = get_user_subcat_ids( $id_uppercat );
175  foreach ( $ids as $id ) {
176    $category = $page['plain_structure'][$id];
177    $category['subcats'] = create_user_structure( $id );
178    array_push( $structure, $category );
179  }
180  return $structure;
181}
182
183function get_user_subcat_ids( $id_uppercat )
184{
185  global $page;
186
187  $ids = array();
188  foreach ( $page['plain_structure'] as $id => $category ) {
189    if ( $category['id_uppercat'] == $id_uppercat ) array_push( $ids, $id );
190    else if ( count( $ids ) > 0 )                   return $ids;
191  }
192  return $ids;
193}
194
195// update_structure updates or add informations about each node of the
196// structure :
197//
198// 1. should the category be expanded in the menu ?
199// If the category has to be expanded (ie its id is in the
200// $page['tab_expand'] or all the categories must be expanded by default),
201// $category['expanded'] is set to true.
202//
203// 2. associated expand string
204// in the menu, there is a expand string (used in the URL) to tell which
205// categories must be expanded in the menu if this category is chosen
206function update_structure( $categories )
207{
208  global $page, $user;
209
210  $updated_categories = array();
211
212  foreach ( $categories as $category ) {
213    // update the "expanded" key
214    if ( $user['expand']
215         or in_array( $category['id'], $page['tab_expand'] ) )
216    {
217      $category['expanded'] = true;
218    }
219    else
220    {
221      $category['expanded'] = false;
222    }
223    // recursive call
224    $category['subcats'] = update_structure( $category['subcats'] );
225    // adding the updated category
226    array_push( $updated_categories, $category );
227  }
228
229  return $updated_categories;
230}
231
232// count_images returns the number of pictures contained in the given
233// category represented by an array, in this array, we have (among other
234// things) :
235// $category['nb_images'] -> number of pictures in this category
236// $category['subcats'] -> array of sub-categories
237// count_images goes to the deepest sub-category to find the total number of
238// pictures contained in the given given category
239function count_images( $categories )
240{
241  return count_user_total_images();
242  $total = 0;
243  foreach ( $categories as $category ) {
244    $total+= $category['nb_images'];
245    $total+= count_images( $category['subcats'] );
246  }
247  return $total;
248}
249
250function count_user_total_images()
251{
252  global $user;
253
254  $query = 'SELECT SUM(nb_images) AS total';
255  $query.= ' FROM '.CATEGORIES_TABLE;
256  if ( count( $user['restrictions'] ) > 0 )
257    $query.= ' WHERE id NOT IN ('.$user['forbidden_categories'].')';
258  $query.= ';';
259 
260//   $query = '
261// SELECT COUNT(DISTINCT(image_id)) as total
262//   FROM '.PREFIX_TABLE.'image_category';
263//   if (count($user['restrictions']) > 0)
264//   {
265//     $query.= '
266//   WHERE category_id NOT IN ('.$user['forbidden_categories'].')';
267//   }
268//   $query = '
269// ;';
270 
271  $row = mysql_fetch_array( mysql_query( $query ) );
272
273  if ( !isset( $row['total'] ) ) $row['total'] = 0;
274
275  return $row['total'];
276}
277
278/**
279 * Retrieve informations about a category in the database
280 *
281 * Returns an array with following keys :
282 *
283 *  - comment
284 *  - dir : directory, might be empty for virtual categories
285 *  - name : an array with indexes from 0 (lowest cat name) to n (most
286 *           uppercat name findable)
287 *  - nb_images
288 *  - id_uppercat
289 *  - site_id
290 *  -
291 *
292 * @param int category id
293 * @return array
294 */
295function get_cat_info( $id )
296{
297  $infos = array( 'nb_images','id_uppercat','comment','site_id','galleries_url'
298                  ,'dir','date_last','uploadable','status','visible'
299                  ,'representative_picture_id','uppercats' );
300
301  $query = 'SELECT '.implode( ',', $infos );
302  $query.= ' FROM '.CATEGORIES_TABLE.' AS a';
303  $query.= ', '.SITES_TABLE.' AS b';
304  $query.= ' WHERE a.id = '.$id;
305  $query.= ' AND a.site_id = b.id';
306  $query.= ';';
307  $row = mysql_fetch_array( mysql_query( $query ) );
308
309  $cat = array();
310  // affectation of each field of the table "config" to an information of the
311  // array $cat.
312  foreach ( $infos as $info ) {
313    if ( isset( $row[$info] ) ) $cat[$info] = $row[$info];
314    else                        $cat[$info] = '';
315    // If the field is true or false, the variable is transformed into a
316    // boolean value.
317    if ( $cat[$info] == 'true' or $cat[$info] == 'false' )
318    {
319      $cat[$info] = get_boolean( $cat[$info] );
320    }
321  }
322  $cat['comment'] = nl2br( $cat['comment'] );
323
324  $cat['name'] = array();
325
326  $query = 'SELECT name,id FROM '.CATEGORIES_TABLE;
327  $query.= ' WHERE id IN ('.$cat['uppercats'].')';
328  $query.= ' ORDER BY id ASC';
329  $query.= ';';
330  $result = mysql_query( $query );
331  while( $row = mysql_fetch_array( $result ) )
332  {
333    $cat['name'][$row['id']] = $row['name'];
334  }
335 
336  return $cat;
337}
338
339// get_complete_dir returns the concatenation of get_site_url and
340// get_local_dir
341// Example : "pets > rex > 1_year_old" is on the the same site as the
342// PhpWebGallery files and this category has 22 for identifier
343// get_complete_dir(22) returns "./galleries/pets/rex/1_year_old/"
344function get_complete_dir( $category_id )
345{
346  return get_site_url( $category_id ).get_local_dir( $category_id );
347}
348
349// get_local_dir returns an array with complete path without the site url
350// Example : "pets > rex > 1_year_old" is on the the same site as the
351// PhpWebGallery files and this category has 22 for identifier
352// get_local_dir(22) returns "pets/rex/1_year_old/"
353function get_local_dir( $category_id )
354{
355  global $page;
356
357  $uppercats = '';
358  $local_dir = '';
359
360  if ( isset( $page['plain_structure'][$category_id]['uppercats'] ) )
361  {
362    $uppercats = $page['plain_structure'][$category_id]['uppercats'];
363  }
364  else
365  {
366    $query = 'SELECT uppercats';
367    $query.= ' FROM '.CATEGORIES_TABLE.' WHERE id = '.$category_id;
368    $query.= ';';
369    $row = mysql_fetch_array( mysql_query( $query ) );
370    $uppercats = $row['uppercats'];
371  }
372
373  $upper_array = explode( ',', $uppercats );
374
375  $database_dirs = array();
376  $query = 'SELECT id,dir';
377  $query.= ' FROM '.CATEGORIES_TABLE.' WHERE id IN ('.$uppercats.')';
378  $query.= ';';
379  $result = mysql_query( $query );
380  while( $row = mysql_fetch_array( $result ) )
381  {
382    $database_dirs[$row['id']] = $row['dir'];
383  }
384  foreach ( $upper_array as $id ) {
385    $local_dir.= $database_dirs[$id].'/';
386  }
387
388  return $local_dir;
389}
390
391// retrieving the site url : "http://domain.com/gallery/" or
392// simply "./galleries/"
393function get_site_url( $category_id )
394{
395  global $page;
396
397  $query = 'SELECT galleries_url';
398  $query.= ' FROM '.SITES_TABLE.' AS s,'.CATEGORIES_TABLE.' AS c';
399  $query.= ' WHERE s.id = c.site_id';
400  $query.= ' AND c.id = '.$category_id;
401  $query.= ';';
402  $row = mysql_fetch_array( mysql_query( $query ) );
403  return $row['galleries_url'];
404}
405
406// initialize_category initializes ;-) the variables in relation
407// with category :
408// 1. calculation of the number of pictures in the category
409// 2. determination of the SQL query part to ask to find the right category
410//    $page['where'] is not the same if we are in
411//       - simple category
412//       - search result
413//       - favorites displaying
414//       - most visited pictures
415//       - best rated pictures
416//       - recent pictures
417// 3. determination of the title of the page
418// 4. creation of the navigation bar
419function initialize_category( $calling_page = 'category' )
420{
421  pwg_debug( 'start initialize_category' );
422  global $page,$lang,$user,$conf;
423
424  if ( isset( $page['cat'] ) )
425  {
426    // $page['nb_image_page'] is the number of picture to display on this page
427    // By default, it is the same as the $user['nb_image_page']
428    $page['nb_image_page'] = $user['nb_image_page'];
429    // $url is used to create the navigation bar
430    $url = './category.php?cat='.$page['cat'];
431    if ( isset($page['expand']) ) $url.= '&amp;expand='.$page['expand'];
432    // simple category
433    if ( is_numeric( $page['cat'] ) )
434    {
435      $result = get_cat_info( $page['cat'] );
436      $page['comment']        = $result['comment'];
437      $page['cat_dir']        = $result['dir'];
438      $page['cat_name']       = $result['name'];
439      $page['cat_nb_images']  = $result['nb_images'];
440      $page['cat_site_id']    = $result['site_id'];
441      $page['cat_uploadable'] = $result['uploadable'];
442      $page['uppercats']      = $result['uppercats'];
443      $page['title'] = get_cat_display_name( $page['cat_name'],' - ','',false);
444      $page['where'] = ' WHERE category_id = '.$page['cat'];
445    }
446    else
447    {
448      if ( $page['cat'] == 'search'
449           or $page['cat'] == 'most_visited'
450           or $page['cat'] == 'recent_pics'
451           or $page['cat'] == 'recent_cats'
452           or $page['cat'] == 'best_rated'
453           or $page['cat'] == 'calendar' )
454      {
455        // we must not show pictures of a forbidden category
456        if ( $user['forbidden_categories'] != '' )
457        {
458          $forbidden = ' category_id NOT IN ';
459          $forbidden.= '('.$user['forbidden_categories'].')';
460        }
461      }
462      // search result
463      if ( $page['cat'] == 'search' )
464      {
465        // analyze search string given in URL (created in search.php)
466        $tokens = explode('|', $_GET['search']);
467
468        if (isset($tokens[1]) and $tokens[1] == 'AND')
469        {
470          $search['mode'] = 'AND';
471        }
472        else
473        {
474          $search['mode'] = 'OR';
475        }
476
477        $search_tokens = explode(';', $tokens[0]);
478        foreach ($search_tokens as $search_token)
479        {
480          $tokens = explode(':', $search_token);
481          $field_name = $tokens[0];
482          $field_content = $tokens[1];
483
484          $tokens = explode('~', $tokens[1]);
485          if (isset($tokens[1]))
486          {
487            $search['fields'][$field_name]['mode'] = $tokens[1];
488          }
489          else
490          {
491            $search['fields'][$field_name]['mode'] = '';
492          }
493
494          $search['fields'][$field_name]['words'] = array();
495          $tokens = explode(',', $tokens[0]);
496          foreach ($tokens as $token)
497          {
498            array_push($search['fields'][$field_name]['words'], $token);
499          }
500        }
501       
502        $page['title'] = $lang['search_result'];
503        if ( $calling_page == 'picture' )
504        {
505          $page['title'].= ' : <span style="font-style:italic;">';
506          $page['title'].= $_GET['search']."</span>";
507        }
508
509        // SQL where clauses are stored in $clauses array during query
510        // construction
511        $clauses = array();
512       
513        $textfields = array('file', 'name', 'comment', 'keywords', 'author');
514        foreach ($textfields as $textfield)
515        {
516          if (isset($search['fields'][$textfield]))
517          {
518            $local_clauses = array();
519            foreach ($search['fields'][$textfield]['words'] as $word)
520            {
521              array_push($local_clauses, $textfield." LIKE '%".$word."%'");
522            }
523            // adds brackets around where clauses
524            array_walk($local_clauses,create_function('&$s','$s="(".$s.")";'));
525            array_push($clauses,
526                       implode(' '.$search['fields'][$textfield]['mode'].' ',
527                               $local_clauses));
528          }
529        }
530
531        $datefields = array('date_available', 'date_creation');
532        foreach ($datefields as $datefield)
533        {
534          $key = $datefield;
535          if (isset($search['fields'][$key]))
536          {
537            $local_clause = $datefield." = '";
538            $local_clause.= str_replace('.', '-',
539                                        $search['fields'][$key]['words'][0]);
540            $local_clause.= "'";
541            array_push($clauses, $local_clause);
542          }
543
544          foreach (array('after','before') as $suffix)
545          {
546            $key = $datefield.'-'.$suffix;
547            if (isset($search['fields'][$key]))
548            {
549              $local_clause = $datefield;
550              if ($suffix == 'after')
551              {
552                $local_clause.= ' >';
553              }
554              else
555              {
556                $local_clause.= ' <';
557              }
558              if (isset($search['fields'][$key]['mode'])
559                  and $search['fields'][$key]['mode'] == 'inc')
560              {
561                $local_clause.= '=';
562              }
563              $local_clause.= " '";
564              $local_clause.= str_replace('.', '-',
565                                          $search['fields'][$key]['words'][0]);
566              $local_clause.= "'";
567              array_push($clauses, $local_clause);
568            }
569          }
570        }
571
572        if (isset($search['fields']['cat']))
573        {
574          if ($search['fields']['cat']['mode'] == 'sub_inc')
575          {
576            // searching all the categories id of sub-categories
577            $search_cat_clauses = array();
578            foreach ($search['fields']['cat']['words'] as $cat_id)
579            {
580              $local_clause = 'uppercats REGEXP \'(^|,)'.$cat_id.'(,|$)\'';
581              array_push($search_cat_clauses, $local_clause);
582            }
583            array_walk($search_cat_clauses,
584                       create_function('&$s', '$s = "(".$s.")";'));
585           
586            $query = '
587SELECT DISTINCT(id) AS id
588  FROM '.CATEGORIES_TABLE.'
589  WHERE '.implode(' OR ', $search_cat_clauses).'
590;';
591            $result = mysql_query($query);
592            $cat_ids = array();
593            while ($row = mysql_fetch_array($result))
594            {
595              array_push($cat_ids, $row['id']);
596            }
597            $local_clause = 'category_id IN (';
598            $local_clause.= implode(',',$cat_ids);
599            $local_clause.= ')';
600            array_push($clauses, $local_clause);
601          }
602          else
603          {
604            $local_clause = 'category_id IN (';
605            $local_clause.= implode(',',$search['fields']['cat']['words']);
606            $local_clause.= ')';
607            array_push($clauses, $local_clause);
608          }
609        }
610
611        // adds brackets around where clauses
612        array_walk($clauses, create_function('&$s', '$s = "(".$s.")";'));
613        $page['where'] = 'WHERE '.implode(' '.$search['mode'].' ', $clauses);
614        if ( isset( $forbidden ) ) $page['where'].= ' AND '.$forbidden;
615
616        $query = '
617SELECT COUNT(DISTINCT(id)) AS nb_total_images
618  FROM '.IMAGES_TABLE.'
619    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
620  '.$page['where'].'
621;';
622        $url.= '&amp;search='.$_GET['search'];
623      }
624      // favorites displaying
625      else if ( $page['cat'] == 'fav' )
626      {
627        $page['title'] = $lang['favorites'];
628
629        $page['where'] = ', '.FAVORITES_TABLE.' AS fav';
630        $page['where'].= ' WHERE user_id = '.$user['id'];
631        $page['where'].= ' AND fav.image_id = id';
632     
633        $query = 'SELECT COUNT(*) AS nb_total_images';
634        $query.= ' FROM '.FAVORITES_TABLE;
635        $query.= ' WHERE user_id = '.$user['id'];
636        $query.= ';';
637      }
638      // pictures within the short period
639      else if ( $page['cat'] == 'recent_pics' )
640      {
641        $page['title'] = $lang['recent_pics_cat'];
642        // We must find the date corresponding to :
643        // today - $conf['periode_courte']
644        $date = time() - 60*60*24*$user['recent_period'];
645        $page['where'] = " WHERE date_available > '";
646        $page['where'].= date( 'Y-m-d', $date )."'";
647        if ( isset( $forbidden ) ) $page['where'].= ' AND '.$forbidden;
648
649        $query = 'SELECT COUNT(DISTINCT(id)) AS nb_total_images';
650        $query.= ' FROM '.IMAGES_TABLE;
651        $query.= ' INNER JOIN '.PREFIX_TABLE.'image_category AS ic';
652        $query.= ' ON id = ic.image_id';
653        $query.= $page['where'];
654        $query.= ';';
655      }
656      // categories containing recent pictures
657      else if ( $page['cat'] == 'recent_cats' )
658      {
659        $page['title'] = $lang['recent_cats_cat'];
660        $page['cat_nb_images'] = 0;
661      }
662      // most visited pictures
663      else if ( $page['cat'] == 'most_visited' )
664      {
665        $page['title'] = $conf['top_number'].' '.$lang['most_visited_cat'];
666       
667        if ( isset( $forbidden ) ) $page['where'] = ' WHERE '.$forbidden;
668        else                       $page['where'] = '';
669        $conf['order_by'] = ' ORDER BY hit DESC, file ASC';
670        $page['cat_nb_images'] = $conf['top_number'];
671        if ( isset( $page['start'] )
672             and ($page['start']+$user['nb_image_page']>=$conf['top_number']))
673        {
674          $page['nb_image_page'] = $conf['top_number'] - $page['start'];
675        }
676      }
677      else if ( $page['cat'] == 'calendar' )
678      {
679        $page['cat_nb_images'] = 0;
680        $page['title'] = $lang['calendar'];
681        if (isset($_GET['year'])
682            and preg_match('/^\d+$/', $_GET['year']))
683        {
684          $page['calendar_year'] = (int)$_GET['year'];
685        }
686        if (isset($_GET['month'])
687            and preg_match('/^(\d+)\.(\d{2})$/', $_GET['month'], $matches))
688        {
689          $page['calendar_year'] = (int)$matches[1];
690          $page['calendar_month'] = (int)$matches[2];
691        }
692        if (isset($_GET['day'])
693            and preg_match('/^(\d+)\.(\d{2})\.(\d{2})$/',
694                           $_GET['day'],
695                           $matches))
696        {
697          $page['calendar_year'] = (int)$matches[1];
698          $page['calendar_month'] = (int)$matches[2];
699          $page['calendar_day'] = (int)$matches[3];
700        }
701        if (isset($page['calendar_year']))
702        {
703          $page['title'] .= ' (';
704          if (isset($page['calendar_day']))
705          {
706            $unixdate = mktime(0,0,0,
707                               $page['calendar_month'],
708                               $page['calendar_day'],
709                               $page['calendar_year']);
710            $page['title'].= $lang['day'][date("w", $unixdate)];
711            $page['title'].= ' '.$page['calendar_day'].', ';
712          }
713          if (isset($page['calendar_month']))
714          {
715            $page['title'] .= $lang['month'][$page['calendar_month']].' ';
716          }
717          $page['title'] .= $page['calendar_year'];
718          $page['title'] .= ')';
719        }
720       
721        $page['where'] = 'WHERE '.$conf['calendar_datefield'].' IS NOT NULL';
722        if (isset($forbidden))
723        {
724          $page['where'].= ' AND '.$forbidden;
725        }
726      }
727      else if ($page['cat'] == 'best_rated')
728      {
729        $page['title'] = $conf['top_number'].' '.$lang['best_rated_cat'];
730
731        $page['where'] = ' WHERE average_rate IS NOT NULL';
732       
733        if (isset($forbidden))
734        {
735          $page['where'] = ' AND '.$forbidden;
736        }
737
738        $conf['order_by'] = ' ORDER BY average_rate DESC, id ASC';
739
740        // $page['cat_nb_images'] equals $conf['top_number'] unless there
741        // are less rated items
742        $query ='
743SELECT COUNT(1) AS count
744  FROM '.IMAGES_TABLE.'
745  '.$page['where'].'
746;';
747        $row = mysql_fetch_array(mysql_query($query));
748        if ($row['count'] < $conf['top_number'])
749        {
750          $page['cat_nb_images'] = $row['count'];
751        }
752        else
753        {
754          $page['cat_nb_images'] = $conf['top_number'];
755        }
756        unset($query);
757         
758
759        if (isset($page['start'])
760            and ($page['start']+$user['nb_image_page']>=$conf['top_number']))
761        {
762          $page['nb_image_page'] = $conf['top_number'] - $page['start'];
763        }
764      }
765
766      if (isset($query))
767      {
768        $result = mysql_query( $query );
769        $row = mysql_fetch_array( $result );
770        $page['cat_nb_images'] = $row['nb_total_images'];
771      }
772    }
773    if ( $calling_page == 'category' )
774    {
775      $page['navigation_bar'] =
776        create_navigation_bar( $url, $page['cat_nb_images'], $page['start'],
777                               $user['nb_image_page'], 'back' );
778    }
779  }
780  else
781  {
782    $page['title'] = $lang['diapo_default_page_title'];
783  }
784  pwg_debug( 'end initialize_category' );
785}
786
787// get_non_empty_subcat_ids returns an array with sub-categories id
788// associated with their first non empty category id.
789//
790//                          example :
791//
792// - catname [cat_id]
793// - cat1 [1] -> given uppercat
794//   - cat1.1 [12] (empty)
795//     - cat1.1.1 [5] (empty)
796//     - cat1.1.2 [6]
797//   - cat1.2 [3]
798//   - cat1.3 [4]
799//
800// get_non_empty_sub_cat_ids will return :
801//   $ids[12] = 6;
802//   $ids[3]  = 3;
803//   $ids[4]  = 4;
804function get_non_empty_subcat_ids( $id_uppercat )
805{
806  global $user;
807
808  $ids = array();
809
810  $query = 'SELECT id,nb_images';
811  $query.= ' FROM '.CATEGORIES_TABLE;
812  $query.= ' WHERE id_uppercat ';
813  if ( !is_numeric( $id_uppercat ) ) $query.= 'is NULL';
814  else                               $query.= '= '.$id_uppercat;
815  // we must not show pictures of a forbidden category
816  if ( $user['forbidden_categories'] != '' )
817  {
818    $query.= ' AND id NOT IN ('.$user['forbidden_categories'].')';
819  }
820  $query.= ' ORDER BY rank';
821  $query.= ';';
822
823  $result = mysql_query( $query );
824  while ( $row = mysql_fetch_array( $result ) )
825  {
826    // only categories with findable picture in any of its subcats is
827    // represented.
828    if ( ( $row['nb_images'] != 0 and $non_empty_cat = $row['id'] )
829         or $non_empty_cat = get_first_non_empty_cat_id( $row['id'] ) )
830    {
831      $ids[$row['id']] = $non_empty_cat;
832    }
833  }
834  return $ids;
835}
836
837// get_first_non_empty_cat_id returns the id of the first non empty
838// sub-category to the given uppercat. If no picture is found in any
839// subcategory, false is returned.
840function get_first_non_empty_cat_id( $id_uppercat )
841{
842  global $user;
843
844  $query = 'SELECT id,nb_images';
845  $query.= ' FROM '.CATEGORIES_TABLE;
846  $query.= ' WHERE id_uppercat = '.$id_uppercat;
847  // we must not show pictures of a forbidden category
848  if ( $user['forbidden_categories'] != '' )
849  {
850    $query.= ' AND id NOT IN ('.$user['forbidden_categories'].')';
851  }
852  $query.= ' ORDER BY RAND()';
853  $query.= ';';
854  $result = mysql_query( $query );
855  while ( $row = mysql_fetch_array( $result ) )
856  {
857    if ( $row['nb_images'] > 0 )
858    {
859      return $row['id'];
860    }
861  }
862  $result = mysql_query( $query );
863  while ( $row = mysql_fetch_array( $result ) )
864  {
865    // recursive call
866    if ( $subcat = get_first_non_empty_cat_id( $row['id'] ) )
867    {
868      return $subcat;
869    }
870  }
871  return false;
872}
873?>
Note: See TracBrowser for help on using the repository browser.