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

Last change on this file since 496 was 496, checked in by gweltas, 20 years ago
  • Deletion of obsolete functions in the administrative part
  • Repair of virtual category management
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 24.8 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-25 22:25:58 +0000 (Wed, 25 Aug 2004) $
10// | last modifier : $Author: gweltas $
11// | revision      : $Revision: 496 $
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 ( 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          $local_clause = 'category_id IN (';
575          $local_clause.= implode(',',$search['fields']['cat']['words']);
576          $local_clause.= ')';
577          array_push($clauses, $local_clause);
578        }
579
580        // adds brackets around where clauses
581        array_walk($clauses, create_function('&$s', '$s = "(".$s.")";'));
582        $page['where'] = 'WHERE '.implode(' '.$search['mode'].' ', $clauses);
583        if ( isset( $forbidden ) ) $page['where'].= ' AND '.$forbidden;
584
585        $query = '
586SELECT COUNT(DISTINCT(id)) AS nb_total_images
587  FROM '.IMAGES_TABLE.'
588    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
589  '.$page['where'].'
590;';
591        $url.= '&amp;search='.$_GET['search'];
592      }
593      // favorites displaying
594      else if ( $page['cat'] == 'fav' )
595      {
596        $page['title'] = $lang['favorites'];
597
598        $page['where'] = ', '.FAVORITES_TABLE.' AS fav';
599        $page['where'].= ' WHERE user_id = '.$user['id'];
600        $page['where'].= ' AND fav.image_id = id';
601     
602        $query = 'SELECT COUNT(*) AS nb_total_images';
603        $query.= ' FROM '.FAVORITES_TABLE;
604        $query.= ' WHERE user_id = '.$user['id'];
605        $query.= ';';
606      }
607      // pictures within the short period
608      else if ( $page['cat'] == 'recent_pics' )
609      {
610        $page['title'] = $lang['recent_pics_cat'];
611        // We must find the date corresponding to :
612        // today - $conf['periode_courte']
613        $date = time() - 60*60*24*$user['recent_period'];
614        $page['where'] = " WHERE date_available > '";
615        $page['where'].= date( 'Y-m-d', $date )."'";
616        if ( isset( $forbidden ) ) $page['where'].= ' AND '.$forbidden;
617
618        $query = 'SELECT COUNT(DISTINCT(id)) AS nb_total_images';
619        $query.= ' FROM '.IMAGES_TABLE;
620        $query.= ' INNER JOIN '.PREFIX_TABLE.'image_category AS ic';
621        $query.= ' ON id = ic.image_id';
622        $query.= $page['where'];
623        $query.= ';';
624      }
625      // categories containing recent pictures
626      else if ( $page['cat'] == 'recent_cats' )
627      {
628        $page['title'] = $lang['recent_cats_cat'];
629        $page['cat_nb_images'] = 0;
630      }
631      // most visited pictures
632      else if ( $page['cat'] == 'most_visited' )
633      {
634        $page['title'] = $conf['top_number'].' '.$lang['most_visited_cat'];
635       
636        if ( isset( $forbidden ) ) $page['where'] = ' WHERE '.$forbidden;
637        else                       $page['where'] = '';
638        $conf['order_by'] = ' ORDER BY hit DESC, file ASC';
639        $page['cat_nb_images'] = $conf['top_number'];
640        if ( isset( $page['start'] )
641             and ($page['start']+$user['nb_image_page']>=$conf['top_number']))
642        {
643          $page['nb_image_page'] = $conf['top_number'] - $page['start'];
644        }
645      }
646      else if ( $page['cat'] == 'calendar' )
647      {
648        $page['cat_nb_images'] = 0;
649        $page['title'] = $lang['calendar'];
650        if (isset($_GET['year'])
651            and preg_match('/^\d+$/', $_GET['year']))
652        {
653          $page['calendar_year'] = (int)$_GET['year'];
654        }
655        if (isset($_GET['month'])
656            and preg_match('/^(\d+)\.(\d{2})$/', $_GET['month'], $matches))
657        {
658          $page['calendar_year'] = (int)$matches[1];
659          $page['calendar_month'] = (int)$matches[2];
660        }
661        if (isset($_GET['day'])
662            and preg_match('/^(\d+)\.(\d{2})\.(\d{2})$/',
663                           $_GET['day'],
664                           $matches))
665        {
666          $page['calendar_year'] = (int)$matches[1];
667          $page['calendar_month'] = (int)$matches[2];
668          $page['calendar_day'] = (int)$matches[3];
669        }
670        if (isset($page['calendar_year']))
671        {
672          $page['title'] .= ' (';
673          if (isset($page['calendar_day']))
674          {
675            $unixdate = mktime(0,0,0,
676                               $page['calendar_month'],
677                               $page['calendar_day'],
678                               $page['calendar_year']);
679            $page['title'].= $lang['day'][date("w", $unixdate)];
680            $page['title'].= ' '.$page['calendar_day'].', ';
681          }
682          if (isset($page['calendar_month']))
683          {
684            $page['title'] .= $lang['month'][$page['calendar_month']].' ';
685          }
686          $page['title'] .= $page['calendar_year'];
687          $page['title'] .= ')';
688        }
689        if (isset($forbidden))
690        {
691          $page['where'] = 'WHERE '.$forbidden;
692        }
693        else
694        {
695          $page['where'] = 'WHERE 1=1';
696        }
697      }
698
699      if (isset($query))
700      {
701        $result = mysql_query( $query );
702        $row = mysql_fetch_array( $result );
703        $page['cat_nb_images'] = $row['nb_total_images'];
704      }
705    }
706    if ( $calling_page == 'category' )
707    {
708      $page['navigation_bar'] =
709        create_navigation_bar( $url, $page['cat_nb_images'], $page['start'],
710                               $user['nb_image_page'], 'back' );
711    }
712  }
713  else
714  {
715    $page['title'] = $lang['diapo_default_page_title'];
716  }
717  pwg_debug( 'end initialize_category' );
718}
719
720// get_non_empty_subcat_ids returns an array with sub-categories id
721// associated with their first non empty category id.
722//
723//                          example :
724//
725// - catname [cat_id]
726// - cat1 [1] -> given uppercat
727//   - cat1.1 [12] (empty)
728//     - cat1.1.1 [5] (empty)
729//     - cat1.1.2 [6]
730//   - cat1.2 [3]
731//   - cat1.3 [4]
732//
733// get_non_empty_sub_cat_ids will return :
734//   $ids[12] = 6;
735//   $ids[3]  = 3;
736//   $ids[4]  = 4;
737function get_non_empty_subcat_ids( $id_uppercat )
738{
739  global $user;
740
741  $ids = array();
742
743  $query = 'SELECT id,nb_images';
744  $query.= ' FROM '.CATEGORIES_TABLE;
745  $query.= ' WHERE id_uppercat ';
746  if ( !is_numeric( $id_uppercat ) ) $query.= 'is NULL';
747  else                               $query.= '= '.$id_uppercat;
748  // we must not show pictures of a forbidden category
749  if ( $user['forbidden_categories'] != '' )
750  {
751    $query.= ' AND id NOT IN ('.$user['forbidden_categories'].')';
752  }
753  $query.= ' ORDER BY rank';
754  $query.= ';';
755
756  $result = mysql_query( $query );
757  while ( $row = mysql_fetch_array( $result ) )
758  {
759    // only categories with findable picture in any of its subcats is
760    // represented.
761    if ( ( $row['nb_images'] != 0 and $non_empty_cat = $row['id'] )
762         or $non_empty_cat = get_first_non_empty_cat_id( $row['id'] ) )
763    {
764      $ids[$row['id']] = $non_empty_cat;
765    }
766  }
767  return $ids;
768}
769
770// get_first_non_empty_cat_id returns the id of the first non empty
771// sub-category to the given uppercat. If no picture is found in any
772// subcategory, false is returned.
773function get_first_non_empty_cat_id( $id_uppercat )
774{
775  global $user;
776
777  $query = 'SELECT id,nb_images';
778  $query.= ' FROM '.CATEGORIES_TABLE;
779  $query.= ' WHERE id_uppercat = '.$id_uppercat;
780  // we must not show pictures of a forbidden category
781  if ( $user['forbidden_categories'] != '' )
782  {
783    $query.= ' AND id NOT IN ('.$user['forbidden_categories'].')';
784  }
785  $query.= ' ORDER BY RAND()';
786  $query.= ';';
787  $result = mysql_query( $query );
788  while ( $row = mysql_fetch_array( $result ) )
789  {
790    if ( $row['nb_images'] > 0 )
791    {
792      return $row['id'];
793    }
794  }
795  $result = mysql_query( $query );
796  while ( $row = mysql_fetch_array( $result ) )
797  {
798    // recursive call
799    if ( $subcat = get_first_non_empty_cat_id( $row['id'] ) )
800    {
801      return $subcat;
802    }
803  }
804  return false;
805}
806?>
Note: See TracBrowser for help on using the repository browser.