source: tags/release-1_7_0RC2/include/section_init.inc.php @ 2945

Last change on this file since 2945 was 1900, checked in by rub, 17 years ago

Apply property svn:eol-style Value: LF

  • Property svn:eol-style set to LF
  • Property svn:keywords set to Author Date Id Revision
File size: 20.3 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 1900 2007-03-12 22:33:53Z rub $
8// | last update   : $Date: 2007-03-12 22:33:53 +0000 (Mon, 12 Mar 2007) $
9// | last modifier : $Author: rub $
10// | revision      : $Revision: 1900 $
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  }
100  else
101  {
102    preg_match('/^(\d+-)?(.*)?$/', $token, $matches);
103    if (isset($matches[1]) and is_numeric($matches[1]=rtrim($matches[1],'-')) )
104    {
105      $page['image_id'] = $matches[1];
106      if ( !empty($matches[2]) )
107      {
108        $page['image_file'] = $matches[2];
109      }
110    }
111    else
112    {
113      if ( !empty($matches[2]) )
114      {
115        $page['image_file'] = $matches[2];
116      }
117      else
118      {
119        bad_request('picture identifier is missing');
120      }
121    }
122  }
123}
124
125if (0 === strpos(@$tokens[$next_token], 'categor'))
126{
127  $page['section'] = 'categories';
128  $next_token++;
129
130  if (isset($tokens[$next_token]) )
131  {
132    if (preg_match('/^(\d+)(?:-(.+))?$/', $tokens[$next_token], $matches))
133    {
134      if ( isset($matches[2]) )
135        $page['hit_by']['cat_url_name'] = $matches[2];
136      $page['category'] = $matches[1];
137      $next_token++;
138    }
139    else
140    {
141      if ( strpos($tokens[$next_token], 'created-')!==0
142          and strpos($tokens[$next_token], 'posted-')!==0
143          and $tokens[$next_token] != 'flat')
144      {// try a permalink
145        $cat_id = get_cat_id_from_permalink($tokens[$next_token]);
146        if ( !isset($cat_id) )
147        {//try old permalink
148          $cat_id = get_cat_id_from_old_permalink($tokens[$next_token], true);
149        }
150        if ( isset($cat_id) )
151        {
152          $page['category'] = $cat_id;
153          $page['hit_by']['cat_permalink'] = $tokens[$next_token];
154        }
155        else
156        {
157          page_not_found('Permalink for album not found');
158        }
159        unset($cat_id);
160        $next_token++;
161      }
162    }
163  }
164}
165else if (0 === strpos(@$tokens[$next_token], 'tag'))
166{
167  $page['section'] = 'tags';
168  $page['tags'] = array();
169
170  $next_token++;
171  $i = $next_token;
172
173  $requested_tag_ids = array();
174  $requested_tag_url_names = array();
175
176  while (isset($tokens[$i]))
177  {
178    if ( preg_match('/^(created-|posted-|start-(\d)+)/', $tokens[$i]) )
179      break;
180
181    if ( preg_match('/^(\d+)(?:-(.*))?/', $tokens[$i], $matches) )
182    {
183      array_push($requested_tag_ids, $matches[1]);
184    }
185    else
186    {
187      array_push($requested_tag_url_names, $tokens[$i]);
188    }
189    $i++;
190  }
191  $next_token = $i;
192
193  if ( empty($requested_tag_ids) && empty($requested_tag_url_names) )
194  {
195    bad_request('at least one tag required');
196  }
197
198  $page['tags'] = find_tags($requested_tag_ids, $requested_tag_url_names);
199  if ( empty($page['tags']) )
200  {
201    page_not_found('Requested tag does not exist', get_root_url().'tags.php' );
202  }
203}
204else if (0 === strpos(@$tokens[$next_token], 'fav'))
205{
206  $page['section'] = 'favorites';
207  $next_token++;
208}
209else if ('most_visited' == @$tokens[$next_token])
210{
211  $page['section'] = 'most_visited';
212  $next_token++;
213}
214else if ('best_rated' == @$tokens[$next_token])
215{
216  $page['section'] = 'best_rated';
217  $next_token++;
218}
219else if ('recent_pics' == @$tokens[$next_token])
220{
221  $page['section'] = 'recent_pics';
222  $next_token++;
223}
224else if ('recent_cats' == @$tokens[$next_token])
225{
226  $page['section'] = 'recent_cats';
227  $next_token++;
228}
229else if ('search' == @$tokens[$next_token])
230{
231  $page['section'] = 'search';
232  $next_token++;
233
234  preg_match('/(\d+)/', @$tokens[$next_token], $matches);
235  if (!isset($matches[1]))
236  {
237    bad_request('search identifier is missing');
238  }
239  $page['search'] = $matches[1];
240  $next_token++;
241}
242else if ('list' == @$tokens[$next_token])
243{
244  $page['section'] = 'list';
245  $next_token++;
246
247  $page['list'] = array();
248
249  // No pictures
250  if (empty($tokens[$next_token]))
251  {
252    // Add dummy element list
253    array_push($page['list'], -1);
254  }
255  // With pictures list
256  else
257  {
258    if (!preg_match('/^\d+(,\d+)*$/', $tokens[$next_token]))
259    {
260      bad_request('wrong format on list GET parameter');
261    }
262    foreach (explode(',', $tokens[$next_token]) as $image_id)
263    {
264      array_push($page['list'], $image_id);
265    }
266  }
267  $next_token++;
268}
269else
270{
271  $page['section'] = 'categories';
272
273  switch (script_basename())
274  {
275    case 'picture':
276    {
277      //access a picture only by id, file or id-file without given section
278      $page['flat'] = true;
279      break;
280    }
281    case 'index':
282    {
283      // No section defined, go to selected url
284      if (!empty($conf['random_index_redirect']) and empty($tokens[$next_token]) )
285      {
286        $random_index_redirect = array();
287        foreach ($conf['random_index_redirect'] as $random_url => $random_url_condition)
288        {
289          if (empty($random_url_condition) or eval($random_url_condition))
290          {
291            $random_index_redirect[] = $random_url;
292          }
293        }
294        if (!empty($random_index_redirect))
295        {
296          redirect($random_index_redirect[mt_rand(0, count($random_index_redirect)-1)]);
297        }
298      }
299      break;
300    }
301    default:
302      trigger_error('script_basename "'.script_basename().'" unknown',
303        E_USER_WARNING);
304  }
305}
306
307$i = $next_token;
308
309while (isset($tokens[$i]))
310{
311  if (preg_match('/^start-(\d+)/', $tokens[$i], $matches))
312  {
313    $page['start'] = $matches[1];
314  }
315
316  if ('categories' == $page['section'] and
317      'flat' == $tokens[$i])
318  {
319    // indicate a special list of images
320    $page['flat'] = true;
321  }
322
323  if (preg_match('/^(posted|created)/', $tokens[$i] ))
324  {
325    $chronology_tokens = explode('-', $tokens[$i] );
326
327    $page['chronology_field'] = $chronology_tokens[0];
328
329    array_shift($chronology_tokens);
330    $page['chronology_style'] = $chronology_tokens[0];
331
332    array_shift($chronology_tokens);
333    if ( count($chronology_tokens)>0 )
334    {
335      if ('list'==$chronology_tokens[0] or
336          'calendar'==$chronology_tokens[0])
337      {
338        $page['chronology_view'] = $chronology_tokens[0];
339        array_shift($chronology_tokens);
340      }
341      $page['chronology_date'] = $chronology_tokens;
342    }
343  }
344
345  $i++;
346}
347
348
349// $page['nb_image_page'] is the number of picture to display on this page
350// By default, it is the same as the $user['nb_image_page']
351$page['nb_image_page'] = $user['nb_image_page'];
352
353if (pwg_get_session_var('image_order',0) > 0)
354{
355  $orders = get_category_preferred_image_orders();
356
357  $conf['order_by'] = str_replace(
358    'ORDER BY ',
359    'ORDER BY '.$orders[ pwg_get_session_var('image_order',0) ][1].',',
360    $conf['order_by']
361    );
362  $page['super_order_by'] = true;
363}
364
365$forbidden = get_sql_condition_FandF(
366      array
367        (
368          'forbidden_categories' => 'category_id',
369          'visible_categories' => 'category_id',
370          'visible_images' => 'id'
371        ),
372      'AND'
373  );
374
375// +-----------------------------------------------------------------------+
376// |                              category                                 |
377// +-----------------------------------------------------------------------+
378if ('categories' == $page['section'])
379{
380  if (isset($page['category']))
381  {
382    $result = get_cat_info($page['category']);
383    if (empty($result))
384    {
385      page_not_found('Requested category does not exist' );
386    }
387
388    $page = array_merge(
389      $page,
390      array(
391        'comment'            => $result['comment'],
392        'category'          => $result,
393        'title'             =>
394          get_cat_display_name($result['upper_names'], '', false),
395        )
396      );
397  }
398  else
399  {
400    $page['title'] = $lang['no_category'];
401  }
402
403  if
404    (
405      (!isset($page['chronology_field'])) and
406      (
407        (isset($page['category'])) or
408        (isset($page['flat']))
409      )
410    )
411  {
412    if ( !empty($result['image_order']) and !isset($page['super_order_by']) )
413    {
414      $conf[ 'order_by' ] = ' ORDER BY '.$result['image_order'];
415    }
416
417    if (isset($page['flat']))
418    {// flat categories mode
419      if ( isset($page['category']) )
420      {
421        $subcat_ids = get_subcat_ids( array($page['category']['id']) );
422        $where_sql = 'category_id IN ('.implode(',',$subcat_ids).')';
423      }
424      else
425      {
426        $where_sql = '1=1';
427      }
428    }
429    else
430    {// Normal mode
431      $where_sql = 'category_id = '.$page['category']['id'];
432    }
433
434    // Main query
435    $query = '
436SELECT DISTINCT(image_id)
437  FROM '.IMAGE_CATEGORY_TABLE.'
438    INNER JOIN '.IMAGES_TABLE.' ON id = image_id
439  WHERE
440    '.$where_sql.'
441'.$forbidden.'
442  '.$conf['order_by'].'
443;';
444
445    $page['items'] = array_from_query($query, 'image_id');
446  } //otherwise the calendar will requery all subitems
447}
448// special sections
449else
450{
451// +-----------------------------------------------------------------------+
452// |                            tags section                               |
453// +-----------------------------------------------------------------------+
454  if ($page['section'] == 'tags')
455  {
456    $page['tag_ids'] = array();
457    foreach ($page['tags'] as $tag)
458    {
459      array_push($page['tag_ids'], $tag['id']);
460    }
461
462    $items = get_image_ids_for_tags($page['tag_ids']);
463
464    // permissions depends on category, so to only keep images that are
465    // reachable to the connected user, we need to check category
466    // associations
467    if (!empty($items) )
468    {
469      $query = '
470SELECT image_id
471  FROM '.IMAGE_CATEGORY_TABLE.' INNER JOIN '.IMAGES_TABLE.' ON image_id=id
472  WHERE image_id IN ('.implode(',', $items).')
473    '.$forbidden.
474    $conf['order_by'].'
475;';
476      $items = array_unique(
477        array_from_query($query, 'image_id')
478        );
479    }
480
481    $title = get_tags_content_title();
482
483    $page = array_merge(
484      $page,
485      array(
486        'title' => $title,
487        'items' => array_values($items),
488        )
489      );
490  }
491// +-----------------------------------------------------------------------+
492// |                           search section                              |
493// +-----------------------------------------------------------------------+
494  if ($page['section'] == 'search')
495  {
496    include_once( PHPWG_ROOT_PATH .'include/functions_search.inc.php' );
497
498    $search_result = get_search_results($page['search']);
499    if ( !empty($search_result['items']) and !isset($search_result['as_is']) )
500    {
501      $query = '
502SELECT DISTINCT(id)
503  FROM '.IMAGES_TABLE.'
504    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
505  WHERE id IN ('.implode(',', $search_result['items']).')
506    '.$forbidden.'
507  '.$conf['order_by'].'
508;';
509      $page['items'] = array_from_query($query, 'id');
510    }
511    else
512    {
513      $page['items'] = $search_result['items'];
514    }
515
516    $page = array_merge(
517      $page,
518      array(
519        'title' => $lang['search_result'],
520        )
521      );
522  }
523// +-----------------------------------------------------------------------+
524// |                           favorite section                            |
525// +-----------------------------------------------------------------------+
526  else if ($page['section'] == 'favorites')
527  {
528    check_user_favorites();
529
530    $query = '
531SELECT image_id
532  FROM '.FAVORITES_TABLE.'
533    INNER JOIN '.IMAGES_TABLE.' ON image_id = id
534  WHERE user_id = '.$user['id'].'
535'.get_sql_condition_FandF
536  (
537    array
538      (
539        'visible_images' => 'image_id'
540      ),
541    'AND'
542  ).'
543  '.$conf['order_by'].'
544;';
545
546    $page = array_merge(
547      $page,
548      array(
549        'title' => $lang['favorites'],
550        'items' => array_from_query($query, 'image_id'),
551        )
552      );
553  }
554// +-----------------------------------------------------------------------+
555// |                       recent pictures section                         |
556// +-----------------------------------------------------------------------+
557  else if ($page['section'] == 'recent_pics')
558  {
559    $query = '
560SELECT DISTINCT(id)
561  FROM '.IMAGES_TABLE.'
562    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
563  WHERE
564    date_available >= SUBDATE(
565      CURRENT_DATE,INTERVAL '.$user['recent_period'].' DAY)
566    '.$forbidden.'
567  '.$conf['order_by'].'
568;';
569
570    $page = array_merge(
571      $page,
572      array(
573        'title' => '<a href="'.duplicate_index_url().'">'
574                  .$lang['recent_pics_cat'].'</a>',
575        'items' => array_from_query($query, 'id'),
576        )
577      );
578  }
579// +-----------------------------------------------------------------------+
580// |                 recently updated categories section                   |
581// +-----------------------------------------------------------------------+
582  else if ($page['section'] == 'recent_cats')
583  {
584    $page = array_merge(
585      $page,
586      array(
587        'title' => $lang['recent_cats_cat'],
588        )
589      );
590  }
591// +-----------------------------------------------------------------------+
592// |                        most visited section                           |
593// +-----------------------------------------------------------------------+
594  else if ($page['section'] == 'most_visited')
595  {
596    $page['super_order_by'] = true;
597    $conf['order_by'] = ' ORDER BY hit DESC, file ASC';
598    $query = '
599SELECT DISTINCT(id)
600  FROM '.IMAGES_TABLE.'
601    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
602  WHERE hit > 0
603    '.$forbidden.'
604    '.$conf['order_by'].'
605  LIMIT 0, '.$conf['top_number'].'
606;';
607
608    $page = array_merge(
609      $page,
610      array(
611        'title' => '<a href="'.duplicate_index_url().'">'
612                  .$conf['top_number'].' '.$lang['most_visited_cat'].'</a>',
613        'items' => array_from_query($query, 'id'),
614        )
615      );
616  }
617// +-----------------------------------------------------------------------+
618// |                          best rated section                           |
619// +-----------------------------------------------------------------------+
620  else if ($page['section'] == 'best_rated')
621  {
622    $page['super_order_by'] = true;
623    $conf['order_by'] = ' ORDER BY average_rate DESC, id ASC';
624
625    $query ='
626SELECT DISTINCT(id)
627  FROM '.IMAGES_TABLE.'
628    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
629  WHERE average_rate IS NOT NULL
630    '.$forbidden.'
631    '.$conf['order_by'].'
632  LIMIT 0, '.$conf['top_number'].'
633;';
634    $page = array_merge(
635      $page,
636      array(
637        'title' => '<a href="'.duplicate_index_url().'">'
638                  .$conf['top_number'].' '.$lang['best_rated_cat'].'</a>',
639        'items' => array_from_query($query, 'id'),
640        )
641      );
642  }
643// +-----------------------------------------------------------------------+
644// |                             list section                              |
645// +-----------------------------------------------------------------------+
646  else if ($page['section'] == 'list')
647  {
648    $query ='
649SELECT DISTINCT(id)
650  FROM '.IMAGES_TABLE.'
651    INNER JOIN '.IMAGE_CATEGORY_TABLE.' AS ic ON id = ic.image_id
652  WHERE image_id IN ('.implode(',', $page['list']).')
653    '.$forbidden.'
654  '.$conf['order_by'].'
655;';
656
657    $page = array_merge(
658      $page,
659      array(
660        'title' => '<a href="'.duplicate_index_url().'">'
661                    .$lang['random_cat'].'</a>',
662        'items' => array_from_query($query, 'id'),
663        )
664      );
665  }
666}
667
668// +-----------------------------------------------------------------------+
669// |                             chronology                                |
670// +-----------------------------------------------------------------------+
671
672if (isset($page['chronology_field']))
673{
674  include_once( PHPWG_ROOT_PATH.'include/functions_calendar.inc.php' );
675  initialize_calendar();
676}
677
678if (script_basename() == 'picture'
679    and !isset($page['image_id']) )
680{
681  if ( !empty($page['items']) )
682  {
683    $query = '
684SELECT id,file
685  FROM '.IMAGES_TABLE .'
686  WHERE id IN ('.implode(',',$page['items']).')
687  AND file LIKE "' . $page['image_file'] . '.%" ESCAPE "|"'
688;
689    $result = pwg_query($query);
690    if (mysql_num_rows($result)>0)
691    {
692      list($page['image_id'], $page['image_file']) = mysql_fetch_row($result);
693    }
694  }
695  if ( !isset($page['image_id']) )
696  {
697    $page['image_id'] = -1; // will fail in picture.php
698  }
699}
700
701// add meta robots noindex, nofollow to avoid unnecesary robot crawls
702$page['meta_robots']=array();
703if ( isset($page['chronology_field']) or isset($page['flat'])
704      or 'list'==$page['section'] or 'recent_pics'==$page['section'] )
705{
706  $page['meta_robots']=array('noindex'=>1, 'nofollow'=>1);
707}
708elseif ('tags' == $page['section'])
709{
710  if ( count($page['tag_ids'])>1 )
711  {
712    $page['meta_robots']=array('noindex'=>1, 'nofollow'=>1);
713  }
714}
715elseif ('recent_cats'==$page['section'])
716{
717  $page['meta_robots']['nofollow']=1;
718}
719if ( $filter['enabled'] )
720{
721  $page['meta_robots']['noindex']=1;
722}
723
724// see if we need a redirect because of a permalink
725if ( 'categories'==$page['section'] and isset($page['category']) )
726{
727  $need_redirect=false;
728  if ( empty($page['category']['permalink']) )
729  {
730    if ( $conf['category_url_style'] == 'id-name' and
731        @$page['hit_by']['cat_url_name'] !== str2url($page['category']['name']) )
732    {
733      $need_redirect=true;
734    }
735  }
736  else
737  {
738    if ( $page['category']['permalink'] !== @$page['hit_by']['cat_permalink'] )
739    {
740      $need_redirect=true;
741    }
742  }
743
744  if ($need_redirect)
745  {
746    $redirect_url = ( script_basename()=='picture'
747        ? duplicate_picture_url()
748          : duplicate_index_url()
749      );
750    if (!headers_sent())
751    { // this is a permanent redirection
752      set_status_header(302);
753      redirect_http( $redirect_url );
754    }
755    redirect( $redirect_url );
756  }
757  unset( $need_redirect, $page['hit_by'] );
758}
759
760trigger_action('loc_end_section_init');
761?>
Note: See TracBrowser for help on using the repository browser.