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

Last change on this file since 2356 was 2356, checked in by rvelices, 16 years ago
  • merge r2355 from 1.7 to trunk: fix display of menubar related tags in IE7
  • optimized sql query in permalinks
  • remove some unused global variable declarations
  • fix bug in admin/themeconf.inc.php
  • Property svn:eol-style set to LF
  • Property svn:keywords set to Author Date Id Revision
File size: 13.0 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based picture gallery                                  |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008      Piwigo Team                  http://piwigo.org |
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// +-----------------------------------------------------------------------+
23
24/**
25 * Provides functions to handle categories.
26 *
27 *
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 */
39function check_restrictions($category_id)
40{
41  global $user;
42
43  // $filter['visible_categories'] and $filter['visible_images']
44  // are not used because it's not necessary (filter <> restriction)
45  if (in_array($category_id, explode(',', $user['forbidden_categories'])))
46  {
47    access_denied();
48  }
49}
50
51function get_categories_menu()
52{
53  global $page, $user, $filter;
54
55  $query = '
56SELECT ';
57  // From CATEGORIES_TABLE
58  $query.= '
59  id, name, permalink, nb_images, global_rank,';
60  // From USER_CACHE_CATEGORIES_TABLE
61  $query.= '
62  date_last, max_date_last, count_images, count_categories';
63
64  // $user['forbidden_categories'] including with USER_CACHE_CATEGORIES_TABLE
65  $query.= '
66FROM '.CATEGORIES_TABLE.' INNER JOIN '.USER_CACHE_CATEGORIES_TABLE.'
67  ON id = cat_id and user_id = '.$user['id'];
68
69  // Always expand when filter is activated
70  if (!$user['expand'] and !$filter['enabled'])
71  {
72    $where = '
73(id_uppercat is NULL';
74    if (isset($page['category']))
75    {
76      $where .= ' OR id_uppercat IN ('.$page['category']['uppercats'].')';
77    }
78    $where .= ')';
79  }
80  else
81  {
82    $where = '
83  '.get_sql_condition_FandF
84    (
85      array
86        (
87          'visible_categories' => 'id',
88        ),
89      null,
90      true
91    );
92  }
93
94  $where = trigger_event('get_categories_menu_sql_where',
95    $where, $user['expand'], $filter['enabled'] );
96
97  $query.= '
98WHERE '.$where.'
99;';
100
101  $result = pwg_query($query);
102  $cats = array();
103  while ($row = mysql_fetch_assoc($result))
104  {
105    array_push($cats, $row);
106  }
107  usort($cats, 'global_rank_compare');
108
109  // Update filtered data
110  if (function_exists('update_cats_with_filtered_data'))
111  {
112    update_cats_with_filtered_data($cats);
113  }
114
115  return get_html_menu_category($cats, @$page['category'] );
116}
117
118
119/**
120 * Retrieve informations about a category in the database
121 *
122 * Returns an array with following keys :
123 *
124 *  - comment
125 *  - dir : directory, might be empty for virtual categories
126 *  - name : an array with indexes from 0 (lowest cat name) to n (most
127 *           uppercat name findable)
128 *  - nb_images
129 *  - id_uppercat
130 *  - site_id
131 *  -
132 *
133 * @param int category id
134 * @return array
135 */
136function get_cat_info( $id )
137{
138  $query = '
139SELECT *
140  FROM '.CATEGORIES_TABLE.'
141  WHERE id = '.$id.'
142;';
143  $cat = mysql_fetch_assoc(pwg_query($query));
144  if (empty($cat))
145    return null;
146
147  foreach ($cat as $k => $v)
148  {
149    // If the field is true or false, the variable is transformed into a
150    // boolean value.
151    if ($cat[$k] == 'true' or $cat[$k] == 'false')
152    {
153      $cat[$k] = get_boolean( $cat[$k] );
154    }
155  }
156
157  $upper_ids = explode(',', $cat['uppercats']);
158  if ( count($upper_ids)==1 )
159  {// no need to make a query for level 1
160    $cat['upper_names'] = array(
161        array(
162          'id' => $cat['id'],
163          'name' => $cat['name'],
164          'permalink' => $cat['permalink'],
165          )
166      );
167  }
168  else
169  {
170    $names = array();
171    $query = '
172  SELECT id, name, permalink
173    FROM '.CATEGORIES_TABLE.'
174    WHERE id IN ('.$cat['uppercats'].')
175  ;';
176    $names = hash_from_query($query, 'id');
177
178    // category names must be in the same order than uppercats list
179    $cat['upper_names'] = array();
180    foreach ($upper_ids as $cat_id)
181    {
182      array_push( $cat['upper_names'], $names[$cat_id]);
183    }
184  }
185  return $cat;
186}
187
188// get_complete_dir returns the concatenation of get_site_url and
189// get_local_dir
190// Example : "pets > rex > 1_year_old" is on the the same site as the
191// Piwigo files and this category has 22 for identifier
192// get_complete_dir(22) returns "./galleries/pets/rex/1_year_old/"
193function get_complete_dir( $category_id )
194{
195  return get_site_url($category_id).get_local_dir($category_id);
196}
197
198// get_local_dir returns an array with complete path without the site url
199// Example : "pets > rex > 1_year_old" is on the the same site as the
200// Piwigo files and this category has 22 for identifier
201// get_local_dir(22) returns "pets/rex/1_year_old/"
202function get_local_dir( $category_id )
203{
204  global $page;
205
206  $uppercats = '';
207  $local_dir = '';
208
209  if ( isset( $page['plain_structure'][$category_id]['uppercats'] ) )
210  {
211    $uppercats = $page['plain_structure'][$category_id]['uppercats'];
212  }
213  else
214  {
215    $query = 'SELECT uppercats';
216    $query.= ' FROM '.CATEGORIES_TABLE.' WHERE id = '.$category_id;
217    $query.= ';';
218    $row = mysql_fetch_array( pwg_query( $query ) );
219    $uppercats = $row['uppercats'];
220  }
221
222  $upper_array = explode( ',', $uppercats );
223
224  $database_dirs = array();
225  $query = 'SELECT id,dir';
226  $query.= ' FROM '.CATEGORIES_TABLE.' WHERE id IN ('.$uppercats.')';
227  $query.= ';';
228  $result = pwg_query( $query );
229  while( $row = mysql_fetch_array( $result ) )
230  {
231    $database_dirs[$row['id']] = $row['dir'];
232  }
233  foreach ($upper_array as $id)
234  {
235    $local_dir.= $database_dirs[$id].'/';
236  }
237
238  return $local_dir;
239}
240
241// retrieving the site url : "http://domain.com/gallery/" or
242// simply "./galleries/"
243function get_site_url($category_id)
244{
245  global $page;
246
247  $query = '
248SELECT galleries_url
249  FROM '.SITES_TABLE.' AS s,'.CATEGORIES_TABLE.' AS c
250  WHERE s.id = c.site_id
251    AND c.id = '.$category_id.'
252;';
253  $row = mysql_fetch_array(pwg_query($query));
254  return $row['galleries_url'];
255}
256
257// returns an array of image orders available for users/visitors
258function get_category_preferred_image_orders()
259{
260  global $conf;
261  return array(
262    array(l10n('default_sort'), '', true),
263    array(l10n('Average rate'), 'average_rate DESC', $conf['rate']),
264    array(l10n('most_visited_cat'), 'hit DESC', true),
265    array(l10n('Creation date'), 'date_creation DESC', true),
266    array(l10n('Post date'), 'date_available DESC', true),
267    array(l10n('File name'), 'file ASC', true)
268  );
269}
270
271function display_select_categories($categories,
272                                   $selecteds,
273                                   $blockname,
274                                   $fullname = true)
275{
276  global $template;
277
278  $tpl_cats = array();
279  foreach ($categories as $category)
280  {
281    if ($fullname)
282    {
283      $option = get_cat_display_name_cache($category['uppercats'],
284                                           null,
285                                           false);
286    }
287    else
288    {
289      $option = str_repeat('&nbsp;',
290                           (3 * substr_count($category['global_rank'], '.')));
291      $option.= '- '.$category['name'];
292    }
293    $tpl_cats[ $category['id'] ] = $option;
294  }
295
296  $template->assign( $blockname, $tpl_cats);
297  $template->assign( $blockname.'_selected', $selecteds);
298}
299
300function display_select_cat_wrapper($query, $selecteds, $blockname,
301                                    $fullname = true)
302{
303  $result = pwg_query($query);
304  $categories = array();
305  if (!empty($result))
306  {
307    while ($row = mysql_fetch_assoc($result))
308    {
309      array_push($categories, $row);
310    }
311  }
312  usort($categories, 'global_rank_compare');
313  display_select_categories($categories, $selecteds, $blockname, $fullname);
314}
315
316/**
317 * returns all subcategory identifiers of given category ids
318 *
319 * @param array ids
320 * @return array
321 */
322function get_subcat_ids($ids)
323{
324  $query = '
325SELECT DISTINCT(id)
326  FROM '.CATEGORIES_TABLE.'
327  WHERE ';
328  foreach ($ids as $num => $category_id)
329  {
330    is_numeric($category_id)
331      or trigger_error(
332        'get_subcat_ids expecting numeric, not '.gettype($category_id),
333        E_USER_WARNING
334      );
335    if ($num > 0)
336    {
337      $query.= '
338    OR ';
339    }
340    $query.= 'uppercats REGEXP \'(^|,)'.$category_id.'(,|$)\'';
341  }
342  $query.= '
343;';
344  $result = pwg_query($query);
345
346  $subcats = array();
347  while ($row = mysql_fetch_array($result))
348  {
349    array_push($subcats, $row['id']);
350  }
351  return $subcats;
352}
353
354/** finds a matching category id from a potential list of permalinks
355 * @param array permalinks example: holiday holiday/france holiday/france/paris
356 * @param int idx - output of the index in $permalinks that matches
357 * return category id or null if no match
358 */
359function get_cat_id_from_permalinks( $permalinks, &$idx )
360{
361  $in = '';
362  foreach($permalinks as $permalink)
363  {
364    if ( !empty($in) ) $in.=', ';
365    $in .= '"'.$permalink.'"';
366  }
367  $query ='
368SELECT cat_id AS id, permalink, 1 AS is_old
369  FROM '.OLD_PERMALINKS_TABLE.'
370  WHERE permalink IN ('.$in.')
371UNION
372SELECT id, permalink, 0 AS is_old
373  FROM '.CATEGORIES_TABLE.'
374  WHERE permalink IN ('.$in.')
375;';
376  $perma_hash = hash_from_query($query, 'permalink');
377
378  if ( empty($perma_hash) )
379    return null;
380  for ($i=count($permalinks)-1; $i>=0; $i--)
381  {
382    if ( isset( $perma_hash[ $permalinks[$i] ] ) )
383    {
384      $idx = $i;
385      $cat_id = $perma_hash[ $permalinks[$i] ]['id'];
386      if ($perma_hash[ $permalinks[$i] ]['is_old'])
387      {
388        $query='
389UPDATE '.OLD_PERMALINKS_TABLE.' SET last_hit=NOW(), hit=hit+1
390  WHERE permalink="'.$permalinks[$i].'" AND cat_id='.$cat_id.'
391  LIMIT 1';
392        pwg_query($query);
393      }
394      return $cat_id;
395    }
396  }
397  return null;
398}
399
400function global_rank_compare($a, $b)
401{
402  return strnatcasecmp($a['global_rank'], $b['global_rank']);
403}
404
405function rank_compare($a, $b)
406{
407  if ($a['rank'] == $b['rank'])
408  {
409    return 0;
410  }
411
412  return ($a['rank'] < $b['rank']) ? -1 : 1;
413}
414
415/**
416 * returns display text for information images of category
417 *
418 * @param array categories
419 * @return string
420 */
421function get_display_images_count($cat_nb_images, $cat_count_images, $cat_count_categories, $short_message = true, $Separator = '\n')
422{
423  $display_text = '';
424
425  if ($cat_count_images > 0)
426  {
427    if ($cat_nb_images > 0 and $cat_nb_images < $cat_count_images)
428    {
429      $display_text.= get_display_images_count($cat_nb_images, $cat_nb_images, 0, $short_message, $Separator).$Separator;
430      $cat_count_images-= $cat_nb_images;
431      $cat_nb_images = 0;
432    }
433
434    //at least one image direct or indirect
435    $display_text.= l10n_dec('%d element', '%d elements', $cat_count_images);
436
437    if ($cat_count_categories == 0 or $cat_nb_images == $cat_count_images)
438    {
439      //no descendant categories or descendants do not contain images
440      if (! $short_message)
441      {
442        $display_text.= ' '.l10n('images_available_cpl');
443      }
444    }
445    else
446    {
447      $display_text.= ' '.l10n_dec('images_available_cat', 'images_available_cats', $cat_count_categories);
448    }
449  }
450
451  return $display_text;
452}
453
454/**
455 * returns the link of upload menu
456 *
457 * @param null
458 * @return string or null
459 */
460function get_upload_menu_link()
461{
462  global $conf, $page, $user;
463
464  $show_link = false;
465  $arg_link = null;
466
467  if (is_autorize_status($conf['upload_user_access']))
468  {
469    if (isset($page['category']) and $page['category']['uploadable'] )
470    {
471      // upload a picture in the category
472      $show_link = true;
473      $arg_link = 'cat='.$page['category']['id'];
474    }
475    else
476    if ($conf['upload_link_everytime'])
477    {
478      // upload a picture in the category
479      $query = '
480SELECT
481  1
482FROM '.CATEGORIES_TABLE.' INNER JOIN '.USER_CACHE_CATEGORIES_TABLE.'
483  ON id = cat_id and user_id = '.$user['id'].'
484WHERE
485  uploadable = \'true\'
486  '.get_sql_condition_FandF
487    (
488      array
489        (
490          'visible_categories' => 'id',
491        ),
492      'AND'
493    ).'
494LIMIT 1';
495
496      $show_link = mysql_num_rows(pwg_query($query)) <> 0;
497    }
498  }
499  if ($show_link)
500  {
501    return get_root_url().'upload.php'.(empty($arg_link) ? '' : '?'.$arg_link);
502  }
503  else
504  {
505    return;
506  }
507}
508
509?>
Note: See TracBrowser for help on using the repository browser.