source: branches/2.0/include/functions_category.inc.php @ 2765

Last change on this file since 2765 was 2586, checked in by rvelices, 16 years ago
  • sql optim: do not include category_cats (which makes a query) if current category does not have children (info known when building menubar)
  • in index.php - fill the template completely before including menubar/category_cats/thumbnails (some themes might want to use in the menubar some vars ...)
  • Property svn:eol-style set to LF
  • Property svn:keywords set to Author Date Id Revision
File size: 13.5 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    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    ));
278}
279
280function display_select_categories($categories,
281                                   $selecteds,
282                                   $blockname,
283                                   $fullname = true)
284{
285  global $template;
286
287  $tpl_cats = array();
288  foreach ($categories as $category)
289  {
290    if ($fullname)
291    {
292      $option = get_cat_display_name_cache($category['uppercats'],
293                                           null,
294                                           false);
295    }
296    else
297    {
298      $option = str_repeat('&nbsp;',
299                           (3 * substr_count($category['global_rank'], '.')));
300      $option.= '- ';
301      $option.= strip_tags(
302        trigger_event(
303          'render_category_name',
304          $category['name'],
305          'display_select_categories'
306          )
307        );
308    }
309    $tpl_cats[ $category['id'] ] = $option;
310  }
311
312  $template->assign( $blockname, $tpl_cats);
313  $template->assign( $blockname.'_selected', $selecteds);
314}
315
316function display_select_cat_wrapper($query, $selecteds, $blockname,
317                                    $fullname = true)
318{
319  $result = pwg_query($query);
320  $categories = array();
321  if (!empty($result))
322  {
323    while ($row = mysql_fetch_assoc($result))
324    {
325      array_push($categories, $row);
326    }
327  }
328  usort($categories, 'global_rank_compare');
329  display_select_categories($categories, $selecteds, $blockname, $fullname);
330}
331
332/**
333 * returns all subcategory identifiers of given category ids
334 *
335 * @param array ids
336 * @return array
337 */
338function get_subcat_ids($ids)
339{
340  $query = '
341SELECT DISTINCT(id)
342  FROM '.CATEGORIES_TABLE.'
343  WHERE ';
344  foreach ($ids as $num => $category_id)
345  {
346    is_numeric($category_id)
347      or trigger_error(
348        'get_subcat_ids expecting numeric, not '.gettype($category_id),
349        E_USER_WARNING
350      );
351    if ($num > 0)
352    {
353      $query.= '
354    OR ';
355    }
356    $query.= 'uppercats REGEXP \'(^|,)'.$category_id.'(,|$)\'';
357  }
358  $query.= '
359;';
360  $result = pwg_query($query);
361
362  $subcats = array();
363  while ($row = mysql_fetch_array($result))
364  {
365    array_push($subcats, $row['id']);
366  }
367  return $subcats;
368}
369
370/** finds a matching category id from a potential list of permalinks
371 * @param array permalinks example: holiday holiday/france holiday/france/paris
372 * @param int idx - output of the index in $permalinks that matches
373 * return category id or null if no match
374 */
375function get_cat_id_from_permalinks( $permalinks, &$idx )
376{
377  $in = '';
378  foreach($permalinks as $permalink)
379  {
380    if ( !empty($in) ) $in.=', ';
381    $in .= '"'.$permalink.'"';
382  }
383  $query ='
384SELECT cat_id AS id, permalink, 1 AS is_old
385  FROM '.OLD_PERMALINKS_TABLE.'
386  WHERE permalink IN ('.$in.')
387UNION
388SELECT id, permalink, 0 AS is_old
389  FROM '.CATEGORIES_TABLE.'
390  WHERE permalink IN ('.$in.')
391;';
392  $perma_hash = hash_from_query($query, 'permalink');
393
394  if ( empty($perma_hash) )
395    return null;
396  for ($i=count($permalinks)-1; $i>=0; $i--)
397  {
398    if ( isset( $perma_hash[ $permalinks[$i] ] ) )
399    {
400      $idx = $i;
401      $cat_id = $perma_hash[ $permalinks[$i] ]['id'];
402      if ($perma_hash[ $permalinks[$i] ]['is_old'])
403      {
404        $query='
405UPDATE '.OLD_PERMALINKS_TABLE.' SET last_hit=NOW(), hit=hit+1
406  WHERE permalink="'.$permalinks[$i].'" AND cat_id='.$cat_id.'
407  LIMIT 1';
408        pwg_query($query);
409      }
410      return $cat_id;
411    }
412  }
413  return null;
414}
415
416function global_rank_compare($a, $b)
417{
418  return strnatcasecmp($a['global_rank'], $b['global_rank']);
419}
420
421function rank_compare($a, $b)
422{
423  if ($a['rank'] == $b['rank'])
424  {
425    return 0;
426  }
427
428  return ($a['rank'] < $b['rank']) ? -1 : 1;
429}
430
431/**
432 * returns display text for information images of category
433 *
434 * @param array categories
435 * @return string
436 */
437function get_display_images_count($cat_nb_images, $cat_count_images, $cat_count_categories, $short_message = true, $Separator = '\n')
438{
439  $display_text = '';
440
441  if ($cat_count_images > 0)
442  {
443    if ($cat_nb_images > 0 and $cat_nb_images < $cat_count_images)
444    {
445      $display_text.= get_display_images_count($cat_nb_images, $cat_nb_images, 0, $short_message, $Separator).$Separator;
446      $cat_count_images-= $cat_nb_images;
447      $cat_nb_images = 0;
448    }
449
450    //at least one image direct or indirect
451    $display_text.= l10n_dec('%d element', '%d elements', $cat_count_images);
452
453    if ($cat_count_categories == 0 or $cat_nb_images == $cat_count_images)
454    {
455      //no descendant categories or descendants do not contain images
456      if (! $short_message)
457      {
458        $display_text.= ' '.l10n('images_available_cpl');
459      }
460    }
461    else
462    {
463      $display_text.= ' '.l10n_dec('images_available_cat', 'images_available_cats', $cat_count_categories);
464    }
465  }
466
467  return $display_text;
468}
469
470/**
471 * returns the link of upload menu
472 *
473 * @param null
474 * @return string or null
475 */
476function get_upload_menu_link()
477{
478  global $conf, $page, $user;
479
480  $show_link = false;
481  $arg_link = null;
482
483  if (is_autorize_status($conf['upload_user_access']))
484  {
485    if (isset($page['category']) and $page['category']['uploadable'] )
486    {
487      // upload a picture in the category
488      $show_link = true;
489      $arg_link = 'cat='.$page['category']['id'];
490    }
491    else
492    if ($conf['upload_link_everytime'])
493    {
494      // upload a picture in the category
495      $query = '
496SELECT
497  1
498FROM '.CATEGORIES_TABLE.' INNER JOIN '.USER_CACHE_CATEGORIES_TABLE.'
499  ON id = cat_id and user_id = '.$user['id'].'
500WHERE
501  uploadable = \'true\'
502  '.get_sql_condition_FandF
503    (
504      array
505        (
506          'visible_categories' => 'id',
507        ),
508      'AND'
509    ).'
510LIMIT 1';
511
512      $show_link = mysql_num_rows(pwg_query($query)) <> 0;
513    }
514  }
515  if ($show_link)
516  {
517    return get_root_url().'upload.php'.(empty($arg_link) ? '' : '?'.$arg_link);
518  }
519  else
520  {
521    return;
522  }
523}
524
525?>
Note: See TracBrowser for help on using the repository browser.