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

Last change on this file since 13668 was 13488, checked in by rvelices, 12 years ago

remove remote sites feature

  • Property svn:eol-style set to LF
File size: 42.9 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based photo gallery                                    |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008-2012 Piwigo Team                  http://piwigo.org |
6// | Copyright(C) 2003-2008 PhpWebGallery Team    http://phpwebgallery.net |
7// | Copyright(C) 2002-2003 Pierrick LE GALL   http://le-gall.net/pierrick |
8// +-----------------------------------------------------------------------+
9// | This program is free software; you can redistribute it and/or modify  |
10// | it under the terms of the GNU General Public License as published by  |
11// | the Free Software Foundation                                          |
12// |                                                                       |
13// | This program is distributed in the hope that it will be useful, but   |
14// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
15// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
16// | General Public License for more details.                              |
17// |                                                                       |
18// | You should have received a copy of the GNU General Public License     |
19// | along with this program; if not, write to the Free Software           |
20// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
21// | USA.                                                                  |
22// +-----------------------------------------------------------------------+
23
24include_once( PHPWG_ROOT_PATH .'include/functions_user.inc.php' );
25include_once( PHPWG_ROOT_PATH .'include/functions_cookie.inc.php' );
26include_once( PHPWG_ROOT_PATH .'include/functions_session.inc.php' );
27include_once( PHPWG_ROOT_PATH .'include/functions_category.inc.php' );
28include_once( PHPWG_ROOT_PATH .'include/functions_html.inc.php' );
29include_once( PHPWG_ROOT_PATH .'include/functions_tag.inc.php' );
30include_once( PHPWG_ROOT_PATH .'include/functions_url.inc.php' );
31include_once( PHPWG_ROOT_PATH .'include/functions_plugins.inc.php' );
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');
35require_once( PHPWG_ROOT_PATH .'include/smarty/libs/Smarty.class.php');
36include_once( PHPWG_ROOT_PATH .'include/template.class.php');
37
38//----------------------------------------------------------- generic functions
39
40/**
41 * stupidly returns the current microsecond since Unix epoch
42 */
43function micro_seconds()
44{
45  $t1 = explode(' ', microtime());
46  $t2 = explode('.', $t1[0]);
47  $t2 = $t1[1].substr($t2[1], 0, 6);
48  return $t2;
49}
50
51// The function get_moment returns a float value coresponding to the number
52// of seconds since the unix epoch (1st January 1970) and the microseconds
53// are precised : e.g. 1052343429.89276600
54function get_moment()
55{
56  return microtime(true);
57}
58
59// The function get_elapsed_time returns the number of seconds (with 3
60// decimals precision) between the start time and the end time given.
61function get_elapsed_time( $start, $end )
62{
63  return number_format( $end - $start, 3, '.', ' ').' s';
64}
65
66// - The replace_space function replaces space and '-' characters
67//   by their HTML equivalent  &nbsb; and &minus;
68// - The function does not replace characters in HTML tags
69// - This function was created because IE5 does not respect the
70//   CSS "white-space: nowrap;" property unless space and minus
71//   characters are replaced like this function does.
72// - Example :
73//                 <div class="foo">My friend</div>
74//               ( 01234567891111111111222222222233 )
75//               (           0123456789012345678901 )
76// becomes :
77//             <div class="foo">My&nbsp;friend</div>
78function replace_space( $string )
79{
80  //return $string;
81  $return_string = '';
82  // $remaining is the rest of the string where to replace spaces characters
83  $remaining = $string;
84  // $start represents the position of the next '<' character
85  // $end   represents the position of the next '>' character
86  ; // -> 0
87  $end   = strpos ( $remaining, '>' ); // -> 16
88  // as long as a '<' and his friend '>' are found, we loop
89  while ( ($start=strpos( $remaining, '<' )) !==false
90        and ($end=strpos( $remaining, '>' )) !== false )
91  {
92    // $treatment is the part of the string to treat
93    // In the first loop of our example, this variable is empty, but in the
94    // second loop, it equals 'My friend'
95    $treatment = substr ( $remaining, 0, $start );
96    // Replacement of ' ' by his equivalent '&nbsp;'
97    $treatment = str_replace( ' ', '&nbsp;', $treatment );
98    $treatment = str_replace( '-', '&minus;', $treatment );
99    // composing the string to return by adding the treated string and the
100    // following HTML tag -> 'My&nbsp;friend</div>'
101    $return_string.= $treatment.substr( $remaining, $start, $end-$start+1 );
102    // the remaining string is deplaced to the part after the '>' of this
103    // loop
104    $remaining = substr ( $remaining, $end + 1, strlen( $remaining ) );
105  }
106  $treatment = str_replace( ' ', '&nbsp;', $remaining );
107  $treatment = str_replace( '-', '&minus;', $treatment );
108  $return_string.= $treatment;
109
110  return $return_string;
111}
112
113// get_extension returns the part of the string after the last "."
114function get_extension( $filename )
115{
116  return substr( strrchr( $filename, '.' ), 1, strlen ( $filename ) );
117}
118
119// get_filename_wo_extension returns the part of the string before the last
120// ".".
121// get_filename_wo_extension( 'test.tar.gz' ) -> 'test.tar'
122function get_filename_wo_extension( $filename )
123{
124  $pos = strrpos( $filename, '.' );
125  return ($pos===false) ? $filename : substr( $filename, 0, $pos);
126}
127
128/**
129 * returns an array contening sub-directories, excluding ".svn"
130 *
131 * @param string $dir
132 * @return array
133 */
134function get_dirs($directory)
135{
136  $sub_dirs = array();
137  if ($opendir = opendir($directory))
138  {
139    while ($file = readdir($opendir))
140    {
141      if ($file != '.'
142          and $file != '..'
143          and is_dir($directory.'/'.$file)
144          and $file != '.svn')
145      {
146        array_push($sub_dirs, $file);
147      }
148    }
149    closedir($opendir);
150  }
151  return $sub_dirs;
152}
153
154define('MKGETDIR_NONE', 0);
155define('MKGETDIR_RECURSIVE', 1);
156define('MKGETDIR_DIE_ON_ERROR', 2);
157define('MKGETDIR_PROTECT_INDEX', 4);
158define('MKGETDIR_PROTECT_HTACCESS', 8);
159define('MKGETDIR_DEFAULT', 7);
160/**
161 * creates directory if not exists; ensures that directory is writable
162 * @param:
163 *  string $dir
164 *  int $flags combination of MKGETDIR_xxx
165 * @return bool false on error else true
166 */
167function mkgetdir($dir, $flags=MKGETDIR_DEFAULT)
168{
169  if ( !is_dir($dir) )
170  {
171    global $conf;
172    if (substr(PHP_OS, 0, 3) == 'WIN')
173    {
174      $dir = str_replace('/', DIRECTORY_SEPARATOR, $dir);
175    }
176    $umask = umask(0);
177    $mkd = @mkdir($dir, $conf['chmod_value'], ($flags&MKGETDIR_RECURSIVE) ? true:false );
178    umask($umask);
179    if ($mkd==false)
180    {
181      !($flags&MKGETDIR_DIE_ON_ERROR) or fatal_error( "$dir ".l10n('no write access'));
182      return false;
183    }
184    if( $flags&MKGETDIR_PROTECT_HTACCESS )
185    {
186      $file = $dir.'/.htaccess';
187      file_exists($file) or @file_put_contents( $file, 'deny from all' );
188    }
189    if( $flags&MKGETDIR_PROTECT_INDEX )
190    {
191      $file = $dir.'/index.htm';
192      file_exists($file) or @file_put_contents( $file, 'Not allowed!' );
193    }
194  }
195  if ( !is_writable($dir) )
196  {
197    !($flags&MKGETDIR_DIE_ON_ERROR) or fatal_error( "$dir ".l10n('no write access'));
198    return false;
199  }
200  return true;
201}
202
203/**
204 * returns thumbnail directory name of input diretoty name
205 * make thumbnail directory is necessary
206 * set error messages on array messages
207 *
208 * @param:
209 *  string $dirname
210 *  arrayy $errors
211 * @return bool false on error else string directory name
212 */
213function mkget_thumbnail_dir($dirname, &$errors)
214{
215  global $conf;
216
217  $tndir = $dirname.'/'.$conf['dir_thumbnail'];
218  if (! mkgetdir($tndir, MKGETDIR_NONE) )
219  {
220    array_push($errors,
221          '['.$dirname.'] : '.l10n('no write access'));
222    return false;
223  }
224  return $tndir;
225}
226
227/* Returns true if the string appears to be encoded in UTF-8. (from wordpress)
228 * @param string Str
229 */
230function seems_utf8($Str) { # by bmorel at ssi dot fr
231  for ($i=0; $i<strlen($Str); $i++) {
232    if (ord($Str[$i]) < 0x80) continue; # 0bbbbbbb
233    elseif ((ord($Str[$i]) & 0xE0) == 0xC0) $n=1; # 110bbbbb
234    elseif ((ord($Str[$i]) & 0xF0) == 0xE0) $n=2; # 1110bbbb
235    elseif ((ord($Str[$i]) & 0xF8) == 0xF0) $n=3; # 11110bbb
236    elseif ((ord($Str[$i]) & 0xFC) == 0xF8) $n=4; # 111110bb
237    elseif ((ord($Str[$i]) & 0xFE) == 0xFC) $n=5; # 1111110b
238    else return false; # Does not match any model
239    for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ?
240      if ((++$i == strlen($Str)) || ((ord($Str[$i]) & 0xC0) != 0x80))
241      return false;
242    }
243  }
244  return true;
245}
246
247/* Remove accents from a UTF-8 or ISO-859-1 string (from wordpress)
248 * @param string sstring - an UTF-8 or ISO-8859-1 string
249 */
250function remove_accents($string)
251{
252  if ( !preg_match('/[\x80-\xff]/', $string) )
253    return $string;
254
255  if (seems_utf8($string)) {
256    $chars = array(
257    // Decompositions for Latin-1 Supplement
258    "\xc3\x80"=>'A', "\xc3\x81"=>'A',
259    "\xc3\x82"=>'A', "\xc3\x83"=>'A',
260    "\xc3\x84"=>'A', "\xc3\x85"=>'A',
261    "\xc3\x87"=>'C', "\xc3\x88"=>'E',
262    "\xc3\x89"=>'E', "\xc3\x8a"=>'E',
263    "\xc3\x8b"=>'E', "\xc3\x8c"=>'I',
264    "\xc3\x8d"=>'I', "\xc3\x8e"=>'I',
265    "\xc3\x8f"=>'I', "\xc3\x91"=>'N',
266    "\xc3\x92"=>'O', "\xc3\x93"=>'O',
267    "\xc3\x94"=>'O', "\xc3\x95"=>'O',
268    "\xc3\x96"=>'O', "\xc3\x99"=>'U',
269    "\xc3\x9a"=>'U', "\xc3\x9b"=>'U',
270    "\xc3\x9c"=>'U', "\xc3\x9d"=>'Y',
271    "\xc3\x9f"=>'s', "\xc3\xa0"=>'a',
272    "\xc3\xa1"=>'a', "\xc3\xa2"=>'a',
273    "\xc3\xa3"=>'a', "\xc3\xa4"=>'a',
274    "\xc3\xa5"=>'a', "\xc3\xa7"=>'c',
275    "\xc3\xa8"=>'e', "\xc3\xa9"=>'e',
276    "\xc3\xaa"=>'e', "\xc3\xab"=>'e',
277    "\xc3\xac"=>'i', "\xc3\xad"=>'i',
278    "\xc3\xae"=>'i', "\xc3\xaf"=>'i',
279    "\xc3\xb1"=>'n', "\xc3\xb2"=>'o',
280    "\xc3\xb3"=>'o', "\xc3\xb4"=>'o',
281    "\xc3\xb5"=>'o', "\xc3\xb6"=>'o',
282    "\xc3\xb9"=>'u', "\xc3\xba"=>'u',
283    "\xc3\xbb"=>'u', "\xc3\xbc"=>'u',
284    "\xc3\xbd"=>'y', "\xc3\xbf"=>'y',
285    // Decompositions for Latin Extended-A
286    "\xc4\x80"=>'A', "\xc4\x81"=>'a',
287    "\xc4\x82"=>'A', "\xc4\x83"=>'a',
288    "\xc4\x84"=>'A', "\xc4\x85"=>'a',
289    "\xc4\x86"=>'C', "\xc4\x87"=>'c',
290    "\xc4\x88"=>'C', "\xc4\x89"=>'c',
291    "\xc4\x8a"=>'C', "\xc4\x8b"=>'c',
292    "\xc4\x8c"=>'C', "\xc4\x8d"=>'c',
293    "\xc4\x8e"=>'D', "\xc4\x8f"=>'d',
294    "\xc4\x90"=>'D', "\xc4\x91"=>'d',
295    "\xc4\x92"=>'E', "\xc4\x93"=>'e',
296    "\xc4\x94"=>'E', "\xc4\x95"=>'e',
297    "\xc4\x96"=>'E', "\xc4\x97"=>'e',
298    "\xc4\x98"=>'E', "\xc4\x99"=>'e',
299    "\xc4\x9a"=>'E', "\xc4\x9b"=>'e',
300    "\xc4\x9c"=>'G', "\xc4\x9d"=>'g',
301    "\xc4\x9e"=>'G', "\xc4\x9f"=>'g',
302    "\xc4\xa0"=>'G', "\xc4\xa1"=>'g',
303    "\xc4\xa2"=>'G', "\xc4\xa3"=>'g',
304    "\xc4\xa4"=>'H', "\xc4\xa5"=>'h',
305    "\xc4\xa6"=>'H', "\xc4\xa7"=>'h',
306    "\xc4\xa8"=>'I', "\xc4\xa9"=>'i',
307    "\xc4\xaa"=>'I', "\xc4\xab"=>'i',
308    "\xc4\xac"=>'I', "\xc4\xad"=>'i',
309    "\xc4\xae"=>'I', "\xc4\xaf"=>'i',
310    "\xc4\xb0"=>'I', "\xc4\xb1"=>'i',
311    "\xc4\xb2"=>'IJ', "\xc4\xb3"=>'ij',
312    "\xc4\xb4"=>'J', "\xc4\xb5"=>'j',
313    "\xc4\xb6"=>'K', "\xc4\xb7"=>'k',
314    "\xc4\xb8"=>'k', "\xc4\xb9"=>'L',
315    "\xc4\xba"=>'l', "\xc4\xbb"=>'L',
316    "\xc4\xbc"=>'l', "\xc4\xbd"=>'L',
317    "\xc4\xbe"=>'l', "\xc4\xbf"=>'L',
318    "\xc5\x80"=>'l', "\xc5\x81"=>'L',
319    "\xc5\x82"=>'l', "\xc5\x83"=>'N',
320    "\xc5\x84"=>'n', "\xc5\x85"=>'N',
321    "\xc5\x86"=>'n', "\xc5\x87"=>'N',
322    "\xc5\x88"=>'n', "\xc5\x89"=>'N',
323    "\xc5\x8a"=>'n', "\xc5\x8b"=>'N',
324    "\xc5\x8c"=>'O', "\xc5\x8d"=>'o',
325    "\xc5\x8e"=>'O', "\xc5\x8f"=>'o',
326    "\xc5\x90"=>'O', "\xc5\x91"=>'o',
327    "\xc5\x92"=>'OE', "\xc5\x93"=>'oe',
328    "\xc5\x94"=>'R', "\xc5\x95"=>'r',
329    "\xc5\x96"=>'R', "\xc5\x97"=>'r',
330    "\xc5\x98"=>'R', "\xc5\x99"=>'r',
331    "\xc5\x9a"=>'S', "\xc5\x9b"=>'s',
332    "\xc5\x9c"=>'S', "\xc5\x9d"=>'s',
333    "\xc5\x9e"=>'S', "\xc5\x9f"=>'s',
334    "\xc5\xa0"=>'S', "\xc5\xa1"=>'s',
335    "\xc5\xa2"=>'T', "\xc5\xa3"=>'t',
336    "\xc5\xa4"=>'T', "\xc5\xa5"=>'t',
337    "\xc5\xa6"=>'T', "\xc5\xa7"=>'t',
338    "\xc5\xa8"=>'U', "\xc5\xa9"=>'u',
339    "\xc5\xaa"=>'U', "\xc5\xab"=>'u',
340    "\xc5\xac"=>'U', "\xc5\xad"=>'u',
341    "\xc5\xae"=>'U', "\xc5\xaf"=>'u',
342    "\xc5\xb0"=>'U', "\xc5\xb1"=>'u',
343    "\xc5\xb2"=>'U', "\xc5\xb3"=>'u',
344    "\xc5\xb4"=>'W', "\xc5\xb5"=>'w',
345    "\xc5\xb6"=>'Y', "\xc5\xb7"=>'y',
346    "\xc5\xb8"=>'Y', "\xc5\xb9"=>'Z',
347    "\xc5\xba"=>'z', "\xc5\xbb"=>'Z',
348    "\xc5\xbc"=>'z', "\xc5\xbd"=>'Z',
349    "\xc5\xbe"=>'z', "\xc5\xbf"=>'s',
350    // Euro Sign
351    "\xe2\x82\xac"=>'E',
352    // GBP (Pound) Sign
353    "\xc2\xa3"=>'');
354
355    $string = strtr($string, $chars);
356  } else {
357    // Assume ISO-8859-1 if not UTF-8
358    $chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158)
359      .chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194)
360      .chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202)
361      .chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210)
362      .chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218)
363      .chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227)
364      .chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235)
365      .chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243)
366      .chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251)
367      .chr(252).chr(253).chr(255);
368
369    $chars['out'] = "EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy";
370
371    $string = strtr($string, $chars['in'], $chars['out']);
372    $double_chars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254));
373    $double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th');
374    $string = str_replace($double_chars['in'], $double_chars['out'], $string);
375  }
376
377  return $string;
378}
379
380/**
381 * simplify a string to insert it into an URL
382 *
383 * @param string
384 * @return string
385 */
386function str2url($str)
387{
388  $raw = $str;
389
390  $str = remove_accents($str);
391  $str = preg_replace('/[^a-z0-9_\s\'\:\/\[\],-]/','',strtolower($str));
392  $str = preg_replace('/[\s\'\:\/\[\],-]+/',' ',trim($str));
393  $res = str_replace(' ','_',$str);
394
395  if (empty($res))
396  {
397    $res = str_replace(' ','_', $raw);
398  }
399
400  return $res;
401}
402
403//-------------------------------------------- Piwigo specific functions
404
405/**
406 * returns an array with a list of {language_code => language_name}
407 *
408 * @returns array
409 */
410function get_languages()
411{
412  $query = '
413SELECT id, name
414  FROM '.LANGUAGES_TABLE.'
415  ORDER BY name ASC
416;';
417  $result = pwg_query($query);
418
419  $languages = array();
420  while ($row = pwg_db_fetch_assoc($result))
421  {
422    if (is_dir(PHPWG_ROOT_PATH.'language/'.$row['id']))
423    {
424      $languages[ $row['id'] ] = $row['name'];
425    }
426  }
427
428  return $languages;
429}
430
431function pwg_log($image_id = null, $image_type = null)
432{
433  global $conf, $user, $page;
434
435  $do_log = $conf['log'];
436  if (is_admin())
437  {
438    $do_log = $conf['history_admin'];
439  }
440  if (is_a_guest())
441  {
442    $do_log = $conf['history_guest'];
443  }
444
445  $do_log = trigger_event('pwg_log_allowed', $do_log, $image_id, $image_type);
446
447  if (!$do_log)
448  {
449    return false;
450  }
451
452  $tags_string = null;
453  if ('tags'==@$page['section'])
454  {
455    $tags_string = implode(',', $page['tag_ids']);
456  }
457
458  $query = '
459INSERT INTO '.HISTORY_TABLE.'
460  (
461    date,
462    time,
463    user_id,
464    IP,
465    section,
466    category_id,
467    image_id,
468    image_type,
469    tag_ids
470  )
471  VALUES
472  (
473    CURRENT_DATE,
474    CURRENT_TIME,
475    '.$user['id'].',
476    \''.$_SERVER['REMOTE_ADDR'].'\',
477    '.(isset($page['section']) ? "'".$page['section']."'" : 'NULL').',
478    '.(isset($page['category']['id']) ? $page['category']['id'] : 'NULL').',
479    '.(isset($image_id) ? $image_id : 'NULL').',
480    '.(isset($image_type) ? "'".$image_type."'" : 'NULL').',
481    '.(isset($tags_string) ? "'".$tags_string."'" : 'NULL').'
482  )
483;';
484  pwg_query($query);
485
486  return true;
487}
488
489// format_date returns a formatted date for display. The date given in
490// argument must be an american format (2003-09-15). By option, you can show the time.
491// The output is internationalized.
492//
493// format_date( "2003-09-15", true ) -> "Monday 15 September 2003 21:52"
494function format_date($date, $show_time = false, $show_day_name = true)
495{
496  global $lang;
497
498  if (strpos($date, '0') == 0)
499  {
500    return l10n('N/A');
501  }
502
503  $ymdhms = array();
504  $tok = strtok( $date, '- :');
505  while ($tok !== false)
506  {
507    $ymdhms[] = $tok;
508    $tok = strtok('- :');
509  }
510
511  if ( count($ymdhms)<3 )
512  {
513    return false;
514  }
515
516  $formated_date = '';
517  // before 1970, Microsoft Windows can't mktime
518  if ($show_day_name and $ymdhms[0] >= 1970)
519  {
520    // we ask midday because Windows think it's prior to midnight with a
521    // zero and refuse to work
522    $formated_date.= $lang['day'][date('w', mktime(12,0,0,$ymdhms[1],$ymdhms[2],$ymdhms[0]))];
523  }
524  $formated_date.= ' '.$ymdhms[2];
525  $formated_date.= ' '.$lang['month'][(int)$ymdhms[1]];
526  $formated_date.= ' '.$ymdhms[0];
527  if ($show_time and count($ymdhms)>=5 )
528  {
529    $formated_date.= ' '.$ymdhms[3].':'.$ymdhms[4];
530  }
531  return $formated_date;
532}
533
534/**
535 * Works out the time since the entry post, takes a an argument in unix time or datetime
536 */
537function time_since($original, $stop = 'minute')
538{
539  if (!is_int($original))
540  {
541    $ymdhms = array();
542    $tok = strtok($original, '- :');
543    while ($tok !== false)
544    {
545      $ymdhms[] = $tok;
546      $tok = strtok('- :');
547    }
548   
549    if ($ymdhms[0] < 1970) return false;
550    if (!isset($ymdhms[3])) $ymdhms[3] = 12;
551    if (!isset($ymdhms[4])) $ymdhms[4] = 0;
552    if (!isset($ymdhms[5])) $ymdhms[5] = 0;
553    $original = mktime($ymdhms[3],$ymdhms[4],$ymdhms[5],$ymdhms[1],$ymdhms[2],$ymdhms[0]);
554  }
555 
556  // array of time period chunks
557  $chunks = array(
558    'year' => 60 * 60 * 24 * 365,
559    'month' => 60 * 60 * 24 * 30,
560    'week' => 60 * 60 * 24 * 7,
561    'day' => 60 * 60 * 24,
562    'hour' => 60 * 60,
563    'minute' => 60,
564    'second' => 1,
565  );
566 
567  $today = time(); /* Current unix time  */
568  $since = abs($today - $original);
569 
570  $print = null;
571  foreach ($chunks as $name => $seconds)
572  {
573    if (($count = floor($since / $seconds)) != 0)
574    {
575      $print.= l10n_dec('%d '.$name, '%d '.$name.'s', $count);
576      $since-= $count*$seconds;
577    }
578    if (!empty($print) and $chunks[$name] <= $chunks[$stop])
579    {
580      break;
581    }
582  }
583
584  if ($today > $original) 
585  {
586    $print = sprintf(l10n('%s ago'), $print);
587  }
588  else
589  {
590    $print = sprintf(l10n('%s in the future'), $print);
591  }
592 
593  return $print;
594}
595
596function pwg_debug( $string )
597{
598  global $debug,$t2,$page;
599
600  $now = explode( ' ', microtime() );
601  $now2 = explode( '.', $now[0] );
602  $now2 = $now[1].'.'.$now2[1];
603  $time = number_format( $now2 - $t2, 3, '.', ' ').' s';
604  $debug .= '<p>';
605  $debug.= '['.$time.', ';
606  $debug.= $page['count_queries'].' queries] : '.$string;
607  $debug.= "</p>\n";
608}
609
610/**
611 * Redirects to the given URL (HTTP method)
612 *
613 * Note : once this function called, the execution doesn't go further
614 * (presence of an exit() instruction.
615 *
616 * @param string $url
617 * @return void
618 */
619function redirect_http( $url )
620{
621  if (ob_get_length () !== FALSE)
622  {
623    ob_clean();
624  }
625  // default url is on html format
626  $url = html_entity_decode($url);
627  header('Request-URI: '.$url);
628  header('Content-Location: '.$url);
629  header('Location: '.$url);
630  exit();
631}
632
633/**
634 * Redirects to the given URL (HTML method)
635 *
636 * Note : once this function called, the execution doesn't go further
637 * (presence of an exit() instruction.
638 *
639 * @param string $url
640 * @param string $title_msg
641 * @param integer $refreh_time
642 * @return void
643 */
644function redirect_html( $url , $msg = '', $refresh_time = 0)
645{
646  global $user, $template, $lang_info, $conf, $lang, $t2, $page, $debug;
647
648  if (!isset($lang_info) || !isset($template) )
649  {
650    $user = build_user( $conf['guest_id'], true);
651    load_language('common.lang');
652    trigger_action('loading_lang');
653    load_language('lang', PHPWG_ROOT_PATH.PWG_LOCAL_DIR, array('no_fallback'=>true, 'local'=>true) );
654    $template = new Template(PHPWG_ROOT_PATH.'themes', get_default_theme());
655  }
656        elseif (defined('IN_ADMIN') and IN_ADMIN)
657        {
658                $template = new Template(PHPWG_ROOT_PATH.'themes', get_default_theme());
659        }
660
661  if (empty($msg))
662  {
663    $msg = nl2br(l10n('Redirection...'));
664  }
665
666  $refresh = $refresh_time;
667  $url_link = $url;
668  $title = 'redirection';
669
670  $template->set_filenames( array( 'redirect' => 'redirect.tpl' ) );
671
672  include( PHPWG_ROOT_PATH.'include/page_header.php' );
673
674  $template->set_filenames( array( 'redirect' => 'redirect.tpl' ) );
675  $template->assign('REDIRECT_MSG', $msg);
676
677  $template->parse('redirect');
678
679  include( PHPWG_ROOT_PATH.'include/page_tail.php' );
680
681  exit();
682}
683
684/**
685 * Redirects to the given URL (Switch to HTTP method or HTML method)
686 *
687 * Note : once this function called, the execution doesn't go further
688 * (presence of an exit() instruction.
689 *
690 * @param string $url
691 * @param string $title_msg
692 * @param integer $refreh_time
693 * @return void
694 */
695function redirect( $url , $msg = '', $refresh_time = 0)
696{
697  global $conf;
698
699  // with RefeshTime <> 0, only html must be used
700  if ($conf['default_redirect_method']=='http'
701      and $refresh_time==0
702      and !headers_sent()
703    )
704  {
705    redirect_http($url);
706  }
707  else
708  {
709    redirect_html($url, $msg, $refresh_time);
710  }
711}
712
713/**
714 * returns $_SERVER['QUERY_STRING'] whitout keys given in parameters
715 *
716 * @param array $rejects
717 * @param boolean $escape - if true escape & to &amp; (for html)
718 * @returns string
719 */
720function get_query_string_diff($rejects=array(), $escape=true)
721{
722  if (empty($_SERVER['QUERY_STRING']))
723  {
724    return '';
725  }
726
727  $query_string = '';
728
729  $str = $_SERVER['QUERY_STRING'];
730  parse_str($str, $vars);
731
732  $is_first = true;
733  foreach ($vars as $key => $value)
734  {
735    if (!in_array($key, $rejects))
736    {
737      $query_string.= $is_first ? '?' : ($escape ? '&amp;' : '&' );
738      $is_first = false;
739      $query_string.= $key.'='.$value;
740    }
741  }
742
743  return $query_string;
744}
745
746function url_is_remote($url)
747{
748  if ( strncmp($url, 'http://', 7)==0
749    or strncmp($url, 'https://', 8)==0 )
750  {
751    return true;
752  }
753  return false;
754}
755
756/**
757 * returns available themes
758 */
759function get_pwg_themes($show_mobile=false)
760{
761  global $conf;
762
763  $themes = array();
764
765  $query = '
766SELECT
767    id,
768    name
769  FROM '.THEMES_TABLE.'
770  ORDER BY name ASC
771;';
772  $result = pwg_query($query);
773  while ($row = pwg_db_fetch_assoc($result))
774  {
775    if ($row['id'] == $conf['mobile_theme'])
776    {
777      if (!$show_mobile)
778      {
779        continue;
780      }
781      $row['name'] .= ' ('.l10n('Mobile').')';
782    }
783    if (check_theme_installed($row['id']))
784    {
785      $themes[ $row['id'] ] = $row['name'];
786    }
787  }
788
789  // plugins want remove some themes based on user status maybe?
790  $themes = trigger_event('get_pwg_themes', $themes);
791
792  return $themes;
793}
794
795function check_theme_installed($theme_id)
796{
797  global $conf;
798
799  return file_exists($conf['themes_dir'].'/'.$theme_id.'/'.'themeconf.inc.php');
800}
801
802/** Transforms an original path to its pwg representative */
803function original_to_representative($path, $representative_ext)
804{
805  $pos = strrpos($path, '/');
806  $path = substr_replace($path, 'pwg_representative/', $pos+1, 0);
807  $pos = strrpos($path, '.');
808  return substr_replace($path, $representative_ext, $pos+1);
809}
810
811/**
812 * @param element_info array containing element information from db;
813 * at least 'id', 'path' should be present
814 */
815function get_element_path($element_info)
816{
817  $path = $element_info['path'];
818  if ( !url_is_remote($path) )
819  {
820    $path = PHPWG_ROOT_PATH.$path;
821  }
822  return $path;
823}
824
825
826/* Returns the URL of the thumbnail to be displayed. If the element does not
827 * have a thumbnail, the default mime image url is returned. The URL can be
828 * sent to the browser, but not used in the php script.
829 * @param array element_info assoc array containing element info from db
830 * at least 'path', 'tn_ext' and 'id' should be present
831 */
832function get_thumbnail_url($element_info)
833{
834  return DerivativeImage::thumb_url($element_info);
835}
836
837/**
838 * fill the current user caddie with given elements, if not already in
839 * caddie
840 *
841 * @param array elements_id
842 */
843function fill_caddie($elements_id)
844{
845  global $user;
846
847  $query = '
848SELECT element_id
849  FROM '.CADDIE_TABLE.'
850  WHERE user_id = '.$user['id'].'
851;';
852  $in_caddie = array_from_query($query, 'element_id');
853
854  $caddiables = array_diff($elements_id, $in_caddie);
855
856  $datas = array();
857
858  foreach ($caddiables as $caddiable)
859  {
860    array_push($datas, array('element_id' => $caddiable,
861                             'user_id' => $user['id']));
862  }
863
864  if (count($caddiables) > 0)
865  {
866    mass_inserts(CADDIE_TABLE, array('element_id','user_id'), $datas);
867  }
868}
869
870/**
871 * returns the element name from its filename
872 *
873 * @param string filename
874 * @return string name
875 */
876function get_name_from_file($filename)
877{
878  return str_replace('_',' ',get_filename_wo_extension($filename));
879}
880
881/**
882 * returns the corresponding value from $lang if existing. Else, the key is
883 * returned
884 *
885 * @param string key
886 * @return string
887 */
888function l10n($key)
889{
890  global $lang, $conf;
891
892  if ( ($val=@$lang[$key]) == null)
893  {
894    if ($conf['debug_l10n'] and !isset($lang[$key]) and !empty($key))
895    {
896      trigger_error('[l10n] language key "'.$key.'" is not defined', E_USER_WARNING);
897    }
898    $val = $key;
899  }
900  return $val;
901}
902
903/**
904 * returns the prinft value for strings including %d
905 * return is concorded with decimal value (singular, plural)
906 *
907 * @param singular string key
908 * @param plural string key
909 * @param decimal value
910 * @return string
911 */
912function l10n_dec($singular_fmt_key, $plural_fmt_key, $decimal)
913{
914  global $lang_info;
915
916  return
917    sprintf(
918      l10n((
919        (($decimal > 1) or ($decimal == 0 and $lang_info['zero_plural']))
920          ? $plural_fmt_key
921          : $singular_fmt_key
922        )), $decimal);
923}
924
925/*
926 * returns a single element to use with l10n_args
927 *
928 * @param string key: translation key
929 * @param array/string/../number args:
930 *   arguments to use on sprintf($key, args)
931 *   if args is a array, each values are used on sprintf
932 * @return string
933 */
934function get_l10n_args($key, $args)
935{
936  if (is_array($args))
937  {
938    $key_arg = array_merge(array($key), $args);
939  }
940  else
941  {
942    $key_arg = array($key,  $args);
943  }
944  return array('key_args' => $key_arg);
945}
946
947/*
948 * returns a string with formated with l10n_args elements
949 *
950 * @param element/array $key_args: element or array of l10n_args elements
951 * @param $sep: if $key_args is array,
952 *   separator is used when translated l10n_args elements are concated
953 * @return string
954 */
955function l10n_args($key_args, $sep = "\n")
956{
957  if (is_array($key_args))
958  {
959    foreach ($key_args as $key => $element)
960    {
961      if (isset($result))
962      {
963        $result .= $sep;
964      }
965      else
966      {
967        $result = '';
968      }
969
970      if ($key === 'key_args')
971      {
972        array_unshift($element, l10n(array_shift($element)));
973        $result .= call_user_func_array('sprintf', $element);
974      }
975      else
976      {
977        $result .= l10n_args($element, $sep);
978      }
979    }
980  }
981  else
982  {
983    fatal_error('l10n_args: Invalid arguments');
984  }
985
986  return $result;
987}
988
989/**
990 * returns the corresponding value from $themeconf if existing. Else, the
991 * key is returned
992 *
993 * @param string key
994 * @return string
995 */
996function get_themeconf($key)
997{
998  global $template;
999
1000  return $template->get_themeconf($key);
1001}
1002
1003/**
1004 * Returns webmaster mail address depending on $conf['webmaster_id']
1005 *
1006 * @return string
1007 */
1008function get_webmaster_mail_address()
1009{
1010  global $conf;
1011
1012  $query = '
1013SELECT '.$conf['user_fields']['email'].'
1014  FROM '.USERS_TABLE.'
1015  WHERE '.$conf['user_fields']['id'].' = '.$conf['webmaster_id'].'
1016;';
1017  list($email) = pwg_db_fetch_row(pwg_query($query));
1018
1019  return $email;
1020}
1021
1022/**
1023 * Add configuration parameters from database to global $conf array
1024 *
1025 * @return void
1026 */
1027function load_conf_from_db($condition = '')
1028{
1029  global $conf;
1030
1031  $query = '
1032SELECT param, value
1033 FROM '.CONFIG_TABLE.'
1034 '.(!empty($condition) ? 'WHERE '.$condition : '').'
1035;';
1036  $result = pwg_query($query);
1037
1038  if ((pwg_db_num_rows($result) == 0) and !empty($condition))
1039  {
1040    fatal_error('No configuration data');
1041  }
1042
1043  while ($row = pwg_db_fetch_assoc($result))
1044  {
1045    $val = isset($row['value']) ? $row['value'] : '';
1046    // If the field is true or false, the variable is transformed into a boolean value.
1047    if ($val == 'true')
1048    {
1049      $val = true;
1050    }
1051    elseif ($val == 'false')
1052    {
1053      $val = false;
1054    }
1055    $conf[ $row['param'] ] = $val;
1056  }
1057}
1058
1059function conf_update_param($param, $value)
1060{
1061  $query = '
1062SELECT
1063    param,
1064    value
1065  FROM '.CONFIG_TABLE.'
1066  WHERE param = \''.$param.'\'
1067;';
1068  $params = array_from_query($query, 'param');
1069
1070  if (count($params) == 0)
1071  {
1072    $query = '
1073INSERT
1074  INTO '.CONFIG_TABLE.'
1075  (param, value)
1076  VALUES(\''.$param.'\', \''.$value.'\')
1077;';
1078    pwg_query($query);
1079  }
1080  else
1081  {
1082    $query = '
1083UPDATE '.CONFIG_TABLE.'
1084  SET value = \''.$value.'\'
1085  WHERE param = \''.$param.'\'
1086;';
1087    pwg_query($query);
1088  }
1089}
1090
1091/**
1092 * Prepends and appends a string at each value of the given array.
1093 *
1094 * @param array
1095 * @param string prefix to each array values
1096 * @param string suffix to each array values
1097 */
1098function prepend_append_array_items($array, $prepend_str, $append_str)
1099{
1100  array_walk(
1101    $array,
1102    create_function('&$s', '$s = "'.$prepend_str.'".$s."'.$append_str.'";')
1103    );
1104
1105  return $array;
1106}
1107
1108/**
1109 * creates an hashed based on a query, this function is a very common
1110 * pattern used here. Among the selected columns fetched, choose one to be
1111 * the key, another one to be the value.
1112 *
1113 * @param string $query
1114 * @param string $keyname
1115 * @param string $valuename
1116 * @return array
1117 */
1118function simple_hash_from_query($query, $keyname, $valuename)
1119{
1120  $array = array();
1121
1122  $result = pwg_query($query);
1123  while ($row = pwg_db_fetch_assoc($result))
1124  {
1125    $array[ $row[$keyname] ] = $row[$valuename];
1126  }
1127
1128  return $array;
1129}
1130
1131/**
1132 * creates an hashed based on a query, this function is a very common
1133 * pattern used here. The key is given as parameter, the value is an associative
1134 * array.
1135 *
1136 * @param string $query
1137 * @param string $keyname
1138 * @return array
1139 */
1140function hash_from_query($query, $keyname)
1141{
1142  $array = array();
1143  $result = pwg_query($query);
1144  while ($row = pwg_db_fetch_assoc($result))
1145  {
1146    $array[ $row[$keyname] ] = $row;
1147  }
1148  return $array;
1149}
1150
1151/**
1152 * Return basename of the current script
1153 * Lower case convertion is applied on return value
1154 * Return value is without file extention ".php"
1155 *
1156 * @param void
1157 *
1158 * @return script basename
1159 */
1160function script_basename()
1161{
1162  global $conf;
1163
1164  foreach (array('SCRIPT_NAME', 'SCRIPT_FILENAME', 'PHP_SELF') as $value)
1165  {
1166    if (!empty($_SERVER[$value]))
1167    {
1168      $filename = strtolower($_SERVER[$value]);
1169      if ($conf['php_extension_in_urls'] and get_extension($filename)!=='php')
1170        continue;
1171      $basename = basename($filename, '.php');
1172      if (!empty($basename))
1173      {
1174        return $basename;
1175      }
1176    }
1177  }
1178  return '';
1179}
1180
1181/**
1182 * Return value for the current page define on $conf['filter_pages']
1183 * Îf value is not defined, default value are returned
1184 *
1185 * @param value name
1186 *
1187 * @return filter page value
1188 */
1189function get_filter_page_value($value_name)
1190{
1191  global $conf;
1192
1193  $page_name = script_basename();
1194
1195  if (isset($conf['filter_pages'][$page_name][$value_name]))
1196  {
1197    return $conf['filter_pages'][$page_name][$value_name];
1198  }
1199  else if (isset($conf['filter_pages']['default'][$value_name]))
1200  {
1201    return $conf['filter_pages']['default'][$value_name];
1202  }
1203  else
1204  {
1205    return null;
1206  }
1207}
1208
1209/**
1210 * returns the character set of data sent to browsers / received from forms
1211 */
1212function get_pwg_charset()
1213{
1214  $pwg_charset = 'utf-8';
1215  if (defined('PWG_CHARSET'))
1216  {
1217    $pwg_charset = PWG_CHARSET;
1218  }
1219  return $pwg_charset;
1220}
1221
1222/**
1223 * includes a language file or returns the content of a language file
1224 * availability of the file
1225 *
1226 * in descending order of preference:
1227 *   param language, user language, default language
1228 * Piwigo default language.
1229 *
1230 * @param string filename
1231 * @param string dirname
1232 * @param mixed options can contain
1233 *     language - language to load (if empty uses user language)
1234 *     return - if true the file content is returned otherwise the file is evaluated as php
1235 *     target_charset -
1236 *     no_fallback - the language must be respected
1237 *     local - if true, get local language file
1238 * @return boolean success status or a string if options['return'] is true
1239 */
1240function load_language($filename, $dirname = '',
1241    $options = array() )
1242{
1243  global $user;
1244
1245  if (! @$options['return'] )
1246  {
1247    $filename .= '.php'; //MAYBE to do .. load .po and .mo localization files
1248  }
1249  if (empty($dirname))
1250  {
1251    $dirname = PHPWG_ROOT_PATH;
1252  }
1253  $dirname .= 'language/';
1254
1255  $languages = array();
1256  if ( !empty($options['language']) )
1257  {
1258    $languages[] = $options['language'];
1259  }
1260  if ( !empty($user['language']) )
1261  {
1262    $languages[] = $user['language'];
1263  }
1264  if ( ! @$options['no_fallback'] )
1265  {
1266    if ( defined('PHPWG_INSTALLED') )
1267    {
1268      $languages[] = get_default_language();
1269    }
1270    $languages[] = PHPWG_DEFAULT_LANGUAGE;
1271  }
1272
1273  $languages = array_unique($languages);
1274
1275  if ( empty($options['target_charset']) )
1276  {
1277    $target_charset = get_pwg_charset();
1278  }
1279  else
1280  {
1281    $target_charset = $options['target_charset'];
1282  }
1283  $target_charset = strtolower($target_charset);
1284  $source_file    = '';
1285  foreach ($languages as $language)
1286  {
1287    $f = @$options['local'] ?
1288      $dirname.$language.'.'.$filename:
1289      $dirname.$language.'/'.$filename;
1290
1291    if (file_exists($f))
1292    {
1293      $source_file = $f;
1294      break;
1295    }
1296  }
1297
1298  if ( !empty($source_file) )
1299  {
1300    if (! @$options['return'] )
1301    {
1302      @include($source_file);
1303      $load_lang = @$lang;
1304      $load_lang_info = @$lang_info;
1305
1306      global $lang, $lang_info;
1307      if ( !isset($lang) ) $lang=array();
1308      if ( !isset($lang_info) ) $lang_info=array();
1309
1310      if ( 'utf-8'!=$target_charset)
1311      {
1312        if ( is_array($load_lang) )
1313        {
1314          foreach ($load_lang as $k => $v)
1315          {
1316            if ( is_array($v) )
1317            {
1318              $func = create_function('$v', 'return convert_charset($v, "utf-8", "'.$target_charset.'");' );
1319              $lang[$k] = array_map($func, $v);
1320            }
1321            else
1322              $lang[$k] = convert_charset($v, 'utf-8', $target_charset);
1323          }
1324        }
1325        if ( is_array($load_lang_info) )
1326        {
1327          foreach ($load_lang_info as $k => $v)
1328          {
1329            $lang_info[$k] = convert_charset($v, 'utf-8', $target_charset);
1330          }
1331        }
1332      }
1333      else
1334      {
1335        $lang = array_merge( $lang, (array)$load_lang );
1336        $lang_info = array_merge( $lang_info, (array)$load_lang_info );
1337      }
1338      return true;
1339    }
1340    else
1341    {
1342      $content = @file_get_contents($source_file);
1343      $content = convert_charset($content, 'utf-8', $target_charset);
1344      return $content;
1345    }
1346  }
1347  return false;
1348}
1349
1350/**
1351 * converts a string from a character set to another character set
1352 * @param string str the string to be converted
1353 * @param string source_charset the character set in which the string is encoded
1354 * @param string dest_charset the destination character set
1355 */
1356function convert_charset($str, $source_charset, $dest_charset)
1357{
1358  if ($source_charset==$dest_charset)
1359    return $str;
1360  if ($source_charset=='iso-8859-1' and $dest_charset=='utf-8')
1361  {
1362    return utf8_encode($str);
1363  }
1364  if ($source_charset=='utf-8' and $dest_charset=='iso-8859-1')
1365  {
1366    return utf8_decode($str);
1367  }
1368  if (function_exists('iconv'))
1369  {
1370    return iconv($source_charset, $dest_charset, $str);
1371  }
1372  if (function_exists('mb_convert_encoding'))
1373  {
1374    return mb_convert_encoding( $str, $dest_charset, $source_charset );
1375  }
1376  return $str; //???
1377}
1378
1379/**
1380 * makes sure a index.htm protects the directory from browser file listing
1381 *
1382 * @param string dir directory
1383 */
1384function secure_directory($dir)
1385{
1386  $file = $dir.'/index.htm';
1387  if (!file_exists($file))
1388  {
1389    @file_put_contents($file, 'Not allowed!');
1390  }
1391}
1392
1393/**
1394 * returns a "secret key" that is to be sent back when a user posts a form
1395 *
1396 * @param int valid_after_seconds - key validity start time from now
1397 */
1398function get_ephemeral_key($valid_after_seconds, $aditionnal_data_to_hash = '')
1399{
1400        global $conf;
1401        $time = round(microtime(true), 1);
1402        return $time.':'.$valid_after_seconds.':'
1403                .hash_hmac(
1404                        'md5',
1405                        $time.substr($_SERVER['REMOTE_ADDR'],0,5).$valid_after_seconds.$aditionnal_data_to_hash,
1406                        $conf['secret_key']);
1407}
1408
1409function verify_ephemeral_key($key, $aditionnal_data_to_hash = '')
1410{
1411        global $conf;
1412        $time = microtime(true);
1413        $key = explode( ':', @$key );
1414        if ( count($key)!=3
1415                or $key[0]>$time-(float)$key[1] // page must have been retrieved more than X sec ago
1416                or $key[0]<$time-3600 // 60 minutes expiration
1417                or hash_hmac(
1418                          'md5', $key[0].substr($_SERVER['REMOTE_ADDR'],0,5).$key[1].$aditionnal_data_to_hash, $conf['secret_key']
1419                        ) != $key[2]
1420          )
1421        {
1422                return false;
1423        }
1424        return true;
1425}
1426
1427/**
1428 * return an array which will be sent to template to display navigation bar
1429 */
1430function create_navigation_bar($url, $nb_element, $start, $nb_element_page, $clean_url = false)
1431{
1432  global $conf;
1433
1434  $navbar = array();
1435  $pages_around = $conf['paginate_pages_around'];
1436  $start_str = $clean_url ? '/start-' : (strpos($url, '?')===false ? '?':'&amp;').'start=';
1437
1438  if (!isset($start) or !is_numeric($start) or (is_numeric($start) and $start < 0))
1439  {
1440    $start = 0;
1441  }
1442
1443  // navigation bar useful only if more than one page to display !
1444  if ($nb_element > $nb_element_page)
1445  {
1446    $cur_page = ceil($start / $nb_element_page) + 1;
1447    $maximum = ceil($nb_element / $nb_element_page);
1448    $previous = $start - $nb_element_page;
1449    $next = $start + $nb_element_page;
1450    $last = ($maximum - 1) * $nb_element_page;
1451
1452    $navbar['CURRENT_PAGE'] = $cur_page;
1453
1454    // link to first page and previous page?
1455    if ($cur_page != 1)
1456    {
1457      $navbar['URL_FIRST'] = $url;
1458      $navbar['URL_PREV'] = $url.($previous > 0 ? $start_str.$previous : '');
1459    }
1460    // link on next page and last page?
1461    if ($cur_page != $maximum)
1462    {
1463      $navbar['URL_NEXT'] = $url.$start_str.$next;
1464      $navbar['URL_LAST'] = $url.$start_str.$last;
1465    }
1466
1467    // pages to display
1468    $navbar['pages'] = array();
1469    $navbar['pages'][1] = $url;
1470    $navbar['pages'][$maximum] = $url.$start_str.$last;
1471
1472    for ($i = max($cur_page - $pages_around , 2), $stop = min($cur_page + $pages_around + 1, $maximum);
1473         $i < $stop; $i++)
1474    {
1475      $navbar['pages'][$i] = $url.$start_str.(($i - 1) * $nb_element_page);
1476    }
1477    ksort($navbar['pages']);
1478  }
1479  return $navbar;
1480}
1481
1482/**
1483 * return an array which will be sent to template to display recent icon
1484 */
1485function get_icon($date, $is_child_date = false)
1486{
1487  global $cache, $user;
1488
1489  if (empty($date))
1490  {
1491    return false;
1492  }
1493
1494  if (!isset($cache['get_icon']['title']))
1495  {
1496    $cache['get_icon']['title'] = sprintf(
1497      l10n('photos posted during the last %d days'),
1498      $user['recent_period']
1499      );
1500  }
1501
1502  $icon = array(
1503    'TITLE' => $cache['get_icon']['title'],
1504    'IS_CHILD_DATE' => $is_child_date,
1505    );
1506
1507  if (isset($cache['get_icon'][$date]))
1508  {
1509    return $cache['get_icon'][$date] ? $icon : array();
1510  }
1511
1512  if (!isset($cache['get_icon']['sql_recent_date']))
1513  {
1514    // Use MySql date in order to standardize all recent "actions/queries"
1515    $cache['get_icon']['sql_recent_date'] = pwg_db_get_recent_period($user['recent_period']);
1516  }
1517
1518  $cache['get_icon'][$date] = $date > $cache['get_icon']['sql_recent_date'];
1519
1520  return $cache['get_icon'][$date] ? $icon : array();
1521}
1522
1523/**
1524 * check token comming from form posted or get params to prevent csrf attacks
1525 * if pwg_token is empty action doesn't require token
1526 * else pwg_token is compare to server token
1527 *
1528 * @return void access denied if token given is not equal to server token
1529 */
1530function check_pwg_token()
1531{
1532  if (!empty($_REQUEST['pwg_token']))
1533  {
1534    if (get_pwg_token() != $_REQUEST['pwg_token'])
1535    {
1536      access_denied();
1537    }
1538  }
1539  else
1540    bad_request('missing token');
1541}
1542
1543function get_pwg_token()
1544{
1545  global $conf;
1546
1547  return hash_hmac('md5', session_id(), $conf['secret_key']);
1548}
1549
1550/*
1551 * breaks the script execution if the given value doesn't match the given
1552 * pattern. This should happen only during hacking attempts.
1553 *
1554 * @param string param_name
1555 * @param array param_array
1556 * @param boolean is_array
1557 * @param string pattern
1558 *
1559 * @return void
1560 */
1561function check_input_parameter($param_name, $param_array, $is_array, $pattern)
1562{
1563  $param_value = null;
1564  if (isset($param_array[$param_name]))
1565  {
1566    $param_value = $param_array[$param_name];
1567  }
1568
1569  // it's ok if the input parameter is null
1570  if (empty($param_value))
1571  {
1572    return true;
1573  }
1574
1575  if ($is_array)
1576  {
1577    if (!is_array($param_value))
1578    {
1579      fatal_error('[Hacking attempt] the input parameter "'.$param_name.'" should be an array');
1580    }
1581
1582    foreach ($param_value as $item_to_check)
1583    {
1584      if (!preg_match($pattern, $item_to_check))
1585      {
1586        fatal_error('[Hacking attempt] an item is not valid in input parameter "'.$param_name.'"');
1587      }
1588    }
1589  }
1590  else
1591  {
1592    if (!preg_match($pattern, $param_value))
1593    {
1594      fatal_error('[Hacking attempt] the input parameter "'.$param_name.'" is not valid');
1595    }
1596  }
1597}
1598
1599
1600function get_privacy_level_options()
1601{
1602  global $conf;
1603
1604  $options = array();
1605  foreach (array_reverse($conf['available_permission_levels']) as $level)
1606  {
1607    $label = null;
1608
1609    if (0 == $level)
1610    {
1611      $label = l10n('Everybody');
1612    }
1613    else
1614    {
1615      $labels = array();
1616      $sub_levels = array_reverse($conf['available_permission_levels']);
1617      foreach ($sub_levels as $sub_level)
1618      {
1619        if ($sub_level == 0 or $sub_level < $level)
1620        {
1621          break;
1622        }
1623        array_push(
1624          $labels,
1625          l10n(
1626            sprintf(
1627              'Level %d',
1628              $sub_level
1629              )
1630            )
1631          );
1632      }
1633
1634      $label = implode(', ', $labels);
1635    }
1636    $options[$level] = $label;
1637  }
1638  return $options;
1639}
1640
1641
1642/**
1643 * return the branch from the version. For example version 2.2.4 is for branch 2.2
1644 */
1645function get_branch_from_version($version)
1646{
1647  return implode('.', array_slice(explode('.', $version), 0, 2));
1648}
1649
1650/**
1651 * return the device type: mobile, tablet or desktop
1652 */
1653function get_device()
1654{
1655  $device = pwg_get_session_var('device');
1656
1657  if (is_null($device))
1658  {
1659    include_once(PHPWG_ROOT_PATH.'include/mdetect.php');
1660    $uagent_obj = new uagent_info();
1661    if ($uagent_obj->DetectTierIphone())
1662    {
1663      $device = 'mobile';
1664    }
1665    elseif ($uagent_obj->DetectTierTablet())
1666    {
1667      $device = 'tablet';
1668    }
1669    else
1670    {
1671      $device = 'desktop';
1672    }
1673    pwg_set_session_var('device', $device);
1674  }
1675
1676  return $device;
1677}
1678
1679/**
1680 * return true if mobile theme should be loaded
1681 */
1682function mobile_theme()
1683{
1684  global $conf;
1685
1686  if (empty($conf['mobile_theme']))
1687  {
1688    return false;
1689  }
1690
1691  if (isset($_GET['mobile']))
1692  {
1693    $is_mobile_theme = get_boolean($_GET['mobile']);
1694    pwg_set_session_var('mobile_theme', $is_mobile_theme);
1695    unset($_GET['mobile']);
1696  }
1697  else
1698  {
1699    $is_mobile_theme = pwg_get_session_var('mobile_theme');
1700  }
1701
1702  if (is_null($is_mobile_theme))
1703  {
1704    $is_mobile_theme = (get_device() == 'mobile');
1705    pwg_set_session_var('mobile_theme', $is_mobile_theme);
1706  }
1707
1708  return $is_mobile_theme;
1709}
1710?>
Note: See TracBrowser for help on using the repository browser.