source: branches/2.2/include/functions_category.inc.php @ 22544

Last change on this file since 22544 was 11513, checked in by mistic100, 13 years ago

merge r11512 form trunk
bug:2361 fixed : remove html tags in categories drop-down lists

  • Property svn:eol-style set to LF
File size: 15.2 KB
RevLine 
[2]1<?php
[362]2// +-----------------------------------------------------------------------+
[8728]3// | Piwigo - a PHP based photo gallery                                    |
[2297]4// +-----------------------------------------------------------------------+
[8728]5// | Copyright(C) 2008-2011 Piwigo Team                  http://piwigo.org |
[2297]6// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
7// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
8// +-----------------------------------------------------------------------+
9// | This program is free software; you can redistribute it and/or modify  |
10// | it under the terms of the GNU General Public License as published by  |
11// | the Free Software Foundation                                          |
12// |                                                                       |
13// | This program is distributed in the hope that it will be useful, but   |
14// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
15// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
16// | General Public License for more details.                              |
17// |                                                                       |
18// | You should have received a copy of the GNU General Public License     |
19// | along with this program; if not, write to the Free Software           |
20// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
21// | USA.                                                                  |
22// +-----------------------------------------------------------------------+
[2]23
[423]24/**
25 * Provides functions to handle categories.
26 *
[1059]27 *
[423]28 */
29
30/**
31 * Is the category accessible to the connected user ?
32 *
33 * Note : if the user is not authorized to see this category, page creation
34 * ends (exit command in this function)
35 *
36 * @param int category id to verify
37 * @return void
38 */
[808]39function check_restrictions($category_id)
[2]40{
[1113]41  global $user;
[2]42
[1677]43  // $filter['visible_categories'] and $filter['visible_images']
44  // are not used because it's not necessary (filter <> restriction)
[808]45  if (in_array($category_id, explode(',', $user['forbidden_categories'])))
[2]46  {
[1113]47    access_denied();
[2]48  }
49}
[345]50
[614]51function get_categories_menu()
[2]52{
[1677]53  global $page, $user, $filter;
[1059]54
[1624]55  $query = '
56SELECT ';
57  // From CATEGORIES_TABLE
58  $query.= '
[1866]59  id, name, permalink, nb_images, global_rank,';
[1624]60  // From USER_CACHE_CATEGORIES_TABLE
61  $query.= '
[1641]62  date_last, max_date_last, count_images, count_categories';
[1059]63
[1624]64  // $user['forbidden_categories'] including with USER_CACHE_CATEGORIES_TABLE
65  $query.= '
[1677]66FROM '.CATEGORIES_TABLE.' INNER JOIN '.USER_CACHE_CATEGORIES_TABLE.'
[1624]67  ON id = cat_id and user_id = '.$user['id'];
[1677]68
69  // Always expand when filter is activated
70  if (!$user['expand'] and !$filter['enabled'])
[345]71  {
[2070]72    $where = '
[1677]73(id_uppercat is NULL';
74    if (isset($page['category']))
75    {
[2070]76      $where .= ' OR id_uppercat IN ('.$page['category']['uppercats'].')';
[1677]77    }
[2070]78    $where .= ')';
[1648]79  }
80  else
81  {
[2070]82    $where = '
[1677]83  '.get_sql_condition_FandF
84    (
85      array
86        (
87          'visible_categories' => 'id',
88        ),
[2070]89      null,
90      true
[1677]91    );
[2]92  }
[1677]93
[2070]94  $where = trigger_event('get_categories_menu_sql_where',
95    $where, $user['expand'], $filter['enabled'] );
96
[589]97  $query.= '
[2070]98WHERE '.$where.'
[589]99;';
[26]100
[589]101  $result = pwg_query($query);
[614]102  $cats = array();
[3171]103  $selected_category = isset($page['category']) ? $page['category'] : null;
[4325]104  while ($row = pwg_db_fetch_assoc($result))
[2]105  {
[3171]106    $child_date_last = @$row['max_date_last']> @$row['date_last'];
107    $row = array_merge($row,
108      array(
109        'NAME' => trigger_event(
110          'render_category_name',
111          $row['name'],
112          'get_categories_menu'
113        ),
114        'TITLE' => get_display_images_count(
115          $row['nb_images'],
116          $row['count_images'],
117          $row['count_categories'],
118          false,
119          ' / '
120        ),
121        'URL' => make_index_url(array('category' => $row)),
122        'LEVEL' => substr_count($row['global_rank'], '.') + 1,
[3188]123        'icon_ts' => get_icon($row['max_date_last'], $child_date_last),
[3171]124        'SELECTED' => $selected_category['id'] == $row['id'] ? true : false,
125        'IS_UPPERCAT' => $selected_category['id_uppercat'] == $row['id'] ? true : false,
126      )
127    );
[614]128    array_push($cats, $row);
[2586]129    if ($row['id']==@$page['category']['id']) //save the number of subcats for later optim
130      $page['category']['count_categories'] = $row['count_categories'];
[26]131  }
[614]132  usort($cats, 'global_rank_compare');
[2]133
[1677]134  // Update filtered data
[1722]135  if (function_exists('update_cats_with_filtered_data'))
136  {
137    update_cats_with_filtered_data($cats);
138  }
[1677]139
[3171]140  return $cats;
[26]141}
[2]142
[1624]143
[761]144/**
[423]145 * Retrieve informations about a category in the database
146 *
147 * Returns an array with following keys :
148 *
149 *  - comment
150 *  - dir : directory, might be empty for virtual categories
151 *  - name : an array with indexes from 0 (lowest cat name) to n (most
152 *           uppercat name findable)
153 *  - nb_images
154 *  - id_uppercat
155 *  - site_id
[1059]156 *  -
[423]157 *
158 * @param int category id
159 * @return array
160 */
[2]161function get_cat_info( $id )
162{
[603]163  $query = '
[1861]164SELECT *
[603]165  FROM '.CATEGORIES_TABLE.'
166  WHERE id = '.$id.'
167;';
[4325]168  $cat = pwg_db_fetch_assoc(pwg_query($query));
[1861]169  if (empty($cat))
[1288]170    return null;
[345]171
[1861]172  foreach ($cat as $k => $v)
[603]173  {
[345]174    // If the field is true or false, the variable is transformed into a
175    // boolean value.
[1861]176    if ($cat[$k] == 'true' or $cat[$k] == 'false')
[345]177    {
[1861]178      $cat[$k] = get_boolean( $cat[$k] );
[345]179    }
180  }
181
[1866]182  $upper_ids = explode(',', $cat['uppercats']);
183  if ( count($upper_ids)==1 )
184  {// no need to make a query for level 1
185    $cat['upper_names'] = array(
186        array(
187          'id' => $cat['id'],
188          'name' => $cat['name'],
189          'permalink' => $cat['permalink'],
190          )
191      );
192  }
193  else
[2]194  {
[1866]195    $names = array();
196    $query = '
197  SELECT id, name, permalink
198    FROM '.CATEGORIES_TABLE.'
199    WHERE id IN ('.$cat['uppercats'].')
200  ;';
201    $names = hash_from_query($query, 'id');
[672]202
[1866]203    // category names must be in the same order than uppercats list
204    $cat['upper_names'] = array();
205    foreach ($upper_ids as $cat_id)
206    {
207      array_push( $cat['upper_names'], $names[$cat_id]);
208    }
[672]209  }
[2]210  return $cat;
211}
[61]212
213// get_complete_dir returns the concatenation of get_site_url and
214// get_local_dir
215// Example : "pets > rex > 1_year_old" is on the the same site as the
[2339]216// Piwigo files and this category has 22 for identifier
[61]217// get_complete_dir(22) returns "./galleries/pets/rex/1_year_old/"
218function get_complete_dir( $category_id )
219{
[579]220  return get_site_url($category_id).get_local_dir($category_id);
[61]221}
222
223// get_local_dir returns an array with complete path without the site url
224// Example : "pets > rex > 1_year_old" is on the the same site as the
[2339]225// Piwigo files and this category has 22 for identifier
[61]226// get_local_dir(22) returns "pets/rex/1_year_old/"
227function get_local_dir( $category_id )
228{
229  global $page;
230
[345]231  $uppercats = '';
232  $local_dir = '';
233
234  if ( isset( $page['plain_structure'][$category_id]['uppercats'] ) )
[61]235  {
[345]236    $uppercats = $page['plain_structure'][$category_id]['uppercats'];
[61]237  }
[345]238  else
239  {
240    $query = 'SELECT uppercats';
241    $query.= ' FROM '.CATEGORIES_TABLE.' WHERE id = '.$category_id;
242    $query.= ';';
[4325]243    $row = pwg_db_fetch_assoc( pwg_query( $query ) );
[345]244    $uppercats = $row['uppercats'];
245  }
246
247  $upper_array = explode( ',', $uppercats );
248
249  $database_dirs = array();
250  $query = 'SELECT id,dir';
251  $query.= ' FROM '.CATEGORIES_TABLE.' WHERE id IN ('.$uppercats.')';
252  $query.= ';';
[587]253  $result = pwg_query( $query );
[4325]254  while( $row = pwg_db_fetch_assoc( $result ) )
[345]255  {
256    $database_dirs[$row['id']] = $row['dir'];
257  }
[579]258  foreach ($upper_array as $id)
259  {
[345]260    $local_dir.= $database_dirs[$id].'/';
261  }
262
263  return $local_dir;
[61]264}
265
266// retrieving the site url : "http://domain.com/gallery/" or
267// simply "./galleries/"
[579]268function get_site_url($category_id)
[61]269{
270  global $page;
271
[579]272  $query = '
273SELECT galleries_url
274  FROM '.SITES_TABLE.' AS s,'.CATEGORIES_TABLE.' AS c
275  WHERE s.id = c.site_id
276    AND c.id = '.$category_id.'
277;';
[4325]278  $row = pwg_db_fetch_assoc(pwg_query($query));
[61]279  return $row['galleries_url'];
280}
281
[1020]282// returns an array of image orders available for users/visitors
283function get_category_preferred_image_orders()
284{
[2517]285  global $conf, $page;
[2521]286
287  return trigger_event('get_category_preferred_image_orders',
288    array(
[5021]289    array(l10n('Default'), '', true),
[1042]290    array(l10n('Average rate'), 'average_rate DESC', $conf['rate']),
[5021]291    array(l10n('Most visited'), 'hit DESC', true),
[1031]292    array(l10n('Creation date'), 'date_creation DESC', true),
[1059]293    array(l10n('Post date'), 'date_available DESC', true),
[2517]294    array(l10n('File name'), 'file ASC', true),
295    array(
296      l10n('Rank'),
297      'rank ASC',
[2572]298      ('categories' == @$page['section'] and !isset($page['flat']) and !isset($page['chronology_field']) )
[2770]299      ),
[5021]300    array( l10n('Permissions'), 'level DESC', is_admin() )
[2521]301    ));
[1020]302}
303
[589]304function display_select_categories($categories,
305                                   $selecteds,
[602]306                                   $blockname,
[614]307                                   $fullname = true)
[589]308{
[614]309  global $template;
[589]310
[2223]311  $tpl_cats = array();
312  foreach ($categories as $category)
313  {
[5192]314    if (!empty($category['permalink']))
315    {
316      $category['name'] .= ' &radic;';
317    }
[2223]318    if ($fullname)
319    {
[11513]320      $option = strip_tags(
321        get_cat_display_name_cache(
322          $category['uppercats'],
323          null,
324          false
325          )
326        );
[2223]327    }
328    else
329    {
330      $option = str_repeat('&nbsp;',
331                           (3 * substr_count($category['global_rank'], '.')));
[2433]332      $option.= '- ';
333      $option.= strip_tags(
334        trigger_event(
335          'render_category_name',
336          $category['name'],
337          'display_select_categories'
338          )
339        );
[2223]340    }
341    $tpl_cats[ $category['id'] ] = $option;
342  }
343
[2290]344  $template->assign( $blockname, $tpl_cats);
345  $template->assign( $blockname.'_selected', $selecteds);
[589]346}
[603]347
[614]348function display_select_cat_wrapper($query, $selecteds, $blockname,
349                                    $fullname = true)
350{
351  $result = pwg_query($query);
352  $categories = array();
[655]353  if (!empty($result))
354  {
[4325]355    while ($row = pwg_db_fetch_assoc($result))
[657]356    {
357      array_push($categories, $row);
358    }
[614]359  }
360  usort($categories, 'global_rank_compare');
361  display_select_categories($categories, $selecteds, $blockname, $fullname);
362}
363
[603]364/**
365 * returns all subcategory identifiers of given category ids
366 *
367 * @param array ids
368 * @return array
369 */
370function get_subcat_ids($ids)
371{
372  $query = '
373SELECT DISTINCT(id)
374  FROM '.CATEGORIES_TABLE.'
375  WHERE ';
376  foreach ($ids as $num => $category_id)
377  {
[1861]378    is_numeric($category_id)
379      or trigger_error(
380        'get_subcat_ids expecting numeric, not '.gettype($category_id),
381        E_USER_WARNING
382      );
[603]383    if ($num > 0)
384    {
385      $query.= '
386    OR ';
387    }
[4367]388    $query.= 'uppercats '.DB_REGEX_OPERATOR.' \'(^|,)'.$category_id.'(,|$)\'';
[603]389  }
390  $query.= '
391;';
392  $result = pwg_query($query);
393
394  $subcats = array();
[4325]395  while ($row = pwg_db_fetch_assoc($result))
[603]396  {
397    array_push($subcats, $row['id']);
398  }
399  return $subcats;
400}
[614]401
[2047]402/** finds a matching category id from a potential list of permalinks
403 * @param array permalinks example: holiday holiday/france holiday/france/paris
404 * @param int idx - output of the index in $permalinks that matches
405 * return category id or null if no match
[1866]406 */
[2047]407function get_cat_id_from_permalinks( $permalinks, &$idx )
[1866]408{
[2047]409  $in = '';
410  foreach($permalinks as $permalink)
[1866]411  {
[2047]412    if ( !empty($in) ) $in.=', ';
[6664]413    $in .= '\''.$permalink.'\'';
[1866]414  }
[2047]415  $query ='
[2356]416SELECT cat_id AS id, permalink, 1 AS is_old
417  FROM '.OLD_PERMALINKS_TABLE.'
418  WHERE permalink IN ('.$in.')
[2047]419UNION
420SELECT id, permalink, 0 AS is_old
421  FROM '.CATEGORIES_TABLE.'
422  WHERE permalink IN ('.$in.')
423;';
424  $perma_hash = hash_from_query($query, 'permalink');
[1866]425
[2047]426  if ( empty($perma_hash) )
427    return null;
428  for ($i=count($permalinks)-1; $i>=0; $i--)
[1866]429  {
[2047]430    if ( isset( $perma_hash[ $permalinks[$i] ] ) )
431    {
432      $idx = $i;
433      $cat_id = $perma_hash[ $permalinks[$i] ]['id'];
434      if ($perma_hash[ $permalinks[$i] ]['is_old'])
435      {
436        $query='
[1866]437UPDATE '.OLD_PERMALINKS_TABLE.' SET last_hit=NOW(), hit=hit+1
[6654]438  WHERE permalink=\''.$permalinks[$i].'\' AND cat_id='.$cat_id.'
[1866]439  LIMIT 1';
[2047]440        pwg_query($query);
441      }
442      return $cat_id;
443    }
[1866]444  }
[2047]445  return null;
[1866]446}
447
[614]448function global_rank_compare($a, $b)
449{
450  return strnatcasecmp($a['global_rank'], $b['global_rank']);
451}
[1036]452
453function rank_compare($a, $b)
454{
455  if ($a['rank'] == $b['rank'])
456  {
457    return 0;
458  }
459
460  return ($a['rank'] < $b['rank']) ? -1 : 1;
461}
[1624]462
463/**
464 * returns display text for information images of category
465 *
466 * @param array categories
467 * @return string
468 */
[1851]469function get_display_images_count($cat_nb_images, $cat_count_images, $cat_count_categories, $short_message = true, $Separator = '\n')
[1624]470{
471  $display_text = '';
472
[1851]473  if ($cat_count_images > 0)
474  {
475    if ($cat_nb_images > 0 and $cat_nb_images < $cat_count_images)
476    {
477      $display_text.= get_display_images_count($cat_nb_images, $cat_nb_images, 0, $short_message, $Separator).$Separator;
478      $cat_count_images-= $cat_nb_images;
479      $cat_nb_images = 0;
480    }
[2117]481
[1851]482    //at least one image direct or indirect
[8665]483    $display_text.= l10n_dec('%d photo', '%d photos', $cat_count_images);
[1624]484
[1851]485    if ($cat_count_categories == 0 or $cat_nb_images == $cat_count_images)
486    {
487      //no descendant categories or descendants do not contain images
[1624]488      if (! $short_message)
489      {
[6951]490        $display_text.= ' '.l10n('in this album');
[1624]491      }
492    }
493    else
494    {
[6951]495      $display_text.= ' '.l10n_dec('in %d sub-album', 'in %d sub-albums', $cat_count_categories);
[1624]496    }
497  }
498
499  return $display_text;
500}
501
[8802]502/**
503 * Find a random photo among all photos below a given album in the tree (not
504 * only photo directly associated to the album but also to sub-albums)
505 *
506 * we need $category['uppercats'], $category['id'], $category['count_images']
507 */
[11486]508function get_random_image_in_category($category, $recursive=true)
[8802]509{
510  $image_id = null;
511  if ($category['count_images']>0)
512  {
513    $query = '
514SELECT image_id
515  FROM '.CATEGORIES_TABLE.' AS c
516    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON ic.category_id = c.id
[11486]517  WHERE ';
518    if ($recursive)
519    {
520      $query.= '
521    (c.id='.$category['id'].' OR uppercats LIKE \''.$category['uppercats'].',%\')';
522    }
523    else
524    {
525      $query.= '
526    c.id='.$category['id'];
527    }
528    $query.= '
529    '.get_sql_condition_FandF
[8802]530    (
531      array
532        (
533          'forbidden_categories' => 'c.id',
534          'visible_categories' => 'c.id',
535          'visible_images' => 'image_id',
536        ),
537      "\n  AND"
538    ).'
539  ORDER BY '.DB_RANDOM_FUNCTION.'()
540  LIMIT 1
541;';
542    $result = pwg_query($query);
543    if (pwg_db_num_rows($result) > 0)
544    {
545      list($image_id) = pwg_db_fetch_row($result);
546    }
547  }
548
549  return $image_id;
550}
[11152]551
552/**
553 * create a tree from a flat list of categories, no recursivity for high speed
554 */
555function categories_flatlist_to_tree($categories)
556{
557  $tree = array();
558  $key_of_cat = array();
559 
560  foreach ($categories as $key => &$node)
561  {
562    $key_of_cat[$node['id']] = $key;
563   
564    if (!isset($node['id_uppercat']))
565    {
566      $tree[$key] = &$node;
567    }
568    else
569    {
570      if (!isset($categories[ $key_of_cat[ $node['id_uppercat'] ] ]['sub_categories']))
571      {
572        $categories[ $key_of_cat[ $node['id_uppercat'] ] ]['sub_categories'] = array();
573      }
574     
575      $categories[ $key_of_cat[ $node['id_uppercat'] ] ]['sub_categories'][$key] = &$node;
576    }
577  }
578 
579  return $tree;
580}
[2770]581?>
Note: See TracBrowser for help on using the repository browser.