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

Last change on this file since 2488 was 2451, checked in by rvelices, 16 years ago
  • normalize behaviour of query search versus std search (now both return items already sorted and permission checked); also more optimized sql queries (in some cases)
  • Property svn:eol-style set to LF
  • Property svn:keywords set to Author Date Id Revision
File size: 16.8 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based picture gallery                                  |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008      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(
69  '/',
70  preg_replace('#^/#', '', $rewritten)
71  );
72// $tokens = array(
73//   0 => category,
74//   1 => 12-foo,
75//   2 => start-24
76//   );
77
78$next_token = 0;
79if (script_basename() == 'picture') // basename without file extention
80{ // the first token must be the identifier for the picture
81  if ( isset($_GET['image_id'])
82       and isset($_GET['cat']) and is_numeric($_GET['cat']) )
83  {// url compatibility with versions below 1.6
84    $url = make_picture_url( array(
85        'section' => 'categories',
86        'category' => get_cat_info($_GET['cat']),
87        'image_id' => $_GET['image_id']
88      ) );
89    redirect($url);
90  }
91  $token = $tokens[$next_token];
92  $next_token++;
93  if ( is_numeric($token) )
94  {
95    $page['image_id'] = $token;
96    if ($page['image_id']==0)
97    {
98      bad_request('invalid picture identifier');
99    }
100  }
101  else
102  {
103    preg_match('/^(\d+-)?(.*)?$/', $token, $matches);
104    if (isset($matches[1]) and is_numeric($matches[1]=rtrim($matches[1],'-')) )
105    {
106      $page['image_id'] = $matches[1];
107      if ( !empty($matches[2]) )
108      {
109        $page['image_file'] = $matches[2];
110      }
111    }
112    else
113    {
114      if ( !empty($matches[2]) )
115      {
116        $page['image_file'] = $matches[2];
117      }
118      else
119      {
120        bad_request('picture identifier is missing');
121      }
122    }
123  }
124}
125
126$page = array_merge( $page, parse_section_url( $tokens, $next_token) );
127if ( !isset($page['section']) )
128{
129  $page['section'] = 'categories';
130
131  switch (script_basename())
132  {
133    case 'picture':
134      break;
135    case 'index':
136    {
137      // No section defined, go to selected url
138      if (!empty($conf['random_index_redirect']) and empty($tokens[$next_token]) )
139      {
140        $random_index_redirect = array();
141        foreach ($conf['random_index_redirect'] as $random_url => $random_url_condition)
142        {
143          if (empty($random_url_condition) or eval($random_url_condition))
144          {
145            $random_index_redirect[] = $random_url;
146          }
147        }
148        if (!empty($random_index_redirect))
149        {
150          redirect($random_index_redirect[mt_rand(0, count($random_index_redirect)-1)]);
151        }
152      }
153      break;
154    }
155    default:
156      trigger_error('script_basename "'.script_basename().'" unknown',
157        E_USER_WARNING);
158  }
159}
160
161
162$page = array_merge( $page, parse_well_known_params_url( $tokens, $next_token) );
163
164
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
175if (pwg_get_session_var('image_order',0) > 0)
176{
177  $orders = get_category_preferred_image_orders();
178
179  $conf['order_by'] = str_replace(
180    'ORDER BY ',
181    'ORDER BY '.$orders[ pwg_get_session_var('image_order',0) ][1].',',
182    $conf['order_by']
183    );
184  $page['super_order_by'] = true;
185}
186
187$forbidden = get_sql_condition_FandF(
188      array
189        (
190          'forbidden_categories' => 'category_id',
191          'visible_categories' => 'category_id',
192          'visible_images' => 'id'
193        ),
194      'AND'
195  );
196
197// +-----------------------------------------------------------------------+
198// |                              category                                 |
199// +-----------------------------------------------------------------------+
200if ('categories' == $page['section'])
201{
202  if (isset($page['category']))
203  {
204    $page = array_merge(
205      $page,
206      array(
207        'comment'           =>
208            trigger_event(
209              'render_category_description',
210              $page['category']['comment'],
211              'main_page_category_description'
212            ),
213        'title'             =>
214          get_cat_display_name($page['category']['upper_names'], '', false),
215        )
216      );
217  }
218  else
219  {
220    $page['title'] = l10n('no_category');
221  }
222
223  if
224    (
225      (!isset($page['chronology_field'])) and
226      (
227        (isset($page['category'])) or
228        (isset($page['flat']))
229      )
230    )
231  {
232    if ( !empty($page['category']['image_order']) and !isset($page['super_order_by']) )
233    {
234      $conf[ 'order_by' ] = ' ORDER BY '.$page['category']['image_order'];
235    }
236
237    if (isset($page['flat']))
238    {// flat categories mode
239      if ( isset($page['category']) )
240      { // get all allowed sub-categories
241        $query = '
242SELECT id
243  FROM '.CATEGORIES_TABLE.'
244  WHERE
245    uppercats LIKE "'.$page['category']['uppercats'].',%" '
246    .get_sql_condition_FandF(
247      array
248        (
249          'forbidden_categories' => 'id',
250          'visible_categories' => 'id',
251        ),
252      "\n  AND"
253          );
254        $subcat_ids = array_from_query($query, 'id');
255        $subcat_ids[] = $page['category']['id'];
256        $where_sql = 'category_id IN ('.implode(',',$subcat_ids).')';
257        // remove categories from forbidden because just checked above
258        $forbidden = get_sql_condition_FandF(
259              array( 'visible_images' => 'id' ),
260              'AND'
261          );
262      }
263      else
264      {
265        $where_sql = '1=1';
266      }
267    }
268    else
269    {// Normal mode
270      $where_sql = 'category_id = '.$page['category']['id'];
271    }
272
273    // Main query
274    $query = '
275SELECT DISTINCT(image_id)
276  FROM '.IMAGE_CATEGORY_TABLE.'
277    INNER JOIN '.IMAGES_TABLE.' ON id = image_id
278  WHERE
279    '.$where_sql.'
280'.$forbidden.'
281  '.$conf['order_by'].'
282;';
283
284    $page['items'] = array_from_query($query, 'image_id');
285  } //otherwise the calendar will requery all subitems
286}
287// special sections
288else
289{
290// +-----------------------------------------------------------------------+
291// |                            tags section                               |
292// +-----------------------------------------------------------------------+
293  if ($page['section'] == 'tags')
294  {
295    $page['tag_ids'] = array();
296    foreach ($page['tags'] as $tag)
297    {
298      array_push($page['tag_ids'], $tag['id']);
299    }
300
301    $items = get_image_ids_for_tags($page['tag_ids']);
302
303    // permissions depends on category, so to only keep images that are
304    // reachable to the connected user, we need to check category
305    // associations
306    if (!empty($items) )
307    {
308      $query = '
309SELECT DISTINCT image_id
310  FROM '.IMAGE_CATEGORY_TABLE.' INNER JOIN '.IMAGES_TABLE.' ON image_id=id
311  WHERE image_id IN ('.implode(',', $items).')
312    '.$forbidden.
313    $conf['order_by'].'
314;';
315      $items =  array_from_query($query, 'image_id');
316    }
317
318    $title = get_tags_content_title();
319
320    $page = array_merge(
321      $page,
322      array(
323        'title' => $title,
324        'items' => $items,
325        )
326      );
327  }
328// +-----------------------------------------------------------------------+
329// |                           search section                              |
330// +-----------------------------------------------------------------------+
331  if ($page['section'] == 'search')
332  {
333    include_once( PHPWG_ROOT_PATH .'include/functions_search.inc.php' );
334
335    $search_result = get_search_results($page['search'], @$page['super_order_by'] );
336    if ( isset($search_result['qs']) )
337    {//save the details of the query search
338      $page['qsearch_details'] = $search_result['qs'];
339    }
340
341    $page = array_merge(
342      $page,
343      array(
344        'items' => $search_result['items'],
345        'title' => '<a href="'.duplicate_index_url(array('start'=>0)).'">'
346                  .l10n('search_result').'</a>',
347        )
348      );
349  }
350// +-----------------------------------------------------------------------+
351// |                           favorite section                            |
352// +-----------------------------------------------------------------------+
353  else if ($page['section'] == 'favorites')
354  {
355    check_user_favorites();
356
357    $query = '
358SELECT image_id
359  FROM '.FAVORITES_TABLE.'
360    INNER JOIN '.IMAGES_TABLE.' ON image_id = id
361  WHERE user_id = '.$user['id'].'
362'.get_sql_condition_FandF
363  (
364    array
365      (
366        'visible_images' => 'id'
367      ),
368    'AND'
369  ).'
370  '.$conf['order_by'].'
371;';
372
373    $page = array_merge(
374      $page,
375      array(
376        'title' => l10n('favorites'),
377        'items' => array_from_query($query, 'image_id'),
378        )
379      );
380  }
381// +-----------------------------------------------------------------------+
382// |                       recent pictures section                         |
383// +-----------------------------------------------------------------------+
384  else if ($page['section'] == 'recent_pics')
385  {
386    if ( !isset($page['super_order_by']) )
387    {
388      $conf['order_by'] = str_replace(
389        'ORDER BY ',
390        'ORDER BY date_available DESC,',
391        $conf['order_by']
392        );
393    }
394
395    $query = '
396SELECT DISTINCT(id)
397  FROM '.IMAGES_TABLE.'
398    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
399  WHERE
400    date_available >= SUBDATE(
401      CURRENT_DATE,INTERVAL '.$user['recent_period'].' DAY)
402    '.$forbidden.'
403  '.$conf['order_by'].'
404;';
405
406    $page = array_merge(
407      $page,
408      array(
409        'title' => '<a href="'.duplicate_index_url(array('start'=>0)).'">'
410                  .l10n('recent_pics_cat').'</a>',
411        'items' => array_from_query($query, 'id'),
412        )
413      );
414  }
415// +-----------------------------------------------------------------------+
416// |                 recently updated categories section                   |
417// +-----------------------------------------------------------------------+
418  else if ($page['section'] == 'recent_cats')
419  {
420    $page = array_merge(
421      $page,
422      array(
423        'title' => l10n('recent_cats_cat'),
424        )
425      );
426  }
427// +-----------------------------------------------------------------------+
428// |                        most visited section                           |
429// +-----------------------------------------------------------------------+
430  else if ($page['section'] == 'most_visited')
431  {
432    $page['super_order_by'] = true;
433    $conf['order_by'] = ' ORDER BY hit DESC, file ASC';
434    $query = '
435SELECT DISTINCT(id)
436  FROM '.IMAGES_TABLE.'
437    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
438  WHERE hit > 0
439    '.$forbidden.'
440    '.$conf['order_by'].'
441  LIMIT 0, '.$conf['top_number'].'
442;';
443
444    $page = array_merge(
445      $page,
446      array(
447        'title' => '<a href="'.duplicate_index_url(array('start'=>0)).'">'
448                  .$conf['top_number'].' '.l10n('most_visited_cat').'</a>',
449        'items' => array_from_query($query, 'id'),
450        )
451      );
452  }
453// +-----------------------------------------------------------------------+
454// |                          best rated section                           |
455// +-----------------------------------------------------------------------+
456  else if ($page['section'] == 'best_rated')
457  {
458    $page['super_order_by'] = true;
459    $conf['order_by'] = ' ORDER BY average_rate DESC, id ASC';
460
461    $query ='
462SELECT DISTINCT(id)
463  FROM '.IMAGES_TABLE.'
464    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
465  WHERE average_rate IS NOT NULL
466    '.$forbidden.'
467    '.$conf['order_by'].'
468  LIMIT 0, '.$conf['top_number'].'
469;';
470    $page = array_merge(
471      $page,
472      array(
473        'title' => '<a href="'.duplicate_index_url(array('start'=>0)).'">'
474                  .$conf['top_number'].' '.l10n('best_rated_cat').'</a>',
475        'items' => array_from_query($query, 'id'),
476        )
477      );
478  }
479// +-----------------------------------------------------------------------+
480// |                             list section                              |
481// +-----------------------------------------------------------------------+
482  else if ($page['section'] == 'list')
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 image_id IN ('.implode(',', $page['list']).')
489    '.$forbidden.'
490  '.$conf['order_by'].'
491;';
492
493    $page = array_merge(
494      $page,
495      array(
496        'title' => '<a href="'.duplicate_index_url(array('start'=>0)).'">'
497                    .l10n('random_cat').'</a>',
498        'items' => array_from_query($query, 'id'),
499        )
500      );
501  }
502}
503
504// +-----------------------------------------------------------------------+
505// |                             chronology                                |
506// +-----------------------------------------------------------------------+
507
508if (isset($page['chronology_field']))
509{
510  include_once( PHPWG_ROOT_PATH.'include/functions_calendar.inc.php' );
511  initialize_calendar();
512}
513
514if (script_basename() == 'picture'
515    and !isset($page['image_id']) )
516{
517  $page['image_id'] = 0; // more work in picture.php
518}
519
520// add meta robots noindex, nofollow to avoid unnecesary robot crawls
521$page['meta_robots']=array();
522if ( isset($page['chronology_field'])
523      or ( isset($page['flat']) and isset($page['category']) )
524      or 'list'==$page['section'] or 'recent_pics'==$page['section'] )
525{
526  $page['meta_robots']=array('noindex'=>1, 'nofollow'=>1);
527}
528elseif ('tags' == $page['section'])
529{
530  if ( count($page['tag_ids'])>1 )
531  {
532    $page['meta_robots']=array('noindex'=>1, 'nofollow'=>1);
533  }
534}
535elseif ('recent_cats'==$page['section'])
536{
537  $page['meta_robots']['noindex']=1;
538}
539elseif ('search'==$page['section'])
540{
541  $page['meta_robots']['nofollow']=1;
542}
543if ( $filter['enabled'] )
544{
545  $page['meta_robots']['noindex']=1;
546}
547
548// see if we need a redirect because of a permalink
549if ( 'categories'==$page['section'] and isset($page['category']) )
550{
551  $need_redirect=false;
552  if ( empty($page['category']['permalink']) )
553  {
554    if ( $conf['category_url_style'] == 'id-name' and
555        @$page['hit_by']['cat_url_name'] !== str2url($page['category']['name']) )
556    {
557      $need_redirect=true;
558    }
559  }
560  else
561  {
562    if ( $page['category']['permalink'] !== @$page['hit_by']['cat_permalink'] )
563    {
564      $need_redirect=true;
565    }
566  }
567
568  if ($need_redirect)
569  {
570    $redirect_url = ( script_basename()=='picture'
571        ? duplicate_picture_url()
572          : duplicate_index_url()
573      );
574    if (!headers_sent())
575    { // this is a permanent redirection
576      set_status_header(301);
577      redirect_http( $redirect_url );
578    }
579    redirect( $redirect_url );
580  }
581  unset( $need_redirect, $page['hit_by'] );
582}
583
584trigger_action('loc_end_section_init');
585?>
Note: See TracBrowser for help on using the repository browser.