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

Last change on this file since 11999 was 11893, checked in by rvelices, 13 years ago

rename #images.average_rate to rating_score

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