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

Last change on this file since 2362 was 2327, checked in by rvelices, 16 years ago

just some optimizations (especially for large dbs)

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