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

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

use custom safe_version_compare instead of version_compare to handle versions numbers with letters

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