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

Last change on this file since 28587 was 28587, checked in by mistic100, 10 years ago

feature 3010 : replace trigger_action/event by trigger_notify/change

  • 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-2014 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;
86
87// +-----------------------------------------------------------------------+
88// |                             picture page                              |
89// +-----------------------------------------------------------------------+
90// the first token must be the identifier for the picture
91if (script_basename() == 'picture')
92{
93  $token = $tokens[$next_token];
94  $next_token++;
95  if ( is_numeric($token) )
96  {
97    $page['image_id'] = $token;
98    if ($page['image_id']==0)
99    {
100      bad_request('invalid picture identifier');
101    }
102  }
103  else
104  {
105    preg_match('/^(\d+-)?(.*)?$/', $token, $matches);
106    if (isset($matches[1]) and is_numeric($matches[1]=rtrim($matches[1],'-')) )
107    {
108      $page['image_id'] = $matches[1];
109      if ( !empty($matches[2]) )
110      {
111        $page['image_file'] = $matches[2];
112      }
113    }
114    else
115    {
116      $page['image_id'] = 0; // more work in picture.php
117      if ( !empty($matches[2]) )
118      {
119        $page['image_file'] = $matches[2];
120      }
121      else
122      {
123        bad_request('picture identifier is missing');
124      }
125    }
126  }
127}
128
129
130$page = array_merge( $page, parse_section_url( $tokens, $next_token) );
131
132if ( !isset($page['section']) )
133{
134  $page['section'] = 'categories';
135
136  switch (script_basename())
137  {
138    case 'picture':
139      break;
140    case 'index':
141    {
142      // No section defined, go to random url
143      if ( !empty($conf['random_index_redirect']) and empty($tokens[$next_token]) )
144      {
145        $random_index_redirect = array();
146        foreach ($conf['random_index_redirect'] as $random_url => $random_url_condition)
147        {
148          if (empty($random_url_condition) or eval($random_url_condition))
149          {
150            $random_index_redirect[] = $random_url;
151          }
152        }
153        if (!empty($random_index_redirect))
154        {
155          redirect($random_index_redirect[mt_rand(0, count($random_index_redirect)-1)]);
156        }
157      }
158      $page['is_homepage'] = true;
159      break;
160    }
161    default:
162      trigger_error('script_basename "'.script_basename().'" unknown',
163        E_USER_WARNING);
164  }
165}
166
167$page = array_merge( $page, parse_well_known_params_url( $tokens, $next_token) );
168
169//access a picture only by id, file or id-file without given section
170if ( script_basename()=='picture' and 'categories'==$page['section'] and
171      !isset($page['category']) and !isset($page['chronology_field']) )
172{
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  else
209  {
210    pwg_unset_session_var('image_order');
211    $page['super_order_by'] = false;
212  }
213}
214
215$forbidden = get_sql_condition_FandF(
216      array(
217        'forbidden_categories' => 'category_id',
218        'visible_categories' => 'category_id',
219        'visible_images' => 'id'
220        ),
221      'AND'
222  );
223
224// +-----------------------------------------------------------------------+
225// |                              category                                 |
226// +-----------------------------------------------------------------------+
227if ('categories' == $page['section'])
228{
229  if (isset($page['category']))
230  {
231    $page = array_merge(
232      $page,
233      array(
234        'comment' => trigger_change(
235            'render_category_description',
236            $page['category']['comment'],
237            'main_page_category_description'
238            ),
239        'title'   => get_cat_display_name($page['category']['upper_names'], '', false),
240        )
241      );
242  }
243  else
244  {
245    $page['title'] = ''; // will be set later
246  }
247
248  // GET IMAGES LIST
249  if
250    (
251      $page['startcat'] == 0 and
252      (!isset($page['chronology_field'])) and // otherwise the calendar will requery all subitems
253      (
254        (isset($page['category'])) or
255        (isset($page['flat']))
256      )
257    )
258  {
259    if ( !empty($page['category']['image_order']) and !isset($page['super_order_by']) )
260    {
261      $conf[ 'order_by' ] = ' ORDER BY '.$page['category']['image_order'];
262    }
263
264    // flat categories mode
265    if (isset($page['flat']))
266    {
267      // get all allowed sub-categories
268      if ( isset($page['category']) )
269      {
270        $query = '
271SELECT id
272  FROM '.CATEGORIES_TABLE.'
273  WHERE
274    uppercats LIKE \''.$page['category']['uppercats'].',%\' '
275    .get_sql_condition_FandF(
276        array(
277          'forbidden_categories' => 'id',
278          'visible_categories' => 'id',
279          ),
280        "\n  AND"
281        );
282
283        $subcat_ids = query2array($query,null, 'id');
284        $subcat_ids[] = $page['category']['id'];
285        $where_sql = 'category_id IN ('.implode(',',$subcat_ids).')';
286        // remove categories from forbidden because just checked above
287        $forbidden = get_sql_condition_FandF(
288              array( 'visible_images' => 'id' ),
289              'AND'
290          );
291      }
292      else
293      {
294        $cache_key = $persistent_cache->make_key('all_iids'.$user['id'].$user['cache_update_time'].$conf['order_by']);
295        unset($page['is_homepage']);
296        $where_sql = '1=1';
297      }
298    }
299    // normal mode
300    else
301    {
302      $where_sql = 'category_id = '.$page['category']['id'];
303    }
304
305    if ( !isset($cache_key) || !$persistent_cache->get($cache_key, $page['items']))
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'] = query2array($query,null, 'image_id');
319     
320      if ( isset($cache_key) )
321        $persistent_cache->set($cache_key, $page['items']);
322    }
323  }
324}
325// special sections
326else
327{
328// +-----------------------------------------------------------------------+
329// |                            tags section                               |
330// +-----------------------------------------------------------------------+
331  if ($page['section'] == 'tags')
332  {
333    $page['tag_ids'] = array();
334    foreach ($page['tags'] as $tag)
335    {
336      $page['tag_ids'][] = $tag['id'];
337    }
338
339    $items = get_image_ids_for_tags($page['tag_ids']);
340
341    $page = array_merge(
342      $page,
343      array(
344        'title' => get_tags_content_title(),
345        'items' => $items,
346        )
347      );
348  }
349// +-----------------------------------------------------------------------+
350// |                           search section                              |
351// +-----------------------------------------------------------------------+
352  else if ($page['section'] == 'search')
353  {
354    include_once( PHPWG_ROOT_PATH .'include/functions_search.inc.php' );
355
356    $search_result = get_search_results($page['search'], @$page['super_order_by'] );
357    //save the details of the query search
358    if ( isset($search_result['qs']) )
359    {
360      $page['qsearch_details'] = $search_result['qs'];
361    }
362
363    $page = array_merge(
364      $page,
365      array(
366        'items' => $search_result['items'],
367        'title' => '<a href="'.duplicate_index_url(array('start'=>0)).'">'
368                    .l10n('Search results').'</a>',
369        )
370      );
371  }
372// +-----------------------------------------------------------------------+
373// |                           favorite section                            |
374// +-----------------------------------------------------------------------+
375  else if ($page['section'] == 'favorites')
376  {
377    check_user_favorites();
378
379    $page = array_merge(
380      $page,
381      array(
382        'title' => l10n('Favorites')
383      )
384    );
385
386    if (!empty($_GET['action']) && ($_GET['action'] == 'remove_all_from_favorites'))
387    {
388      $query = '
389DELETE FROM '.FAVORITES_TABLE.'
390  WHERE user_id = '.$user['id'].'
391;';
392      pwg_query($query);
393      redirect(make_index_url( array('section'=>'favorites') ));
394    }
395    else
396    {
397      $query = '
398SELECT image_id
399  FROM '.FAVORITES_TABLE.'
400    INNER JOIN '.IMAGES_TABLE.' ON image_id = id
401  WHERE user_id = '.$user['id'].'
402'.get_sql_condition_FandF(
403      array(
404        'visible_images' => 'id'
405        ),
406      'AND'
407      ).'
408  '.$conf['order_by'].'
409;';
410      $page = array_merge(
411        $page,
412        array(
413          'items' => query2array($query,null, 'image_id'),
414          )
415        );
416
417      if (count($page['items'])>0)
418      {
419        $template->assign(
420            'favorite',
421            array(
422              'U_FAVORITE' => add_url_params(
423                  make_index_url( array('section'=>'favorites') ),
424                  array('action'=>'remove_all_from_favorites')
425                  ),
426              )
427            );
428      }
429    }
430  }
431// +-----------------------------------------------------------------------+
432// |                       recent pictures section                         |
433// +-----------------------------------------------------------------------+
434  else if ($page['section'] == 'recent_pics')
435  {
436    if ( !isset($page['super_order_by']) )
437    {
438      $conf['order_by'] = str_replace(
439          'ORDER BY ',
440          'ORDER BY date_available DESC,',
441          $conf['order_by']
442          );
443    }
444
445    $query = '
446SELECT DISTINCT(id)
447  FROM '.IMAGES_TABLE.'
448    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
449  WHERE '
450  .get_recent_photos_sql('date_available').'
451  '.$forbidden
452  .$conf['order_by'].'
453;';
454
455    $page = array_merge(
456      $page,
457      array(
458        'title' => '<a href="'.duplicate_index_url(array('start'=>0)).'">'
459                    .l10n('Recent photos').'</a>',
460        'items' => query2array($query,null, 'id'),
461        )
462      );
463  }
464// +-----------------------------------------------------------------------+
465// |                 recently updated categories section                   |
466// +-----------------------------------------------------------------------+
467  else if ($page['section'] == 'recent_cats')
468  {
469    $page = array_merge(
470      $page,
471      array(
472        'title' => l10n('Recent albums'),
473        )
474      );
475  }
476// +-----------------------------------------------------------------------+
477// |                        most visited section                           |
478// +-----------------------------------------------------------------------+
479  else if ($page['section'] == 'most_visited')
480  {
481    $page['super_order_by'] = true;
482    $conf['order_by'] = ' ORDER BY hit DESC, id DESC';
483
484    $query = '
485SELECT DISTINCT(id)
486  FROM '.IMAGES_TABLE.'
487    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
488  WHERE hit > 0
489    '.$forbidden.'
490    '.$conf['order_by'].'
491  LIMIT '.$conf['top_number'].'
492;';
493
494    $page = array_merge(
495      $page,
496      array(
497        'title' => '<a href="'.duplicate_index_url(array('start'=>0)).'">'
498                    .$conf['top_number'].' '.l10n('Most visited').'</a>',
499        'items' => query2array($query,null, 'id'),
500        )
501      );
502  }
503// +-----------------------------------------------------------------------+
504// |                          best rated section                           |
505// +-----------------------------------------------------------------------+
506  else if ($page['section'] == 'best_rated')
507  {
508    $page['super_order_by'] = true;
509    $conf['order_by'] = ' ORDER BY rating_score DESC, id DESC';
510
511    $query ='
512SELECT DISTINCT(id)
513  FROM '.IMAGES_TABLE.'
514    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
515  WHERE rating_score IS NOT NULL
516    '.$forbidden.'
517    '.$conf['order_by'].'
518  LIMIT '.$conf['top_number'].'
519;';
520    $page = array_merge(
521      $page,
522      array(
523        'title' => '<a href="'.duplicate_index_url(array('start'=>0)).'">'
524                    .$conf['top_number'].' '.l10n('Best rated').'</a>',
525        'items' => query2array($query,null, 'id'),
526        )
527      );
528  }
529// +-----------------------------------------------------------------------+
530// |                             list section                              |
531// +-----------------------------------------------------------------------+
532  else if ($page['section'] == 'list')
533  {
534    $query ='
535SELECT DISTINCT(id)
536  FROM '.IMAGES_TABLE.'
537    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
538  WHERE image_id IN ('.implode(',', $page['list']).')
539    '.$forbidden.'
540  '.$conf['order_by'].'
541;';
542
543    $page = array_merge(
544      $page,
545      array(
546        'title' => '<a href="'.duplicate_index_url(array('start'=>0)).'">'
547                    .l10n('Random photos').'</a>',
548        'items' => query2array($query,null, 'id'),
549        )
550      );
551  }
552}
553
554// +-----------------------------------------------------------------------+
555// |                             chronology                                |
556// +-----------------------------------------------------------------------+
557if (isset($page['chronology_field']))
558{
559  unset($page['is_homepage']);
560  include_once( PHPWG_ROOT_PATH.'include/functions_calendar.inc.php' );
561  initialize_calendar();
562}
563
564// title update
565if (isset($page['title']))
566{
567  $page['section_title'] = '<a href="'.get_gallery_home_url().'">'.l10n('Home').'</a>';
568  if (!empty($page['title']))
569  {
570    $page['section_title'] .= $conf['level_separator'].$page['title'];
571  }
572  else
573  {
574    $page['title'] = $page['section_title'];
575  }
576}
577
578// add meta robots noindex, nofollow to avoid unnecesary robot crawls
579$page['meta_robots']=array();
580if ( isset($page['chronology_field'])
581      or ( isset($page['flat']) and isset($page['category']) )
582      or 'list'==$page['section'] or 'recent_pics'==$page['section'] )
583{
584  $page['meta_robots']=array('noindex'=>1, 'nofollow'=>1);
585}
586elseif ('tags'==$page['section'])
587{
588  if ( count($page['tag_ids'])>1 )
589  {
590    $page['meta_robots']=array('noindex'=>1, 'nofollow'=>1);
591  }
592}
593elseif ('recent_cats'==$page['section'])
594{
595  $page['meta_robots']['noindex']=1;
596}
597elseif ('search'==$page['section'])
598{
599  $page['meta_robots']['nofollow']=1;
600}
601if ( $filter['enabled'] )
602{
603  $page['meta_robots']['noindex']=1;
604}
605
606// see if we need a redirect because of a permalink
607if ( 'categories'==$page['section'] and isset($page['category']) )
608{
609  $need_redirect=false;
610  if ( empty($page['category']['permalink']) )
611  {
612    if ( $conf['category_url_style'] == 'id-name' and
613        @$page['hit_by']['cat_url_name'] !== str2url($page['category']['name']) )
614    {
615      $need_redirect=true;
616    }
617  }
618  else
619  {
620    if ( $page['category']['permalink'] !== @$page['hit_by']['cat_permalink'] )
621    {
622      $need_redirect=true;
623    }
624  }
625
626  if ($need_redirect)
627  {
628    $redirect_url = script_basename()=='picture' ? duplicate_picture_url() : duplicate_index_url();
629
630    if (!headers_sent())
631    { // this is a permanent redirection
632      set_status_header(301);
633      redirect_http( $redirect_url );
634    }
635    redirect( $redirect_url );
636  }
637  unset( $need_redirect, $page['hit_by'] );
638}
639
640trigger_notify('loc_end_section_init');
641?>
Note: See TracBrowser for help on using the repository browser.