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

Last change on this file since 31102 was 31102, checked in by mistic100, 9 years ago

feature 3221 Add Logger class

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