Subversion Repositories svnkaklik

Rev

Go to most recent revision | Details | Last modification | View Log

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