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

Last change on this file since 3108 was 3049, checked in by plg, 16 years ago

Administration: happy new year 2009, all PHP headers updated.

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