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

Last change on this file since 3185 was 3185, checked in by nikrou, 15 years ago

fix html warnings. unclosed monotags

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