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

Last change on this file since 28913 was 28715, checked in by rvelices, 10 years ago

removed unused get_html_tag_selection function + css rules

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