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

Last change on this file since 18165 was 18165, checked in by mistic100, 12 years ago

feature 2614: pagination on albums

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