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

Last change on this file since 2265 was 2265, checked in by rvelices, 16 years ago
  • upload.tpl goes smarty
  • start some language cleanup and a small attempt to standardize a bit ...
  • debug_language now calls trigger_error instead of echo when missing language key
  • Property svn:eol-style set to LF
  • Property svn:keywords set to Author Date Id Revision
File size: 12.9 KB
Line 
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-2007 PhpWebGallery Team - http://phpwebgallery.net |
6// +-----------------------------------------------------------------------+
7// | file          : $Id: functions_category.inc.php 2265 2008-03-08 01:38:37Z rvelices $
8// | last update   : $Date: 2008-03-08 01:38:37 +0000 (Sat, 08 Mar 2008) $
9// | last modifier : $Author: rvelices $
10// | revision      : $Revision: 2265 $
11// +-----------------------------------------------------------------------+
12// | This program is free software; you can redistribute it and/or modify  |
13// | it under the terms of the GNU General Public License as published by  |
14// | the Free Software Foundation                                          |
15// |                                                                       |
16// | This program is distributed in the hope that it will be useful, but   |
17// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
18// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
19// | General Public License for more details.                              |
20// |                                                                       |
21// | You should have received a copy of the GNU General Public License     |
22// | along with this program; if not, write to the Free Software           |
23// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
24// | USA.                                                                  |
25// +-----------------------------------------------------------------------+
26
27/**
28 * Provides functions to handle categories.
29 *
30 *
31 */
32
33/**
34 * Is the category accessible to the connected user ?
35 *
36 * Note : if the user is not authorized to see this category, page creation
37 * ends (exit command in this function)
38 *
39 * @param int category id to verify
40 * @return void
41 */
42function check_restrictions($category_id)
43{
44  global $user;
45
46  // $filter['visible_categories'] and $filter['visible_images']
47  // are not used because it's not necessary (filter <> restriction)
48  if (in_array($category_id, explode(',', $user['forbidden_categories'])))
49  {
50    access_denied();
51  }
52}
53
54function get_categories_menu()
55{
56  global $page, $user, $filter;
57
58  $query = '
59SELECT ';
60  // From CATEGORIES_TABLE
61  $query.= '
62  id, name, permalink, nb_images, global_rank,';
63  // From USER_CACHE_CATEGORIES_TABLE
64  $query.= '
65  date_last, max_date_last, count_images, count_categories';
66
67  // $user['forbidden_categories'] including with USER_CACHE_CATEGORIES_TABLE
68  $query.= '
69FROM '.CATEGORIES_TABLE.' INNER JOIN '.USER_CACHE_CATEGORIES_TABLE.'
70  ON id = cat_id and user_id = '.$user['id'];
71
72  // Always expand when filter is activated
73  if (!$user['expand'] and !$filter['enabled'])
74  {
75    $where = '
76(id_uppercat is NULL';
77    if (isset($page['category']))
78    {
79      $where .= ' OR id_uppercat IN ('.$page['category']['uppercats'].')';
80    }
81    $where .= ')';
82  }
83  else
84  {
85    $where = '
86  '.get_sql_condition_FandF
87    (
88      array
89        (
90          'visible_categories' => 'id',
91        ),
92      null,
93      true
94    );
95  }
96
97  $where = trigger_event('get_categories_menu_sql_where',
98    $where, $user['expand'], $filter['enabled'] );
99
100  $query.= '
101WHERE '.$where.'
102;';
103
104  $result = pwg_query($query);
105  $cats = array();
106  while ($row = mysql_fetch_assoc($result))
107  {
108    array_push($cats, $row);
109  }
110  usort($cats, 'global_rank_compare');
111
112  // Update filtered data
113  if (function_exists('update_cats_with_filtered_data'))
114  {
115    update_cats_with_filtered_data($cats);
116  }
117
118  return get_html_menu_category($cats, @$page['category'] );
119}
120
121
122/**
123 * Retrieve informations about a category in the database
124 *
125 * Returns an array with following keys :
126 *
127 *  - comment
128 *  - dir : directory, might be empty for virtual categories
129 *  - name : an array with indexes from 0 (lowest cat name) to n (most
130 *           uppercat name findable)
131 *  - nb_images
132 *  - id_uppercat
133 *  - site_id
134 *  -
135 *
136 * @param int category id
137 * @return array
138 */
139function get_cat_info( $id )
140{
141  $query = '
142SELECT *
143  FROM '.CATEGORIES_TABLE.'
144  WHERE id = '.$id.'
145;';
146  $cat = mysql_fetch_assoc(pwg_query($query));
147  if (empty($cat))
148    return null;
149
150  foreach ($cat as $k => $v)
151  {
152    // If the field is true or false, the variable is transformed into a
153    // boolean value.
154    if ($cat[$k] == 'true' or $cat[$k] == 'false')
155    {
156      $cat[$k] = get_boolean( $cat[$k] );
157    }
158  }
159
160  $upper_ids = explode(',', $cat['uppercats']);
161  if ( count($upper_ids)==1 )
162  {// no need to make a query for level 1
163    $cat['upper_names'] = array(
164        array(
165          'id' => $cat['id'],
166          'name' => $cat['name'],
167          'permalink' => $cat['permalink'],
168          )
169      );
170  }
171  else
172  {
173    $names = array();
174    $query = '
175  SELECT id, name, permalink
176    FROM '.CATEGORIES_TABLE.'
177    WHERE id IN ('.$cat['uppercats'].')
178  ;';
179    $names = hash_from_query($query, 'id');
180
181    // category names must be in the same order than uppercats list
182    $cat['upper_names'] = array();
183    foreach ($upper_ids as $cat_id)
184    {
185      array_push( $cat['upper_names'], $names[$cat_id]);
186    }
187  }
188  return $cat;
189}
190
191// get_complete_dir returns the concatenation of get_site_url and
192// get_local_dir
193// Example : "pets > rex > 1_year_old" is on the the same site as the
194// PhpWebGallery files and this category has 22 for identifier
195// get_complete_dir(22) returns "./galleries/pets/rex/1_year_old/"
196function get_complete_dir( $category_id )
197{
198  return get_site_url($category_id).get_local_dir($category_id);
199}
200
201// get_local_dir returns an array with complete path without the site url
202// Example : "pets > rex > 1_year_old" is on the the same site as the
203// PhpWebGallery files and this category has 22 for identifier
204// get_local_dir(22) returns "pets/rex/1_year_old/"
205function get_local_dir( $category_id )
206{
207  global $page;
208
209  $uppercats = '';
210  $local_dir = '';
211
212  if ( isset( $page['plain_structure'][$category_id]['uppercats'] ) )
213  {
214    $uppercats = $page['plain_structure'][$category_id]['uppercats'];
215  }
216  else
217  {
218    $query = 'SELECT uppercats';
219    $query.= ' FROM '.CATEGORIES_TABLE.' WHERE id = '.$category_id;
220    $query.= ';';
221    $row = mysql_fetch_array( pwg_query( $query ) );
222    $uppercats = $row['uppercats'];
223  }
224
225  $upper_array = explode( ',', $uppercats );
226
227  $database_dirs = array();
228  $query = 'SELECT id,dir';
229  $query.= ' FROM '.CATEGORIES_TABLE.' WHERE id IN ('.$uppercats.')';
230  $query.= ';';
231  $result = pwg_query( $query );
232  while( $row = mysql_fetch_array( $result ) )
233  {
234    $database_dirs[$row['id']] = $row['dir'];
235  }
236  foreach ($upper_array as $id)
237  {
238    $local_dir.= $database_dirs[$id].'/';
239  }
240
241  return $local_dir;
242}
243
244// retrieving the site url : "http://domain.com/gallery/" or
245// simply "./galleries/"
246function get_site_url($category_id)
247{
248  global $page;
249
250  $query = '
251SELECT galleries_url
252  FROM '.SITES_TABLE.' AS s,'.CATEGORIES_TABLE.' AS c
253  WHERE s.id = c.site_id
254    AND c.id = '.$category_id.'
255;';
256  $row = mysql_fetch_array(pwg_query($query));
257  return $row['galleries_url'];
258}
259
260// returns an array of image orders available for users/visitors
261function get_category_preferred_image_orders()
262{
263  global $conf;
264  return array(
265    array(l10n('default_sort'), '', true),
266    array(l10n('Average rate'), 'average_rate DESC', $conf['rate']),
267    array(l10n('most_visited_cat'), 'hit DESC', true),
268    array(l10n('Creation date'), 'date_creation DESC', true),
269    array(l10n('Post date'), 'date_available DESC', true),
270    array(l10n('File name'), 'file ASC', true)
271  );
272}
273
274function display_select_categories($categories,
275                                   $selecteds,
276                                   $blockname,
277                                   $fullname = true)
278{
279  global $template;
280
281  // TODO - remove from here after old template removed
282  foreach ($categories as $category)
283  {
284    $selected = '';
285    if (in_array($category['id'], $selecteds))
286    {
287      $selected = ' selected="selected"';
288    }
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.= '- '.$category['name'];
301    }
302
303    $template->_old->assign_block_vars(
304      $blockname,
305      array('SELECTED'=>$selected,
306            'VALUE'=>$category['id'],
307            'OPTION'=>$option
308        ));
309  }
310  // TODO - remove until here after old template removed
311  $tpl_cats = array();
312  foreach ($categories as $category)
313  {
314    if ($fullname)
315    {
316      $option = get_cat_display_name_cache($category['uppercats'],
317                                           null,
318                                           false);
319    }
320    else
321    {
322      $option = str_repeat('&nbsp;',
323                           (3 * substr_count($category['global_rank'], '.')));
324      $option.= '- '.$category['name'];
325    }
326    $tpl_cats[ $category['id'] ] = $option;
327  }
328
329  $template->smarty->assign( $blockname, $tpl_cats);
330  $template->smarty->assign( $blockname.'_selected', $selecteds);
331}
332
333function display_select_cat_wrapper($query, $selecteds, $blockname,
334                                    $fullname = true)
335{
336  $result = pwg_query($query);
337  $categories = array();
338  if (!empty($result))
339  {
340    while ($row = mysql_fetch_assoc($result))
341    {
342      array_push($categories, $row);
343    }
344  }
345  usort($categories, 'global_rank_compare');
346  display_select_categories($categories, $selecteds, $blockname, $fullname);
347}
348
349/**
350 * returns all subcategory identifiers of given category ids
351 *
352 * @param array ids
353 * @return array
354 */
355function get_subcat_ids($ids)
356{
357  $query = '
358SELECT DISTINCT(id)
359  FROM '.CATEGORIES_TABLE.'
360  WHERE ';
361  foreach ($ids as $num => $category_id)
362  {
363    is_numeric($category_id)
364      or trigger_error(
365        'get_subcat_ids expecting numeric, not '.gettype($category_id),
366        E_USER_WARNING
367      );
368    if ($num > 0)
369    {
370      $query.= '
371    OR ';
372    }
373    $query.= 'uppercats REGEXP \'(^|,)'.$category_id.'(,|$)\'';
374  }
375  $query.= '
376;';
377  $result = pwg_query($query);
378
379  $subcats = array();
380  while ($row = mysql_fetch_array($result))
381  {
382    array_push($subcats, $row['id']);
383  }
384  return $subcats;
385}
386
387/** finds a matching category id from a potential list of permalinks
388 * @param array permalinks example: holiday holiday/france holiday/france/paris
389 * @param int idx - output of the index in $permalinks that matches
390 * return category id or null if no match
391 */
392function get_cat_id_from_permalinks( $permalinks, &$idx )
393{
394  $in = '';
395  foreach($permalinks as $permalink)
396  {
397    if ( !empty($in) ) $in.=', ';
398    $in .= '"'.$permalink.'"';
399  }
400  $query ='
401SELECT c.id, op.permalink, 1 AS is_old
402  FROM '.OLD_PERMALINKS_TABLE.' op INNER JOIN '.CATEGORIES_TABLE.' c
403    ON op.cat_id=c.id
404  WHERE op.permalink IN ('.$in.')
405UNION
406SELECT id, permalink, 0 AS is_old
407  FROM '.CATEGORIES_TABLE.'
408  WHERE permalink IN ('.$in.')
409;';
410  $perma_hash = hash_from_query($query, 'permalink');
411
412  if ( empty($perma_hash) )
413    return null;
414  for ($i=count($permalinks)-1; $i>=0; $i--)
415  {
416    if ( isset( $perma_hash[ $permalinks[$i] ] ) )
417    {
418      $idx = $i;
419      $cat_id = $perma_hash[ $permalinks[$i] ]['id'];
420      if ($perma_hash[ $permalinks[$i] ]['is_old'])
421      {
422        $query='
423UPDATE '.OLD_PERMALINKS_TABLE.' SET last_hit=NOW(), hit=hit+1
424  WHERE permalink="'.$permalinks[$i].'" AND cat_id='.$cat_id.'
425  LIMIT 1';
426        pwg_query($query);
427      }
428      return $cat_id;
429    }
430  }
431  return null;
432}
433
434function global_rank_compare($a, $b)
435{
436  return strnatcasecmp($a['global_rank'], $b['global_rank']);
437}
438
439function rank_compare($a, $b)
440{
441  if ($a['rank'] == $b['rank'])
442  {
443    return 0;
444  }
445
446  return ($a['rank'] < $b['rank']) ? -1 : 1;
447}
448
449/**
450 * returns display text for information images of category
451 *
452 * @param array categories
453 * @return string
454 */
455function get_display_images_count($cat_nb_images, $cat_count_images, $cat_count_categories, $short_message = true, $Separator = '\n')
456{
457  $display_text = '';
458
459  if ($cat_count_images > 0)
460  {
461    if ($cat_nb_images > 0 and $cat_nb_images < $cat_count_images)
462    {
463      $display_text.= get_display_images_count($cat_nb_images, $cat_nb_images, 0, $short_message, $Separator).$Separator;
464      $cat_count_images-= $cat_nb_images;
465      $cat_nb_images = 0;
466    }
467
468    //at least one image direct or indirect
469    $display_text.= l10n_dec('%d element', '%d elements', $cat_count_images);
470
471    if ($cat_count_categories == 0 or $cat_nb_images == $cat_count_images)
472    {
473      //no descendant categories or descendants do not contain images
474      if (! $short_message)
475      {
476        $display_text.= ' '.l10n('images_available_cpl');
477      }
478    }
479    else
480    {
481      $display_text.= ' '.l10n_dec('images_available_cat', 'images_available_cats', $cat_count_categories);
482    }
483  }
484
485  return $display_text;
486}
487
488?>
Note: See TracBrowser for help on using the repository browser.