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

Last change on this file since 27336 was 27336, checked in by rvelices, 7 years ago

arrayfromquery optimizations: move double if from inside loop to outside + use directly mysqli calls to avoid function call overhead for every row retrieved from db

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