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

Last change on this file since 25425 was 25425, checked in by mistic100, 10 years ago

delete replace_space function, modify get_cat_display_name_* functions

  • Property svn:eol-style set to LF
File size: 16.5 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based photo gallery                                    |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008-2013 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 * returns the list of categories as a HTML string
26 *
27 * categories string returned contains categories as given in the input
28 * array $cat_informations. $cat_informations array must be an array
29 * of array( id=>?, name=>?, permalink=>?). If url input parameter is null,
30 * returns only the categories name without links.
31 *
32 * @param array cat_informations
33 * @param string url
34 * @return string
35 */
36function get_cat_display_name($cat_informations, $url = '')
37{
38  global $conf;
39
40  //$output = '<a href="'.get_absolute_root_url().$conf['home_page'].'">'.l10n('Home').'</a>';
41  $output = '';
42  $is_first=true;
43
44  foreach ($cat_informations as $cat)
45  {
46    is_array($cat) or trigger_error(
47        'get_cat_display_name wrong type for category ', E_USER_WARNING
48      );
49
50    $cat['name'] = trigger_event(
51      'render_category_name',
52      $cat['name'],
53      'get_cat_display_name'
54      );
55
56    if ($is_first)
57    {
58      $is_first=false;
59    }
60    else
61    {
62      $output.= $conf['level_separator'];
63    }
64
65    if ( !isset($url) )
66    {
67      $output.= $cat['name'];
68    }
69    elseif ($url == '')
70    {
71      $output.= '<a href="'
72            .make_index_url(
73                array(
74                  'category' => $cat,
75                  )
76              )
77            .'">';
78      $output.= $cat['name'].'</a>';
79    }
80    else
81    {
82      $output.= '<a href="'.PHPWG_ROOT_PATH.$url.$cat['id'].'">';
83      $output.= $cat['name'].'</a>';
84    }
85  }
86  return $output;
87}
88
89/**
90 * returns the list of categories as a HTML string, with cache of names
91 *
92 * categories string returned contains categories as given in the input
93 * array $cat_informations. $uppercats is the list of category ids to
94 * display in the right order. If url input parameter is empty, returns only
95 * the categories name without links.
96 *
97 * @param string uppercats
98 * @param string url
99 * @return string
100 */
101function get_cat_display_name_cache($uppercats,
102                                    $url = '',
103                                    $single_link = false,
104                                    $link_class = null)
105{
106  global $cache, $conf;
107
108  if (!isset($cache['cat_names']))
109  {
110    $query = '
111SELECT id, name, permalink
112  FROM '.CATEGORIES_TABLE.'
113;';
114    $cache['cat_names'] = hash_from_query($query, 'id');
115  }
116
117  $output = '';
118  if ($single_link)
119  {
120    $single_url = get_root_url().$url.array_pop(explode(',', $uppercats));
121    $output.= '<a href="'.$single_url.'"';
122    if (isset($link_class))
123    {
124      $output.= ' class="'.$link_class.'"';
125    }
126    $output.= '>';
127  }
128  $is_first = true;
129  foreach (explode(',', $uppercats) as $category_id)
130  {
131    $cat = $cache['cat_names'][$category_id];
132
133    $cat['name'] = trigger_event(
134      'render_category_name',
135      $cat['name'],
136      'get_cat_display_name_cache'
137      );
138
139    if ($is_first)
140    {
141      $is_first = false;
142    }
143    else
144    {
145      $output.= $conf['level_separator'];
146    }
147
148    if ( !isset($url) or $single_link )
149    {
150      $output.= $cat['name'];
151    }
152    elseif ($url == '')
153    {
154      $output.= '
155<a href="'
156      .make_index_url(
157          array(
158            'category' => $cat,
159            )
160        )
161      .'">'.$cat['name'].'</a>';
162    }
163    else
164    {
165      $output.= '
166<a href="'.PHPWG_ROOT_PATH.$url.$category_id.'">'.$cat['name'].'</a>';
167    }
168  }
169
170  if ($single_link and isset($single_url))
171  {
172    $output.= '</a>';
173  }
174
175  return $output;
176}
177
178/**
179 * returns HTMLized comment contents retrieved from database
180 *
181 * newlines becomes br tags, _word_ becomes underline, /word/ becomes
182 * italic, *word* becomes bolded
183 *
184 * @param string content
185 * @return string
186 */
187function render_comment_content($content)
188{
189  $content = htmlspecialchars($content);
190  $pattern = '/(https?:\/\/\S*)/';
191  $replacement = '<a href="$1" rel="nofollow">$1</a>';
192  $content = preg_replace($pattern, $replacement, $content);
193
194  $content = nl2br($content);
195
196  // replace _word_ by an underlined word
197  $pattern = '/\b_(\S*)_\b/';
198  $replacement = '<span style="text-decoration:underline;">$1</span>';
199  $content = preg_replace($pattern, $replacement, $content);
200
201  // replace *word* by a bolded word
202  $pattern = '/\b\*(\S*)\*\b/';
203  $replacement = '<span style="font-weight:bold;">$1</span>';
204  $content = preg_replace($pattern, $replacement, $content);
205
206  // replace /word/ by an italic word
207  $pattern = "/\/(\S*)\/(\s)/";
208  $replacement = '<span style="font-style:italic;">$1$2</span>';
209  $content = preg_replace($pattern, $replacement, $content);
210
211  return $content;
212}
213
214function get_cat_display_name_from_id($cat_id, $url = '')
215{
216  $cat_info = get_cat_info($cat_id);
217  return get_cat_display_name($cat_info['upper_names'], $url);
218}
219
220/**
221 * Returns an HTML list of tags. It can be a multi select field or a list of
222 * checkboxes.
223 *
224 * @param string HTML field name
225 * @param array selected tag ids
226 * @return array
227 */
228function get_html_tag_selection(
229  $tags,
230  $fieldname,
231  $selecteds = array(),
232  $forbidden_categories = null
233  )
234{
235  global $conf;
236
237  if (count ($tags) == 0 )
238  {
239    return '';
240  }
241  $output = '<ul class="tagSelection">';
242  foreach ($tags as $tag)
243  {
244    $output.=
245      '<li>'
246      .'<label>'
247      .'<input type="checkbox" name="'.$fieldname.'[]"'
248      .' value="'.$tag['id'].'"'
249      ;
250
251    if (in_array($tag['id'], $selecteds))
252    {
253      $output.= ' checked="checked"';
254    }
255
256    $output.=
257      '> '
258      .$tag['name']
259      .'</label>'
260      .'</li>'
261      ."\n"
262      ;
263  }
264  $output.= '</ul>';
265
266  return $output;
267}
268
269function name_compare($a, $b)
270{
271  return strcmp(strtolower($a['name']), strtolower($b['name']));
272}
273
274function tag_alpha_compare($a, $b)
275{
276  global $cache;
277
278  foreach (array($a, $b) as $tag)
279  {
280    if (!isset($cache[__FUNCTION__][ $tag['name'] ]))
281    {
282      $cache[__FUNCTION__][ $tag['name'] ] = transliterate($tag['name']);
283    }
284  }
285
286  return strcmp($cache[__FUNCTION__][ $a['name'] ], $cache[__FUNCTION__][ $b['name'] ]);
287}
288
289/**
290 * exits the current script (either exit or redirect)
291 */
292function access_denied()
293{
294  global $user;
295
296  $login_url =
297      get_root_url().'identification.php?redirect='
298      .urlencode(urlencode($_SERVER['REQUEST_URI']));
299
300  set_status_header(401);
301  if ( isset($user) and !is_a_guest() )
302  {
303    echo '<meta http-equiv="Content-Type" content="text/html; charset=utf-8">';
304    echo '<div style="text-align:center;">'.l10n('You are not authorized to access the requested page').'<br>';
305    echo '<a href="'.get_root_url().'identification.php">'.l10n('Identification').'</a>&nbsp;';
306    echo '<a href="'.make_index_url().'">'.l10n('Home').'</a></div>';
307    echo str_repeat( ' ', 512); //IE6 doesn't error output if below a size
308    exit();
309  }
310  else
311  {
312    redirect_html($login_url);
313  }
314}
315
316/**
317 * exits the current script with 403 code
318 * @param string msg a message to display
319 * @param string alternate_url redirect to this url
320 */
321function page_forbidden($msg, $alternate_url=null)
322{
323  set_status_header(403);
324  if ($alternate_url==null)
325    $alternate_url = make_index_url();
326  redirect_html( $alternate_url,
327    '<div style="text-align:left; margin-left:5em;margin-bottom:5em;">
328<h1 style="text-align:left; font-size:36px;">'.l10n('Forbidden').'</h1><br>'
329.$msg.'</div>',
330    5 );
331}
332
333/**
334 * exits the current script with 400 code
335 * @param string msg a message to display
336 * @param string alternate_url redirect to this url
337 */
338function bad_request($msg, $alternate_url=null)
339{
340  set_status_header(400);
341  if ($alternate_url==null)
342    $alternate_url = make_index_url();
343  redirect_html( $alternate_url,
344    '<div style="text-align:left; margin-left:5em;margin-bottom:5em;">
345<h1 style="text-align:left; font-size:36px;">'.l10n('Bad request').'</h1><br>'
346.$msg.'</div>',
347    5 );
348}
349
350/**
351 * exits the current script with 404 code when a page cannot be found
352 * @param string msg a message to display
353 * @param string alternate_url redirect to this url
354 */
355function page_not_found($msg, $alternate_url=null)
356{
357  set_status_header(404);
358  if ($alternate_url==null)
359    $alternate_url = make_index_url();
360  redirect_html( $alternate_url,
361    '<div style="text-align:left; margin-left:5em;margin-bottom:5em;">
362<h1 style="text-align:left; font-size:36px;">'.l10n('Page not found').'</h1><br>'
363.$msg.'</div>',
364    5 );
365}
366
367/**
368 * exits the current script with 500 http code
369 * this method can be called at any time (does not use template/language/user etc...)
370 * @param string msg a message to display
371 */
372function fatal_error($msg, $title=null, $show_trace=true)
373{
374  if (empty($title))
375  {
376    $title = l10n('Piwigo encountered a non recoverable error');
377  }
378
379  $btrace_msg = '';
380  if ($show_trace and function_exists('debug_backtrace'))
381  {
382    $bt = debug_backtrace();
383    for ($i=1; $i<count($bt); $i++)
384    {
385      $class = isset($bt[$i]['class']) ? (@$bt[$i]['class'].'::') : '';
386      $btrace_msg .= "#$i\t".$class.@$bt[$i]['function'].' '.@$bt[$i]['file']."(".@$bt[$i]['line'].")\n";
387    }
388    $btrace_msg = trim($btrace_msg);
389    $msg .= "\n";
390  }
391
392  $display = "<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
393<h1>$title</h1>
394<pre style='font-size:larger;background:white;color:red;padding:1em;margin:0;clear:both;display:block;width:auto;height:auto;overflow:auto'>
395<b>$msg</b>
396$btrace_msg
397</pre>\n";
398
399  @set_status_header(500);
400  echo $display.str_repeat( ' ', 300); //IE6 doesn't error output if below a size
401
402  if ( function_exists('ini_set') )
403  {// if possible turn off error display (we display it)
404    ini_set('display_errors', false);
405  }
406  error_reporting( E_ALL );
407  trigger_error( strip_tags($msg).$btrace_msg, E_USER_ERROR );
408  die(0); // just in case
409}
410
411/* returns the title to be displayed above thumbnails on tag page
412 */
413function get_tags_content_title()
414{
415  global $page;
416  $title = '<a href="'.get_root_url().'tags.php" title="'.l10n('display available tags').'">'
417    . l10n( count($page['tags']) > 1 ? 'Tags' : 'Tag' )
418    . '</a> ';
419
420  for ($i=0; $i<count($page['tags']); $i++)
421  {
422    $title.= $i>0 ? ' + ' : '';
423
424    $title.=
425      '<a href="'
426      .make_index_url(
427        array(
428          'tags' => array( $page['tags'][$i] )
429          )
430        )
431      .'" title="'
432      .l10n('display photos linked to this tag')
433      .'">'
434      .trigger_event('render_tag_name', $page['tags'][$i]['name'])
435      .'</a>';
436
437    if (count($page['tags']) > 2)
438    {
439      $other_tags = $page['tags'];
440      unset($other_tags[$i]);
441      $remove_url = make_index_url(
442        array(
443          'tags' => $other_tags
444          )
445        );
446
447      $title.=
448        '<a href="'.$remove_url.'" style="border:none;" title="'
449        .l10n('remove this tag from the list')
450        .'"><img src="'
451          .get_root_url().get_themeconf('icon_dir').'/remove_s.png'
452        .'" alt="x" style="vertical-align:bottom;">'
453        .'</a>';
454    }
455  }
456  return $title;
457}
458
459/**
460  Sets the http status header (200,401,...)
461 */
462function set_status_header($code, $text='')
463{
464  if (empty($text))
465  {
466    switch ($code)
467    {
468      case 200: $text='OK';break;
469      case 301: $text='Moved permanently';break;
470      case 302: $text='Moved temporarily';break;
471      case 304: $text='Not modified';break;
472      case 400: $text='Bad request';break;
473      case 401: $text='Authorization required';break;
474      case 403: $text='Forbidden';break;
475      case 404: $text='Not found';break;
476      case 500: $text='Server error';break;
477      case 501: $text='Not implemented';break;
478      case 503: $text='Service unavailable';break;
479    }
480  }
481  $protocol = $_SERVER["SERVER_PROTOCOL"];
482  if ( ('HTTP/1.1' != $protocol) && ('HTTP/1.0' != $protocol) )
483    $protocol = 'HTTP/1.0';
484
485  header( "$protocol $code $text", true, $code );
486  trigger_action('set_status_header', $code, $text);
487}
488
489/** returns the category comment for rendering in html textual mode (subcatify)
490 * this is an event handler. don't call directly
491 */
492function render_category_literal_description($desc)
493{
494  return strip_tags($desc, '<span><p><a><br><b><i><small><big><strong><em>');
495}
496
497/*event handler for menu*/
498function register_default_menubar_blocks( $menu_ref_arr )
499{
500  $menu = & $menu_ref_arr[0];
501  if ($menu->get_id() != 'menubar')
502    return;
503  $menu->register_block( new RegisteredBlock( 'mbLinks', 'Links', 'piwigo'));
504  $menu->register_block( new RegisteredBlock( 'mbCategories', 'Albums', 'piwigo'));
505  $menu->register_block( new RegisteredBlock( 'mbTags', 'Related tags', 'piwigo'));
506  $menu->register_block( new RegisteredBlock( 'mbSpecials', 'Specials', 'piwigo'));
507  $menu->register_block( new RegisteredBlock( 'mbMenu', 'Menu', 'piwigo'));
508  $menu->register_block( new RegisteredBlock( 'mbIdentification', 'Identification', 'piwigo') );
509}
510
511/**
512 */
513function render_element_name($info)
514{
515  $name = $info['name'];
516  if (!empty($name))
517  {
518    $name = trigger_event('render_element_name', $name);
519    return $name;
520  }
521
522  return get_name_from_file($info['file']);
523}
524
525function render_element_description($info, $param='')
526{
527  $comment = $info['comment'];
528  if (!empty($comment))
529  {
530    $comment = trigger_event('render_element_description', $comment, $param);
531    return $comment;
532  }
533  return '';
534}
535
536/**
537 * returns the title of the thumbnail based on photo properties
538 */
539function get_thumbnail_title($info, $title, $comment)
540{
541  global $conf, $user;
542
543  $details = array();
544
545  if (!empty($info['hit']))
546  {
547    $details[] = $info['hit'].' '.strtolower(l10n('Visits'));
548  }
549
550  if ($conf['rate'] and !empty($info['rating_score']))
551  {
552    $details[] = strtolower(l10n('Rating score')).' '.$info['rating_score'];
553  }
554
555  if (isset($info['nb_comments']) and $info['nb_comments'] != 0)
556  {
557    $details[] = l10n_dec('%d comment', '%d comments', $info['nb_comments']);
558  }
559
560  if (count($details) > 0)
561  {
562    $title.= ' ('.implode(', ', $details).')';
563  }
564
565  if (!empty($comment))
566  {
567    $comment = strip_tags($comment);
568    $title.= ' '.substr($comment, 0, 100).(strlen($comment) > 100 ? '...' : '');
569  }
570
571  $title = htmlspecialchars(strip_tags($title));
572  $title = trigger_event('get_thumbnail_title', $title, $info);
573  return $title;
574}
575
576/** optional event handler to protect src image urls */
577function get_src_image_url_protection_handler($url, $src_image)
578{
579  return get_action_url($src_image->id, $src_image->is_original() ? 'e' : 'r', false);
580}
581
582/** optional event handler to protect element urls */
583function get_element_url_protection_handler($url, $infos)
584{
585  global $conf;
586  if ('images'==$conf['original_url_protection'])
587  {// protect only images and not other file types (for example large movies that we don't want to send through our file proxy)
588    $ext = get_extension($infos['path']);
589    if (!in_array($ext, $conf['picture_ext']))
590    {
591      return $url;
592    }
593  }
594  return get_action_url($infos['id'], 'e', false);
595}
596
597
598function flush_page_messages()
599{
600  global $template, $page;
601  if ($template->get_template_vars('page_refresh') === null)
602  {
603    foreach (array('errors','infos','warnings') as $mode)
604    {
605      if (isset($_SESSION['page_'.$mode]))
606      {
607        $page[$mode] = array_merge($page[$mode], $_SESSION['page_'.$mode]);
608        unset($_SESSION['page_'.$mode]);
609      }
610
611      if (count($page[$mode]) != 0)
612      {
613        $template->assign($mode, $page[$mode]);
614      }
615    }
616  }
617}
618
619?>
Note: See TracBrowser for help on using the repository browser.