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

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

Resolved 0000738: Double port on url

Merge branch-1_7 2048:2050 into BSF

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