source: trunk/include/functions_url.inc.php @ 1980

Last change on this file since 1980 was 1980, checked in by rvelices, 17 years ago

put some code from the huge section_init to 2 functions

  • parse_section_url does the exact opposite of make_section_in_url
  • parse_well_known_params_url does the exact opposite of add_well_known_params_in_url

section_init is more readable and plugins can have their own views with the same url style
this is not a bug correction but I will merge it to branch 1_7 to take advantage for a plugin

  • Property svn:eol-style set to LF
  • Property svn:keywords set to Author Date Id Revision
File size: 16.5 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | PhpWebGallery - a PHP based picture gallery                           |
4// | Copyright (C) 2003-2007 PhpWebGallery Team - http://phpwebgallery.net |
5// +-----------------------------------------------------------------------+
6// | file          : $Id: functions_url.inc.php 1980 2007-04-26 03:07:50Z rvelices $
7// | last update   : $Date: 2007-04-26 03:07:50 +0000 (Thu, 26 Apr 2007) $
8// | last modifier : $Author: rvelices $
9// | revision      : $Revision: 1980 $
10// +-----------------------------------------------------------------------+
11// | This program is free software; you can redistribute it and/or modify  |
12// | it under the terms of the GNU General Public License as published by  |
13// | the Free Software Foundation                                          |
14// |                                                                       |
15// | This program is distributed in the hope that it will be useful, but   |
16// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
17// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
18// | General Public License for more details.                              |
19// |                                                                       |
20// | You should have received a copy of the GNU General Public License     |
21// | along with this program; if not, write to the Free Software           |
22// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
23// | USA.                                                                  |
24// +-----------------------------------------------------------------------+
25
26
27/**
28 * returns a prefix for each url link on displayed page
29 * and return an empty string for current path
30 * @return string
31 */
32function get_root_url()
33{
34  global $page;
35  if ( isset($page['root_path']) )
36  {
37    $root_url = $page['root_path'];
38  }
39  else
40  {// TODO - add HERE the possibility to call PWG functions from external scripts
41    $root_url = PHPWG_ROOT_PATH;
42  }
43  if ( dirname($root_url)!='.' )
44  {
45    return $root_url;
46  }
47  else
48  {
49    return substr($root_url, 2);
50  }
51}
52
53/**
54 * returns the absolute url to the root of PWG
55 * @param boolean with_scheme if false - does not add http://toto.com
56 */
57function get_absolute_root_url($with_scheme=true)
58{
59  // TODO - add HERE the possibility to call PWG functions from external scripts
60  $url = '';
61  if ($with_scheme)
62  {
63    $url .= 'http://'.$_SERVER['HTTP_HOST'];
64    if ($_SERVER['SERVER_PORT']!=80)
65    {
66      $url .= ':'.$_SERVER['SERVER_PORT'];
67    }
68  }
69  $url .= cookie_path();
70  return $url;
71}
72
73/**
74 * adds one or more _GET style parameters to an url
75 * example: add_url_params('/x', array('a'=>'b')) returns /x?a=b
76 * add_url_params('/x?cat_id=10', array('a'=>'b')) returns /x?cat_id=10&amp;a=b
77 * @param string url
78 * @param array params
79 * @return string
80 */
81function add_url_params($url, $params)
82{
83  if ( !empty($params) )
84  {
85    assert( is_array($params) );
86    $is_first = true;
87    foreach($params as $param=>$val)
88    {
89      if ($is_first)
90      {
91        $is_first = false;
92        $url .= ( strstr($url, '?')===false ) ? '?' :'&amp;';
93      }
94      else
95      {
96        $url .= '&amp;';
97      }
98      $url .= $param;
99      if (isset($val))
100      {
101        $url .= '='.$val;
102      }
103    }
104  }
105  return $url;
106}
107
108/**
109 * build an index URL for a specific section
110 *
111 * @param array
112 * @return string
113 */
114function make_index_url($params = array())
115{
116  global $conf;
117  $url = get_root_url().'index';
118  if ($conf['php_extension_in_urls'])
119  {
120    $url .= '.php';
121  }
122  if ($conf['question_mark_in_urls'])
123  {
124    $url .= '?';
125  }
126  $url.= make_section_in_url($params);
127  $url = add_well_known_params_in_url($url, $params);
128  return $url;
129}
130
131/**
132 * build an index URL with current page parameters, but with redefinitions
133 * and removes.
134 *
135 * duplicate_index_url( array(
136 *   'category' => array('id'=>12, 'name'=>'toto'),
137 *   array('start')
138 * ) will create an index URL on the current section (categories), but on
139 * a redefined category and without the start URL parameter.
140 *
141 * @param array redefined keys
142 * @param array removed keys
143 * @return string
144 */
145function duplicate_index_url($redefined = array(), $removed = array())
146{
147  return make_index_url(
148    params_for_duplication($redefined, $removed)
149    );
150}
151
152/**
153 * returns $page global array with key redefined and key removed
154 *
155 * @param array redefined keys
156 * @param array removed keys
157 * @return array
158 */
159function params_for_duplication($redefined, $removed)
160{
161  global $page;
162
163  if (count($removed) > 0)
164  {
165    $params = array();
166
167    foreach ($page as $page_item_key => $page_item_value)
168    {
169      if (!in_array($page_item_key, $removed))
170      {
171        $params[$page_item_key] = $page_item_value;
172      }
173    }
174  }
175  else
176  {
177    $params = $page;
178  }
179
180  foreach ($redefined as $redefined_param => $redefined_value)
181  {
182    $params[$redefined_param] = $redefined_value;
183  }
184
185  return $params;
186}
187
188/**
189 * create a picture URL with current page parameters, but with redefinitions
190 * and removes. See duplicate_index_url.
191 *
192 * @param array redefined keys
193 * @param array removed keys
194 * @return string
195 */
196function duplicate_picture_url($redefined = array(), $removed = array())
197{
198  return make_picture_url(
199    params_for_duplication($redefined, $removed)
200    );
201}
202
203/**
204 * create a picture URL on a specific section for a specific picture
205 *
206 * @param array
207 * @return string
208 */
209function make_picture_url($params)
210{
211  global $conf;
212  if (!isset($params['image_id']))
213  {
214    die('make_picture_url: image_id is a required parameter');
215  }
216
217  $url = get_root_url().'picture';
218  if ($conf['php_extension_in_urls'])
219  {
220    $url .= '.php';
221  }
222  if ($conf['question_mark_in_urls'])
223  {
224    $url .= '?';
225  }
226  $url.= '/';
227  switch ( $conf['picture_url_style'] )
228  {
229    case 'id-file':
230      $url .= $params['image_id'];
231      if ( isset($params['image_file']) )
232      {
233        $url .= '-'.get_filename_wo_extension($params['image_file']);
234      }
235      break;
236    case 'file':
237      if ( isset($params['image_file']) )
238      {
239        $fname_wo_ext = get_filename_wo_extension($params['image_file']);
240        if (! preg_match('/^\d+(-|$)/', $fname_wo_ext) )
241        {
242          $url .= $fname_wo_ext;
243          break;
244        }
245      }
246    default:
247      $url .= $params['image_id'];
248  }
249  if ( !isset($params['category'] ) )
250  {// make urls shorter ...
251    unset( $params['flat'] ); 
252  }
253  $url .= make_section_in_url($params);
254  $url = add_well_known_params_in_url($url, $params);
255  return $url;
256}
257
258/**
259 *adds to the url the chronology and start parameters
260*/
261function add_well_known_params_in_url($url, $params)
262{
263  if ( isset($params['chronology_field']) )
264  {
265    $url .= '/'. $params['chronology_field'];
266    $url .= '-'. $params['chronology_style'];
267    if ( isset($params['chronology_view']) )
268    {
269      $url .= '-'. $params['chronology_view'];
270    }
271    if ( !empty($params['chronology_date']) )
272    {
273      $url .= '-'. implode('-', $params['chronology_date'] );
274    }
275  }
276
277  if (isset($params['flat']))
278  {
279    $url.= '/flat';
280  }
281
282  if (isset($params['start']) and $params['start'] > 0)
283  {
284    $url.= '/start-'.$params['start'];
285  }
286  return $url;
287}
288
289/**
290 * return the section token of an index or picture URL.
291 *
292 * Depending on section, other parameters are required (see function code
293 * for details)
294 *
295 * @param array
296 * @return string
297 */
298function make_section_in_url($params)
299{
300  global $conf;
301  $section_string = '';
302
303  $section_of = array(
304    'category' => 'categories',
305    'tags'     => 'tags',
306    'list'     => 'list',
307    'search'   => 'search',
308    );
309
310  foreach ($section_of as $param => $section)
311  {
312    if (isset($params[$param]))
313    {
314      $params['section'] = $section;
315    }
316  }
317
318  if (!isset($params['section']))
319  {
320    $params['section'] = 'none';
321  }
322
323  switch($params['section'])
324  {
325    case 'categories' :
326    {
327      if (!isset($params['category']))
328      {
329        $section_string.= '/categories';
330      }
331      else
332      {
333        is_array($params['category']) or trigger_error(
334            'make_section_in_url wrong type for category', E_USER_WARNING
335            );
336        is_numeric($params['category']['id']) or trigger_error(
337            'make_section_in_url category id not numeric', E_USER_WARNING
338            );
339        isset($params['category']['name']) or trigger_error(
340            'make_section_in_url category name not set', E_USER_WARNING
341            );
342
343        array_key_exists('permalink', $params['category']) or trigger_error(
344            'make_section_in_url category permalink not set', E_USER_WARNING
345            );
346
347        $section_string.= '/category/';
348        if ( empty($params['category']['permalink']) )
349        {
350          $section_string.= $params['category']['id'];
351          if ( $conf['category_url_style']=='id-name' )
352          {
353            $section_string.= '-'.str2url($params['category']['name']);
354          }
355        }
356        else
357        {
358          $section_string.= $params['category']['permalink'];
359        }
360      }
361
362      break;
363    }
364    case 'tags' :
365    {
366      if (!isset($params['tags']) or count($params['tags']) == 0)
367      {
368        die('make_section_in_url: require at least one tag');
369      }
370
371      $section_string.= '/tags';
372
373      foreach ($params['tags'] as $tag)
374      {
375        switch ( $conf['tag_url_style'] )
376        {
377          case 'id':
378            $section_string.= '/'.$tag['id'];
379            break;
380          case 'tag':
381            if (isset($tag['url_name']) and !is_numeric($tag['url_name']) )
382            {
383              $section_string.= '/'.$tag['url_name'];
384              break;
385            }
386          default:
387            $section_string.= '/'.$tag['id'];
388            if (isset($tag['url_name']))
389            {
390              $section_string.= '-'.$tag['url_name'];
391            }
392        }
393      }
394
395      break;
396    }
397    case 'search' :
398    {
399      if (!isset($params['search']))
400      {
401        die('make_section_in_url: require a search identifier');
402      }
403
404      $section_string.= '/search/'.$params['search'];
405
406      break;
407    }
408    case 'list' :
409    {
410      if (!isset($params['list']))
411      {
412        die('make_section_in_url: require a list of items');
413      }
414
415      $section_string.= '/list/'.implode(',', $params['list']);
416
417      break;
418    }
419    case 'none' :
420    {
421      break;
422    }
423    default :
424    {
425      $section_string.= '/'.$params['section'];
426    }
427  }
428
429  return $section_string;
430}
431
432/**
433 * the reverse of make_section_in_url
434 * returns the 'section' (categories/tags/...) and the data associated with it
435 *
436 * Depending on section, other parameters are returned (category/tags/list/...)
437 *
438 * @param array of url tokens to parse
439 * @param int the index in the array of url tokens; in/out
440 * @return array
441 */
442function parse_section_url( $tokens, &$next_token)
443{
444  $page=array();
445  if (0 === strpos(@$tokens[$next_token], 'categor'))
446  {
447    $page['section'] = 'categories';
448    $next_token++;
449
450    if (isset($tokens[$next_token]) )
451    {
452      if (preg_match('/^(\d+)(?:-(.+))?$/', $tokens[$next_token], $matches))
453      {
454        if ( isset($matches[2]) )
455          $page['hit_by']['cat_url_name'] = $matches[2];
456        $page['category'] = $matches[1];
457        $next_token++;
458      }
459      else
460      {
461        if ( strpos($tokens[$next_token], 'created-')!==0
462            and strpos($tokens[$next_token], 'posted-')!==0
463            and strpos($tokens[$next_token], 'start-')!==0
464            and $tokens[$next_token] != 'flat')
465        {// try a permalink
466          $cat_id = get_cat_id_from_permalink($tokens[$next_token]);
467          if ( !isset($cat_id) )
468          {//try old permalink
469            $cat_id = get_cat_id_from_old_permalink($tokens[$next_token], true);
470          }
471          if ( isset($cat_id) )
472          {
473            $page['category'] = $cat_id;
474            $page['hit_by']['cat_permalink'] = $tokens[$next_token];
475          }
476          else
477          {
478            page_not_found('Permalink for album not found');
479          }
480          $next_token++;
481        }
482       }
483    }
484
485    if (isset($page['category']))
486    {
487      $result = get_cat_info($page['category']);
488      if (empty($result))
489      {
490        page_not_found('Requested category does not exist' );
491      }
492      $page['category']=$result;
493    }
494  }
495  else if (0 === strpos(@$tokens[$next_token], 'tag'))
496  {
497    $page['section'] = 'tags';
498    $page['tags'] = array();
499
500    $next_token++;
501    $i = $next_token;
502
503    $requested_tag_ids = array();
504    $requested_tag_url_names = array();
505
506    while (isset($tokens[$i]))
507    {
508      if ( preg_match('/^(created-|posted-|start-(\d)+)/', $tokens[$i]) )
509        break;
510
511      if ( preg_match('/^(\d+)(?:-(.*))?/', $tokens[$i], $matches) )
512      {
513        array_push($requested_tag_ids, $matches[1]);
514      }
515      else
516      {
517        array_push($requested_tag_url_names, $tokens[$i]);
518      }
519      $i++;
520    }
521    $next_token = $i;
522
523    if ( empty($requested_tag_ids) && empty($requested_tag_url_names) )
524    {
525      bad_request('at least one tag required');
526    }
527
528    $page['tags'] = find_tags($requested_tag_ids, $requested_tag_url_names);
529    if ( empty($page['tags']) )
530    {
531      page_not_found('Requested tag does not exist', get_root_url().'tags.php' );
532    }
533  }
534  else if (0 === strpos(@$tokens[$next_token], 'fav'))
535  {
536    $page['section'] = 'favorites';
537    $next_token++;
538  }
539  else if ('most_visited' == @$tokens[$next_token])
540  {
541    $page['section'] = 'most_visited';
542    $next_token++;
543  }
544  else if ('best_rated' == @$tokens[$next_token])
545  {
546    $page['section'] = 'best_rated';
547    $next_token++;
548  }
549  else if ('recent_pics' == @$tokens[$next_token])
550  {
551    $page['section'] = 'recent_pics';
552    $next_token++;
553  }
554  else if ('recent_cats' == @$tokens[$next_token])
555  {
556    $page['section'] = 'recent_cats';
557    $next_token++;
558  }
559  else if ('search' == @$tokens[$next_token])
560  {
561    $page['section'] = 'search';
562    $next_token++;
563
564    preg_match('/(\d+)/', @$tokens[$next_token], $matches);
565    if (!isset($matches[1]))
566    {
567      bad_request('search identifier is missing');
568    }
569    $page['search'] = $matches[1];
570    $next_token++;
571  }
572  else if ('list' == @$tokens[$next_token])
573  {
574    $page['section'] = 'list';
575    $next_token++;
576
577    $page['list'] = array();
578
579    // No pictures
580    if (empty($tokens[$next_token]))
581    {
582      // Add dummy element list
583      array_push($page['list'], -1);
584    }
585    // With pictures list
586    else
587    {
588      if (!preg_match('/^\d+(,\d+)*$/', $tokens[$next_token]))
589      {
590        bad_request('wrong format on list GET parameter');
591      }
592      foreach (explode(',', $tokens[$next_token]) as $image_id)
593      {
594        array_push($page['list'], $image_id);
595      }
596    }
597    $next_token++;
598  }
599  return $page;
600}
601
602/**
603 * the reverse of add_well_known_params_in_url
604 * parses start, flat and chronology from url tokens
605*/
606function parse_well_known_params_url($tokens, $i)
607{
608  $page = array();
609  while (isset($tokens[$i]))
610  {
611    if (preg_match('/^start-(\d+)/', $tokens[$i], $matches))
612    {
613      $page['start'] = $matches[1];
614    }
615
616    if ( 'flat' == $tokens[$i] )
617    {
618      // indicate a special list of images
619      $page['flat'] = true;
620    }
621
622    if (preg_match('/^(posted|created)/', $tokens[$i] ))
623    {
624      $chronology_tokens = explode('-', $tokens[$i] );
625
626      $page['chronology_field'] = $chronology_tokens[0];
627
628      array_shift($chronology_tokens);
629      $page['chronology_style'] = $chronology_tokens[0];
630
631      array_shift($chronology_tokens);
632      if ( count($chronology_tokens)>0 )
633      {
634        if ('list'==$chronology_tokens[0] or
635            'calendar'==$chronology_tokens[0])
636        {
637          $page['chronology_view'] = $chronology_tokens[0];
638          array_shift($chronology_tokens);
639        }
640        $page['chronology_date'] = $chronology_tokens;
641      }
642    }
643    $i++;
644  }
645  return $page;
646}
647
648/**
649 * Indicate to build url with full path
650 *
651 * @param null
652 * @return null
653 */
654function set_make_full_url()
655{
656  global $page;
657
658  if (!isset($page['save_root_path']))
659  {
660    if (isset($page['root_path']))
661    {
662      $page['save_root_path']['path'] = $page['root_path'];
663    }
664    $page['save_root_path']['count'] = 1;
665    $page['root_path'] = get_absolute_root_url();
666  }
667  else
668  {
669    $page['save_root_path']['count'] += 1;
670  }
671}
672
673/**
674 * Restore old parameter to build url with full path
675 *
676 * @param null
677 * @return null
678 */
679function unset_make_full_url()
680{
681  global $page;
682
683  if (isset($page['save_root_path']))
684  {
685    if ($page['save_root_path']['count'] == 1)
686    {
687      if (isset($page['save_root_path']['path']))
688      {
689        $page['root_path'] = $page['save_root_path']['path'];
690      }
691      else
692      {
693        unset($page['root_path']);
694      }
695      unset($page['save_root_path']);
696    }
697    else
698    {
699      $page['save_root_path']['count'] -= 1;
700    }
701  }
702}
703
704?>
Note: See TracBrowser for help on using the repository browser.