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

Last change on this file since 25601 was 25550, checked in by mistic100, 11 years ago

feature 2999: Documentation of include/functions_mail|metadata|picture

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