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

Last change on this file since 28171 was 28171, checked in by flop25, 10 years ago

lang key with an empty value are not displayed

  • Property svn:eol-style set to LF
File size: 47.9 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\___
26 */
27
28include_once( PHPWG_ROOT_PATH .'include/functions_plugins.inc.php' );
29include_once( PHPWG_ROOT_PATH .'include/functions_user.inc.php' );
30include_once( PHPWG_ROOT_PATH .'include/functions_cookie.inc.php' );
31include_once( PHPWG_ROOT_PATH .'include/functions_session.inc.php' );
32include_once( PHPWG_ROOT_PATH .'include/functions_category.inc.php' );
33include_once( PHPWG_ROOT_PATH .'include/functions_html.inc.php' );
34include_once( PHPWG_ROOT_PATH .'include/functions_tag.inc.php' );
35include_once( PHPWG_ROOT_PATH .'include/functions_url.inc.php' );
36include_once( PHPWG_ROOT_PATH .'include/derivative_params.inc.php');
37include_once( PHPWG_ROOT_PATH .'include/derivative_std_params.inc.php');
38include_once( PHPWG_ROOT_PATH .'include/derivative.inc.php');
39include_once( PHPWG_ROOT_PATH .'include/template.class.php');
40
41
42/**
43 * returns the current microsecond since Unix epoch
44 *
45 * @return int
46 */
47function micro_seconds()
48{
49  $t1 = explode(' ', microtime());
50  $t2 = explode('.', $t1[0]);
51  $t2 = $t1[1].substr($t2[1], 0, 6);
52  return $t2;
53}
54
55/**
56 * returns a float value coresponding to the number of seconds since
57 * the unix epoch (1st January 1970) and the microseconds are precised
58 * e.g. 1052343429.89276600
59 *
60 * @return float
61 */
62function get_moment()
63{
64  return microtime(true);
65}
66
67/**
68 * returns the number of seconds (with 3 decimals precision)
69 * between the start time and the end time given
70 *
71 * @param float $start
72 * @param float $end
73 * @return string "$TIME s"
74 */
75function get_elapsed_time($start, $end)
76{
77  return number_format($end - $start, 3, '.', ' ').' s';
78}
79
80/**
81 * returns the part of the string after the last "."
82 *
83 * @param string $filename
84 * @return string
85 */
86function get_extension( $filename )
87{
88  return substr( strrchr( $filename, '.' ), 1, strlen ( $filename ) );
89}
90
91/**
92 * returns the part of the string before the last ".".
93 * get_filename_wo_extension( 'test.tar.gz' ) = 'test.tar'
94 *
95 * @param string $filename
96 * @return string
97 */
98function get_filename_wo_extension( $filename )
99{
100  $pos = strrpos( $filename, '.' );
101  return ($pos===false) ? $filename : substr( $filename, 0, $pos);
102}
103
104/** no option for mkgetdir() */
105define('MKGETDIR_NONE', 0);
106/** sets mkgetdir() recursive */
107define('MKGETDIR_RECURSIVE', 1);
108/** sets mkgetdir() exit script on error */
109define('MKGETDIR_DIE_ON_ERROR', 2);
110/** sets mkgetdir() add a index.htm file */
111define('MKGETDIR_PROTECT_INDEX', 4);
112/** sets mkgetdir() add a .htaccess file*/
113define('MKGETDIR_PROTECT_HTACCESS', 8);
114/** default options for mkgetdir() = MKGETDIR_RECURSIVE | MKGETDIR_DIE_ON_ERROR | MKGETDIR_PROTECT_INDEX */
115define('MKGETDIR_DEFAULT', MKGETDIR_RECURSIVE | MKGETDIR_DIE_ON_ERROR | MKGETDIR_PROTECT_INDEX);
116
117/**
118 * creates directory if not exists and ensures that directory is writable
119 *
120 * @param string $dir
121 * @param int $flags combination of MKGETDIR_xxx
122 * @return bool
123 */
124function mkgetdir($dir, $flags=MKGETDIR_DEFAULT)
125{
126  if ( !is_dir($dir) )
127  {
128    global $conf;
129    if (substr(PHP_OS, 0, 3) == 'WIN')
130    {
131      $dir = str_replace('/', DIRECTORY_SEPARATOR, $dir);
132    }
133    $umask = umask(0);
134    $mkd = @mkdir($dir, $conf['chmod_value'], ($flags&MKGETDIR_RECURSIVE) ? true:false );
135    umask($umask);
136    if ($mkd==false)
137    {
138      !($flags&MKGETDIR_DIE_ON_ERROR) or fatal_error( "$dir ".l10n('no write access'));
139      return false;
140    }
141    if( $flags&MKGETDIR_PROTECT_HTACCESS )
142    {
143      $file = $dir.'/.htaccess';
144      file_exists($file) or @file_put_contents( $file, 'deny from all' );
145    }
146    if( $flags&MKGETDIR_PROTECT_INDEX )
147    {
148      $file = $dir.'/index.htm';
149      file_exists($file) or @file_put_contents( $file, 'Not allowed!' );
150    }
151  }
152  if ( !is_writable($dir) )
153  {
154    !($flags&MKGETDIR_DIE_ON_ERROR) or fatal_error( "$dir ".l10n('no write access'));
155    return false;
156  }
157  return true;
158}
159
160/**
161 * finds out if a string is in ASCII, UTF-8 or other encoding
162 *
163 * @param string $str
164 * @return int *0* if _$str_ is ASCII, *1* if UTF-8, *-1* otherwise
165 */
166function qualify_utf8($Str)
167{
168  $ret = 0;
169  for ($i=0; $i<strlen($Str); $i++)
170  {
171    if (ord($Str[$i]) < 0x80) continue; # 0bbbbbbb
172    $ret = 1;
173    if ((ord($Str[$i]) & 0xE0) == 0xC0) $n=1; # 110bbbbb
174    elseif ((ord($Str[$i]) & 0xF0) == 0xE0) $n=2; # 1110bbbb
175    elseif ((ord($Str[$i]) & 0xF8) == 0xF0) $n=3; # 11110bbb
176    elseif ((ord($Str[$i]) & 0xFC) == 0xF8) $n=4; # 111110bb
177    elseif ((ord($Str[$i]) & 0xFE) == 0xFC) $n=5; # 1111110b
178    else return -1; # Does not match any model
179    for ($j=0; $j<$n; $j++)
180    { # n bytes matching 10bbbbbb follow ?
181      if ((++$i == strlen($Str)) || ((ord($Str[$i]) & 0xC0) != 0x80))
182        return -1;
183    }
184  }
185  return $ret;
186}
187
188/**
189 * Remove accents from a UTF-8 or ISO-8859-1 string (from wordpress)
190 *
191 * @param string $string
192 * @return string
193 */
194function remove_accents($string)
195{
196  $utf = qualify_utf8($string);
197  if ( $utf == 0 )
198  {
199    return $string; // ascii
200  }
201
202  if ( $utf > 0 )
203  {
204    $chars = array(
205    // Decompositions for Latin-1 Supplement
206    "\xc3\x80"=>'A', "\xc3\x81"=>'A',
207    "\xc3\x82"=>'A', "\xc3\x83"=>'A',
208    "\xc3\x84"=>'A', "\xc3\x85"=>'A',
209    "\xc3\x87"=>'C', "\xc3\x88"=>'E',
210    "\xc3\x89"=>'E', "\xc3\x8a"=>'E',
211    "\xc3\x8b"=>'E', "\xc3\x8c"=>'I',
212    "\xc3\x8d"=>'I', "\xc3\x8e"=>'I',
213    "\xc3\x8f"=>'I', "\xc3\x91"=>'N',
214    "\xc3\x92"=>'O', "\xc3\x93"=>'O',
215    "\xc3\x94"=>'O', "\xc3\x95"=>'O',
216    "\xc3\x96"=>'O', "\xc3\x99"=>'U',
217    "\xc3\x9a"=>'U', "\xc3\x9b"=>'U',
218    "\xc3\x9c"=>'U', "\xc3\x9d"=>'Y',
219    "\xc3\x9f"=>'s', "\xc3\xa0"=>'a',
220    "\xc3\xa1"=>'a', "\xc3\xa2"=>'a',
221    "\xc3\xa3"=>'a', "\xc3\xa4"=>'a',
222    "\xc3\xa5"=>'a', "\xc3\xa7"=>'c',
223    "\xc3\xa8"=>'e', "\xc3\xa9"=>'e',
224    "\xc3\xaa"=>'e', "\xc3\xab"=>'e',
225    "\xc3\xac"=>'i', "\xc3\xad"=>'i',
226    "\xc3\xae"=>'i', "\xc3\xaf"=>'i',
227    "\xc3\xb1"=>'n', "\xc3\xb2"=>'o',
228    "\xc3\xb3"=>'o', "\xc3\xb4"=>'o',
229    "\xc3\xb5"=>'o', "\xc3\xb6"=>'o',
230    "\xc3\xb9"=>'u', "\xc3\xba"=>'u',
231    "\xc3\xbb"=>'u', "\xc3\xbc"=>'u',
232    "\xc3\xbd"=>'y', "\xc3\xbf"=>'y',
233    // Decompositions for Latin Extended-A
234    "\xc4\x80"=>'A', "\xc4\x81"=>'a',
235    "\xc4\x82"=>'A', "\xc4\x83"=>'a',
236    "\xc4\x84"=>'A', "\xc4\x85"=>'a',
237    "\xc4\x86"=>'C', "\xc4\x87"=>'c',
238    "\xc4\x88"=>'C', "\xc4\x89"=>'c',
239    "\xc4\x8a"=>'C', "\xc4\x8b"=>'c',
240    "\xc4\x8c"=>'C', "\xc4\x8d"=>'c',
241    "\xc4\x8e"=>'D', "\xc4\x8f"=>'d',
242    "\xc4\x90"=>'D', "\xc4\x91"=>'d',
243    "\xc4\x92"=>'E', "\xc4\x93"=>'e',
244    "\xc4\x94"=>'E', "\xc4\x95"=>'e',
245    "\xc4\x96"=>'E', "\xc4\x97"=>'e',
246    "\xc4\x98"=>'E', "\xc4\x99"=>'e',
247    "\xc4\x9a"=>'E', "\xc4\x9b"=>'e',
248    "\xc4\x9c"=>'G', "\xc4\x9d"=>'g',
249    "\xc4\x9e"=>'G', "\xc4\x9f"=>'g',
250    "\xc4\xa0"=>'G', "\xc4\xa1"=>'g',
251    "\xc4\xa2"=>'G', "\xc4\xa3"=>'g',
252    "\xc4\xa4"=>'H', "\xc4\xa5"=>'h',
253    "\xc4\xa6"=>'H', "\xc4\xa7"=>'h',
254    "\xc4\xa8"=>'I', "\xc4\xa9"=>'i',
255    "\xc4\xaa"=>'I', "\xc4\xab"=>'i',
256    "\xc4\xac"=>'I', "\xc4\xad"=>'i',
257    "\xc4\xae"=>'I', "\xc4\xaf"=>'i',
258    "\xc4\xb0"=>'I', "\xc4\xb1"=>'i',
259    "\xc4\xb2"=>'IJ', "\xc4\xb3"=>'ij',
260    "\xc4\xb4"=>'J', "\xc4\xb5"=>'j',
261    "\xc4\xb6"=>'K', "\xc4\xb7"=>'k',
262    "\xc4\xb8"=>'k', "\xc4\xb9"=>'L',
263    "\xc4\xba"=>'l', "\xc4\xbb"=>'L',
264    "\xc4\xbc"=>'l', "\xc4\xbd"=>'L',
265    "\xc4\xbe"=>'l', "\xc4\xbf"=>'L',
266    "\xc5\x80"=>'l', "\xc5\x81"=>'L',
267    "\xc5\x82"=>'l', "\xc5\x83"=>'N',
268    "\xc5\x84"=>'n', "\xc5\x85"=>'N',
269    "\xc5\x86"=>'n', "\xc5\x87"=>'N',
270    "\xc5\x88"=>'n', "\xc5\x89"=>'N',
271    "\xc5\x8a"=>'n', "\xc5\x8b"=>'N',
272    "\xc5\x8c"=>'O', "\xc5\x8d"=>'o',
273    "\xc5\x8e"=>'O', "\xc5\x8f"=>'o',
274    "\xc5\x90"=>'O', "\xc5\x91"=>'o',
275    "\xc5\x92"=>'OE', "\xc5\x93"=>'oe',
276    "\xc5\x94"=>'R', "\xc5\x95"=>'r',
277    "\xc5\x96"=>'R', "\xc5\x97"=>'r',
278    "\xc5\x98"=>'R', "\xc5\x99"=>'r',
279    "\xc5\x9a"=>'S', "\xc5\x9b"=>'s',
280    "\xc5\x9c"=>'S', "\xc5\x9d"=>'s',
281    "\xc5\x9e"=>'S', "\xc5\x9f"=>'s',
282    "\xc5\xa0"=>'S', "\xc5\xa1"=>'s',
283    "\xc5\xa2"=>'T', "\xc5\xa3"=>'t',
284    "\xc5\xa4"=>'T', "\xc5\xa5"=>'t',
285    "\xc5\xa6"=>'T', "\xc5\xa7"=>'t',
286    "\xc5\xa8"=>'U', "\xc5\xa9"=>'u',
287    "\xc5\xaa"=>'U', "\xc5\xab"=>'u',
288    "\xc5\xac"=>'U', "\xc5\xad"=>'u',
289    "\xc5\xae"=>'U', "\xc5\xaf"=>'u',
290    "\xc5\xb0"=>'U', "\xc5\xb1"=>'u',
291    "\xc5\xb2"=>'U', "\xc5\xb3"=>'u',
292    "\xc5\xb4"=>'W', "\xc5\xb5"=>'w',
293    "\xc5\xb6"=>'Y', "\xc5\xb7"=>'y',
294    "\xc5\xb8"=>'Y', "\xc5\xb9"=>'Z',
295    "\xc5\xba"=>'z', "\xc5\xbb"=>'Z',
296    "\xc5\xbc"=>'z', "\xc5\xbd"=>'Z',
297    "\xc5\xbe"=>'z', "\xc5\xbf"=>'s',
298    // Decompositions for Latin Extended-B
299    "\xc8\x98"=>'S', "\xc8\x99"=>'s',
300    "\xc8\x9a"=>'T', "\xc8\x9b"=>'t',
301    // Euro Sign
302    "\xe2\x82\xac"=>'E',
303    // GBP (Pound) Sign
304    "\xc2\xa3"=>'');
305
306    $string = strtr($string, $chars);
307  }
308  else
309  {
310    // Assume ISO-8859-1 if not UTF-8
311    $chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158)
312      .chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194)
313      .chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202)
314      .chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210)
315      .chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218)
316      .chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227)
317      .chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235)
318      .chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243)
319      .chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251)
320      .chr(252).chr(253).chr(255);
321
322    $chars['out'] = "EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy";
323
324    $string = strtr($string, $chars['in'], $chars['out']);
325    $double_chars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254));
326    $double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th');
327    $string = str_replace($double_chars['in'], $double_chars['out'], $string);
328  }
329
330  return $string;
331}
332
333if (function_exists('mb_strtolower') && defined('PWG_CHARSET'))
334{
335  /**
336   * removes accents from a string and converts it to lower case
337   *
338   * @param string $term
339   * @return string
340   */
341  function transliterate($term)
342  {
343    return remove_accents( mb_strtolower($term, PWG_CHARSET) );
344  }
345}
346else
347{
348  /**
349   * @ignore
350   */
351  function transliterate($term)
352  {
353    return remove_accents( strtolower($term) );
354  }
355}
356
357/**
358 * simplify a string to insert it into an URL
359 *
360 * @param string $str
361 * @return string
362 */
363function str2url($str)
364{
365  $str = $safe = transliterate($str);
366  $str = preg_replace('/[^\x80-\xffa-z0-9_\s\'\:\/\[\],-]/','',$str);
367  $str = preg_replace('/[\s\'\:\/\[\],-]+/',' ',trim($str));
368  $res = str_replace(' ','_',$str);
369
370  if (empty($res))
371  {
372    $res = str_replace(' ','_', $safe);
373  }
374
375  return $res;
376}
377
378/**
379 * returns an array with a list of {language_code => language_name}
380 *
381 * @return string[]
382 */
383function get_languages()
384{
385  $query = '
386SELECT id, name
387  FROM '.LANGUAGES_TABLE.'
388  ORDER BY name ASC
389;';
390  $result = pwg_query($query);
391
392  $languages = array();
393  while ($row = pwg_db_fetch_assoc($result))
394  {
395    if (is_dir(PHPWG_ROOT_PATH.'language/'.$row['id']))
396    {
397      $languages[ $row['id'] ] = $row['name'];
398    }
399  }
400
401  return $languages;
402}
403
404/**
405 * log the visit into history table
406 *
407 * @param int $image_id
408 * @param string $image_type
409 * @return bool
410 */
411function pwg_log($image_id = null, $image_type = null)
412{
413  global $conf, $user, $page;
414
415  $do_log = $conf['log'];
416  if (is_admin())
417  {
418    $do_log = $conf['history_admin'];
419  }
420  if (is_a_guest())
421  {
422    $do_log = $conf['history_guest'];
423  }
424
425  $do_log = trigger_event('pwg_log_allowed', $do_log, $image_id, $image_type);
426
427  if (!$do_log)
428  {
429    return false;
430  }
431
432  $tags_string = null;
433  if ('tags'==@$page['section'])
434  {
435    $tags_string = implode(',', $page['tag_ids']);
436  }
437
438  $query = '
439INSERT INTO '.HISTORY_TABLE.'
440  (
441    date,
442    time,
443    user_id,
444    IP,
445    section,
446    category_id,
447    image_id,
448    image_type,
449    tag_ids
450  )
451  VALUES
452  (
453    CURRENT_DATE,
454    CURRENT_TIME,
455    '.$user['id'].',
456    \''.$_SERVER['REMOTE_ADDR'].'\',
457    '.(isset($page['section']) ? "'".$page['section']."'" : 'NULL').',
458    '.(isset($page['category']['id']) ? $page['category']['id'] : 'NULL').',
459    '.(isset($image_id) ? $image_id : 'NULL').',
460    '.(isset($image_type) ? "'".$image_type."'" : 'NULL').',
461    '.(isset($tags_string) ? "'".$tags_string."'" : 'NULL').'
462  )
463;';
464  pwg_query($query);
465
466  return true;
467}
468
469/**
470 * Computes the difference between two dates.
471 * returns a DateInterval object or a stdClass with the same attributes
472 * http://stephenharris.info/date-intervals-in-php-5-2
473 *
474 * @param DateTime $date1
475 * @param DateTime $date2
476 * @return DateInterval|stdClass
477 */
478function dateDiff($date1, $date2)
479{
480  if (version_compare(PHP_VERSION, '5.3.0') >= 0)
481  {
482    return $date1->diff($date2);
483  }
484
485  $diff = new stdClass();
486
487  //Make sure $date1 is ealier
488  $diff->invert = $date2 < $date1;
489  if ($diff->invert)
490  {
491    list($date1, $date2) = array($date2, $date1);
492  }
493
494  //Calculate R values
495  $R = ($date1 <= $date2 ? '+' : '-');
496  $r = ($date1 <= $date2 ? '' : '-');
497
498  //Calculate total days
499  $diff->days = round(abs($date1->format('U') - $date2->format('U'))/86400);
500
501  //A leap year work around - consistent with DateInterval
502  $leap_year = $date1->format('m-d') == '02-29';
503  if ($leap_year)
504  {
505    $date1->modify('-1 day');
506  }
507
508  //Years, months, days, hours
509  $periods = array('years'=>-1, 'months'=>-1, 'days'=>-1, 'hours'=>-1);
510
511  foreach ($periods as $period => &$i)
512  {
513    if ($period == 'days' && $leap_year)
514    {
515      $date1->modify('+1 day');
516    }
517
518    while ($date1 <= $date2 )
519    {
520      $date1->modify('+1 '.$period);
521      $i++;
522    }
523
524    //Reset date and record increments
525    $date1->modify('-1 '.$period);
526  }
527
528  list($diff->y, $diff->m, $diff->d, $diff->h) = array_values($periods);
529
530  //Minutes, seconds
531  $diff->s = round(abs($date1->format('U') - $date2->format('U')));
532  $diff->i = floor($diff->s/60);
533  $diff->s = $diff->s - $diff->i*60;
534
535  return $diff;
536}
537
538/**
539 * converts a string into a DateTime object
540 *
541 * @param int|string timestamp or datetime string
542 * @param string $format input format respecting date() syntax
543 * @return DateTime|false
544 */
545function str2DateTime($original, $format=null)
546{
547  if (empty($original))
548  {
549    return false;
550  }
551
552  if (!empty($format) && version_compare(PHP_VERSION, '5.3.0') >= 0)// from known date format
553  {
554    return DateTime::createFromFormat('!'.$format, $original); // ! char to reset fields to UNIX epoch
555  }
556  else
557  {
558    $t = trim($original, '0123456789');
559    if (empty($t)) // from timestamp
560    {
561      return new DateTime('@'.$original);
562    }
563    else // from unknown date format (assuming something like Y-m-d H:i:s)
564    {
565      $ymdhms = array();
566      $tok = strtok($original, '- :/');
567      while ($tok !== false)
568      {
569        $ymdhms[] = $tok;
570        $tok = strtok('- :/');
571      }
572
573      if (count($ymdhms)<3) return false;
574      if (!isset($ymdhms[3])) $ymdhms[3] = 0;
575      if (!isset($ymdhms[4])) $ymdhms[4] = 0;
576      if (!isset($ymdhms[5])) $ymdhms[5] = 0;
577
578      $date = new DateTime();
579      $date->setDate($ymdhms[0], $ymdhms[1], $ymdhms[2]);
580      $date->setTime($ymdhms[3], $ymdhms[4], $ymdhms[5]);
581      return $date;
582    }
583  }
584}
585
586/**
587 * returns a formatted and localized date for display
588 *
589 * @param int|string timestamp or datetime string
590 * @param bool $show_time
591 * @param bool $show_day_name
592 * @param string $format input format respecting date() syntax
593 * @return string
594 */
595function format_date($original, $show_time=false, $show_day_name=true, $format=null)
596{
597  global $lang;
598
599  $date = str2DateTime($original, $format);
600
601  if (!$date)
602  {
603    return l10n('N/A');
604  }
605
606  $print = '';
607  if ($show_day_name)
608  {
609    $print.= $lang['day'][ $date->format('w') ].' ';
610  }
611
612  $print.= $date->format('j');
613  $print.= ' '.$lang['month'][ $date->format('n') ];
614  $print.= ' '.$date->format('Y');
615
616  if ($show_time)
617  {
618    $temp = $date->format('H:i');
619    if ($temp != '00:00')
620    {
621      $print.= ' '.$temp;
622    }
623  }
624
625  return trim($print);
626}
627
628/**
629 * Works out the time since the given date
630 *
631 * @param int|string timestamp or datetime string
632 * @param string $stop year,month,week,day,hour,minute,second
633 * @param string $format input format respecting date() syntax
634 * @param bool $with_text append "ago" or "in the future"
635 * @param bool $with_weeks
636 * @return string
637 */
638function time_since($original, $stop='minute', $format=null, $with_text=true, $with_week=true)
639{
640  $date = str2DateTime($original, $format);
641
642  if (!$date)
643  {
644    return l10n('N/A');
645  }
646
647  $now = new DateTime();
648  $diff = dateDiff($now, $date);
649
650  $chunks = array(
651    'year' => $diff->y,
652    'month' => $diff->m,
653    'week' => 0,
654    'day' => $diff->d,
655    'hour' => $diff->h,
656    'minute' => $diff->i,
657    'second' => $diff->s,
658  );
659
660  // DateInterval does not contain the number of weeks
661  if ($with_week)
662  {
663    $chunks['week'] = (int)floor($chunks['day']/7);
664    $chunks['day'] = $chunks['day'] - $chunks['week']*7;
665  }
666
667  $j = array_search($stop, array_keys($chunks));
668
669  $print = ''; $i=0;
670  foreach ($chunks as $name => $value)
671  {
672    if ($value != 0)
673    {
674      $print.= ' '.l10n_dec('%d '.$name, '%d '.$name.'s', $value);
675    }
676    if (!empty($print) && $i >= $j)
677    {
678      break;
679    }
680    $i++;
681  }
682
683  $print = trim($print);
684
685  if ($with_text)
686  {
687    if ($diff->invert)
688    {
689      $print = l10n('%s ago', $print);
690    }
691    else
692    {
693      $print = l10n('%s in the future', $print);
694    }
695  }
696
697  return $print;
698}
699
700/**
701 * transform a date string from a format to another (MySQL to d/M/Y for instance)
702 *
703 * @param string $original
704 * @param string $format_in respecting date() syntax
705 * @param string $format_out respecting date() syntax
706 * @param string $default if _$original_ is empty
707 * @return string
708 */
709function transform_date($original, $format_in, $format_out, $default=null)
710{
711  if (empty($original)) return $default;
712  $date = str2DateTime($original, $format_in);
713  return $date->format($format_out);
714}
715
716/**
717 * append a variable to _$debug_ global
718 *
719 * @param string $string
720 */
721function pwg_debug( $string )
722{
723  global $debug,$t2,$page;
724
725  $now = explode( ' ', microtime() );
726  $now2 = explode( '.', $now[0] );
727  $now2 = $now[1].'.'.$now2[1];
728  $time = number_format( $now2 - $t2, 3, '.', ' ').' s';
729  $debug .= '<p>';
730  $debug.= '['.$time.', ';
731  $debug.= $page['count_queries'].' queries] : '.$string;
732  $debug.= "</p>\n";
733}
734
735/**
736 * Redirects to the given URL (HTTP method).
737 * once this function called, the execution doesn't go further
738 * (presence of an exit() instruction.
739 *
740 * @param string $url
741 * @return void
742 */
743function redirect_http( $url )
744{
745  if (ob_get_length () !== FALSE)
746  {
747    ob_clean();
748  }
749  // default url is on html format
750  $url = html_entity_decode($url);
751  header('Request-URI: '.$url);
752  header('Content-Location: '.$url);
753  header('Location: '.$url);
754  exit();
755}
756
757/**
758 * Redirects to the given URL (HTML method).
759 * once this function called, the execution doesn't go further
760 * (presence of an exit() instruction.
761 *
762 * @param string $url
763 * @param string $msg
764 * @param integer $refresh_time
765 * @return void
766 */
767function redirect_html( $url , $msg = '', $refresh_time = 0)
768{
769  global $user, $template, $lang_info, $conf, $lang, $t2, $page, $debug;
770
771  if (!isset($lang_info) || !isset($template) )
772  {
773    $user = build_user( $conf['guest_id'], true);
774    load_language('common.lang');
775    trigger_action('loading_lang');
776    load_language('lang', PHPWG_ROOT_PATH.PWG_LOCAL_DIR, array('no_fallback'=>true, 'local'=>true) );
777    $template = new Template(PHPWG_ROOT_PATH.'themes', get_default_theme());
778  }
779        elseif (defined('IN_ADMIN') and IN_ADMIN)
780        {
781                $template = new Template(PHPWG_ROOT_PATH.'themes', get_default_theme());
782        }
783
784  if (empty($msg))
785  {
786    $msg = nl2br(l10n('Redirection...'));
787  }
788
789  $refresh = $refresh_time;
790  $url_link = $url;
791  $title = 'redirection';
792
793  $template->set_filenames( array( 'redirect' => 'redirect.tpl' ) );
794
795  include( PHPWG_ROOT_PATH.'include/page_header.php' );
796
797  $template->set_filenames( array( 'redirect' => 'redirect.tpl' ) );
798  $template->assign('REDIRECT_MSG', $msg);
799
800  $template->parse('redirect');
801
802  include( PHPWG_ROOT_PATH.'include/page_tail.php' );
803
804  exit();
805}
806
807/**
808 * Redirects to the given URL (automatically choose HTTP or HTML method).
809 * once this function called, the execution doesn't go further
810 * (presence of an exit() instruction.
811 *
812 * @param string $url
813 * @param string $msg
814 * @param integer $refresh_time
815 * @return void
816 */
817function redirect( $url , $msg = '', $refresh_time = 0)
818{
819  global $conf;
820
821  // with RefeshTime <> 0, only html must be used
822  if ($conf['default_redirect_method']=='http'
823      and $refresh_time==0
824      and !headers_sent()
825    )
826  {
827    redirect_http($url);
828  }
829  else
830  {
831    redirect_html($url, $msg, $refresh_time);
832  }
833}
834
835/**
836 * returns available themes
837 *
838 * @param bool $show_mobile
839 * @return array
840 */
841function get_pwg_themes($show_mobile=false)
842{
843  global $conf;
844
845  $themes = array();
846
847  $query = '
848SELECT
849    id,
850    name
851  FROM '.THEMES_TABLE.'
852  ORDER BY name ASC
853;';
854  $result = pwg_query($query);
855  while ($row = pwg_db_fetch_assoc($result))
856  {
857    if ($row['id'] == $conf['mobile_theme'])
858    {
859      if (!$show_mobile)
860      {
861        continue;
862      }
863      $row['name'] .= ' ('.l10n('Mobile').')';
864    }
865    if (check_theme_installed($row['id']))
866    {
867      $themes[ $row['id'] ] = $row['name'];
868    }
869  }
870
871  // plugins want remove some themes based on user status maybe?
872  $themes = trigger_event('get_pwg_themes', $themes);
873
874  return $themes;
875}
876
877/**
878 * check if a theme is installed (directory exsists)
879 *
880 * @param string $theme_id
881 * @return bool
882 */
883function check_theme_installed($theme_id)
884{
885  global $conf;
886
887  return file_exists($conf['themes_dir'].'/'.$theme_id.'/'.'themeconf.inc.php');
888}
889
890/**
891 * Transforms an original path to its pwg representative
892 *
893 * @param string $path
894 * @param string $representative_ext
895 * @return string
896 */
897function original_to_representative($path, $representative_ext)
898{
899  $pos = strrpos($path, '/');
900  $path = substr_replace($path, 'pwg_representative/', $pos+1, 0);
901  $pos = strrpos($path, '.');
902  return substr_replace($path, $representative_ext, $pos+1);
903}
904
905/**
906 * get the full path of an image
907 *
908 * @param array $element_info element information from db (at least 'path')
909 * @return string
910 */
911function get_element_path($element_info)
912{
913  $path = $element_info['path'];
914  if ( !url_is_remote($path) )
915  {
916    $path = PHPWG_ROOT_PATH.$path;
917  }
918  return $path;
919}
920
921
922/**
923 * fill the current user caddie with given elements, if not already in caddie
924 *
925 * @param int[] $elements_id
926 */
927function fill_caddie($elements_id)
928{
929  global $user;
930
931  $query = '
932SELECT element_id
933  FROM '.CADDIE_TABLE.'
934  WHERE user_id = '.$user['id'].'
935;';
936  $in_caddie = query2array($query, null, 'element_id');
937
938  $caddiables = array_diff($elements_id, $in_caddie);
939
940  $datas = array();
941
942  foreach ($caddiables as $caddiable)
943  {
944    $datas[] = array(
945      'element_id' => $caddiable,
946      'user_id' => $user['id'],
947      );
948  }
949
950  if (count($caddiables) > 0)
951  {
952    mass_inserts(CADDIE_TABLE, array('element_id','user_id'), $datas);
953  }
954}
955
956/**
957 * returns the element name from its filename.
958 * removes file extension and replace underscores by spaces
959 *
960 * @param string $filename
961 * @return string name
962 */
963function get_name_from_file($filename)
964{
965  return str_replace('_',' ',get_filename_wo_extension($filename));
966}
967
968/**
969 * translation function.
970 * returns the corresponding value from _$lang_ if existing else the key is returned
971 * if more than one parameter is provided sprintf is applied
972 *
973 * @param string $key
974 * @param mixed $args,... optional arguments
975 * @return string
976 */
977function l10n($key)
978{
979  global $lang, $conf;
980
981  if ( ($val=@$lang[$key]) === null)
982  {
983    if ($conf['debug_l10n'] and !isset($lang[$key]) and !empty($key))
984    {
985      trigger_error('[l10n] language key "'. $key .'" not defined', E_USER_WARNING);
986    }
987    $val = $key;
988  }
989
990  if (func_num_args() > 1)
991  {
992    $args = func_get_args();
993    $val = vsprintf($val, array_slice($args, 1));
994  }
995
996  return $val;
997}
998
999/**
1000 * returns the printf value for strings including %d
1001 * returned value is concorded with decimal value (singular, plural)
1002 *
1003 * @param string $singular_key
1004 * @param string $plural_key
1005 * @param int $decimal
1006 * @return string
1007 */
1008function l10n_dec($singular_key, $plural_key, $decimal)
1009{
1010  global $lang_info;
1011
1012  return
1013    sprintf(
1014      l10n((
1015        (($decimal > 1) or ($decimal == 0 and $lang_info['zero_plural']))
1016          ? $plural_key
1017          : $singular_key
1018        )), $decimal);
1019}
1020
1021/**
1022 * returns a single element to use with l10n_args
1023 *
1024 * @param string $key translation key
1025 * @param mixed $args arguments to use on sprintf($key, args)
1026 *   if args is a array, each values are used on sprintf
1027 * @return string
1028 */
1029function get_l10n_args($key, $args='')
1030{
1031  if (is_array($args))
1032  {
1033    $key_arg = array_merge(array($key), $args);
1034  }
1035  else
1036  {
1037    $key_arg = array($key,  $args);
1038  }
1039  return array('key_args' => $key_arg);
1040}
1041
1042/**
1043 * returns a string formated with l10n elements.
1044 * it is usefull to "prepare" a text and translate it later
1045 * @see get_l10n_args()
1046 *
1047 * @param array $key_args one l10n_args element or array of l10n_args elements
1048 * @param string $sep used when translated elements are concatened
1049 * @return string
1050 */
1051function l10n_args($key_args, $sep = "\n")
1052{
1053  if (is_array($key_args))
1054  {
1055    foreach ($key_args as $key => $element)
1056    {
1057      if (isset($result))
1058      {
1059        $result .= $sep;
1060      }
1061      else
1062      {
1063        $result = '';
1064      }
1065
1066      if ($key === 'key_args')
1067      {
1068        array_unshift($element, l10n(array_shift($element))); // translate the key
1069        $result .= call_user_func_array('sprintf', $element);
1070      }
1071      else
1072      {
1073        $result .= l10n_args($element, $sep);
1074      }
1075    }
1076  }
1077  else
1078  {
1079    fatal_error('l10n_args: Invalid arguments');
1080  }
1081
1082  return $result;
1083}
1084
1085/**
1086 * returns the corresponding value from $themeconf if existing or an empty string
1087 *
1088 * @param string $key
1089 * @return string
1090 */
1091function get_themeconf($key)
1092{
1093  global $template;
1094
1095  return $template->get_themeconf($key);
1096}
1097
1098/**
1099 * Returns webmaster mail address depending on $conf['webmaster_id']
1100 *
1101 * @return string
1102 */
1103function get_webmaster_mail_address()
1104{
1105  global $conf;
1106
1107  $query = '
1108SELECT '.$conf['user_fields']['email'].'
1109  FROM '.USERS_TABLE.'
1110  WHERE '.$conf['user_fields']['id'].' = '.$conf['webmaster_id'].'
1111;';
1112  list($email) = pwg_db_fetch_row(pwg_query($query));
1113
1114  $email = trigger_event('get_webmaster_mail_address', $email);
1115
1116  return $email;
1117}
1118
1119/**
1120 * Add configuration parameters from database to global $conf array
1121 *
1122 * @param string $condition SQL condition
1123 * @return void
1124 */
1125function load_conf_from_db($condition = '')
1126{
1127  global $conf;
1128
1129  $query = '
1130SELECT param, value
1131 FROM '.CONFIG_TABLE.'
1132 '.(!empty($condition) ? 'WHERE '.$condition : '').'
1133;';
1134  $result = pwg_query($query);
1135
1136  if ((pwg_db_num_rows($result) == 0) and !empty($condition))
1137  {
1138    fatal_error('No configuration data');
1139  }
1140
1141  while ($row = pwg_db_fetch_assoc($result))
1142  {
1143    $val = isset($row['value']) ? $row['value'] : '';
1144    // If the field is true or false, the variable is transformed into a boolean value.
1145    if ($val == 'true')
1146    {
1147      $val = true;
1148    }
1149    elseif ($val == 'false')
1150    {
1151      $val = false;
1152    }
1153    $conf[ $row['param'] ] = $val;
1154  }
1155
1156  trigger_action('load_conf', $condition);
1157}
1158
1159/**
1160 * Add or update a config parameter
1161 *
1162 * @param string $param
1163 * @param string $value
1164 */
1165function conf_update_param($param, $value)
1166{
1167  $query = '
1168SELECT param
1169  FROM '.CONFIG_TABLE.'
1170  WHERE param = \''.$param.'\'
1171;';
1172  $params = query2array($query, null, 'param');
1173
1174  if (count($params) == 0)
1175  {
1176    $query = '
1177INSERT
1178  INTO '.CONFIG_TABLE.'
1179  (param, value)
1180  VALUES(\''.$param.'\', \''.$value.'\')
1181;';
1182    pwg_query($query);
1183  }
1184  else
1185  {
1186    $query = '
1187UPDATE '.CONFIG_TABLE.'
1188  SET value = \''.$value.'\'
1189  WHERE param = \''.$param.'\'
1190;';
1191    pwg_query($query);
1192  }
1193}
1194
1195/**
1196 * Delete one or more config parameters
1197 * @since 2.6
1198 *
1199 * @param string|string[] $params
1200 */
1201function conf_delete_param($params)
1202{
1203  global $conf;
1204
1205  if (!is_array($params))
1206  {
1207    $params = array($params);
1208  }
1209  if (empty($params))
1210  {
1211    return;
1212  }
1213
1214  $query = '
1215DELETE FROM '.CONFIG_TABLE.'
1216  WHERE param IN(\''. implode('\',\'', $params) .'\')
1217;';
1218  pwg_query($query);
1219
1220  foreach ($params as $param)
1221  {
1222    unset($conf[$param]);
1223  }
1224}
1225
1226/**
1227 * Prepends and appends strings at each value of the given array.
1228 *
1229 * @param array $array
1230 * @param string $prepend_str
1231 * @param string $append_str
1232 * @return array
1233 */
1234function prepend_append_array_items($array, $prepend_str, $append_str)
1235{
1236  array_walk(
1237    $array,
1238    create_function('&$s', '$s = "'.$prepend_str.'".$s."'.$append_str.'";')
1239    );
1240
1241  return $array;
1242}
1243
1244/**
1245 * creates an simple hashmap based on a SQL query.
1246 * choose one to be the key, another one to be the value.
1247 * @deprecated 2.6
1248 *
1249 * @param string $query
1250 * @param string $keyname
1251 * @param string $valuename
1252 * @return array
1253 */
1254function simple_hash_from_query($query, $keyname, $valuename)
1255{
1256        return query2array($query, $keyname, $valuename);
1257}
1258
1259/**
1260 * creates an associative array based on a SQL query.
1261 * choose one to be the key
1262 * @deprecated 2.6
1263 *
1264 * @param string $query
1265 * @param string $keyname
1266 * @return array
1267 */
1268function hash_from_query($query, $keyname)
1269{
1270        return query2array($query, $keyname);
1271}
1272
1273/**
1274 * creates a numeric array based on a SQL query.
1275 * if _$fieldname_ is empty the returned value will be an array of arrays
1276 * if _$fieldname_ is provided the returned value will be a one dimension array
1277 * @deprecated 2.6
1278 *
1279 * @param string $query
1280 * @param string $fieldname
1281 * @return array
1282 */
1283function array_from_query($query, $fieldname=false)
1284{
1285  if (false === $fieldname)
1286  {
1287                return query2array($query);
1288  }
1289  else
1290  {
1291                return query2array($query, null, $fieldname);
1292  }
1293}
1294
1295/**
1296 * Return the basename of the current script.
1297 * The lowercase case filename of the current script without extension
1298 *
1299 * @return string
1300 */
1301function script_basename()
1302{
1303  global $conf;
1304
1305  foreach (array('SCRIPT_NAME', 'SCRIPT_FILENAME', 'PHP_SELF') as $value)
1306  {
1307    if (!empty($_SERVER[$value]))
1308    {
1309      $filename = strtolower($_SERVER[$value]);
1310      if ($conf['php_extension_in_urls'] and get_extension($filename)!=='php')
1311        continue;
1312      $basename = basename($filename, '.php');
1313      if (!empty($basename))
1314      {
1315        return $basename;
1316      }
1317    }
1318  }
1319  return '';
1320}
1321
1322/**
1323 * Return $conf['filter_pages'] value for the current page
1324 *
1325 * @param string $value_name
1326 * @return mixed
1327 */
1328function get_filter_page_value($value_name)
1329{
1330  global $conf;
1331
1332  $page_name = script_basename();
1333
1334  if (isset($conf['filter_pages'][$page_name][$value_name]))
1335  {
1336    return $conf['filter_pages'][$page_name][$value_name];
1337  }
1338  else if (isset($conf['filter_pages']['default'][$value_name]))
1339  {
1340    return $conf['filter_pages']['default'][$value_name];
1341  }
1342  else
1343  {
1344    return null;
1345  }
1346}
1347
1348/**
1349 * return the character set used by Piwigo
1350 * @return string
1351 */
1352function get_pwg_charset()
1353{
1354  $pwg_charset = 'utf-8';
1355  if (defined('PWG_CHARSET'))
1356  {
1357    $pwg_charset = PWG_CHARSET;
1358  }
1359  return $pwg_charset;
1360}
1361
1362/**
1363 * returns the parent (fallback) language of a language.
1364 * if _$lang_id_ is null it applies to the current language
1365 * @since 2.6
1366 *
1367 * @param string $lang_id
1368 * @return string|null
1369 */
1370function get_parent_language($lang_id=null)
1371{
1372  if (empty($lang_id))
1373  {
1374    global $lang_info;
1375    return !empty($lang_info['parent']) ? $lang_info['parent'] : null;
1376  }
1377  else
1378  {
1379    $f = PHPWG_ROOT_PATH.'language/'.$lang_id.'/common.lang.php';
1380    if (file_exists($f))
1381    {
1382      include($f);
1383      return !empty($lang_info['parent']) ? $lang_info['parent'] : null;
1384    }
1385  }
1386  return null;
1387}
1388
1389/**
1390 * includes a language file or returns the content of a language file
1391 *
1392 * tries to load in descending order:
1393 *   param language, user language, default language
1394 *
1395 * @param string $filename
1396 * @param string $dirname
1397 * @param mixed options can contain
1398 *     @option string language - language to load
1399 *     @option bool return - if true the file content is returned
1400 *     @option bool no_fallback - if true do not load default language
1401 *     @option bool local - if true load file from local directory
1402 * @return boolean|string
1403 */
1404function load_language($filename, $dirname = '', $options = array())
1405{
1406  global $user, $language_files;
1407
1408  if ( !empty($dirname) and !empty($filename) )
1409  {
1410    if ( empty($language_files[$dirname]) or !in_array($filename,$language_files[$dirname]) )
1411    {
1412      $language_files[$dirname][] = $filename;
1413    }
1414  }
1415
1416  if (! @$options['return'] )
1417  {
1418    $filename .= '.php'; //MAYBE to do .. load .po and .mo localization files
1419  }
1420  if (empty($dirname))
1421  {
1422    $dirname = PHPWG_ROOT_PATH;
1423  }
1424  $dirname .= 'language/';
1425
1426  $languages = array();
1427  if ( !empty($options['language']) )
1428  {
1429    $languages[] = $options['language'];
1430  }
1431  if ( !empty($user['language']) )
1432  {
1433    $languages[] = $user['language'];
1434  }
1435  if ( ($parent = get_parent_language()) != null)
1436  {
1437    $languages[] = $parent;
1438  }
1439  if ( ! @$options['no_fallback'] )
1440  {
1441    if ( defined('PHPWG_INSTALLED') )
1442    {
1443      $languages[] = get_default_language();
1444    }
1445    $languages[] = PHPWG_DEFAULT_LANGUAGE;
1446  }
1447
1448  $languages = array_unique($languages);
1449
1450  /*Note: target charset is always utf-8
1451  if ( empty($options['target_charset']) )
1452  {
1453    $target_charset = get_pwg_charset();
1454  }
1455  else
1456  {
1457    $target_charset = $options['target_charset'];
1458  }
1459  $target_charset = strtolower($target_charset);*/
1460  $source_file       = '';
1461  $selected_language = '';
1462  foreach ($languages as $language)
1463  {
1464    $f = @$options['local'] ?
1465      $dirname.$language.'.'.$filename:
1466      $dirname.$language.'/'.$filename;
1467
1468    if (file_exists($f))
1469    {
1470      $selected_language = $language;
1471      $source_file = $f;
1472      break;
1473    }
1474  }
1475
1476  if ( !empty($source_file) )
1477  {
1478    if (! @$options['return'] )
1479    {
1480      @include($source_file);
1481      $load_lang = @$lang;
1482      $load_lang_info = @$lang_info;
1483
1484      global $lang, $lang_info;
1485      if ( !isset($lang) ) $lang=array();
1486      if ( !isset($lang_info) ) $lang_info=array();
1487
1488      $parent_language = !empty($load_lang_info['parent']) ? $load_lang_info['parent'] : (
1489                            !empty($lang_info['parent']) ? $lang_info['parent'] : null );
1490      if (!empty($parent_language) and $parent_language != $selected_language)
1491      {
1492        @include(str_replace($selected_language, $parent_language, $source_file));
1493      }
1494
1495      /* Note: target charset is always utf-8
1496      if ( 'utf-8'!=$target_charset)
1497      {
1498        if ( is_array($load_lang) )
1499        {
1500          foreach ($load_lang as $k => $v)
1501          {
1502            if ( is_array($v) )
1503            {
1504              $func = create_function('$v', 'return convert_charset($v, "utf-8", "'.$target_charset.'");' );
1505              $lang[$k] = array_map($func, $v);
1506            }
1507            else
1508              $lang[$k] = convert_charset($v, 'utf-8', $target_charset);
1509          }
1510        }
1511        if ( is_array($load_lang_info) )
1512        {
1513          foreach ($load_lang_info as $k => $v)
1514          {
1515            $lang_info[$k] = convert_charset($v, 'utf-8', $target_charset);
1516          }
1517        }
1518      }
1519      else
1520      {*/
1521        $lang = array_merge( $lang, (array)$load_lang );
1522        $lang_info = array_merge( $lang_info, (array)$load_lang_info );
1523      //}
1524      return true;
1525    }
1526    else
1527    {
1528      $content = @file_get_contents($source_file);
1529      //Note: target charset is always utf-8 $content = convert_charset($content, 'utf-8', $target_charset);
1530      return $content;
1531    }
1532  }
1533  return false;
1534}
1535
1536/**
1537 * converts a string from a character set to another character set
1538 *
1539 * @param string $str
1540 * @param string $source_charset
1541 * @param string $dest_charset
1542 */
1543function convert_charset($str, $source_charset, $dest_charset)
1544{
1545  if ($source_charset==$dest_charset)
1546    return $str;
1547  if ($source_charset=='iso-8859-1' and $dest_charset=='utf-8')
1548  {
1549    return utf8_encode($str);
1550  }
1551  if ($source_charset=='utf-8' and $dest_charset=='iso-8859-1')
1552  {
1553    return utf8_decode($str);
1554  }
1555  if (function_exists('iconv'))
1556  {
1557    return iconv($source_charset, $dest_charset, $str);
1558  }
1559  if (function_exists('mb_convert_encoding'))
1560  {
1561    return mb_convert_encoding( $str, $dest_charset, $source_charset );
1562  }
1563  return $str; // TODO
1564}
1565
1566/**
1567 * makes sure a index.htm protects the directory from browser file listing
1568 *
1569 * @param string $dir
1570 */
1571function secure_directory($dir)
1572{
1573  $file = $dir.'/index.htm';
1574  if (!file_exists($file))
1575  {
1576    @file_put_contents($file, 'Not allowed!');
1577  }
1578}
1579
1580/**
1581 * returns a "secret key" that is to be sent back when a user posts a form
1582 *
1583 * @param int $valid_after_seconds - key validity start time from now
1584 * @param string $aditionnal_data_to_hash
1585 * @return string
1586 */
1587function get_ephemeral_key($valid_after_seconds, $aditionnal_data_to_hash = '')
1588{
1589        global $conf;
1590        $time = round(microtime(true), 1);
1591        return $time.':'.$valid_after_seconds.':'
1592                .hash_hmac(
1593                        'md5',
1594                        $time.substr($_SERVER['REMOTE_ADDR'],0,5).$valid_after_seconds.$aditionnal_data_to_hash,
1595                        $conf['secret_key']);
1596}
1597
1598/**
1599 * verify a key sent back with a form
1600 *
1601 * @param string $key
1602 * @param string $aditionnal_data_to_hash
1603 * @return bool
1604 */
1605function verify_ephemeral_key($key, $aditionnal_data_to_hash = '')
1606{
1607        global $conf;
1608        $time = microtime(true);
1609        $key = explode( ':', @$key );
1610        if ( count($key)!=3
1611                or $key[0]>$time-(float)$key[1] // page must have been retrieved more than X sec ago
1612                or $key[0]<$time-3600 // 60 minutes expiration
1613                or hash_hmac(
1614                          'md5', $key[0].substr($_SERVER['REMOTE_ADDR'],0,5).$key[1].$aditionnal_data_to_hash, $conf['secret_key']
1615                        ) != $key[2]
1616          )
1617        {
1618                return false;
1619        }
1620        return true;
1621}
1622
1623/**
1624 * return an array which will be sent to template to display navigation bar
1625 *
1626 * @param string $url base url of all links
1627 * @param int $nb_elements
1628 * @param int $start
1629 * @param int $nb_element_page
1630 * @param bool $clean_url
1631 * @param string $param_name
1632 * @return array
1633 */
1634function create_navigation_bar($url, $nb_element, $start, $nb_element_page, $clean_url = false, $param_name='start')
1635{
1636  global $conf;
1637
1638  $navbar = array();
1639  $pages_around = $conf['paginate_pages_around'];
1640  $start_str = $clean_url ? '/'.$param_name.'-' : (strpos($url, '?')===false ? '?':'&amp;').$param_name.'=';
1641
1642  if (!isset($start) or !is_numeric($start) or (is_numeric($start) and $start < 0))
1643  {
1644    $start = 0;
1645  }
1646
1647  // navigation bar useful only if more than one page to display !
1648  if ($nb_element > $nb_element_page)
1649  {
1650    $url_start = $url.$start_str;
1651
1652    $cur_page = $navbar['CURRENT_PAGE'] = $start / $nb_element_page + 1;
1653    $maximum = ceil($nb_element / $nb_element_page);
1654
1655    $start = $nb_element_page * round( $start / $nb_element_page );
1656    $previous = $start - $nb_element_page;
1657    $next = $start + $nb_element_page;
1658    $last = ($maximum - 1) * $nb_element_page;
1659
1660    // link to first page and previous page?
1661    if ($cur_page != 1)
1662    {
1663      $navbar['URL_FIRST'] = $url;
1664      $navbar['URL_PREV'] = $previous > 0 ? $url_start.$previous : $url;
1665    }
1666    // link on next page and last page?
1667    if ($cur_page != $maximum)
1668    {
1669      $navbar['URL_NEXT'] = $url_start.($next < $last ? $next : $last);
1670      $navbar['URL_LAST'] = $url_start.$last;
1671    }
1672
1673    // pages to display
1674    $navbar['pages'] = array();
1675    $navbar['pages'][1] = $url;
1676    for ($i = max( floor($cur_page) - $pages_around , 2), $stop = min( ceil($cur_page) + $pages_around + 1, $maximum);
1677         $i < $stop; $i++)
1678    {
1679      $navbar['pages'][$i] = $url.$start_str.(($i - 1) * $nb_element_page);
1680    }
1681    $navbar['pages'][$maximum] = $url_start.$last;
1682    $navbar['NB_PAGE']=$maximum;
1683  }
1684  return $navbar;
1685}
1686
1687/**
1688 * return an array which will be sent to template to display recent icon
1689 *
1690 * @param string $date
1691 * @param bool $is_child_date
1692 * @return array
1693 */
1694function get_icon($date, $is_child_date = false)
1695{
1696  global $cache, $user;
1697
1698  if (empty($date))
1699  {
1700    return false;
1701  }
1702
1703  if (!isset($cache['get_icon']['title']))
1704  {
1705    $cache['get_icon']['title'] = l10n(
1706      'photos posted during the last %d days',
1707      $user['recent_period']
1708      );
1709  }
1710
1711  $icon = array(
1712    'TITLE' => $cache['get_icon']['title'],
1713    'IS_CHILD_DATE' => $is_child_date,
1714    );
1715
1716  if (isset($cache['get_icon'][$date]))
1717  {
1718    return $cache['get_icon'][$date] ? $icon : array();
1719  }
1720
1721  if (!isset($cache['get_icon']['sql_recent_date']))
1722  {
1723    // Use MySql date in order to standardize all recent "actions/queries"
1724    $cache['get_icon']['sql_recent_date'] = pwg_db_get_recent_period($user['recent_period']);
1725  }
1726
1727  $cache['get_icon'][$date] = $date > $cache['get_icon']['sql_recent_date'];
1728
1729  return $cache['get_icon'][$date] ? $icon : array();
1730}
1731
1732/**
1733 * check token comming from form posted or get params to prevent csrf attacks.
1734 * if pwg_token is empty action doesn't require token
1735 * else pwg_token is compare to server token
1736 *
1737 * @return void access denied if token given is not equal to server token
1738 */
1739function check_pwg_token()
1740{
1741  if (!empty($_REQUEST['pwg_token']))
1742  {
1743    if (get_pwg_token() != $_REQUEST['pwg_token'])
1744    {
1745      access_denied();
1746    }
1747  }
1748  else
1749  {
1750    bad_request('missing token');
1751  }
1752}
1753
1754/**
1755 * get pwg_token used to prevent csrf attacks
1756 *
1757 * @return string
1758 */
1759function get_pwg_token()
1760{
1761  global $conf;
1762
1763  return hash_hmac('md5', session_id(), $conf['secret_key']);
1764}
1765
1766/*
1767 * breaks the script execution if the given value doesn't match the given
1768 * pattern. This should happen only during hacking attempts.
1769 *
1770 * @param string $param_name
1771 * @param array $param_array
1772 * @param boolean $is_array
1773 * @param string $pattern
1774 * @param boolean $mandatory
1775 */
1776function check_input_parameter($param_name, $param_array, $is_array, $pattern, $mandatory=false)
1777{
1778  $param_value = null;
1779  if (isset($param_array[$param_name]))
1780  {
1781    $param_value = $param_array[$param_name];
1782  }
1783
1784  // it's ok if the input parameter is null
1785  if (empty($param_value))
1786  {
1787    if ($mandatory)
1788    {
1789      fatal_error('[Hacking attempt] the input parameter "'.$param_name.'" is not valid');
1790    }
1791    return true;
1792  }
1793
1794  if ($is_array)
1795  {
1796    if (!is_array($param_value))
1797    {
1798      fatal_error('[Hacking attempt] the input parameter "'.$param_name.'" should be an array');
1799    }
1800
1801    foreach ($param_value as $item_to_check)
1802    {
1803      if (!preg_match($pattern, $item_to_check))
1804      {
1805        fatal_error('[Hacking attempt] an item is not valid in input parameter "'.$param_name.'"');
1806      }
1807    }
1808  }
1809  else
1810  {
1811    if (!preg_match($pattern, $param_value))
1812    {
1813      fatal_error('[Hacking attempt] the input parameter "'.$param_name.'" is not valid');
1814    }
1815  }
1816}
1817
1818/**
1819 * get localized privacy level values
1820 *
1821 * @return string[]
1822 */
1823function get_privacy_level_options()
1824{
1825  global $conf;
1826
1827  $options = array();
1828  $label = '';
1829  foreach (array_reverse($conf['available_permission_levels']) as $level)
1830  {
1831    if (0 == $level)
1832    {
1833      $label = l10n('Everybody');
1834    }
1835    else
1836    {
1837      if (strlen($label))
1838      {
1839        $label .= ', ';
1840      }
1841      $label .= l10n( sprintf('Level %d', $level) );
1842    }
1843    $options[$level] = $label;
1844  }
1845  return $options;
1846}
1847
1848
1849/**
1850 * return the branch from the version. For example version 2.2.4 is for branch 2.2
1851 *
1852 * @param string $version
1853 * @return string
1854 */
1855function get_branch_from_version($version)
1856{
1857  return implode('.', array_slice(explode('.', $version), 0, 2));
1858}
1859
1860/**
1861 * return the device type: mobile, tablet or desktop
1862 *
1863 * @return string
1864 */
1865function get_device()
1866{
1867  $device = pwg_get_session_var('device');
1868
1869  if (is_null($device))
1870  {
1871    include_once(PHPWG_ROOT_PATH.'include/mdetect.php');
1872    $uagent_obj = new uagent_info();
1873    if ($uagent_obj->DetectSmartphone())
1874    {
1875      $device = 'mobile';
1876    }
1877    elseif ($uagent_obj->DetectTierTablet())
1878    {
1879      $device = 'tablet';
1880    }
1881    else
1882    {
1883      $device = 'desktop';
1884    }
1885    pwg_set_session_var('device', $device);
1886  }
1887
1888  return $device;
1889}
1890
1891/**
1892 * return true if mobile theme should be loaded
1893 *
1894 * @return bool
1895 */
1896function mobile_theme()
1897{
1898  global $conf;
1899
1900  if (empty($conf['mobile_theme']))
1901  {
1902    return false;
1903  }
1904
1905  if (isset($_GET['mobile']))
1906  {
1907    $is_mobile_theme = get_boolean($_GET['mobile']);
1908    pwg_set_session_var('mobile_theme', $is_mobile_theme);
1909  }
1910  else
1911  {
1912    $is_mobile_theme = pwg_get_session_var('mobile_theme');
1913  }
1914
1915  if (is_null($is_mobile_theme))
1916  {
1917    $is_mobile_theme = (get_device() == 'mobile');
1918    pwg_set_session_var('mobile_theme', $is_mobile_theme);
1919  }
1920
1921  return $is_mobile_theme;
1922}
1923
1924/**
1925 * check url format
1926 *
1927 * @param string $url
1928 * @return bool
1929 */
1930function url_check_format($url)
1931{
1932  return filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED | FILTER_FLAG_HOST_REQUIRED)!==false;
1933}
1934
1935/**
1936 * check email format
1937 *
1938 * @param string $mail_address
1939 * @return bool
1940 */
1941function email_check_format($mail_address)
1942{
1943  return filter_var($mail_address, FILTER_VALIDATE_EMAIL)!==false;
1944}
1945
1946/**
1947 * returns the number of available comments for the connected user
1948 *
1949 * @return int
1950 */
1951function get_nb_available_comments()
1952{
1953  global $user;
1954  if (!isset($user['nb_available_comments']))
1955  {
1956    $where = array();
1957    if ( !is_admin() )
1958      $where[] = 'validated=\'true\'';
1959    $where[] = get_sql_condition_FandF
1960      (
1961        array
1962          (
1963            'forbidden_categories' => 'category_id',
1964            'visible_categories' => 'category_id',
1965            'visible_images' => 'ic.image_id'
1966          ),
1967        '', true
1968      );
1969
1970    $query = '
1971SELECT COUNT(DISTINCT(com.id))
1972  FROM '.IMAGE_CATEGORY_TABLE.' AS ic
1973    INNER JOIN '.COMMENTS_TABLE.' AS com
1974    ON ic.image_id = com.image_id
1975  WHERE '.implode('
1976    AND ', $where);
1977    list($user['nb_available_comments']) = pwg_db_fetch_row(pwg_query($query));
1978
1979    single_update(USER_CACHE_TABLE,
1980      array('nb_available_comments'=>$user['nb_available_comments']),
1981      array('user_id'=>$user['id'])
1982      );
1983  }
1984  return $user['nb_available_comments'];
1985}
1986
1987/**
1988 * Compare two versions with version_compare after having converted
1989 * single chars to their decimal values.
1990 * Needed because version_compare does not understand versions like '2.5.c'.
1991 * @since 2.6
1992 *
1993 * @param string $a
1994 * @param string $b
1995 * @param string $op
1996 */
1997function safe_version_compare($a, $b, $op=null)
1998{
1999  $replace_chars = create_function('$m', 'return ord(strtolower($m[1]));');
2000
2001  // add dot before groups of letters (version_compare does the same thing)
2002  $a = preg_replace('#([0-9]+)([a-z]+)#i', '$1.$2', $a);
2003  $b = preg_replace('#([0-9]+)([a-z]+)#i', '$1.$2', $b);
2004
2005  // apply ord() to any single letter
2006  $a = preg_replace_callback('#\b([a-z]{1})\b#i', $replace_chars, $a);
2007  $b = preg_replace_callback('#\b([a-z]{1})\b#i', $replace_chars, $b);
2008
2009  if (empty($op))
2010  {
2011    return version_compare($a, $b);
2012  }
2013  else
2014  {
2015    return version_compare($a, $b, $op);
2016  }
2017}
2018
2019?>
Note: See TracBrowser for help on using the repository browser.