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

Last change on this file since 2521 was 2521, checked in by rvelices, 16 years ago
  • images.file categories.permalink old_permalinks.permalink - become binary
  • session security improvement: now the sessions are valid only for originating ip addr (with mask 255.255.0.0 to allow users behind load balancing proxies) -> stealing the session cookie is almost a non issue (with the exception of the 65536 machines in range)
  • metadata sync from the sync button does not overwrite valid data with empty metadata
  • other small fixes/enhancements:
    • added event get_category_image_orders
    • fix display issue with redirect.tpl (h1/h2 within h1)
    • fix known_script smarty function registration
    • query search form not submitted if q is empty
    • better admin css rules
    • some other minor changes (ws_core, rest_handler, functions_search...)
  • Property svn:eol-style set to LF
  • Property svn:keywords set to Author Date Id Revision
File size: 13.3 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, $page;
261
262  return trigger_event('get_category_preferred_image_orders',
263    array(
264    array(l10n('default_sort'), '', true),
265    array(l10n('Average rate'), 'average_rate DESC', $conf['rate']),
266    array(l10n('most_visited_cat'), 'hit DESC', true),
267    array(l10n('Creation date'), 'date_creation DESC', true),
268    array(l10n('Post date'), 'date_available DESC', true),
269    array(l10n('File name'), 'file ASC', true),
270    array(
271      l10n('Rank'),
272      'rank ASC',
273      ('categories' == @$page['section'] and !isset($page['flat']))
274      )
275    ));
276}
277
278function display_select_categories($categories,
279                                   $selecteds,
280                                   $blockname,
281                                   $fullname = true)
282{
283  global $template;
284
285  $tpl_cats = array();
286  foreach ($categories as $category)
287  {
288    if ($fullname)
289    {
290      $option = get_cat_display_name_cache($category['uppercats'],
291                                           null,
292                                           false);
293    }
294    else
295    {
296      $option = str_repeat('&nbsp;',
297                           (3 * substr_count($category['global_rank'], '.')));
298      $option.= '- ';
299      $option.= strip_tags(
300        trigger_event(
301          'render_category_name',
302          $category['name'],
303          'display_select_categories'
304          )
305        );
306    }
307    $tpl_cats[ $category['id'] ] = $option;
308  }
309
310  $template->assign( $blockname, $tpl_cats);
311  $template->assign( $blockname.'_selected', $selecteds);
312}
313
314function display_select_cat_wrapper($query, $selecteds, $blockname,
315                                    $fullname = true)
316{
317  $result = pwg_query($query);
318  $categories = array();
319  if (!empty($result))
320  {
321    while ($row = mysql_fetch_assoc($result))
322    {
323      array_push($categories, $row);
324    }
325  }
326  usort($categories, 'global_rank_compare');
327  display_select_categories($categories, $selecteds, $blockname, $fullname);
328}
329
330/**
331 * returns all subcategory identifiers of given category ids
332 *
333 * @param array ids
334 * @return array
335 */
336function get_subcat_ids($ids)
337{
338  $query = '
339SELECT DISTINCT(id)
340  FROM '.CATEGORIES_TABLE.'
341  WHERE ';
342  foreach ($ids as $num => $category_id)
343  {
344    is_numeric($category_id)
345      or trigger_error(
346        'get_subcat_ids expecting numeric, not '.gettype($category_id),
347        E_USER_WARNING
348      );
349    if ($num > 0)
350    {
351      $query.= '
352    OR ';
353    }
354    $query.= 'uppercats REGEXP \'(^|,)'.$category_id.'(,|$)\'';
355  }
356  $query.= '
357;';
358  $result = pwg_query($query);
359
360  $subcats = array();
361  while ($row = mysql_fetch_array($result))
362  {
363    array_push($subcats, $row['id']);
364  }
365  return $subcats;
366}
367
368/** finds a matching category id from a potential list of permalinks
369 * @param array permalinks example: holiday holiday/france holiday/france/paris
370 * @param int idx - output of the index in $permalinks that matches
371 * return category id or null if no match
372 */
373function get_cat_id_from_permalinks( $permalinks, &$idx )
374{
375  $in = '';
376  foreach($permalinks as $permalink)
377  {
378    if ( !empty($in) ) $in.=', ';
379    $in .= '"'.$permalink.'"';
380  }
381  $query ='
382SELECT cat_id AS id, permalink, 1 AS is_old
383  FROM '.OLD_PERMALINKS_TABLE.'
384  WHERE permalink IN ('.$in.')
385UNION
386SELECT id, permalink, 0 AS is_old
387  FROM '.CATEGORIES_TABLE.'
388  WHERE permalink IN ('.$in.')
389;';
390  $perma_hash = hash_from_query($query, 'permalink');
391
392  if ( empty($perma_hash) )
393    return null;
394  for ($i=count($permalinks)-1; $i>=0; $i--)
395  {
396    if ( isset( $perma_hash[ $permalinks[$i] ] ) )
397    {
398      $idx = $i;
399      $cat_id = $perma_hash[ $permalinks[$i] ]['id'];
400      if ($perma_hash[ $permalinks[$i] ]['is_old'])
401      {
402        $query='
403UPDATE '.OLD_PERMALINKS_TABLE.' SET last_hit=NOW(), hit=hit+1
404  WHERE permalink="'.$permalinks[$i].'" AND cat_id='.$cat_id.'
405  LIMIT 1';
406        pwg_query($query);
407      }
408      return $cat_id;
409    }
410  }
411  return null;
412}
413
414function global_rank_compare($a, $b)
415{
416  return strnatcasecmp($a['global_rank'], $b['global_rank']);
417}
418
419function rank_compare($a, $b)
420{
421  if ($a['rank'] == $b['rank'])
422  {
423    return 0;
424  }
425
426  return ($a['rank'] < $b['rank']) ? -1 : 1;
427}
428
429/**
430 * returns display text for information images of category
431 *
432 * @param array categories
433 * @return string
434 */
435function get_display_images_count($cat_nb_images, $cat_count_images, $cat_count_categories, $short_message = true, $Separator = '\n')
436{
437  $display_text = '';
438
439  if ($cat_count_images > 0)
440  {
441    if ($cat_nb_images > 0 and $cat_nb_images < $cat_count_images)
442    {
443      $display_text.= get_display_images_count($cat_nb_images, $cat_nb_images, 0, $short_message, $Separator).$Separator;
444      $cat_count_images-= $cat_nb_images;
445      $cat_nb_images = 0;
446    }
447
448    //at least one image direct or indirect
449    $display_text.= l10n_dec('%d element', '%d elements', $cat_count_images);
450
451    if ($cat_count_categories == 0 or $cat_nb_images == $cat_count_images)
452    {
453      //no descendant categories or descendants do not contain images
454      if (! $short_message)
455      {
456        $display_text.= ' '.l10n('images_available_cpl');
457      }
458    }
459    else
460    {
461      $display_text.= ' '.l10n_dec('images_available_cat', 'images_available_cats', $cat_count_categories);
462    }
463  }
464
465  return $display_text;
466}
467
468/**
469 * returns the link of upload menu
470 *
471 * @param null
472 * @return string or null
473 */
474function get_upload_menu_link()
475{
476  global $conf, $page, $user;
477
478  $show_link = false;
479  $arg_link = null;
480
481  if (is_autorize_status($conf['upload_user_access']))
482  {
483    if (isset($page['category']) and $page['category']['uploadable'] )
484    {
485      // upload a picture in the category
486      $show_link = true;
487      $arg_link = 'cat='.$page['category']['id'];
488    }
489    else
490    if ($conf['upload_link_everytime'])
491    {
492      // upload a picture in the category
493      $query = '
494SELECT
495  1
496FROM '.CATEGORIES_TABLE.' INNER JOIN '.USER_CACHE_CATEGORIES_TABLE.'
497  ON id = cat_id and user_id = '.$user['id'].'
498WHERE
499  uploadable = \'true\'
500  '.get_sql_condition_FandF
501    (
502      array
503        (
504          'visible_categories' => 'id',
505        ),
506      'AND'
507    ).'
508LIMIT 1';
509
510      $show_link = mysql_num_rows(pwg_query($query)) <> 0;
511    }
512  }
513  if ($show_link)
514  {
515    return get_root_url().'upload.php'.(empty($arg_link) ? '' : '?'.$arg_link);
516  }
517  else
518  {
519    return;
520  }
521}
522
523?>
Note: See TracBrowser for help on using the repository browser.