source: branches/2.1/include/section_init.inc.php @ 20384

Last change on this file since 20384 was 6905, checked in by plg, 14 years ago

bug 1849 fixed: protect $_GET keys against SQL injections before parsing URL.

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