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

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