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

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