source: trunk/include/functions_html.inc.php @ 2299

Last change on this file since 2299 was 2299, checked in by plg, 16 years ago

Bug fixed: as rvelices notified me by email, my header replacement script was
bugged (r2297 was repeating new and old header).

By the way, I've also removed the replacement keywords. We were using them
because it was a common usage with CVS but it is advised not to use them with
Subversion. Personnaly, it is a problem when I search differences between 2
Piwigo installations outside Subversion.

  • Property svn:eol-style set to LF
  • Property svn:keywords set to Author Date Id Revision
File size: 18.5 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
24function get_icon($date, $is_child_date = false)
25{
26  global $page, $user;
27
28  if (empty($date))
29  {
30    return '';
31  }
32
33  if (isset($page['get_icon_cache'][$date]))
34  {
35    if (! $page['get_icon_cache'][$date] )
36      return '';
37    return $page['get_icon_cache']['_icons_'][$is_child_date];
38  }
39
40  if (!isset($page['get_icon_cache']['sql_recent_date']))
41  {
42    // Use MySql date in order to standardize all recent "actions/queries"
43    list($page['get_icon_cache']['sql_recent_date']) =
44      mysql_fetch_array(pwg_query('select SUBDATE(
45      CURRENT_DATE,INTERVAL '.$user['recent_period'].' DAY)'));
46  }
47
48  $page['get_icon_cache'][$date] = false;
49  if ( $date > $page['get_icon_cache']['sql_recent_date'] )
50  {
51    if ( !isset($page['get_icon_cache']['_icons_'] ) )
52    {
53      $icons = array(false => 'recent', true => 'recent_by_child' );
54      $title = sprintf(
55        l10n('elements posted during the last %d days'),
56        $user['recent_period']
57        );
58      foreach ($icons as $key => $icon)
59      {
60        $icon_url = get_themeconf('icon_dir').'/'.$icon.'.png';
61        $size = getimagesize( PHPWG_ROOT_PATH.$icon_url );
62        $icon_url = get_root_url().$icon_url;
63        $output = '<img title="'.$title.'" src="'.$icon_url.'" class="icon" style="border:0;';
64        $output.= 'height:'.$size[1].'px;width:'.$size[0].'px" alt="(!)" />';
65        $page['get_icon_cache']['_icons_'][$key] = $output;
66      }
67    }
68    $page['get_icon_cache'][$date] = true;
69  }
70
71  if (! $page['get_icon_cache'][$date] )
72    return '';
73  return $page['get_icon_cache']['_icons_'][$is_child_date];
74}
75
76function create_navigation_bar(
77  $url, $nb_element, $start, $nb_element_page, $clean_url = false
78  )
79{
80  global $conf;
81
82  $pages_around = $conf['paginate_pages_around'];
83  $start_str = $clean_url ? '/start-' :
84    ( ( strstr($url, '?')===false ? '?':'&amp;') . 'start=' );
85
86  $navbar = '';
87
88  // current page detection
89  if (!isset($start)
90      or !is_numeric($start)
91      or (is_numeric($start) and $start < 0))
92  {
93    $start = 0;
94  }
95
96  // navigation bar useful only if more than one page to display !
97  if ($nb_element > $nb_element_page)
98  {
99    // current page and last page
100    $cur_page = ceil($start / $nb_element_page) + 1;
101    $maximum = ceil($nb_element / $nb_element_page);
102
103    // link to first page ?
104    if ($cur_page != 1)
105    {
106      $navbar.=
107        '<a href="'.$url.'" rel="start">'
108        .l10n('first_page')
109        .'</a>';
110    }
111    else
112    {
113      $navbar.= l10n('first_page');
114    }
115    $navbar.= ' | ';
116    // link on previous page ?
117    if ($start != 0)
118    {
119      $previous = $start - $nb_element_page;
120
121      $navbar.=
122        '<a href="'
123        .$url.($previous > 0 ? $start_str.$previous : '')
124        .'" rel="prev">'
125        .l10n('previous_page')
126        .'</a>';
127    }
128    else
129    {
130      $navbar.= l10n('previous_page');
131    }
132    $navbar.= ' |';
133
134    if ($cur_page > $pages_around + 1)
135    {
136      $navbar.= '&nbsp;<a href="'.$url.'">1</a>';
137
138      if ($cur_page > $pages_around + 2)
139      {
140        $navbar.= ' ...';
141      }
142    }
143
144    // inspired from punbb source code
145    for ($i = $cur_page - $pages_around, $stop = $cur_page + $pages_around + 1;
146         $i < $stop;
147         $i++)
148    {
149      if ($i < 1 or $i > $maximum)
150      {
151        continue;
152      }
153      else if ($i != $cur_page)
154      {
155        $temp_start = ($i - 1) * $nb_element_page;
156
157        $navbar.=
158          '&nbsp;'
159          .'<a href="'.$url
160          .($temp_start > 0 ? $start_str.$temp_start : '')
161          .'">'
162          .$i
163          .'</a>';
164      }
165      else
166      {
167        $navbar.=
168          '&nbsp;'
169          .'<span class="pageNumberSelected">'
170          .$i
171          .'</span>';
172      }
173    }
174
175    if ($cur_page < ($maximum - $pages_around))
176    {
177      $temp_start = ($maximum - 1) * $nb_element_page;
178
179      if ($cur_page < ($maximum - $pages_around - 1))
180      {
181        $navbar.= ' ...';
182      }
183
184      $navbar.= ' <a href="'.$url.$start_str.$temp_start.'">'.$maximum.'</a>';
185    }
186
187    $navbar.= ' | ';
188    // link on next page ?
189    if ($nb_element > $nb_element_page
190        and $start + $nb_element_page < $nb_element)
191    {
192      $next = $start + $nb_element_page;
193
194      $navbar.=
195        '<a href="'.$url.$start_str.$next.'" rel="next">'
196        .l10n('next_page')
197        .'</a>';
198    }
199    else
200    {
201      $navbar.= l10n('next_page');
202    }
203
204    $navbar.= ' | ';
205    // link to last page ?
206    if ($cur_page != $maximum)
207    {
208      $temp_start = ($maximum - 1) * $nb_element_page;
209
210      $navbar.=
211        '<a href="'.$url.$start_str.$temp_start.'" rel="last">'
212        .l10n('last_page')
213        .'</a>';
214    }
215    else
216    {
217      $navbar.= l10n('last_page');
218    }
219  }
220  return $navbar;
221}
222
223/**
224 * returns the list of categories as a HTML string
225 *
226 * categories string returned contains categories as given in the input
227 * array $cat_informations. $cat_informations array must be an array
228 * of array( id=>?, name=>?, permalink=>?). If url input parameter is null,
229 * returns only the categories name without links.
230 *
231 * @param array cat_informations
232 * @param string url
233 * @param boolean replace_space
234 * @return string
235 */
236function get_cat_display_name($cat_informations,
237                              $url = '',
238                              $replace_space = true)
239{
240  global $conf;
241
242  $output = '';
243  $is_first = true;
244  foreach ($cat_informations as $cat)
245  {
246    is_array($cat) or trigger_error(
247        'get_cat_display_name wrong type for category ', E_USER_WARNING
248      );
249    if ($is_first)
250    {
251      $is_first = false;
252    }
253    else
254    {
255      $output.= $conf['level_separator'];
256    }
257
258    if ( !isset($url) )
259    {
260      $output.= $cat['name'];
261    }
262    elseif ($url == '')
263    {
264      $output.= '<a href="'
265            .make_index_url(
266                array(
267                  'category' => $cat,
268                  )
269              )
270            .'">';
271      $output.= $cat['name'].'</a>';
272    }
273    else
274    {
275      $output.= '<a href="'.PHPWG_ROOT_PATH.$url.$cat['id'].'">';
276      $output.= $cat['name'].'</a>';
277    }
278  }
279  if ($replace_space)
280  {
281    return replace_space($output);
282  }
283  else
284  {
285    return $output;
286  }
287}
288
289/**
290 * returns the list of categories as a HTML string, with cache of names
291 *
292 * categories string returned contains categories as given in the input
293 * array $cat_informations. $uppercats is the list of category ids to
294 * display in the right order. If url input parameter is empty, returns only
295 * the categories name without links.
296 *
297 * @param string uppercats
298 * @param string url
299 * @param boolean replace_space
300 * @return string
301 */
302function get_cat_display_name_cache($uppercats,
303                                    $url = '',
304                                    $replace_space = true)
305{
306  global $cache, $conf;
307
308  if (!isset($cache['cat_names']))
309  {
310    $query = '
311SELECT id, name, permalink
312  FROM '.CATEGORIES_TABLE.'
313;';
314    $cache['cat_names'] = hash_from_query($query, 'id');
315  }
316
317  $output = '';
318  $is_first = true;
319  foreach (explode(',', $uppercats) as $category_id)
320  {
321    $cat = $cache['cat_names'][$category_id];
322
323    if ($is_first)
324    {
325      $is_first = false;
326    }
327    else
328    {
329      $output.= $conf['level_separator'];
330    }
331
332    if ( !isset($url) )
333    {
334      $output.= $cat['name'];
335    }
336    elseif ($url == '')
337    {
338      $output.= '
339<a href="'
340      .make_index_url(
341          array(
342            'category' => $cat,
343            )
344        )
345      .'">'.$cat['name'].'</a>';
346    }
347    else
348    {
349      $output.= '
350<a href="'.PHPWG_ROOT_PATH.$url.$category_id.'">'.$cat['name'].'</a>';
351    }
352  }
353  if ($replace_space)
354  {
355    return replace_space($output);
356  }
357  else
358  {
359    return $output;
360  }
361}
362
363/**
364 * returns the HTML code for a category item in the menu (for the main page)
365 *
366 * HTML code generated uses logical list tags ul and each category is an
367 * item li. The paramter given is the category informations as an array,
368 * used keys are : id, name, nb_images, max_date_last, date_last
369 * count_images, count_categories
370 *
371 * @param array categories
372 * @return string
373 */
374function get_html_menu_category($categories, $selected_category)
375{
376  $ref_level = 0;
377  $level = 0;
378
379  $menu = trigger_event('get_html_menu_category', '',
380            $categories, $selected_category);
381  if (strlen($menu))
382  {
383    return $menu;
384  }
385
386  foreach ($categories as $category)
387  {
388    $level = substr_count($category['global_rank'], '.') + 1;
389    if ($level > $ref_level)
390    {
391      $menu.= "\n<ul>";
392    }
393    else if ($level == $ref_level)
394    {
395      $menu.= "\n</li>";
396    }
397    else if ($level < $ref_level)
398    {
399      // we may have to close more than one level at the same time...
400      $menu.= "\n</li>";
401      $menu.= str_repeat("\n</ul></li>",($ref_level-$level));
402    }
403    $ref_level = $level;
404
405    $menu.= "\n\n".'<li';
406    if ($category['id'] == @$selected_category['id'])
407    {
408      $menu.= ' class="selected"';
409    }
410    $menu.= '>';
411
412    $url = make_index_url(
413            array(
414              'category' => $category
415              )
416            );
417
418    $title = get_display_images_count
419                (
420                  $category['nb_images'],
421                  $category['count_images'],
422                  $category['count_categories'],
423                  false,
424                  ' / '
425                );
426
427    $menu.= '<a href="'.$url.'"';
428    if ($selected_category!=null
429        and $category['id'] == $selected_category['id_uppercat'])
430    {
431      $menu.= ' rel="up"';
432    }
433    $menu.= ' title="'.$title.'">'.$category['name'].'</a>';
434
435    if ( $category['count_images']>0 )
436    {// at least one direct or indirect image
437      $menu.= "\n".'<span class="';
438      // at least one image in this category -> class menuInfoCat
439      $menu.= ($category['nb_images'] > 0 ? "menuInfoCat"
440                                          : "menuInfoCatByChild").'"';
441      $menu.= ' title=" '.$title.'">';
442      // show total number of images
443      $menu.= '['.$category['count_images'].']';
444      $menu.= '</span>';
445    }
446    $child_date_last = @$category['max_date_last']> @$category['date_last'];
447    $menu.= get_icon($category['max_date_last'], $child_date_last);
448  }
449
450  $menu.= str_repeat("\n</li></ul>",($level));
451
452  return $menu;
453}
454
455/**
456 * returns HTMLized comment contents retrieved from database
457 *
458 * newlines becomes br tags, _word_ becomes underline, /word/ becomes
459 * italic, *word* becomes bolded
460 *
461 * @param string content
462 * @return string
463 */
464function parse_comment_content($content)
465{
466  $pattern = '/(https?:\/\/\S*)/';
467  $replacement = '<a href="$1" rel="nofollow">$1</a>';
468  $content = preg_replace($pattern, $replacement, $content);
469
470  $content = nl2br($content);
471
472  // replace _word_ by an underlined word
473  $pattern = '/\b_(\S*)_\b/';
474  $replacement = '<span style="text-decoration:underline;">$1</span>';
475  $content = preg_replace($pattern, $replacement, $content);
476
477  // replace *word* by a bolded word
478  $pattern = '/\b\*(\S*)\*\b/';
479  $replacement = '<span style="font-weight:bold;">$1</span>';
480  $content = preg_replace($pattern, $replacement, $content);
481
482  // replace /word/ by an italic word
483  $pattern = "/\/(\S*)\/(\s)/";
484  $replacement = '<span style="font-style:italic;">$1$2</span>';
485  $content = preg_replace($pattern, $replacement, $content);
486
487  $content = '<div>'.$content.'</div>';
488  return $content;
489}
490
491function get_cat_display_name_from_id($cat_id,
492                                      $url = '',
493                                      $replace_space = true)
494{
495  $cat_info = get_cat_info($cat_id);
496  return get_cat_display_name($cat_info['upper_names'], $url, $replace_space);
497}
498
499/**
500 * Returns an HTML list of tags. It can be a multi select field or a list of
501 * checkboxes.
502 *
503 * @param string HTML field name
504 * @param array selected tag ids
505 * @return array
506 */
507function get_html_tag_selection(
508  $tags,
509  $fieldname,
510  $selecteds = array(),
511  $forbidden_categories = null
512  )
513{
514  global $conf;
515
516  if (count ($tags) == 0 )
517  {
518    return '';
519  }
520  $output = '<ul class="tagSelection">';
521  foreach ($tags as $tag)
522  {
523    $output.=
524      '<li>'
525      .'<label>'
526      .'<input type="checkbox" name="'.$fieldname.'[]"'
527      .' value="'.$tag['id'].'"'
528      ;
529
530    if (in_array($tag['id'], $selecteds))
531    {
532      $output.= ' checked="checked"';
533    }
534
535    $output.=
536      ' />'
537      .' '. $tag['name']
538      .'</label>'
539      .'</li>'
540      ."\n"
541      ;
542  }
543  $output.= '</ul>';
544
545  return $output;
546}
547
548function name_compare($a, $b)
549{
550  return strcmp(strtolower($a['name']), strtolower($b['name']));
551}
552
553/**
554 * exits the current script (either exit or redirect)
555 */
556function access_denied()
557{
558  global $user;
559
560  $login_url =
561      get_root_url().'identification.php?redirect='
562      .urlencode(urlencode($_SERVER['REQUEST_URI']));
563
564  if ( isset($user) and !is_a_guest() )
565  {
566    echo '<div style="text-align:center;">'.l10n('access_forbiden').'<br />';
567    echo '<a href="'.get_root_url().'identification.php">'.l10n('identification').'</a>&nbsp;';
568    echo '<a href="'.make_index_url().'">'.l10n('home').'</a></div>';
569    exit();
570  }
571  else
572  {
573    set_status_header(401);
574    redirect_html($login_url);
575  }
576}
577
578/**
579 * exits the current script with 403 code
580 * @param string msg a message to display
581 * @param string alternate_url redirect to this url
582 */
583function page_forbidden($msg, $alternate_url=null)
584{
585  set_status_header(403);
586  if ($alternate_url==null)
587    $alternate_url = make_index_url();
588  redirect_html( $alternate_url,
589    '<div style="text-align:left; margin-left:5em;margin-bottom:5em;">
590<h1 style="text-align:left; font-size:36px;">Forbidden</h1><br/>'
591.$msg.'</div>',
592    5 );
593}
594
595/**
596 * exits the current script with 400 code
597 * @param string msg a message to display
598 * @param string alternate_url redirect to this url
599 */
600function bad_request($msg, $alternate_url=null)
601{
602  set_status_header(400);
603  if ($alternate_url==null)
604    $alternate_url = make_index_url();
605  redirect_html( $alternate_url,
606    '<div style="text-align:left; margin-left:5em;margin-bottom:5em;">
607<h1 style="text-align:left; font-size:36px;">Bad request</h1><br/>'
608.$msg.'</div>',
609    5 );
610}
611
612/**
613 * exits the current script with 404 code when a page cannot be found
614 * @param string msg a message to display
615 * @param string alternate_url redirect to this url
616 */
617function page_not_found($msg, $alternate_url=null)
618{
619  set_status_header(404);
620  if ($alternate_url==null)
621    $alternate_url = make_index_url();
622  redirect_html( $alternate_url,
623    '<div style="text-align:left; margin-left:5em;margin-bottom:5em;">
624<h1 style="text-align:left; font-size:36px;">Page not found</h1><br/>'
625.$msg.'</div>',
626    5 );
627}
628
629/* returns the title to be displayed above thumbnails on tag page
630 */
631function get_tags_content_title()
632{
633  global $page;
634  $title = count($page['tags']) > 1 ? l10n('Tags') : l10n('Tag');
635  $title.= ' ';
636
637  for ($i=0; $i<count($page['tags']); $i++)
638  {
639    $title.= $i>0 ? ' + ' : '';
640
641    $title.=
642      '<a href="'
643      .make_index_url(
644        array(
645          'tags' => array( $page['tags'][$i] )
646          )
647        )
648      .'" title="'
649      .l10n('See elements linked to this tag only')
650      .'">'
651      .$page['tags'][$i]['name']
652      .'</a>';
653
654    if ( count($page['tags'])>2 )
655    {
656      $other_tags = $page['tags'];
657      unset ( $other_tags[$i] );
658      $title.=
659        '<a href="'
660        .make_index_url(
661          array(
662            'tags' => $other_tags
663            )
664          )
665        .'" style="border:none;" title="'
666        .l10n('remove this tag')
667        .'"><img src="'
668        .get_root_url().get_themeconf('icon_dir').'/remove_s.png'
669        .'" alt="x" style="vertical-align:bottom;" class="button"/>'
670        .'</a>';
671    }
672
673  }
674  return $title;
675}
676
677/**
678  Sets the http status header (200,401,...)
679 */
680function set_status_header($code, $text='')
681{
682  if (empty($text))
683  {
684    switch ($code)
685    {
686      case 200: $text='OK';break;
687      case 301: $text='Moved permanently';break;
688      case 302: $text='Moved temporarily';break;
689      case 304: $text='Not modified';break;
690      case 400: $text='Bad request';break;
691      case 401: $text='Authorization required';break;
692      case 403: $text='Forbidden';break;
693      case 404: $text='Not found';break;
694      case 500: $text='Server error';break;
695      case 503: $text='Service unavailable';break;
696    }
697  }
698        $protocol = $_SERVER["SERVER_PROTOCOL"];
699        if ( ('HTTP/1.1' != $protocol) && ('HTTP/1.0' != $protocol) )
700                $protocol = 'HTTP/1.0';
701
702        if ( version_compare( phpversion(), '4.3.0', '>=' ) )
703  {
704                header( "$protocol $code $text", true, $code );
705        }
706  else
707  {
708                header( "$protocol $code $text" );
709        }
710  trigger_action('set_status_header', $code, $text);
711}
712
713/** returns the category comment for rendering in html.
714 * this is an event handler. don't call directly
715 */
716function render_category_description($desc)
717{
718  global $conf;
719  if ( !( $conf['allow_html_descriptions'] and
720          preg_match('/<(div|br|img|script).*>/i', $desc) ) )
721  {
722    $desc = nl2br($desc);
723  }
724  return $desc;
725}
726
727/** returns the category comment for rendering in html textual mode (subcatify)
728 * this is an event handler. don't call directly
729 */
730function render_category_literal_description($desc)
731{
732  return strip_tags($desc, '<span><p><a><br><b><i><small><big><strong><em>');
733}
734?>
Note: See TracBrowser for help on using the repository browser.