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

Last change on this file since 6368 was 6368, checked in by laurent.duretz, 14 years ago

Issue 1521 : add linkroot to spacial pages

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