source: trunk/include/section_init.inc.php @ 4367

Last change on this file since 4367 was 4367, checked in by nikrou, 15 years ago

Feature 1255: modification in sql queries

  • manage random function
  • manage regex syntax
  • manage quote (single instead of double)
  • manage interval
  • Property svn:eol-style set to LF
File size: 18.1 KB
RevLine 
[1036]1<?php
2// +-----------------------------------------------------------------------+
[2297]3// | Piwigo - a PHP based picture gallery                                  |
4// +-----------------------------------------------------------------------+
[3049]5// | Copyright(C) 2008-2009 Piwigo Team                  http://piwigo.org |
[2297]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// +-----------------------------------------------------------------------+
[1036]23
24/**
25 * This included page checks section related parameter and provides
26 * following informations:
27 *
28 * - $page['title']
29 *
30 * - $page['items']: ordered list of items to display
31 *
32 */
33
[1861]34// "index.php?/category/12-foo/start-24" or
35// "index.php/category/12-foo/start-24"
[1090]36// must return :
[1082]37//
38// array(
39//   'section'  => 'categories',
[1861]40//   'category' => array('id'=>12, ...),
[1082]41//   'start'    => 24
42//   );
[1036]43
[1820]44$page['items'] = array();
45
[1306]46// some ISPs set PATH_INFO to empty string or to SCRIPT_FILENAME while in the
47// default apache implementation it is not set
48if ( $conf['question_mark_in_urls']==false and
49     isset($_SERVER["PATH_INFO"]) and !empty($_SERVER["PATH_INFO"]) )
[1036]50{
[1090]51  $rewritten = $_SERVER["PATH_INFO"];
52  $rewritten = str_replace('//', '/', $rewritten);
53  $path_count = count( explode('/', $rewritten) );
54  $page['root_path'] = PHPWG_ROOT_PATH.str_repeat('../', $path_count-1);
55}
56else
57{
58  $rewritten = '';
59  foreach (array_keys($_GET) as $keynum => $key)
[1036]60  {
[1090]61    $rewritten = $key;
62    break;
63  }
64  $page['root_path'] = PHPWG_ROOT_PATH;
65}
[1131]66
[1090]67// deleting first "/" if displayed
[2773]68$tokens = explode('/', ltrim($rewritten, '/') );
[1090]69// $tokens = array(
70//   0 => category,
71//   1 => 12-foo,
72//   2 => start-24
73//   );
[1082]74
[1090]75$next_token = 0;
[1690]76if (script_basename() == 'picture') // basename without file extention
[1109]77{ // the first token must be the identifier for the picture
78  if ( isset($_GET['image_id'])
79       and isset($_GET['cat']) and is_numeric($_GET['cat']) )
80  {// url compatibility with versions below 1.6
81    $url = make_picture_url( array(
82        'section' => 'categories',
[1861]83        'category' => get_cat_info($_GET['cat']),
[1109]84        'image_id' => $_GET['image_id']
85      ) );
86    redirect($url);
87  }
88  $token = $tokens[$next_token];
89  $next_token++;
[1092]90  if ( is_numeric($token) )
[1090]91  {
[1092]92    $page['image_id'] = $token;
[2430]93    if ($page['image_id']==0)
94    {
95      bad_request('invalid picture identifier');
96    }
[1090]97  }
[1092]98  else
99  {
[1109]100    preg_match('/^(\d+-)?(.*)?$/', $token, $matches);
[1094]101    if (isset($matches[1]) and is_numeric($matches[1]=rtrim($matches[1],'-')) )
[1092]102    {
103      $page['image_id'] = $matches[1];
[1109]104      if ( !empty($matches[2]) )
[1092]105      {
[1109]106        $page['image_file'] = $matches[2];
[1092]107      }
108    }
109    else
110    {
[3167]111      $page['image_id'] = 0; // more work in picture.php
[1109]112      if ( !empty($matches[2]) )
[1092]113      {
[1109]114        $page['image_file'] = $matches[2];
[1092]115      }
116      else
117      {
[1852]118        bad_request('picture identifier is missing');
[1092]119      }
120    }
121  }
[1090]122}
[1086]123
[1980]124$page = array_merge( $page, parse_section_url( $tokens, $next_token) );
125if ( !isset($page['section']) )
[1090]126{
127  $page['section'] = 'categories';
[1086]128
[1792]129  switch (script_basename())
[1788]130  {
[1792]131    case 'picture':
132      break;
133    case 'index':
134    {
135      // No section defined, go to selected url
136      if (!empty($conf['random_index_redirect']) and empty($tokens[$next_token]) )
[1788]137      {
[1792]138        $random_index_redirect = array();
139        foreach ($conf['random_index_redirect'] as $random_url => $random_url_condition)
140        {
141          if (empty($random_url_condition) or eval($random_url_condition))
142          {
143            $random_index_redirect[] = $random_url;
144          }
145        }
146        if (!empty($random_index_redirect))
147        {
148          redirect($random_index_redirect[mt_rand(0, count($random_index_redirect)-1)]);
149        }
[1788]150      }
[1792]151      break;
[1788]152    }
[1880]153    default:
154      trigger_error('script_basename "'.script_basename().'" unknown',
155        E_USER_WARNING);
[1788]156  }
157}
158
[1119]159
[1980]160$page = array_merge( $page, parse_well_known_params_url( $tokens, $next_token) );
[1090]161
[1980]162
163if ( script_basename()=='picture' and 'categories'==$page['section'] and
[1996]164      !isset($page['category']) and !isset($page['chronology_field']) )
[1980]165{ //access a picture only by id, file or id-file without given section
166  $page['flat']=true;
[1036]167}
168
[1047]169// $page['nb_image_page'] is the number of picture to display on this page
170// By default, it is the same as the $user['nb_image_page']
171$page['nb_image_page'] = $user['nb_image_page'];
[1036]172
[2517]173// if flat mode is active, we must consider the image set as a standard set
174// and not as a category set because we can't use the #image_category.rank :
175// displayed images are not directly linked to the displayed category
176if ('categories' == $page['section'] and !isset($page['flat']))
177{
178  $conf['order_by'] = $conf['order_by_inside_category'];
179}
180
[1623]181if (pwg_get_session_var('image_order',0) > 0)
[1051]182{
[2517]183  $image_order_id = pwg_get_session_var('image_order');
[2773]184
[1051]185  $orders = get_category_preferred_image_orders();
186
[2517]187  // the current session stored image_order might be not compatible with
188  // current image set, for example if the current image_order is the rank
189  // and that we are displaying images related to a tag.
190  //
191  // In case of incompatibility, the session stored image_order is removed.
192  if ($orders[$image_order_id][2])
193  {
194    $conf['order_by'] = str_replace(
195      'ORDER BY ',
196      'ORDER BY '.$orders[$image_order_id][1].',',
197      $conf['order_by']
[1051]198    );
[2517]199    $page['super_order_by'] = true;
200
201  }
202  else
203  {
204    pwg_unset_session_var('image_order');
205    $page['super_order_by'] = false;
206  }
[1051]207}
208
[1711]209$forbidden = get_sql_condition_FandF(
210      array
211        (
212          'forbidden_categories' => 'category_id',
213          'visible_categories' => 'category_id',
[1820]214          'visible_images' => 'id'
[1711]215        ),
216      'AND'
217  );
218
[1036]219// +-----------------------------------------------------------------------+
220// |                              category                                 |
221// +-----------------------------------------------------------------------+
[1082]222if ('categories' == $page['section'])
223{
224  if (isset($page['category']))
[1036]225  {
226    $page = array_merge(
227      $page,
228      array(
[2117]229        'comment'           =>
230            trigger_event(
231              'render_category_description',
[2175]232              $page['category']['comment'],
233              'main_page_category_description'
[2117]234            ),
[1703]235        'title'             =>
[1980]236          get_cat_display_name($page['category']['upper_names'], '', false),
[1051]237        )
238      );
[1677]239  }
240  else
241  {
[2201]242    $page['title'] = l10n('no_category');
[1677]243  }
[1086]244
[1703]245  if
[1677]246    (
247      (!isset($page['chronology_field'])) and
248      (
[1703]249        (isset($page['category'])) or
[1800]250        (isset($page['flat']))
[1677]251      )
252    )
253  {
[1983]254    if ( !empty($page['category']['image_order']) and !isset($page['super_order_by']) )
[1051]255    {
[1983]256      $conf[ 'order_by' ] = ' ORDER BY '.$page['category']['image_order'];
[1677]257    }
258
[1800]259    if (isset($page['flat']))
[1820]260    {// flat categories mode
261      if ( isset($page['category']) )
[2327]262      { // get all allowed sub-categories
263        $query = '
[2424]264SELECT id
[2327]265  FROM '.CATEGORIES_TABLE.'
[2424]266  WHERE
[2327]267    uppercats LIKE "'.$page['category']['uppercats'].',%" '
268    .get_sql_condition_FandF(
269      array
270        (
271          'forbidden_categories' => 'id',
272          'visible_categories' => 'id',
273        ),
274      "\n  AND"
275          );
276        $subcat_ids = array_from_query($query, 'id');
277        $subcat_ids[] = $page['category']['id'];
[1820]278        $where_sql = 'category_id IN ('.implode(',',$subcat_ids).')';
[2327]279        // remove categories from forbidden because just checked above
280        $forbidden = get_sql_condition_FandF(
281              array( 'visible_images' => 'id' ),
282              'AND'
283          );
[1500]284      }
[1820]285      else
286      {
287        $where_sql = '1=1';
288      }
[1677]289    }
290    else
[1820]291    {// Normal mode
[1861]292      $where_sql = 'category_id = '.$page['category']['id'];
[1677]293    }
[1500]294
[1820]295    // Main query
296    $query = '
[1711]297SELECT DISTINCT(image_id)
[1051]298  FROM '.IMAGE_CATEGORY_TABLE.'
299    INNER JOIN '.IMAGES_TABLE.' ON id = image_id
[1677]300  WHERE
301    '.$where_sql.'
[1711]302'.$forbidden.'
[1051]303  '.$conf['order_by'].'
304;';
[1677]305
[1820]306    $page['items'] = array_from_query($query, 'image_id');
[1677]307  } //otherwise the calendar will requery all subitems
[1082]308}
309// special sections
310else
311{
[1036]312// +-----------------------------------------------------------------------+
[1119]313// |                            tags section                               |
314// +-----------------------------------------------------------------------+
315  if ($page['section'] == 'tags')
316  {
317    $page['tag_ids'] = array();
318    foreach ($page['tags'] as $tag)
319    {
320      array_push($page['tag_ids'], $tag['id']);
321    }
322
323    $items = get_image_ids_for_tags($page['tag_ids']);
324
325    // permissions depends on category, so to only keep images that are
326    // reachable to the connected user, we need to check category
327    // associations
[1131]328    if (!empty($items) )
[1119]329    {
330      $query = '
[2296]331SELECT DISTINCT image_id
[1125]332  FROM '.IMAGE_CATEGORY_TABLE.' INNER JOIN '.IMAGES_TABLE.' ON image_id=id
[1119]333  WHERE image_id IN ('.implode(',', $items).')
[1677]334    '.$forbidden.
[1125]335    $conf['order_by'].'
[1119]336;';
[2296]337      $items =  array_from_query($query, 'image_id');
[1119]338    }
339
340    $page = array_merge(
341      $page,
342      array(
[2773]343        'title' => get_tags_content_title(),
[2296]344        'items' => $items,
[1119]345        )
346      );
347  }
348// +-----------------------------------------------------------------------+
[1036]349// |                           search section                              |
350// +-----------------------------------------------------------------------+
[1082]351  if ($page['section'] == 'search')
352  {
[1113]353    include_once( PHPWG_ROOT_PATH .'include/functions_search.inc.php' );
[1119]354
[2451]355    $search_result = get_search_results($page['search'], @$page['super_order_by'] );
356    if ( isset($search_result['qs']) )
357    {//save the details of the query search
358      $page['qsearch_details'] = $search_result['qs'];
[1120]359    }
[1036]360
[1082]361    $page = array_merge(
362      $page,
363      array(
[2451]364        'items' => $search_result['items'],
[2117]365        'title' => '<a href="'.duplicate_index_url(array('start'=>0)).'">'
[2201]366                  .l10n('search_result').'</a>',
[1082]367        )
368      );
369  }
[1036]370// +-----------------------------------------------------------------------+
371// |                           favorite section                            |
372// +-----------------------------------------------------------------------+
[1082]373  else if ($page['section'] == 'favorites')
374  {
375    check_user_favorites();
[1036]376
[3037]377    $page = array_merge(
378      $page,
379      array(
380        'title' => l10n('favorites')
381            )
382    );
383
[3108]384    if (!empty($_GET['action']) && ($_GET['action'] == 'remove_all_from_favorites'))
[3037]385    {
386      $query = '
387DELETE FROM '.FAVORITES_TABLE.'
388  WHERE user_id = '.$user['id'].'
389;';
390      pwg_query($query);
[3108]391      redirect(make_index_url( array('section'=>'favorites') ));
[3037]392    }
[3108]393    else
[3037]394    {
395      $query = '
[1036]396SELECT image_id
397  FROM '.FAVORITES_TABLE.'
398    INNER JOIN '.IMAGES_TABLE.' ON image_id = id
399  WHERE user_id = '.$user['id'].'
[1677]400'.get_sql_condition_FandF
401  (
402    array
403      (
[2451]404        'visible_images' => 'id'
[1677]405      ),
406    'AND'
407  ).'
[1036]408  '.$conf['order_by'].'
409;';
[3037]410      $page = array_merge(
411        $page,
412        array(
413          'items' => array_from_query($query, 'image_id'),
414         )
415      );
[1036]416
[3108]417      if (count($page['items'])>0)
[3037]418      {
419        $template->assign(
420          'favorite',
421          array(
422            'FAVORITE_IMG'  =>
423            get_root_url().get_themeconf('icon_dir').'/del_all_favorites.png',
424            'U_FAVORITE'    => add_url_params(
[3108]425              make_index_url( array('section'=>'favorites') ),
[3037]426              array('action'=>'remove_all_from_favorites')
427               ),
428             )
429           );
430      }
431    }
[1082]432  }
[1036]433// +-----------------------------------------------------------------------+
434// |                       recent pictures section                         |
435// +-----------------------------------------------------------------------+
[1082]436  else if ($page['section'] == 'recent_pics')
437  {
[2424]438    if ( !isset($page['super_order_by']) )
439    {
440      $conf['order_by'] = str_replace(
441        'ORDER BY ',
442        'ORDER BY date_available DESC,',
443        $conf['order_by']
444        );
445    }
446
[1082]447    $query = '
[1036]448SELECT DISTINCT(id)
449  FROM '.IMAGES_TABLE.'
450    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
[1876]451  WHERE
[4367]452    date_available >= '.pwg_db_get_recent_period_expression($user['recent_period']).'
[1677]453    '.$forbidden.'
[1036]454  '.$conf['order_by'].'
455;';
456
[1082]457    $page = array_merge(
458      $page,
459      array(
[2117]460        'title' => '<a href="'.duplicate_index_url(array('start'=>0)).'">'
[2201]461                  .l10n('recent_pics_cat').'</a>',
[1082]462        'items' => array_from_query($query, 'id'),
463        )
464      );
465  }
[1036]466// +-----------------------------------------------------------------------+
467// |                 recently updated categories section                   |
468// +-----------------------------------------------------------------------+
[1082]469  else if ($page['section'] == 'recent_cats')
470  {
471    $page = array_merge(
472      $page,
473      array(
[2201]474        'title' => l10n('recent_cats_cat'),
[1082]475        )
476      );
477  }
[1036]478// +-----------------------------------------------------------------------+
479// |                        most visited section                           |
480// +-----------------------------------------------------------------------+
[1082]481  else if ($page['section'] == 'most_visited')
482  {
483    $page['super_order_by'] = true;
484    $conf['order_by'] = ' ORDER BY hit DESC, file ASC';
485    $query = '
[1036]486SELECT DISTINCT(id)
487  FROM '.IMAGES_TABLE.'
488    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
489  WHERE hit > 0
[1677]490    '.$forbidden.'
[1082]491    '.$conf['order_by'].'
[4334]492  LIMIT '.$conf['top_number'].'
[1036]493;';
[1086]494
[1082]495    $page = array_merge(
496      $page,
497      array(
[2117]498        'title' => '<a href="'.duplicate_index_url(array('start'=>0)).'">'
[2201]499                  .$conf['top_number'].' '.l10n('most_visited_cat').'</a>',
[1082]500        'items' => array_from_query($query, 'id'),
501        )
502      );
503  }
[1036]504// +-----------------------------------------------------------------------+
505// |                          best rated section                           |
506// +-----------------------------------------------------------------------+
[1082]507  else if ($page['section'] == 'best_rated')
508  {
509    $page['super_order_by'] = true;
510    $conf['order_by'] = ' ORDER BY average_rate DESC, id ASC';
[1086]511
[1082]512    $query ='
[1036]513SELECT DISTINCT(id)
514  FROM '.IMAGES_TABLE.'
515    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
516  WHERE average_rate IS NOT NULL
[1677]517    '.$forbidden.'
[1082]518    '.$conf['order_by'].'
[4334]519  LIMIT '.$conf['top_number'].'
[1036]520;';
[1082]521    $page = array_merge(
522      $page,
523      array(
[2117]524        'title' => '<a href="'.duplicate_index_url(array('start'=>0)).'">'
[2201]525                  .$conf['top_number'].' '.l10n('best_rated_cat').'</a>',
[1082]526        'items' => array_from_query($query, 'id'),
527        )
528      );
529  }
[1036]530// +-----------------------------------------------------------------------+
531// |                             list section                              |
532// +-----------------------------------------------------------------------+
[1082]533  else if ($page['section'] == 'list')
534  {
535    $query ='
[1036]536SELECT DISTINCT(id)
537  FROM '.IMAGES_TABLE.'
538    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
[1082]539  WHERE image_id IN ('.implode(',', $page['list']).')
[1677]540    '.$forbidden.'
[1036]541  '.$conf['order_by'].'
542;';
[1086]543
[1082]544    $page = array_merge(
545      $page,
546      array(
[2117]547        'title' => '<a href="'.duplicate_index_url(array('start'=>0)).'">'
[2201]548                    .l10n('random_cat').'</a>',
[1082]549        'items' => array_from_query($query, 'id'),
550        )
551      );
[1036]552  }
553}
[1082]554
[1036]555// +-----------------------------------------------------------------------+
[1082]556// |                             chronology                                |
[1036]557// +-----------------------------------------------------------------------+
[1047]558
[1090]559if (isset($page['chronology_field']))
[1047]560{
561  include_once( PHPWG_ROOT_PATH.'include/functions_calendar.inc.php' );
562  initialize_calendar();
563}
564
[1703]565// add meta robots noindex, nofollow to avoid unnecesary robot crawls
566$page['meta_robots']=array();
[2135]567if ( isset($page['chronology_field'])
568      or ( isset($page['flat']) and isset($page['category']) )
[1703]569      or 'list'==$page['section'] or 'recent_pics'==$page['section'] )
570{
571  $page['meta_robots']=array('noindex'=>1, 'nofollow'=>1);
572}
573elseif ('tags' == $page['section'])
574{
575  if ( count($page['tag_ids'])>1 )
576  {
577    $page['meta_robots']=array('noindex'=>1, 'nofollow'=>1);
578  }
579}
580elseif ('recent_cats'==$page['section'])
581{
[2138]582  $page['meta_robots']['noindex']=1;
583}
584elseif ('search'==$page['section'])
585{
[1703]586  $page['meta_robots']['nofollow']=1;
587}
588if ( $filter['enabled'] )
589{
590  $page['meta_robots']['noindex']=1;
591}
592
[1866]593// see if we need a redirect because of a permalink
594if ( 'categories'==$page['section'] and isset($page['category']) )
595{
596  $need_redirect=false;
597  if ( empty($page['category']['permalink']) )
598  {
599    if ( $conf['category_url_style'] == 'id-name' and
600        @$page['hit_by']['cat_url_name'] !== str2url($page['category']['name']) )
601    {
602      $need_redirect=true;
603    }
604  }
605  else
606  {
607    if ( $page['category']['permalink'] !== @$page['hit_by']['cat_permalink'] )
608    {
609      $need_redirect=true;
610    }
611  }
612
613  if ($need_redirect)
614  {
615    $redirect_url = ( script_basename()=='picture'
616        ? duplicate_picture_url()
617          : duplicate_index_url()
618      );
619    if (!headers_sent())
620    { // this is a permanent redirection
[1950]621      set_status_header(301);
[1866]622      redirect_http( $redirect_url );
623    }
624    redirect( $redirect_url );
625  }
626  unset( $need_redirect, $page['hit_by'] );
627}
628
[1604]629trigger_action('loc_end_section_init');
[1036]630?>
Note: See TracBrowser for help on using the repository browser.