source: branches/1.7/include/section_init.inc.php @ 27713

Last change on this file since 27713 was 2452, checked in by rvelices, 16 years ago
  • merge r2451 from trunk: 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// | PhpWebGallery - a PHP based picture gallery                           |
4// | Copyright (C) 2002-2003 Pierrick LE GALL - pierrick@phpwebgallery.net |
5// | Copyright (C) 2003-2007 PhpWebGallery Team - http://phpwebgallery.net |
6// +-----------------------------------------------------------------------+
7// | file          : $Id: section_init.inc.php 2452 2008-07-23 00:56:53Z rvelices $
8// | last update   : $Date: 2008-07-23 00:56:53 +0000 (Wed, 23 Jul 2008) $
9// | last modifier : $Author: rvelices $
10// | revision      : $Revision: 2452 $
11// +-----------------------------------------------------------------------+
12// | This program is free software; you can redistribute it and/or modify  |
13// | it under the terms of the GNU General Public License as published by  |
14// | the Free Software Foundation                                          |
15// |                                                                       |
16// | This program is distributed in the hope that it will be useful, but   |
17// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
18// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
19// | General Public License for more details.                              |
20// |                                                                       |
21// | You should have received a copy of the GNU General Public License     |
22// | along with this program; if not, write to the Free Software           |
23// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
24// | USA.                                                                  |
25// +-----------------------------------------------------------------------+
26
27/**
28 * This included page checks section related parameter and provides
29 * following informations:
30 *
31 * - $page['title']
32 *
33 * - $page['items']: ordered list of items to display
34 *
35 */
36
37// "index.php?/category/12-foo/start-24" or
38// "index.php/category/12-foo/start-24"
39// must return :
40//
41// array(
42//   'section'  => 'categories',
43//   'category' => array('id'=>12, ...),
44//   'start'    => 24
45//   );
46
47$page['items'] = array();
48
49// some ISPs set PATH_INFO to empty string or to SCRIPT_FILENAME while in the
50// default apache implementation it is not set
51if ( $conf['question_mark_in_urls']==false and
52     isset($_SERVER["PATH_INFO"]) and !empty($_SERVER["PATH_INFO"]) )
53{
54  $rewritten = $_SERVER["PATH_INFO"];
55  $rewritten = str_replace('//', '/', $rewritten);
56  $path_count = count( explode('/', $rewritten) );
57  $page['root_path'] = PHPWG_ROOT_PATH.str_repeat('../', $path_count-1);
58}
59else
60{
61  $rewritten = '';
62  foreach (array_keys($_GET) as $keynum => $key)
63  {
64    $rewritten = $key;
65    break;
66  }
67  $page['root_path'] = PHPWG_ROOT_PATH;
68}
69
70// deleting first "/" if displayed
71$tokens = explode(
72  '/',
73  preg_replace('#^/#', '', $rewritten)
74  );
75// $tokens = array(
76//   0 => category,
77//   1 => 12-foo,
78//   2 => start-24
79//   );
80
81$next_token = 0;
82if (script_basename() == 'picture') // basename without file extention
83{ // the first token must be the identifier for the picture
84  if ( isset($_GET['image_id'])
85       and isset($_GET['cat']) and is_numeric($_GET['cat']) )
86  {// url compatibility with versions below 1.6
87    $url = make_picture_url( array(
88        'section' => 'categories',
89        'category' => get_cat_info($_GET['cat']),
90        'image_id' => $_GET['image_id']
91      ) );
92    redirect($url);
93  }
94  $token = $tokens[$next_token];
95  $next_token++;
96  if ( is_numeric($token) )
97  {
98    $page['image_id'] = $token;
99    if ($page['image_id']==0)
100    {
101      bad_request('invalid picture identifier');
102    }
103  }
104  else
105  {
106    preg_match('/^(\d+-)?(.*)?$/', $token, $matches);
107    if (isset($matches[1]) and is_numeric($matches[1]=rtrim($matches[1],'-')) )
108    {
109      $page['image_id'] = $matches[1];
110      if ( !empty($matches[2]) )
111      {
112        $page['image_file'] = $matches[2];
113      }
114    }
115    else
116    {
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$page = array_merge( $page, parse_section_url( $tokens, $next_token) );
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
165$page = array_merge( $page, parse_well_known_params_url( $tokens, $next_token) );
166
167
168if ( script_basename()=='picture' and 'categories'==$page['section'] and
169      !isset($page['category']) and !isset($page['chronology_field']) )
170{ //access a picture only by id, file or id-file without given section
171  $page['flat']=true;
172}
173
174
175// $page['nb_image_page'] is the number of picture to display on this page
176// By default, it is the same as the $user['nb_image_page']
177$page['nb_image_page'] = $user['nb_image_page'];
178
179if (pwg_get_session_var('image_order',0) > 0)
180{
181  $orders = get_category_preferred_image_orders();
182
183  $conf['order_by'] = str_replace(
184    'ORDER BY ',
185    'ORDER BY '.$orders[ pwg_get_session_var('image_order',0) ][1].',',
186    $conf['order_by']
187    );
188  $page['super_order_by'] = true;
189}
190
191$forbidden = get_sql_condition_FandF(
192      array
193        (
194          'forbidden_categories' => 'category_id',
195          'visible_categories' => 'category_id',
196          'visible_images' => 'id'
197        ),
198      'AND'
199  );
200
201// +-----------------------------------------------------------------------+
202// |                              category                                 |
203// +-----------------------------------------------------------------------+
204if ('categories' == $page['section'])
205{
206  if (isset($page['category']))
207  {
208    $page = array_merge(
209      $page,
210      array(
211        'comment'           =>
212            trigger_event(
213              'render_category_description',
214              $page['category']['comment'],
215              'main_page_category_description'
216            ),
217        'title'             =>
218          get_cat_display_name($page['category']['upper_names'], '', false),
219        )
220      );
221  }
222  else
223  {
224    $page['title'] = l10n('no_category');
225  }
226
227  if
228    (
229      (!isset($page['chronology_field'])) and
230      (
231        (isset($page['category'])) or
232        (isset($page['flat']))
233      )
234    )
235  {
236    if ( !empty($page['category']['image_order']) and !isset($page['super_order_by']) )
237    {
238      $conf[ 'order_by' ] = ' ORDER BY '.$page['category']['image_order'];
239    }
240
241    if (isset($page['flat']))
242    {// flat categories mode
243      if ( isset($page['category']) )
244      { // get all allowed sub-categories
245        $query = '
246SELECT id
247  FROM '.CATEGORIES_TABLE.'
248  WHERE
249    uppercats LIKE "'.$page['category']['uppercats'].',%" '
250    .get_sql_condition_FandF(
251      array
252        (
253          'forbidden_categories' => 'id',
254          'visible_categories' => 'id',
255        ),
256      "\n  AND"
257          );
258        $subcat_ids = array_from_query($query, 'id');
259        $subcat_ids[] = $page['category']['id'];
260        $where_sql = 'category_id IN ('.implode(',',$subcat_ids).')';
261        // remove categories from forbidden because just checked above
262        $forbidden = get_sql_condition_FandF(
263              array( 'visible_images' => 'id' ),
264              'AND'
265          );
266      }
267      else
268      {
269        $where_sql = '1=1';
270      }
271    }
272    else
273    {// Normal mode
274      $where_sql = 'category_id = '.$page['category']['id'];
275    }
276
277    // Main query
278    $query = '
279SELECT DISTINCT(image_id)
280  FROM '.IMAGE_CATEGORY_TABLE.'
281    INNER JOIN '.IMAGES_TABLE.' ON id = image_id
282  WHERE
283    '.$where_sql.'
284'.$forbidden.'
285  '.$conf['order_by'].'
286;';
287
288    $page['items'] = array_from_query($query, 'image_id');
289  } //otherwise the calendar will requery all subitems
290}
291// special sections
292else
293{
294// +-----------------------------------------------------------------------+
295// |                            tags section                               |
296// +-----------------------------------------------------------------------+
297  if ($page['section'] == 'tags')
298  {
299    $page['tag_ids'] = array();
300    foreach ($page['tags'] as $tag)
301    {
302      array_push($page['tag_ids'], $tag['id']);
303    }
304
305    $items = get_image_ids_for_tags($page['tag_ids']);
306
307    // permissions depends on category, so to only keep images that are
308    // reachable to the connected user, we need to check category
309    // associations
310    if (!empty($items) )
311    {
312      $query = '
313SELECT DISTINCT(image_id)
314  FROM '.IMAGE_CATEGORY_TABLE.' INNER JOIN '.IMAGES_TABLE.' ON image_id=id
315  WHERE image_id IN ('.implode(',', $items).')
316    '.$forbidden.
317    $conf['order_by'].'
318;';
319      $items = array_from_query($query, 'image_id');
320    }
321
322    $title = get_tags_content_title();
323
324    $page = array_merge(
325      $page,
326      array(
327        'title' => $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_result').'</a>',
351        )
352      );
353  }
354// +-----------------------------------------------------------------------+
355// |                           favorite section                            |
356// +-----------------------------------------------------------------------+
357  else if ($page['section'] == 'favorites')
358  {
359    check_user_favorites();
360
361    $query = '
362SELECT image_id
363  FROM '.FAVORITES_TABLE.'
364    INNER JOIN '.IMAGES_TABLE.' ON image_id = id
365  WHERE user_id = '.$user['id'].'
366'.get_sql_condition_FandF
367  (
368    array
369      (
370        'visible_images' => 'id'
371      ),
372    'AND'
373  ).'
374  '.$conf['order_by'].'
375;';
376
377    $page = array_merge(
378      $page,
379      array(
380        'title' => l10n('favorites'),
381        'items' => array_from_query($query, 'image_id'),
382        )
383      );
384  }
385// +-----------------------------------------------------------------------+
386// |                       recent pictures section                         |
387// +-----------------------------------------------------------------------+
388  else if ($page['section'] == 'recent_pics')
389  {
390    if ( !isset($page['super_order_by']) )
391    {
392      $conf['order_by'] = str_replace(
393        'ORDER BY ',
394        'ORDER BY date_available DESC,',
395        $conf['order_by']
396        );
397    }
398
399    $query = '
400SELECT DISTINCT(id)
401  FROM '.IMAGES_TABLE.'
402    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
403  WHERE
404    date_available >= SUBDATE(
405      CURRENT_DATE,INTERVAL '.$user['recent_period'].' DAY)
406    '.$forbidden.'
407  '.$conf['order_by'].'
408;';
409
410    $page = array_merge(
411      $page,
412      array(
413        'title' => '<a href="'.duplicate_index_url(array('start'=>0)).'">'
414                  .l10n('recent_pics_cat').'</a>',
415        'items' => array_from_query($query, 'id'),
416        )
417      );
418  }
419// +-----------------------------------------------------------------------+
420// |                 recently updated categories section                   |
421// +-----------------------------------------------------------------------+
422  else if ($page['section'] == 'recent_cats')
423  {
424    $page = array_merge(
425      $page,
426      array(
427        'title' => l10n('recent_cats_cat'),
428        )
429      );
430  }
431// +-----------------------------------------------------------------------+
432// |                        most visited section                           |
433// +-----------------------------------------------------------------------+
434  else if ($page['section'] == 'most_visited')
435  {
436    $page['super_order_by'] = true;
437    $conf['order_by'] = ' ORDER BY hit DESC, file ASC';
438    $query = '
439SELECT DISTINCT(id)
440  FROM '.IMAGES_TABLE.'
441    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
442  WHERE hit > 0
443    '.$forbidden.'
444    '.$conf['order_by'].'
445  LIMIT 0, '.$conf['top_number'].'
446;';
447
448    $page = array_merge(
449      $page,
450      array(
451        'title' => '<a href="'.duplicate_index_url(array('start'=>0)).'">'
452                  .$conf['top_number'].' '.l10n('most_visited_cat').'</a>',
453        'items' => array_from_query($query, 'id'),
454        )
455      );
456  }
457// +-----------------------------------------------------------------------+
458// |                          best rated section                           |
459// +-----------------------------------------------------------------------+
460  else if ($page['section'] == 'best_rated')
461  {
462    $page['super_order_by'] = true;
463    $conf['order_by'] = ' ORDER BY average_rate DESC, id ASC';
464
465    $query ='
466SELECT DISTINCT(id)
467  FROM '.IMAGES_TABLE.'
468    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
469  WHERE average_rate IS NOT NULL
470    '.$forbidden.'
471    '.$conf['order_by'].'
472  LIMIT 0, '.$conf['top_number'].'
473;';
474    $page = array_merge(
475      $page,
476      array(
477        'title' => '<a href="'.duplicate_index_url(array('start'=>0)).'">'
478                  .$conf['top_number'].' '.l10n('best_rated_cat').'</a>',
479        'items' => array_from_query($query, 'id'),
480        )
481      );
482  }
483// +-----------------------------------------------------------------------+
484// |                             list section                              |
485// +-----------------------------------------------------------------------+
486  else if ($page['section'] == 'list')
487  {
488    $query ='
489SELECT DISTINCT(id)
490  FROM '.IMAGES_TABLE.'
491    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
492  WHERE image_id IN ('.implode(',', $page['list']).')
493    '.$forbidden.'
494  '.$conf['order_by'].'
495;';
496
497    $page = array_merge(
498      $page,
499      array(
500        'title' => '<a href="'.duplicate_index_url(array('start'=>0)).'">'
501                    .l10n('random_cat').'</a>',
502        'items' => array_from_query($query, 'id'),
503        )
504      );
505  }
506}
507
508// +-----------------------------------------------------------------------+
509// |                             chronology                                |
510// +-----------------------------------------------------------------------+
511
512if (isset($page['chronology_field']))
513{
514  include_once( PHPWG_ROOT_PATH.'include/functions_calendar.inc.php' );
515  initialize_calendar();
516}
517
518if (script_basename() == 'picture'
519    and !isset($page['image_id']) )
520{
521  $page['image_id'] = 0; // more work in picture.php
522}
523
524// add meta robots noindex, nofollow to avoid unnecesary robot crawls
525$page['meta_robots']=array();
526if ( isset($page['chronology_field'])
527      or ( isset($page['flat']) and isset($page['category']) )
528      or 'list'==$page['section'] or 'recent_pics'==$page['section'] )
529{
530  $page['meta_robots']=array('noindex'=>1, 'nofollow'=>1);
531}
532elseif ('tags' == $page['section'])
533{
534  if ( count($page['tag_ids'])>1 )
535  {
536    $page['meta_robots']=array('noindex'=>1, 'nofollow'=>1);
537  }
538}
539elseif ('recent_cats'==$page['section'])
540{
541  $page['meta_robots']['noindex']=1;
542}
543elseif ('search'==$page['section'])
544{
545  $page['meta_robots']['nofollow']=1;
546}
547
548if ( $filter['enabled'] )
549{
550  $page['meta_robots']['noindex']=1;
551}
552
553// see if we need a redirect because of a permalink
554if ( 'categories'==$page['section'] and isset($page['category']) )
555{
556  $need_redirect=false;
557  if ( empty($page['category']['permalink']) )
558  {
559    if ( $conf['category_url_style'] == 'id-name' and
560        @$page['hit_by']['cat_url_name'] !== str2url($page['category']['name']) )
561    {
562      $need_redirect=true;
563    }
564  }
565  else
566  {
567    if ( $page['category']['permalink'] !== @$page['hit_by']['cat_permalink'] )
568    {
569      $need_redirect=true;
570    }
571  }
572
573  if ($need_redirect)
574  {
575    $redirect_url = ( script_basename()=='picture'
576        ? duplicate_picture_url()
577          : duplicate_index_url()
578      );
579    if (!headers_sent())
580    { // this is a permanent redirection
581      set_status_header(301);
582      redirect_http( $redirect_url );
583    }
584    redirect( $redirect_url );
585  }
586  unset( $need_redirect, $page['hit_by'] );
587}
588
589trigger_action('loc_end_section_init');
590?>
Note: See TracBrowser for help on using the repository browser.