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

Last change on this file since 25292 was 25288, checked in by mistic100, 11 years ago

feature 2651: fallback language, failed when the "child" file does not exists

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