source: trunk/include/functions.inc.php @ 5021

Last change on this file since 5021 was 5021, checked in by nikrou, 14 years ago

Feature 1451 : localization with gettext
Use php-gettext (developpement version rev43, because of php5.3) as fallback
Use native language (english) instead of key for translation
Keep directory en_UK for english customization
Need some refactoring for plurals

Todo : managing plugins in the same way

File size: 40.6 KB
RevLine 
[2]1<?php
[362]2// +-----------------------------------------------------------------------+
[2297]3// | Piwigo - a PHP based picture gallery                                  |
4// +-----------------------------------------------------------------------+
[3049]5// | Copyright(C) 2008-2009 Piwigo Team                  http://piwigo.org |
[2297]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// +-----------------------------------------------------------------------+
[405]23
[394]24include_once( PHPWG_ROOT_PATH .'include/functions_user.inc.php' );
[1992]25include_once( PHPWG_ROOT_PATH .'include/functions_cookie.inc.php' );
[394]26include_once( PHPWG_ROOT_PATH .'include/functions_session.inc.php' );
27include_once( PHPWG_ROOT_PATH .'include/functions_category.inc.php' );
28include_once( PHPWG_ROOT_PATH .'include/functions_xml.inc.php' );
[477]29include_once( PHPWG_ROOT_PATH .'include/functions_html.inc.php' );
[1119]30include_once( PHPWG_ROOT_PATH .'include/functions_tag.inc.php' );
[1109]31include_once( PHPWG_ROOT_PATH .'include/functions_url.inc.php' );
[1578]32include_once( PHPWG_ROOT_PATH .'include/functions_plugins.inc.php' );
[5021]33include_once( PHPWG_ROOT_PATH .'include/php-gettext/gettext.inc.php' );
[2]34
35//----------------------------------------------------------- generic functions
[4388]36function get_extra_fields($order_by_fields) 
[4387]37{
38  $fields = str_ireplace(array(' order by ', ' desc', ' asc'), 
39                         array('', '', ''),
40                         $order_by_fields
41                         );
42  if (!empty($fields))
[5021]43  { 
[4387]44    $fields = ','.$fields;
45  }
46  return $fields;
47}
[2]48
49// The function get_moment returns a float value coresponding to the number
50// of seconds since the unix epoch (1st January 1970) and the microseconds
51// are precised : e.g. 1052343429.89276600
52function get_moment()
53{
[9]54  $t1 = explode( ' ', microtime() );
55  $t2 = explode( '.', $t1[0] );
56  $t2 = $t1[1].'.'.$t2[1];
[2]57  return $t2;
58}
59
60// The function get_elapsed_time returns the number of seconds (with 3
61// decimals precision) between the start time and the end time given.
62function get_elapsed_time( $start, $end )
63{
64  return number_format( $end - $start, 3, '.', ' ').' s';
65}
66
67// - The replace_space function replaces space and '-' characters
68//   by their HTML equivalent  &nbsb; and &minus;
69// - The function does not replace characters in HTML tags
70// - This function was created because IE5 does not respect the
71//   CSS "white-space: nowrap;" property unless space and minus
72//   characters are replaced like this function does.
[15]73// - Example :
74//                 <div class="foo">My friend</div>
75//               ( 01234567891111111111222222222233 )
76//               (           0123456789012345678901 )
77// becomes :
78//             <div class="foo">My&nbsp;friend</div>
[2]79function replace_space( $string )
80{
[15]81  //return $string;
82  $return_string = '';
83  // $remaining is the rest of the string where to replace spaces characters
[2]84  $remaining = $string;
[15]85  // $start represents the position of the next '<' character
86  // $end   represents the position of the next '>' character
[3136]87  ; // -> 0
[15]88  $end   = strpos ( $remaining, '>' ); // -> 16
89  // as long as a '<' and his friend '>' are found, we loop
[3136]90  while ( ($start=strpos( $remaining, '<' )) !==false
91        and ($end=strpos( $remaining, '>' )) !== false )
[2]92  {
[15]93    // $treatment is the part of the string to treat
94    // In the first loop of our example, this variable is empty, but in the
95    // second loop, it equals 'My friend'
[2]96    $treatment = substr ( $remaining, 0, $start );
[15]97    // Replacement of ' ' by his equivalent '&nbsp;'
[6]98    $treatment = str_replace( ' ', '&nbsp;', $treatment );
99    $treatment = str_replace( '-', '&minus;', $treatment );
[15]100    // composing the string to return by adding the treated string and the
101    // following HTML tag -> 'My&nbsp;friend</div>'
102    $return_string.= $treatment.substr( $remaining, $start, $end-$start+1 );
103    // the remaining string is deplaced to the part after the '>' of this
104    // loop
[2]105    $remaining = substr ( $remaining, $end + 1, strlen( $remaining ) );
106  }
[6]107  $treatment = str_replace( ' ', '&nbsp;', $remaining );
108  $treatment = str_replace( '-', '&minus;', $treatment );
[2]109  $return_string.= $treatment;
[15]110
[2]111  return $return_string;
112}
113
[13]114// get_extension returns the part of the string after the last "."
115function get_extension( $filename )
116{
117  return substr( strrchr( $filename, '.' ), 1, strlen ( $filename ) );
118}
119
120// get_filename_wo_extension returns the part of the string before the last
121// ".".
122// get_filename_wo_extension( 'test.tar.gz' ) -> 'test.tar'
123function get_filename_wo_extension( $filename )
124{
[1589]125  $pos = strrpos( $filename, '.' );
126  return ($pos===false) ? $filename : substr( $filename, 0, $pos);
[13]127}
128
[345]129/**
[2497]130 * returns an array contening sub-directories, excluding ".svn"
[345]131 *
132 * @param string $dir
133 * @return array
134 */
[512]135function get_dirs($directory)
[2]136{
[345]137  $sub_dirs = array();
[512]138  if ($opendir = opendir($directory))
[2]139  {
[512]140    while ($file = readdir($opendir))
[2]141    {
[512]142      if ($file != '.'
143          and $file != '..'
144          and is_dir($directory.'/'.$file)
[2497]145          and $file != '.svn')
[2]146      {
[512]147        array_push($sub_dirs, $file);
[2]148      }
149    }
[2497]150    closedir($opendir);
[2]151  }
[345]152  return $sub_dirs;
[2]153}
154
[2497]155define('MKGETDIR_NONE', 0);
156define('MKGETDIR_RECURSIVE', 1);
157define('MKGETDIR_DIE_ON_ERROR', 2);
158define('MKGETDIR_PROTECT_INDEX', 4);
159define('MKGETDIR_PROTECT_HTACCESS', 8);
160define('MKGETDIR_DEFAULT', 7);
[1631]161/**
[2497]162 * creates directory if not exists; ensures that directory is writable
163 * @param:
164 *  string $dir
165 *  int $flags combination of MKGETDIR_xxx
166 * @return bool false on error else true
167 */
168function mkgetdir($dir, $flags=MKGETDIR_DEFAULT)
169{
170  if ( !is_dir($dir) )
171  {
172    $umask = umask(0);
173    $mkd = @mkdir($dir, 0755, ($flags&MKGETDIR_RECURSIVE) ? true:false );
174    umask($umask);
175    if ($mkd==false)
176    {
[5021]177      !($flags&MKGETDIR_DIE_ON_ERROR) or fatal_error( "$dir ".l10n('no write access'));
[2497]178      return false;
179    }
180    if( $flags&MKGETDIR_PROTECT_HTACCESS )
181    {
182      $file = $dir.'/.htaccess';
183      file_exists($file) or @file_put_contents( $file, 'deny from all' );
184    }
185    if( $flags&MKGETDIR_PROTECT_INDEX )
186    {
187      $file = $dir.'/index.htm';
188      file_exists($file) or @file_put_contents( $file, 'Not allowed!' );
189    }
190  }
191  if ( !is_writable($dir) )
192  {
[5021]193    !($flags&MKGETDIR_DIE_ON_ERROR) or fatal_error( "$dir ".l10n('no write access'));
[3136]194    return false;
[2497]195  }
196  return true;
197}
198
199/**
[1631]200 * returns thumbnail directory name of input diretoty name
201 * make thumbnail directory is necessary
202 * set error messages on array messages
203 *
204 * @param:
205 *  string $dirname
206 *  arrayy $errors
207 * @return bool false on error else string directory name
208 */
209function mkget_thumbnail_dir($dirname, &$errors)
210{
[3750]211  global $conf;
212
[3720]213  $tndir = $dirname.'/'.$conf['dir_thumbnail'];
[2505]214  if (! mkgetdir($tndir, MKGETDIR_NONE) )
[1631]215  {
[2497]216    array_push($errors,
[5021]217          '['.$dirname.'] : '.l10n('no write access'));
[2497]218    return false;
[1631]219  }
220  return $tndir;
221}
222
[2123]223/* Returns true if the string appears to be encoded in UTF-8. (from wordpress)
224 * @param string Str
225 */
226function seems_utf8($Str) { # by bmorel at ssi dot fr
227  for ($i=0; $i<strlen($Str); $i++) {
228    if (ord($Str[$i]) < 0x80) continue; # 0bbbbbbb
229    elseif ((ord($Str[$i]) & 0xE0) == 0xC0) $n=1; # 110bbbbb
230    elseif ((ord($Str[$i]) & 0xF0) == 0xE0) $n=2; # 1110bbbb
231    elseif ((ord($Str[$i]) & 0xF8) == 0xF0) $n=3; # 11110bbb
232    elseif ((ord($Str[$i]) & 0xFC) == 0xF8) $n=4; # 111110bb
233    elseif ((ord($Str[$i]) & 0xFE) == 0xFC) $n=5; # 1111110b
234    else return false; # Does not match any model
235    for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ?
236      if ((++$i == strlen($Str)) || ((ord($Str[$i]) & 0xC0) != 0x80))
237      return false;
238    }
239  }
240  return true;
241}
242
243/* Remove accents from a UTF-8 or ISO-859-1 string (from wordpress)
244 * @param string sstring - an UTF-8 or ISO-8859-1 string
245 */
246function remove_accents($string)
247{
248  if ( !preg_match('/[\x80-\xff]/', $string) )
249    return $string;
250
251  if (seems_utf8($string)) {
252    $chars = array(
253    // Decompositions for Latin-1 Supplement
254    chr(195).chr(128) => 'A', chr(195).chr(129) => 'A',
255    chr(195).chr(130) => 'A', chr(195).chr(131) => 'A',
256    chr(195).chr(132) => 'A', chr(195).chr(133) => 'A',
257    chr(195).chr(135) => 'C', chr(195).chr(136) => 'E',
258    chr(195).chr(137) => 'E', chr(195).chr(138) => 'E',
259    chr(195).chr(139) => 'E', chr(195).chr(140) => 'I',
260    chr(195).chr(141) => 'I', chr(195).chr(142) => 'I',
261    chr(195).chr(143) => 'I', chr(195).chr(145) => 'N',
262    chr(195).chr(146) => 'O', chr(195).chr(147) => 'O',
263    chr(195).chr(148) => 'O', chr(195).chr(149) => 'O',
264    chr(195).chr(150) => 'O', chr(195).chr(153) => 'U',
265    chr(195).chr(154) => 'U', chr(195).chr(155) => 'U',
266    chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y',
267    chr(195).chr(159) => 's', chr(195).chr(160) => 'a',
268    chr(195).chr(161) => 'a', chr(195).chr(162) => 'a',
269    chr(195).chr(163) => 'a', chr(195).chr(164) => 'a',
270    chr(195).chr(165) => 'a', chr(195).chr(167) => 'c',
271    chr(195).chr(168) => 'e', chr(195).chr(169) => 'e',
272    chr(195).chr(170) => 'e', chr(195).chr(171) => 'e',
273    chr(195).chr(172) => 'i', chr(195).chr(173) => 'i',
274    chr(195).chr(174) => 'i', chr(195).chr(175) => 'i',
275    chr(195).chr(177) => 'n', chr(195).chr(178) => 'o',
276    chr(195).chr(179) => 'o', chr(195).chr(180) => 'o',
277    chr(195).chr(181) => 'o', chr(195).chr(182) => 'o',
278    chr(195).chr(182) => 'o', chr(195).chr(185) => 'u',
279    chr(195).chr(186) => 'u', chr(195).chr(187) => 'u',
280    chr(195).chr(188) => 'u', chr(195).chr(189) => 'y',
281    chr(195).chr(191) => 'y',
282    // Decompositions for Latin Extended-A
283    chr(196).chr(128) => 'A', chr(196).chr(129) => 'a',
284    chr(196).chr(130) => 'A', chr(196).chr(131) => 'a',
285    chr(196).chr(132) => 'A', chr(196).chr(133) => 'a',
286    chr(196).chr(134) => 'C', chr(196).chr(135) => 'c',
287    chr(196).chr(136) => 'C', chr(196).chr(137) => 'c',
288    chr(196).chr(138) => 'C', chr(196).chr(139) => 'c',
289    chr(196).chr(140) => 'C', chr(196).chr(141) => 'c',
290    chr(196).chr(142) => 'D', chr(196).chr(143) => 'd',
291    chr(196).chr(144) => 'D', chr(196).chr(145) => 'd',
292    chr(196).chr(146) => 'E', chr(196).chr(147) => 'e',
293    chr(196).chr(148) => 'E', chr(196).chr(149) => 'e',
294    chr(196).chr(150) => 'E', chr(196).chr(151) => 'e',
295    chr(196).chr(152) => 'E', chr(196).chr(153) => 'e',
296    chr(196).chr(154) => 'E', chr(196).chr(155) => 'e',
297    chr(196).chr(156) => 'G', chr(196).chr(157) => 'g',
298    chr(196).chr(158) => 'G', chr(196).chr(159) => 'g',
299    chr(196).chr(160) => 'G', chr(196).chr(161) => 'g',
300    chr(196).chr(162) => 'G', chr(196).chr(163) => 'g',
301    chr(196).chr(164) => 'H', chr(196).chr(165) => 'h',
302    chr(196).chr(166) => 'H', chr(196).chr(167) => 'h',
303    chr(196).chr(168) => 'I', chr(196).chr(169) => 'i',
304    chr(196).chr(170) => 'I', chr(196).chr(171) => 'i',
305    chr(196).chr(172) => 'I', chr(196).chr(173) => 'i',
306    chr(196).chr(174) => 'I', chr(196).chr(175) => 'i',
307    chr(196).chr(176) => 'I', chr(196).chr(177) => 'i',
308    chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij',
309    chr(196).chr(180) => 'J', chr(196).chr(181) => 'j',
310    chr(196).chr(182) => 'K', chr(196).chr(183) => 'k',
311    chr(196).chr(184) => 'k', chr(196).chr(185) => 'L',
312    chr(196).chr(186) => 'l', chr(196).chr(187) => 'L',
313    chr(196).chr(188) => 'l', chr(196).chr(189) => 'L',
314    chr(196).chr(190) => 'l', chr(196).chr(191) => 'L',
315    chr(197).chr(128) => 'l', chr(197).chr(129) => 'L',
316    chr(197).chr(130) => 'l', chr(197).chr(131) => 'N',
317    chr(197).chr(132) => 'n', chr(197).chr(133) => 'N',
318    chr(197).chr(134) => 'n', chr(197).chr(135) => 'N',
319    chr(197).chr(136) => 'n', chr(197).chr(137) => 'N',
320    chr(197).chr(138) => 'n', chr(197).chr(139) => 'N',
321    chr(197).chr(140) => 'O', chr(197).chr(141) => 'o',
322    chr(197).chr(142) => 'O', chr(197).chr(143) => 'o',
323    chr(197).chr(144) => 'O', chr(197).chr(145) => 'o',
324    chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe',
325    chr(197).chr(148) => 'R',chr(197).chr(149) => 'r',
326    chr(197).chr(150) => 'R',chr(197).chr(151) => 'r',
327    chr(197).chr(152) => 'R',chr(197).chr(153) => 'r',
328    chr(197).chr(154) => 'S',chr(197).chr(155) => 's',
329    chr(197).chr(156) => 'S',chr(197).chr(157) => 's',
330    chr(197).chr(158) => 'S',chr(197).chr(159) => 's',
331    chr(197).chr(160) => 'S', chr(197).chr(161) => 's',
332    chr(197).chr(162) => 'T', chr(197).chr(163) => 't',
333    chr(197).chr(164) => 'T', chr(197).chr(165) => 't',
334    chr(197).chr(166) => 'T', chr(197).chr(167) => 't',
335    chr(197).chr(168) => 'U', chr(197).chr(169) => 'u',
336    chr(197).chr(170) => 'U', chr(197).chr(171) => 'u',
337    chr(197).chr(172) => 'U', chr(197).chr(173) => 'u',
338    chr(197).chr(174) => 'U', chr(197).chr(175) => 'u',
339    chr(197).chr(176) => 'U', chr(197).chr(177) => 'u',
340    chr(197).chr(178) => 'U', chr(197).chr(179) => 'u',
341    chr(197).chr(180) => 'W', chr(197).chr(181) => 'w',
342    chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y',
343    chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z',
344    chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z',
345    chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z',
346    chr(197).chr(190) => 'z', chr(197).chr(191) => 's',
347    // Euro Sign
348    chr(226).chr(130).chr(172) => 'E',
349    // GBP (Pound) Sign
350    chr(194).chr(163) => '');
351
352    $string = strtr($string, $chars);
353  } else {
354    // Assume ISO-8859-1 if not UTF-8
355    $chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158)
356      .chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194)
357      .chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202)
358      .chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210)
359      .chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218)
360      .chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227)
361      .chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235)
362      .chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243)
363      .chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251)
364      .chr(252).chr(253).chr(255);
365
366    $chars['out'] = "EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy";
367
368    $string = strtr($string, $chars['in'], $chars['out']);
369    $double_chars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254));
370    $double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th');
371    $string = str_replace($double_chars['in'], $double_chars['out'], $string);
372  }
373
374  return $string;
375}
376
[1119]377/**
378 * simplify a string to insert it into an URL
379 *
380 * @param string
381 * @return string
382 */
383function str2url($str)
384{
[2123]385  $str = remove_accents($str);
[1131]386  $str = preg_replace('/[^a-z0-9_\s\'\:\/\[\],-]/','',strtolower($str));
387  $str = preg_replace('/[\s\'\:\/\[\],-]+/',' ',trim($str));
[1119]388  $res = str_replace(' ','_',$str);
[1131]389
[1119]390  return $res;
391}
392
[2339]393//-------------------------------------------- Piwigo specific functions
[2]394
[512]395/**
396 * returns an array with a list of {language_code => language_name}
397 *
398 * @returns array
399 */
[2127]400function get_languages($target_charset = null)
[2]401{
[2127]402  if ( empty($target_charset) )
403  {
404    $target_charset = get_pwg_charset();
405  }
406  $target_charset = strtolower($target_charset);
407
[512]408  $dir = opendir(PHPWG_ROOT_PATH.'language');
[2]409  $languages = array();
[512]410
411  while ($file = readdir($dir))
[2]412  {
[749]413    $path = PHPWG_ROOT_PATH.'language/'.$file;
[3136]414    if (!is_link($path) and file_exists($path.'/iso.txt'))
[2]415    {
[512]416      list($language_name) = @file($path.'/iso.txt');
[2127]417
418      $langdef = explode('.',$file);
419      if (count($langdef)>1) // (langCode,encoding)
420      {
421        $langdef[1] = strtolower($langdef[1]);
422
423        if (
424          $target_charset==$langdef[1]
425         or
426          ($target_charset=='utf-8' and $langdef[1]=='iso-8859-1')
427         or
428          ($target_charset=='iso-8859-1' and
429          in_array( substr($langdef[0],2), array('en','fr','de','es','it','nl')))
430        )
431        {
432          $language_name = convert_charset($language_name,
433              $langdef[1], $target_charset);
434          $languages[ $langdef[0] ] = $language_name;
435        }
436        else
437          continue; // the language encoding is not compatible with our charset
438      }
439      else
[2134]440      { // UTF-8
441        $language_name = convert_charset($language_name,
442              'utf-8', $target_charset);
[2127]443        $languages[$file] = $language_name;
444      }
[2]445    }
446  }
[512]447  closedir($dir);
448  @asort($languages);
449
[2]450  return $languages;
451}
452
[1844]453function pwg_log($image_id = null, $image_type = null)
[2]454{
[1727]455  global $conf, $user, $page;
[2]456
[2620]457  $do_log = $conf['log'];
458  if (is_admin())
[2]459  {
[2620]460    $do_log = $conf['history_admin'];
[1565]461  }
[2620]462  if (is_a_guest())
[1565]463  {
[2620]464    $do_log = $conf['history_guest'];
[1565]465  }
[1880]466
467  $do_log = trigger_event('pwg_log_allowed', $do_log, $image_id, $image_type);
[2089]468
[1880]469  if (!$do_log)
470  {
[1727]471    return false;
[1565]472  }
473
[1727]474  $tags_string = null;
[3136]475  if ('tags'==@$page['section'])
[1565]476  {
[3136]477    $tags_string = implode(',', $page['tag_ids']);
[1565]478  }
479
480  $query = '
[725]481INSERT INTO '.HISTORY_TABLE.'
[1727]482  (
483    date,
484    time,
485    user_id,
486    IP,
487    section,
488    category_id,
489    image_id,
[1844]490    image_type,
[1727]491    tag_ids
492  )
[725]493  VALUES
[1727]494  (
[4367]495    CURRENT_DATE,
496    CURRENT_TIME,
[1727]497    '.$user['id'].',
498    \''.$_SERVER['REMOTE_ADDR'].'\',
499    '.(isset($page['section']) ? "'".$page['section']."'" : 'NULL').',
[2221]500    '.(isset($page['category']['id']) ? $page['category']['id'] : 'NULL').',
[1727]501    '.(isset($image_id) ? $image_id : 'NULL').',
[2086]502    '.(isset($image_type) ? "'".$image_type."'" : 'NULL').',
[1727]503    '.(isset($tags_string) ? "'".$tags_string."'" : 'NULL').'
504  )
[725]505;';
[1565]506  pwg_query($query);
[1727]507
508  return true;
[2]509}
510
[85]511// format_date returns a formatted date for display. The date given in
[3122]512// argument must be an american format (2003-09-15). By option, you can show the time.
513// The output is internationalized.
[85]514//
[3122]515// format_date( "2003-09-15", true ) -> "Monday 15 September 2003 21:52"
516function format_date($date, $show_time = false)
[61]517{
518  global $lang;
519
[4966]520  if (strpos($date, '0') == 0)
521  {
522    return l10n('N/A');
523  }
524
[3117]525  $ymdhms = array();
526  $tok = strtok( $date, '- :');
527  while ($tok !== false)
528  {
529    $ymdhms[] = $tok;
530    $tok = strtok('- :');
531  }
[1086]532
[3117]533  if ( count($ymdhms)<3 )
[61]534  {
[3117]535    return false;
[61]536  }
[3117]537
[599]538  $formated_date = '';
539  // before 1970, Microsoft Windows can't mktime
[3117]540  if ($ymdhms[0] >= 1970)
[61]541  {
[618]542    // we ask midday because Windows think it's prior to midnight with a
543    // zero and refuse to work
[3117]544    $formated_date.= $lang['day'][date('w', mktime(12,0,0,$ymdhms[1],$ymdhms[2],$ymdhms[0]))];
[61]545  }
[3117]546  $formated_date.= ' '.$ymdhms[2];
547  $formated_date.= ' '.$lang['month'][(int)$ymdhms[1]];
548  $formated_date.= ' '.$ymdhms[0];
549  if ($show_time and count($ymdhms)>=5 )
[599]550  {
[3117]551    $formated_date.= ' '.$ymdhms[3].':'.$ymdhms[4];
[599]552  }
[61]553  return $formated_date;
554}
[85]555
[345]556function pwg_debug( $string )
557{
[1033]558  global $debug,$t2,$page;
[345]559
560  $now = explode( ' ', microtime() );
561  $now2 = explode( '.', $now[0] );
562  $now2 = $now[1].'.'.$now2[1];
563  $time = number_format( $now2 - $t2, 3, '.', ' ').' s';
[1012]564  $debug .= '<p>';
[345]565  $debug.= '['.$time.', ';
[1033]566  $debug.= $page['count_queries'].' queries] : '.$string;
[1012]567  $debug.= "</p>\n";
[345]568}
[351]569
[405]570/**
[1649]571 * Redirects to the given URL (HTTP method)
[405]572 *
573 * Note : once this function called, the execution doesn't go further
574 * (presence of an exit() instruction.
575 *
576 * @param string $url
[1649]577 * @return void
578 */
579function redirect_http( $url )
580{
581  if (ob_get_length () !== FALSE)
582  {
583    ob_clean();
584  }
[2218]585  // default url is on html format
586  $url = html_entity_decode($url);
[1649]587  header('Request-URI: '.$url);
588  header('Content-Location: '.$url);
589  header('Location: '.$url);
590  exit();
591}
592
593/**
594 * Redirects to the given URL (HTML method)
595 *
596 * Note : once this function called, the execution doesn't go further
597 * (presence of an exit() instruction.
598 *
599 * @param string $url
[1156]600 * @param string $title_msg
601 * @param integer $refreh_time
[405]602 * @return void
603 */
[1649]604function redirect_html( $url , $msg = '', $refresh_time = 0)
[405]605{
[1567]606  global $user, $template, $lang_info, $conf, $lang, $t2, $page, $debug;
[405]607
[1568]608  if (!isset($lang_info))
609  {
610    $user = build_user( $conf['guest_id'], true);
[2126]611    load_language('common.lang');
[1699]612    trigger_action('loading_lang');
[2479]613    load_language('local.lang', '', array('no_fallback'=>true) );
[1926]614    list($tmpl, $thm) = explode('/', get_default_template());
[1568]615    $template = new Template(PHPWG_ROOT_PATH.'template/'.$tmpl, $thm);
[1298]616  }
[1568]617  else
618  {
619    $template = new Template(PHPWG_ROOT_PATH.'template/'.$user['template'], $user['theme']);
620  }
[1298]621
[1508]622  if (empty($msg))
[1156]623  {
[5021]624    $msg = nl2br(l10n('Redirection...'));
[1156]625  }
[688]626
[1567]627  $refresh = $refresh_time;
628  $url_link = $url;
629  $title = 'redirection';
[1086]630
[1567]631  $template->set_filenames( array( 'redirect' => 'redirect.tpl' ) );
632
633  include( PHPWG_ROOT_PATH.'include/page_header.php' );
634
635  $template->set_filenames( array( 'redirect' => 'redirect.tpl' ) );
[2521]636  $template->assign('REDIRECT_MSG', $msg);
637
[688]638  $template->parse('redirect');
[1567]639
640  include( PHPWG_ROOT_PATH.'include/page_tail.php' );
641
[405]642  exit();
643}
[507]644
645/**
[1649]646 * Redirects to the given URL (Switch to HTTP method or HTML method)
647 *
648 * Note : once this function called, the execution doesn't go further
649 * (presence of an exit() instruction.
650 *
651 * @param string $url
652 * @param string $title_msg
653 * @param integer $refreh_time
654 * @return void
655 */
656function redirect( $url , $msg = '', $refresh_time = 0)
657{
658  global $conf;
659
660  // with RefeshTime <> 0, only html must be used
[1846]661  if ($conf['default_redirect_method']=='http'
662      and $refresh_time==0
663      and !headers_sent()
664    )
[1649]665  {
666    redirect_http($url);
667  }
668  else
669  {
670    redirect_html($url, $msg, $refresh_time);
671  }
672}
673
674/**
[507]675 * returns $_SERVER['QUERY_STRING'] whitout keys given in parameters
676 *
677 * @param array $rejects
[2089]678 * @param boolean $escape - if true escape & to &amp; (for html)
[507]679 * @returns string
680 */
[2089]681function get_query_string_diff($rejects=array(), $escape=true)
[507]682{
683  $query_string = '';
[1086]684
[507]685  $str = $_SERVER['QUERY_STRING'];
686  parse_str($str, $vars);
[1086]687
[507]688  $is_first = true;
689  foreach ($vars as $key => $value)
690  {
691    if (!in_array($key, $rejects))
692    {
[2089]693      $query_string.= $is_first ? '?' : ($escape ? '&amp;' : '&' );
[764]694      $is_first = false;
[507]695      $query_string.= $key.'='.$value;
696    }
697  }
698
699  return $query_string;
700}
[512]701
[1020]702function url_is_remote($url)
703{
[1766]704  if ( strncmp($url, 'http://', 7)==0
705    or strncmp($url, 'https://', 8)==0 )
[1020]706  {
707    return true;
708  }
709  return false;
710}
711
[512]712/**
[1048]713 * returns available template/theme
[512]714 */
[1376]715function get_pwg_themes()
[512]716{
[2313]717  global $conf;
[960]718  $themes = array();
[579]719
[1376]720  $template_dir = PHPWG_ROOT_PATH.'template';
[1086]721
[1048]722  foreach (get_dirs($template_dir) as $template)
[960]723  {
[1048]724    foreach (get_dirs($template_dir.'/'.$template.'/theme') as $theme)
[960]725    {
[2313]726      if ( ($template.'/'.$theme) != $conf['admin_layout'] )
[960]727      array_push($themes, $template.'/'.$theme);
728    }
729  }
730
731  return $themes;
732}
733
[1596]734/* Returns the PATH to the thumbnail to be displayed. If the element does not
735 * have a thumbnail, the default mime image path is returned. The PATH can be
736 * used in the php script, but not sent to the browser.
737 * @param array element_info assoc array containing element info from db
738 * at least 'path', 'tn_ext' and 'id' should be present
739 */
740function get_thumbnail_path($element_info)
741{
742  $path = get_thumbnail_location($element_info);
743  if ( !url_is_remote($path) )
[579]744  {
[1596]745    $path = PHPWG_ROOT_PATH.$path;
746  }
747  return $path;
748}
749
750/* Returns the URL of the thumbnail to be displayed. If the element does not
751 * have a thumbnail, the default mime image url is returned. The URL can be
752 * sent to the browser, but not used in the php script.
753 * @param array element_info assoc array containing element info from db
754 * at least 'path', 'tn_ext' and 'id' should be present
755 */
756function get_thumbnail_url($element_info)
757{
758  $path = get_thumbnail_location($element_info);
759  if ( !url_is_remote($path) )
760  {
[2026]761    $path = embellish_url(get_root_url().$path);
[1596]762  }
[2026]763
[1596]764  // plugins want another url ?
765  $path = trigger_event('get_thumbnail_url', $path, $element_info);
766  return $path;
767}
768
769/* returns the relative path of the thumnail with regards to to the root
[2339]770of piwigo (not the current page!).This function is not intended to be
[1596]771called directly from code.*/
772function get_thumbnail_location($element_info)
773{
774  global $conf;
775  if ( !empty( $element_info['tn_ext'] ) )
776  {
777    $path = substr_replace(
778      get_filename_wo_extension($element_info['path']),
[3720]779      '/'.$conf['dir_thumbnail'].'/'.$conf['prefix_thumbnail'],
[1596]780      strrpos($element_info['path'],'/'),
[1082]781      1
782      );
[1596]783    $path.= '.'.$element_info['tn_ext'];
[579]784  }
785  else
786  {
[1596]787    $path = get_themeconf('mime_icon_dir')
788        .strtolower(get_extension($element_info['path'])).'.png';
[579]789  }
[1086]790
[1596]791  // plugins want another location ?
792  $path = trigger_event( 'get_thumbnail_location', $path, $element_info);
793  return $path;
[579]794}
[672]795
[1868]796/* returns the title of the thumnail */
797function get_thumbnail_title($element_info)
798{
799  // message in title for the thumbnail
800  if (isset($element_info['file']))
801  {
802    $thumbnail_title = $element_info['file'];
803  }
804  else
805  {
806    $thumbnail_title = '';
807  }
[2089]808
[1868]809  if (!empty($element_info['filesize']))
810  {
[3136]811    $thumbnail_title .= ' : '.sprintf(l10n('%d Kb'), $element_info['filesize']);
[1868]812  }
[1596]813
[1868]814  return $thumbnail_title;
815}
816
[755]817/**
[764]818 * fill the current user caddie with given elements, if not already in
819 * caddie
820 *
821 * @param array elements_id
822 */
823function fill_caddie($elements_id)
824{
825  global $user;
[1086]826
[764]827  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
[1086]828
[764]829  $query = '
830SELECT element_id
831  FROM '.CADDIE_TABLE.'
832  WHERE user_id = '.$user['id'].'
833;';
834  $in_caddie = array_from_query($query, 'element_id');
835
836  $caddiables = array_diff($elements_id, $in_caddie);
837
838  $datas = array();
839
840  foreach ($caddiables as $caddiable)
841  {
842    array_push($datas, array('element_id' => $caddiable,
843                             'user_id' => $user['id']));
844  }
845
846  if (count($caddiables) > 0)
847  {
848    mass_inserts(CADDIE_TABLE, array('element_id','user_id'), $datas);
849  }
850}
[793]851
852/**
853 * returns the element name from its filename
854 *
855 * @param string filename
856 * @return string name
857 */
858function get_name_from_file($filename)
859{
860  return str_replace('_',' ',get_filename_wo_extension($filename));
861}
862
863/**
864 * returns the corresponding value from $lang if existing. Else, the key is
865 * returned
866 *
867 * @param string key
868 * @return string
869 */
[5021]870function l10n($key, $textdomain='messages')
[793]871{
[5021]872  global $user;
[793]873
[5021]874  if (empty($user['language']))
[808]875  {
[5021]876    $locale = $GLOBALS['language'];
877  } 
878  else 
879  {
880    $locale = $user['language'];
[808]881  }
[1086]882
[5021]883  T_setlocale(LC_ALL, $locale.'.UTF-8');
884
885  // Specify location of translation tables
886  T_bindtextdomain($textdomain, "./language");
887
888  // Choose domain
889  T_textdomain($textdomain);
890 
891  return T_gettext($key);
[793]892}
[960]893
894/**
[1637]895 * returns the prinft value for strings including %d
896 * return is concorded with decimal value (singular, plural)
897 *
898 * @param singular string key
899 * @param plural string key
900 * @param decimal value
901 * @return string
902 */
[5021]903function l10n_dec($singular_fmt_key, $plural_fmt_key, 
904                  $decimal, $textdomain='messages')
[1637]905{
[5021]906  global $user;
[1864]907
[5021]908  if (empty($user['language']))
909  {
910    $locale = $GLOBALS['language'];
911  } 
912  else 
913  {
914    $locale = $user['language'];
915  }
916
917  T_setlocale(LC_ALL, $locale.'.UTF-8');
918
919  // Specify location of translation tables
920  T_bindtextdomain($textdomain, "./language");
921
922  // Choose domain
923  T_textdomain($textdomain);
924
925  return sprintf(T_ngettext($singular_fmt_key, 
926                            $plural_fmt_key, 
927                            $decimal),
928                 $decimal
929                 );
[1637]930}
[5021]931
[1908]932/*
933 * returns a single element to use with l10n_args
934 *
935 * @param string key: translation key
936 * @param array/string/../number args:
937 *   arguments to use on sprintf($key, args)
938 *   if args is a array, each values are used on sprintf
939 * @return string
940 */
941function get_l10n_args($key, $args)
942{
943  if (is_array($args))
944  {
945    $key_arg = array_merge(array($key), $args);
946  }
947  else
948  {
949    $key_arg = array($key,  $args);
950  }
951  return array('key_args' => $key_arg);
952}
[1637]953
[1908]954/*
955 * returns a string with formated with l10n_args elements
956 *
957 * @param element/array $key_args: element or array of l10n_args elements
[2089]958 * @param $sep: if $key_args is array,
[1908]959 *   separator is used when translated l10n_args elements are concated
960 * @return string
961 */
962function l10n_args($key_args, $sep = "\n")
963{
964  if (is_array($key_args))
965  {
966    foreach ($key_args as $key => $element)
967    {
968      if (isset($result))
969      {
970        $result .= $sep;
971      }
972      else
973      {
974        $result = '';
975      }
976
977      if ($key === 'key_args')
978      {
979        array_unshift($element, l10n(array_shift($element)));
980        $result .= call_user_func_array('sprintf', $element);
981      }
982      else
983      {
984        $result .= l10n_args($element, $sep);
985      }
986    }
987  }
988  else
989  {
[2502]990    fatal_error('l10n_args: Invalid arguments');
[1908]991  }
992
993  return $result;
994}
995
[1637]996/**
[1008]997 * returns the corresponding value from $themeconf if existing. Else, the
998 * key is returned
[960]999 *
1000 * @param string key
1001 * @return string
1002 */
1003function get_themeconf($key)
1004{
[1568]1005  global $template;
[960]1006
[1568]1007  return $template->get_themeconf($key);
[960]1008}
[1008]1009
1010/**
[1021]1011 * Returns webmaster mail address depending on $conf['webmaster_id']
1012 *
1013 * @return string
1014 */
1015function get_webmaster_mail_address()
1016{
1017  global $conf;
1018
1019  $query = '
1020SELECT '.$conf['user_fields']['email'].'
1021  FROM '.USERS_TABLE.'
1022  WHERE '.$conf['user_fields']['id'].' = '.$conf['webmaster_id'].'
1023;';
[4325]1024  list($email) = pwg_db_fetch_row(pwg_query($query));
[1021]1025
1026  return $email;
1027}
[1027]1028
1029/**
[1284]1030 * Add configuration parameters from database to global $conf array
1031 *
1032 * @return void
1033 */
[1748]1034function load_conf_from_db($condition = '')
[1284]1035{
1036  global $conf;
[1565]1037
[1284]1038  $query = '
[1748]1039SELECT param, value
[1284]1040 FROM '.CONFIG_TABLE.'
[1748]1041 '.(!empty($condition) ? 'WHERE '.$condition : '').'
[1284]1042;';
1043  $result = pwg_query($query);
1044
[4325]1045  if ((pwg_db_num_rows($result) == 0) and !empty($condition))
[1284]1046  {
[2502]1047    fatal_error('No configuration data');
[1284]1048  }
1049
[4325]1050  while ($row = pwg_db_fetch_assoc($result))
[1284]1051  {
1052    $conf[ $row['param'] ] = isset($row['value']) ? $row['value'] : '';
[1565]1053
[1284]1054    // If the field is true or false, the variable is transformed into a
1055    // boolean value.
1056    if ($conf[$row['param']] == 'true' or $conf[$row['param']] == 'false')
1057    {
1058      $conf[ $row['param'] ] = get_boolean($conf[ $row['param'] ]);
1059    }
1060  }
1061}
[1687]1062
1063/**
[1727]1064 * Prepends and appends a string at each value of the given array.
1065 *
1066 * @param array
1067 * @param string prefix to each array values
1068 * @param string suffix to each array values
1069 */
1070function prepend_append_array_items($array, $prepend_str, $append_str)
1071{
1072  array_walk(
1073    $array,
1074    create_function('&$s', '$s = "'.$prepend_str.'".$s."'.$append_str.'";')
1075    );
1076
1077  return $array;
1078}
1079
1080/**
1081 * creates an hashed based on a query, this function is a very common
1082 * pattern used here. Among the selected columns fetched, choose one to be
1083 * the key, another one to be the value.
1084 *
1085 * @param string $query
1086 * @param string $keyname
1087 * @param string $valuename
1088 * @return array
1089 */
1090function simple_hash_from_query($query, $keyname, $valuename)
1091{
1092  $array = array();
1093
1094  $result = pwg_query($query);
[4325]1095  while ($row = pwg_db_fetch_assoc($result))
[1727]1096  {
1097    $array[ $row[$keyname] ] = $row[$valuename];
1098  }
1099
1100  return $array;
1101}
1102
1103/**
[1866]1104 * creates an hashed based on a query, this function is a very common
1105 * pattern used here. The key is given as parameter, the value is an associative
1106 * array.
1107 *
1108 * @param string $query
1109 * @param string $keyname
1110 * @return array
1111 */
1112function hash_from_query($query, $keyname)
1113{
1114  $array = array();
1115  $result = pwg_query($query);
[4325]1116  while ($row = pwg_db_fetch_assoc($result))
[1866]1117  {
1118    $array[ $row[$keyname] ] = $row;
1119  }
1120  return $array;
1121}
1122
1123/**
[1687]1124 * Return basename of the current script
[1690]1125 * Lower case convertion is applied on return value
1126 * Return value is without file extention ".php"
[1687]1127 *
1128 * @param void
1129 *
1130 * @return script basename
1131 */
1132function script_basename()
1133{
[2071]1134  global $conf;
1135
1136  foreach (array('SCRIPT_NAME', 'SCRIPT_FILENAME', 'PHP_SELF') as $value)
[1687]1137  {
[3136]1138    if (!empty($_SERVER[$value]))
[2071]1139    {
1140      $filename = strtolower($_SERVER[$value]);
[3136]1141      if ($conf['php_extension_in_urls'] and get_extension($filename)!=='php')
1142        continue;
1143      $basename = basename($filename, '.php');
1144      if (!empty($basename))
[2071]1145      {
1146        return $basename;
1147      }
1148    }
[1687]1149  }
[2071]1150  return '';
[1687]1151}
1152
[1722]1153/**
1154 * Return value for the current page define on $conf['filter_pages']
1155 * Îf value is not defined, default value are returned
1156 *
1157 * @param value name
1158 *
1159 * @return filter page value
1160 */
1161function get_filter_page_value($value_name)
1162{
1163  global $conf;
1164
1165  $page_name = script_basename();
1166
1167  if (isset($conf['filter_pages'][$page_name][$value_name]))
1168  {
1169    return $conf['filter_pages'][$page_name][$value_name];
1170  }
1171  else if (isset($conf['filter_pages']['default'][$value_name]))
1172  {
1173    return $conf['filter_pages']['default'][$value_name];
1174  }
1175  else
1176  {
1177    return null;
1178  }
1179}
1180
[2126]1181/**
1182 * returns the character set of data sent to browsers / received from forms
1183 */
1184function get_pwg_charset()
1185{
[2790]1186  defined('PWG_CHARSET') or fatal_error('PWG_CHARSET undefined');
[2127]1187  return PWG_CHARSET;
[2126]1188}
1189
1190/**
1191 * includes a language file or returns the content of a language file
1192 * availability of the file
1193 *
1194 * in descending order of preference:
1195 *   param language, user language, default language
[2339]1196 * Piwigo default language.
[2126]1197 *
1198 * @param string filename
1199 * @param string dirname
[2479]1200 * @param mixed options can contain
1201 *     language - language to load (if empty uses user language)
1202 *     return - if true the file content is returned otherwise the file is evaluated as php
1203 *     target_charset -
1204 *     no_fallback - the language must be respected
1205 * @return boolean success status or a string if options['return'] is true
[2126]1206 */
[2479]1207function load_language($filename, $dirname = '',
1208    $options = array() )
[2126]1209{
[2127]1210  global $user;
1211
[2479]1212  if (! @$options['return'] )
[2127]1213  {
1214    $filename .= '.php'; //MAYBE to do .. load .po and .mo localization files
1215  }
1216  if (empty($dirname))
1217  {
1218    $dirname = PHPWG_ROOT_PATH;
1219  }
1220  $dirname .= 'language/';
1221
1222  $languages = array();
[2479]1223  if ( !empty($options['language']) )
[2127]1224  {
[2479]1225    $languages[] = $options['language'];
[2127]1226  }
1227  if ( !empty($user['language']) )
1228  {
1229    $languages[] = $user['language'];
1230  }
[2479]1231  if ( ! @$options['no_fallback'] )
[2132]1232  {
[2479]1233    if ( defined('PHPWG_INSTALLED') )
1234    {
1235      $languages[] = get_default_language();
1236    }
1237    $languages[] = PHPWG_DEFAULT_LANGUAGE;
[2132]1238  }
[2479]1239
[2127]1240  $languages = array_unique($languages);
1241
[2479]1242  if ( empty($options['target_charset']) )
[2127]1243  {
1244    $target_charset = get_pwg_charset();
1245  }
[2479]1246  else
1247  {
1248    $target_charset = $options['target_charset'];
1249  }
[2127]1250  $target_charset = strtolower($target_charset);
1251  $source_charset = '';
1252  $source_file    = '';
1253  foreach ($languages as $language)
1254  {
1255    $dir = $dirname.$language;
1256
[2790]1257    if ($target_charset!='utf-8')
[2127]1258    {
[2790]1259      // exact charset match - no conversion required
1260      $f = $dir.'.'.$target_charset.'/'.$filename;
1261      if (file_exists($f))
1262      {
1263        $source_file = $f;
1264        break;
1265      }
[2127]1266    }
1267
[2134]1268    // UTF-8 ?
[2127]1269    $f = $dir.'/'.$filename;
1270    if (file_exists($f))
1271    {
[2134]1272      $source_charset = 'utf-8';
[2127]1273      $source_file = $f;
1274      break;
1275    }
1276  }
1277
1278  if ( !empty($source_file) )
1279  {
[2479]1280    if (! @$options['return'] )
[2127]1281    {
1282      @include($source_file);
1283      $load_lang = @$lang;
1284      $load_lang_info = @$lang_info;
1285
1286      global $lang, $lang_info;
1287      if ( !isset($lang) ) $lang=array();
1288      if ( !isset($lang_info) ) $lang_info=array();
1289
1290      if ( !empty($source_charset) and $source_charset!=$target_charset)
1291      {
1292        if ( is_array($load_lang) )
1293        {
1294          foreach ($load_lang as $k => $v)
1295          {
1296            if ( is_array($v) )
1297            {
1298              $func = create_function('$v', 'return convert_charset($v, "'.$source_charset.'","'.$target_charset.'");' );
1299              $lang[$k] = array_map($func, $v);
1300            }
1301            else
1302              $lang[$k] = convert_charset($v, $source_charset, $target_charset);
1303          }
1304        }
1305        if ( is_array($load_lang_info) )
1306        {
1307          foreach ($load_lang_info as $k => $v)
1308          {
1309            $lang_info[$k] = convert_charset($v, $source_charset, $target_charset);
1310          }
1311        }
1312      }
1313      else
1314      {
[2134]1315        $lang = array_merge( $lang, (array)$load_lang );
1316        $lang_info = array_merge( $lang_info, (array)$load_lang_info );
[2127]1317      }
1318      return true;
1319    }
1320    else
1321    {
1322      $content = @file_get_contents($source_file);
1323      if ( !empty($source_charset) and $source_charset!=$target_charset)
1324      {
1325        $content = convert_charset($content, $source_charset, $target_charset);
1326      }
1327      return $content;
1328    }
1329  }
1330  return false;
[2126]1331}
1332
[2127]1333/**
1334 * converts a string from a character set to another character set
1335 * @param string str the string to be converted
1336 * @param string source_charset the character set in which the string is encoded
1337 * @param string dest_charset the destination character set
1338 */
1339function convert_charset($str, $source_charset, $dest_charset)
1340{
1341  if ($source_charset==$dest_charset)
1342    return $str;
1343  if ($source_charset=='iso-8859-1' and $dest_charset=='utf-8')
1344  {
1345    return utf8_encode($str);
1346  }
1347  if ($source_charset=='utf-8' and $dest_charset=='iso-8859-1')
1348  {
1349    return utf8_decode($str);
1350  }
1351  if (function_exists('iconv'))
1352  {
1353    return iconv($source_charset, $dest_charset, $str);
1354  }
1355  if (function_exists('mb_convert_encoding'))
1356  {
1357    return mb_convert_encoding( $str, $dest_charset, $source_charset );
1358  }
1359  return $str; //???
1360}
[2917]1361
1362/**
1363 * makes sure a index.htm protects the directory from browser file listing
1364 *
1365 * @param string dir directory
1366 */
1367function secure_directory($dir)
1368{
1369  $file = $dir.'/index.htm';
1370  if (!file_exists($file))
1371  {
1372    @file_put_contents($file, 'Not allowed!');
1373  }
1374}
[3145]1375
1376/**
1377 * returns a "secret key" that is to be sent back when a user enters a comment
1378 *
1379 * @param int image_id
1380 */
1381function get_comment_post_key($image_id)
1382{
1383  global $conf;
1384
1385  $time = time();
1386
1387  return sprintf(
1388    '%s:%s',
1389    $time,
1390    hash_hmac(
1391      'md5',
1392      $time.':'.$image_id,
1393      $conf['secret_key']
1394      )
1395    );
1396}
[3172]1397
1398/**
1399 * return an array which will be sent to template to display navigation bar
1400 */
1401function create_navigation_bar($url, $nb_element, $start, $nb_element_page, $clean_url = false)
1402{
1403  global $conf;
1404
[3173]1405  $navbar = array();
[3172]1406  $pages_around = $conf['paginate_pages_around'];
1407  $start_str = $clean_url ? '/start-' : (strpos($url, '?')===false ? '?':'&amp;').'start=';
1408
1409  if (!isset($start) or !is_numeric($start) or (is_numeric($start) and $start < 0))
1410  {
1411    $start = 0;
1412  }
1413
1414  // navigation bar useful only if more than one page to display !
1415  if ($nb_element > $nb_element_page)
1416  {
1417    $cur_page = ceil($start / $nb_element_page) + 1;
1418    $maximum = ceil($nb_element / $nb_element_page);
[3173]1419    $previous = $start - $nb_element_page;
1420    $next = $start + $nb_element_page;
1421    $last = ($maximum - 1) * $nb_element_page;
[3172]1422
1423    $navbar['CURRENT_PAGE'] = $cur_page;
1424
[3173]1425    // link to first page and previous page?
[3172]1426    if ($cur_page != 1)
1427    {
1428      $navbar['URL_FIRST'] = $url;
1429      $navbar['URL_PREV'] = $url.($previous > 0 ? $start_str.$previous : '');
1430    }
[3173]1431    // link on next page and last page?
1432    if ($cur_page != $maximum)
[3172]1433    {
1434      $navbar['URL_NEXT'] = $url.$start_str.$next;
[3173]1435      $navbar['URL_LAST'] = $url.$start_str.$last;
[3172]1436    }
1437
1438    // pages to display
1439    $navbar['pages'] = array();
1440    $navbar['pages'][1] = $url;
[3173]1441    $navbar['pages'][$maximum] = $url.$start_str.$last;
[3172]1442
[3173]1443    for ($i = max($cur_page - $pages_around , 2), $stop = min($cur_page + $pages_around + 1, $maximum);
1444         $i < $stop; $i++)
[3172]1445    {
[3173]1446      $navbar['pages'][$i] = $url.$start_str.(($i - 1) * $nb_element_page);
[3172]1447    }
1448    ksort($navbar['pages']);
1449  }
1450  return $navbar;
1451}
[3188]1452
1453/**
1454 * return an array which will be sent to template to display recent icon
1455 */
1456function get_icon($date, $is_child_date = false)
1457{
1458  global $cache, $user;
1459
1460  if (empty($date))
1461  {
1462    return false;
1463  }
1464
1465  if (!isset($cache['get_icon']['title']))
1466  {
1467    $cache['get_icon']['title'] = sprintf(
[5021]1468      l10n('images posted during the last %d days'),
[3188]1469      $user['recent_period']
1470      );
1471  }
1472
1473  $icon = array(
1474    'TITLE' => $cache['get_icon']['title'],
1475    'IS_CHILD_DATE' => $is_child_date,
1476    );
1477
1478  if (isset($cache['get_icon'][$date]))
1479  {
1480    return $cache['get_icon'][$date] ? $icon : array();
1481  }
1482
1483  if (!isset($cache['get_icon']['sql_recent_date']))
1484  {
1485    // Use MySql date in order to standardize all recent "actions/queries"
[4367]1486    $cache['get_icon']['sql_recent_date'] = pwg_db_get_recent_period($user['recent_period']);
[3188]1487  }
1488
1489  $cache['get_icon'][$date] = $date > $cache['get_icon']['sql_recent_date'];
1490
1491  return $cache['get_icon'][$date] ? $icon : array();
1492}
[2126]1493?>
Note: See TracBrowser for help on using the repository browser.