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

Last change on this file since 20335 was 19703, checked in by plg, 12 years ago

update Piwigo headers to 2013 (the end of the world didn't occur as expected on r12922)

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