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

Last change on this file since 3049 was 3049, checked in by plg, 15 years ago

Administration: happy new year 2009, all PHP headers updated.

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