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

Revision 18392, 19.4 KB checked in by mistic100, 7 years ago (diff)

feature 2614: pagination on albums, save one query on picture page

  • Property svn:eol-style set to LF
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 ( script_basename()=='index'
323    and 0==$page['start']
324    and !isset($page['flat'])
325    and !isset($page['chronology_field'])
326    and ('recent_cats'==$page['section'] or 'categories'==$page['section'])
327    and (!isset($page['category']['count_categories']) or $page['category']['count_categories']>0 )
328  )
329  {
330    $query = '
331SELECT c.id
332  FROM '.CATEGORIES_TABLE.' c
333    INNER JOIN '.USER_CACHE_CATEGORIES_TABLE.' ucc
334    ON id = cat_id
335    AND user_id = '.$user['id'];
336
337    if ('recent_cats' == $page['section'])
338    {
339      $query.= '
340      WHERE date_last >= '.pwg_db_get_recent_period_expression($user['recent_period']);
341    }
342    else
343    {
344      $query.= '
345      WHERE id_uppercat '.(!isset($page['category']) ? 'is NULL' : '= '.$page['category']['id']);
346    }
347
348    $query.= '
349        '.get_sql_condition_FandF(
350          array('visible_categories' => 'id'),
351          'AND'
352          );
353
354    $query.= '
355    ;';
356
357    $page['categories'] = array_from_query($query, 'id');
358  }
359}
360// special sections
361else
362{
363// +-----------------------------------------------------------------------+
364// |                            tags section                               |
365// +-----------------------------------------------------------------------+
366  if ($page['section'] == 'tags')
367  {
368    $page['tag_ids'] = array();
369    foreach ($page['tags'] as $tag)
370    {
371      array_push($page['tag_ids'], $tag['id']);
372    }
373
374    $items = get_image_ids_for_tags($page['tag_ids']);
375
376    $page = array_merge(
377      $page,
378      array(
379        'title' => get_tags_content_title(),
380        'items' => $items,
381        )
382      );
383  }
384// +-----------------------------------------------------------------------+
385// |                           search section                              |
386// +-----------------------------------------------------------------------+
387  if ($page['section'] == 'search')
388  {
389    include_once( PHPWG_ROOT_PATH .'include/functions_search.inc.php' );
390
391    $search_result = get_search_results($page['search'], @$page['super_order_by'] );
392    if ( isset($search_result['qs']) )
393    {//save the details of the query search
394      $page['qsearch_details'] = $search_result['qs'];
395    }
396
397    $page = array_merge(
398      $page,
399      array(
400        'items' => $search_result['items'],
401        'title' => '<a href="'.duplicate_index_url(array('start'=>0)).'">'
402                  .l10n('Search results').'</a>',
403        )
404      );
405  }
406// +-----------------------------------------------------------------------+
407// |                           favorite section                            |
408// +-----------------------------------------------------------------------+
409  else if ($page['section'] == 'favorites')
410  {
411    check_user_favorites();
412
413    $page = array_merge(
414      $page,
415      array(
416        'title' => l10n('Favorites')
417      )
418    );
419
420    if (!empty($_GET['action']) && ($_GET['action'] == 'remove_all_from_favorites'))
421    {
422      $query = '
423DELETE FROM '.FAVORITES_TABLE.'
424  WHERE user_id = '.$user['id'].'
425;';
426      pwg_query($query);
427      redirect(make_index_url( array('section'=>'favorites') ));
428    }
429    else
430    {
431      $query = '
432SELECT image_id
433  FROM '.FAVORITES_TABLE.'
434    INNER JOIN '.IMAGES_TABLE.' ON image_id = id
435  WHERE user_id = '.$user['id'].'
436'.get_sql_condition_FandF
437  (
438    array
439      (
440        'visible_images' => 'id'
441      ),
442    'AND'
443  ).'
444  '.$conf['order_by'].'
445;';
446      $page = array_merge(
447        $page,
448        array(
449          'items' => array_from_query($query, 'image_id'),
450         )
451      );
452
453      if (count($page['items'])>0)
454      {
455        $template->assign(
456          'favorite',
457          array(
458            'U_FAVORITE'    => add_url_params(
459              make_index_url( array('section'=>'favorites') ),
460              array('action'=>'remove_all_from_favorites')
461               ),
462             )
463           );
464      }
465    }
466  }
467// +-----------------------------------------------------------------------+
468// |                       recent pictures section                         |
469// +-----------------------------------------------------------------------+
470  else if ($page['section'] == 'recent_pics')
471  {
472    if ( !isset($page['super_order_by']) )
473    {
474      $conf['order_by'] = str_replace(
475        'ORDER BY ',
476        'ORDER BY date_available DESC,',
477        $conf['order_by']
478        );
479    }
480
481    $query = '
482SELECT DISTINCT(id)
483  FROM '.IMAGES_TABLE.'
484    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
485  WHERE
486    date_available >= '.pwg_db_get_recent_period_expression($user['recent_period']).'
487    '.$forbidden.'
488  '.$conf['order_by'].'
489;';
490
491    $page = array_merge(
492      $page,
493      array(
494        'title' => '<a href="'.duplicate_index_url(array('start'=>0)).'">'
495                  .l10n('Recent photos').'</a>',
496        'items' => array_from_query($query, 'id'),
497        )
498      );
499  }
500// +-----------------------------------------------------------------------+
501// |                 recently updated categories section                   |
502// +-----------------------------------------------------------------------+
503  else if ($page['section'] == 'recent_cats')
504  {
505    $page = array_merge(
506      $page,
507      array(
508        'title' => l10n('Recent albums'),
509        )
510      );
511  }
512// +-----------------------------------------------------------------------+
513// |                        most visited section                           |
514// +-----------------------------------------------------------------------+
515  else if ($page['section'] == 'most_visited')
516  {
517    $page['super_order_by'] = true;
518    $conf['order_by'] = ' ORDER BY hit DESC, id DESC';
519    $query = '
520SELECT DISTINCT(id)
521  FROM '.IMAGES_TABLE.'
522    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
523  WHERE hit > 0
524    '.$forbidden.'
525    '.$conf['order_by'].'
526  LIMIT '.$conf['top_number'].'
527;';
528
529    $page = array_merge(
530      $page,
531      array(
532        'title' => '<a href="'.duplicate_index_url(array('start'=>0)).'">'
533                  .$conf['top_number'].' '.l10n('Most visited').'</a>',
534        'items' => array_from_query($query, 'id'),
535        )
536      );
537  }
538// +-----------------------------------------------------------------------+
539// |                          best rated section                           |
540// +-----------------------------------------------------------------------+
541  else if ($page['section'] == 'best_rated')
542  {
543    $page['super_order_by'] = true;
544    $conf['order_by'] = ' ORDER BY rating_score DESC, id DESC';
545
546    $query ='
547SELECT DISTINCT(id)
548  FROM '.IMAGES_TABLE.'
549    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
550  WHERE rating_score IS NOT NULL
551    '.$forbidden.'
552    '.$conf['order_by'].'
553  LIMIT '.$conf['top_number'].'
554;';
555    $page = array_merge(
556      $page,
557      array(
558        'title' => '<a href="'.duplicate_index_url(array('start'=>0)).'">'
559                  .$conf['top_number'].' '.l10n('Best rated').'</a>',
560        'items' => array_from_query($query, 'id'),
561        )
562      );
563  }
564// +-----------------------------------------------------------------------+
565// |                             list section                              |
566// +-----------------------------------------------------------------------+
567  else if ($page['section'] == 'list')
568  {
569    $query ='
570SELECT DISTINCT(id)
571  FROM '.IMAGES_TABLE.'
572    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
573  WHERE image_id IN ('.implode(',', $page['list']).')
574    '.$forbidden.'
575  '.$conf['order_by'].'
576;';
577
578    $page = array_merge(
579      $page,
580      array(
581        'title' => '<a href="'.duplicate_index_url(array('start'=>0)).'">'
582                    .l10n('Random photos').'</a>',
583        'items' => array_from_query($query, 'id'),
584        )
585      );
586  }
587}
588
589// +-----------------------------------------------------------------------+
590// |                             chronology                                |
591// +-----------------------------------------------------------------------+
592
593if (isset($page['chronology_field']))
594{
595  unset($page['is_homepage']);
596  include_once( PHPWG_ROOT_PATH.'include/functions_calendar.inc.php' );
597  initialize_calendar();
598}
599
600// title update
601if (isset($page['title']))
602{
603  if (!empty($page['title']))
604        {
605          $page['title'] = $conf['level_separator'].$page['title'];
606        }
607  $page['title'] = '<a href="'.get_gallery_home_url().'">'.l10n('Home').'</a>'.$page['title'];
608}
609
610// add meta robots noindex, nofollow to avoid unnecesary robot crawls
611$page['meta_robots']=array();
612if ( isset($page['chronology_field'])
613      or ( isset($page['flat']) and isset($page['category']) )
614      or 'list'==$page['section'] or 'recent_pics'==$page['section'] )
615{
616  $page['meta_robots']=array('noindex'=>1, 'nofollow'=>1);
617}
618elseif ('tags' == $page['section'])
619{
620  if ( count($page['tag_ids'])>1 )
621  {
622    $page['meta_robots']=array('noindex'=>1, 'nofollow'=>1);
623  }
624}
625elseif ('recent_cats'==$page['section'])
626{
627  $page['meta_robots']['noindex']=1;
628}
629elseif ('search'==$page['section'])
630{
631  $page['meta_robots']['nofollow']=1;
632}
633if ( $filter['enabled'] )
634{
635  $page['meta_robots']['noindex']=1;
636}
637
638// see if we need a redirect because of a permalink
639if ( 'categories'==$page['section'] and isset($page['category']) )
640{
641  $need_redirect=false;
642  if ( empty($page['category']['permalink']) )
643  {
644    if ( $conf['category_url_style'] == 'id-name' and
645        @$page['hit_by']['cat_url_name'] !== str2url($page['category']['name']) )
646    {
647      $need_redirect=true;
648    }
649  }
650  else
651  {
652    if ( $page['category']['permalink'] !== @$page['hit_by']['cat_permalink'] )
653    {
654      $need_redirect=true;
655    }
656  }
657
658  if ($need_redirect)
659  {
660    $redirect_url = ( script_basename()=='picture'
661        ? duplicate_picture_url()
662          : duplicate_index_url()
663      );
664    if (!headers_sent())
665    { // this is a permanent redirection
666      set_status_header(301);
667      redirect_http( $redirect_url );
668    }
669    redirect( $redirect_url );
670  }
671  unset( $need_redirect, $page['hit_by'] );
672}
673
674trigger_action('loc_end_section_init');
675?>
Note: See TracBrowser for help on using the repository browser.