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

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

move array_from_query to functions.inc.php

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