source: branches/2.1/include/functions.inc.php @ 6605

Last change on this file since 6605 was 6384, checked in by plg, 14 years ago

bug 1704 fixed: windows needs a specific directory separator when creating
recursive directory.

  • Property svn:eol-style set to LF
File size: 41.9 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
35function get_extra_fields($order_by_fields)
36{
37  $fields = str_ireplace(array(' order by ', ' desc', ' asc'),
38                         array('', '', ''),
39                         $order_by_fields
40                         );
41  if (!empty($fields))
42  {
43    $fields = ','.$fields;
44  }
45  return $fields;
46}
47
48// The function get_moment returns a float value coresponding to the number
49// of seconds since the unix epoch (1st January 1970) and the microseconds
50// are precised : e.g. 1052343429.89276600
51function get_moment()
52{
53  $t1 = explode( ' ', microtime() );
54  $t2 = explode( '.', $t1[0] );
55  $t2 = $t1[1].'.'.$t2[1];
56  return $t2;
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    if (substr(PHP_OS, 0, 3) == 'WIN')
172    {
173      $dir = str_replace('/', DIRECTORY_SEPARATOR, $dir);
174    }
175    $umask = umask(0);
176    $mkd = @mkdir($dir, 0755, ($flags&MKGETDIR_RECURSIVE) ? true:false );
177    umask($umask);
178    if ($mkd==false)
179    {
180      !($flags&MKGETDIR_DIE_ON_ERROR) or fatal_error( "$dir ".l10n('no write access'));
181      return false;
182    }
183    if( $flags&MKGETDIR_PROTECT_HTACCESS )
184    {
185      $file = $dir.'/.htaccess';
186      file_exists($file) or @file_put_contents( $file, 'deny from all' );
187    }
188    if( $flags&MKGETDIR_PROTECT_INDEX )
189    {
190      $file = $dir.'/index.htm';
191      file_exists($file) or @file_put_contents( $file, 'Not allowed!' );
192    }
193  }
194  if ( !is_writable($dir) )
195  {
196    !($flags&MKGETDIR_DIE_ON_ERROR) or fatal_error( "$dir ".l10n('no write access'));
197    return false;
198  }
199  return true;
200}
201
202/**
203 * returns thumbnail directory name of input diretoty name
204 * make thumbnail directory is necessary
205 * set error messages on array messages
206 *
207 * @param:
208 *  string $dirname
209 *  arrayy $errors
210 * @return bool false on error else string directory name
211 */
212function mkget_thumbnail_dir($dirname, &$errors)
213{
214  global $conf;
215
216  $tndir = $dirname.'/'.$conf['dir_thumbnail'];
217  if (! mkgetdir($tndir, MKGETDIR_NONE) )
218  {
219    array_push($errors,
220          '['.$dirname.'] : '.l10n('no write access'));
221    return false;
222  }
223  return $tndir;
224}
225
226/* Returns true if the string appears to be encoded in UTF-8. (from wordpress)
227 * @param string Str
228 */
229function seems_utf8($Str) { # by bmorel at ssi dot fr
230  for ($i=0; $i<strlen($Str); $i++) {
231    if (ord($Str[$i]) < 0x80) continue; # 0bbbbbbb
232    elseif ((ord($Str[$i]) & 0xE0) == 0xC0) $n=1; # 110bbbbb
233    elseif ((ord($Str[$i]) & 0xF0) == 0xE0) $n=2; # 1110bbbb
234    elseif ((ord($Str[$i]) & 0xF8) == 0xF0) $n=3; # 11110bbb
235    elseif ((ord($Str[$i]) & 0xFC) == 0xF8) $n=4; # 111110bb
236    elseif ((ord($Str[$i]) & 0xFE) == 0xFC) $n=5; # 1111110b
237    else return false; # Does not match any model
238    for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ?
239      if ((++$i == strlen($Str)) || ((ord($Str[$i]) & 0xC0) != 0x80))
240      return false;
241    }
242  }
243  return true;
244}
245
246/* Remove accents from a UTF-8 or ISO-859-1 string (from wordpress)
247 * @param string sstring - an UTF-8 or ISO-8859-1 string
248 */
249function remove_accents($string)
250{
251  if ( !preg_match('/[\x80-\xff]/', $string) )
252    return $string;
253
254  if (seems_utf8($string)) {
255    $chars = array(
256    // Decompositions for Latin-1 Supplement
257    chr(195).chr(128) => 'A', chr(195).chr(129) => 'A',
258    chr(195).chr(130) => 'A', chr(195).chr(131) => 'A',
259    chr(195).chr(132) => 'A', chr(195).chr(133) => 'A',
260    chr(195).chr(135) => 'C', chr(195).chr(136) => 'E',
261    chr(195).chr(137) => 'E', chr(195).chr(138) => 'E',
262    chr(195).chr(139) => 'E', chr(195).chr(140) => 'I',
263    chr(195).chr(141) => 'I', chr(195).chr(142) => 'I',
264    chr(195).chr(143) => 'I', chr(195).chr(145) => 'N',
265    chr(195).chr(146) => 'O', chr(195).chr(147) => 'O',
266    chr(195).chr(148) => 'O', chr(195).chr(149) => 'O',
267    chr(195).chr(150) => 'O', chr(195).chr(153) => 'U',
268    chr(195).chr(154) => 'U', chr(195).chr(155) => 'U',
269    chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y',
270    chr(195).chr(159) => 's', chr(195).chr(160) => 'a',
271    chr(195).chr(161) => 'a', chr(195).chr(162) => 'a',
272    chr(195).chr(163) => 'a', chr(195).chr(164) => 'a',
273    chr(195).chr(165) => 'a', chr(195).chr(167) => 'c',
274    chr(195).chr(168) => 'e', chr(195).chr(169) => 'e',
275    chr(195).chr(170) => 'e', chr(195).chr(171) => 'e',
276    chr(195).chr(172) => 'i', chr(195).chr(173) => 'i',
277    chr(195).chr(174) => 'i', chr(195).chr(175) => 'i',
278    chr(195).chr(177) => 'n', chr(195).chr(178) => 'o',
279    chr(195).chr(179) => 'o', chr(195).chr(180) => 'o',
280    chr(195).chr(181) => 'o', chr(195).chr(182) => 'o',
281    chr(195).chr(182) => 'o', chr(195).chr(185) => 'u',
282    chr(195).chr(186) => 'u', chr(195).chr(187) => 'u',
283    chr(195).chr(188) => 'u', chr(195).chr(189) => 'y',
284    chr(195).chr(191) => 'y',
285    // Decompositions for Latin Extended-A
286    chr(196).chr(128) => 'A', chr(196).chr(129) => 'a',
287    chr(196).chr(130) => 'A', chr(196).chr(131) => 'a',
288    chr(196).chr(132) => 'A', chr(196).chr(133) => 'a',
289    chr(196).chr(134) => 'C', chr(196).chr(135) => 'c',
290    chr(196).chr(136) => 'C', chr(196).chr(137) => 'c',
291    chr(196).chr(138) => 'C', chr(196).chr(139) => 'c',
292    chr(196).chr(140) => 'C', chr(196).chr(141) => 'c',
293    chr(196).chr(142) => 'D', chr(196).chr(143) => 'd',
294    chr(196).chr(144) => 'D', chr(196).chr(145) => 'd',
295    chr(196).chr(146) => 'E', chr(196).chr(147) => 'e',
296    chr(196).chr(148) => 'E', chr(196).chr(149) => 'e',
297    chr(196).chr(150) => 'E', chr(196).chr(151) => 'e',
298    chr(196).chr(152) => 'E', chr(196).chr(153) => 'e',
299    chr(196).chr(154) => 'E', chr(196).chr(155) => 'e',
300    chr(196).chr(156) => 'G', chr(196).chr(157) => 'g',
301    chr(196).chr(158) => 'G', chr(196).chr(159) => 'g',
302    chr(196).chr(160) => 'G', chr(196).chr(161) => 'g',
303    chr(196).chr(162) => 'G', chr(196).chr(163) => 'g',
304    chr(196).chr(164) => 'H', chr(196).chr(165) => 'h',
305    chr(196).chr(166) => 'H', chr(196).chr(167) => 'h',
306    chr(196).chr(168) => 'I', chr(196).chr(169) => 'i',
307    chr(196).chr(170) => 'I', chr(196).chr(171) => 'i',
308    chr(196).chr(172) => 'I', chr(196).chr(173) => 'i',
309    chr(196).chr(174) => 'I', chr(196).chr(175) => 'i',
310    chr(196).chr(176) => 'I', chr(196).chr(177) => 'i',
311    chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij',
312    chr(196).chr(180) => 'J', chr(196).chr(181) => 'j',
313    chr(196).chr(182) => 'K', chr(196).chr(183) => 'k',
314    chr(196).chr(184) => 'k', chr(196).chr(185) => 'L',
315    chr(196).chr(186) => 'l', chr(196).chr(187) => 'L',
316    chr(196).chr(188) => 'l', chr(196).chr(189) => 'L',
317    chr(196).chr(190) => 'l', chr(196).chr(191) => 'L',
318    chr(197).chr(128) => 'l', chr(197).chr(129) => 'L',
319    chr(197).chr(130) => 'l', chr(197).chr(131) => 'N',
320    chr(197).chr(132) => 'n', chr(197).chr(133) => 'N',
321    chr(197).chr(134) => 'n', chr(197).chr(135) => 'N',
322    chr(197).chr(136) => 'n', chr(197).chr(137) => 'N',
323    chr(197).chr(138) => 'n', chr(197).chr(139) => 'N',
324    chr(197).chr(140) => 'O', chr(197).chr(141) => 'o',
325    chr(197).chr(142) => 'O', chr(197).chr(143) => 'o',
326    chr(197).chr(144) => 'O', chr(197).chr(145) => 'o',
327    chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe',
328    chr(197).chr(148) => 'R',chr(197).chr(149) => 'r',
329    chr(197).chr(150) => 'R',chr(197).chr(151) => 'r',
330    chr(197).chr(152) => 'R',chr(197).chr(153) => 'r',
331    chr(197).chr(154) => 'S',chr(197).chr(155) => 's',
332    chr(197).chr(156) => 'S',chr(197).chr(157) => 's',
333    chr(197).chr(158) => 'S',chr(197).chr(159) => 's',
334    chr(197).chr(160) => 'S', chr(197).chr(161) => 's',
335    chr(197).chr(162) => 'T', chr(197).chr(163) => 't',
336    chr(197).chr(164) => 'T', chr(197).chr(165) => 't',
337    chr(197).chr(166) => 'T', chr(197).chr(167) => 't',
338    chr(197).chr(168) => 'U', chr(197).chr(169) => 'u',
339    chr(197).chr(170) => 'U', chr(197).chr(171) => 'u',
340    chr(197).chr(172) => 'U', chr(197).chr(173) => 'u',
341    chr(197).chr(174) => 'U', chr(197).chr(175) => 'u',
342    chr(197).chr(176) => 'U', chr(197).chr(177) => 'u',
343    chr(197).chr(178) => 'U', chr(197).chr(179) => 'u',
344    chr(197).chr(180) => 'W', chr(197).chr(181) => 'w',
345    chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y',
346    chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z',
347    chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z',
348    chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z',
349    chr(197).chr(190) => 'z', chr(197).chr(191) => 's',
350    // Euro Sign
351    chr(226).chr(130).chr(172) => 'E',
352    // GBP (Pound) Sign
353    chr(194).chr(163) => '');
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 = $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)
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 ($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
534function pwg_debug( $string )
535{
536  global $debug,$t2,$page;
537
538  $now = explode( ' ', microtime() );
539  $now2 = explode( '.', $now[0] );
540  $now2 = $now[1].'.'.$now2[1];
541  $time = number_format( $now2 - $t2, 3, '.', ' ').' s';
542  $debug .= '<p>';
543  $debug.= '['.$time.', ';
544  $debug.= $page['count_queries'].' queries] : '.$string;
545  $debug.= "</p>\n";
546}
547
548/**
549 * Redirects to the given URL (HTTP method)
550 *
551 * Note : once this function called, the execution doesn't go further
552 * (presence of an exit() instruction.
553 *
554 * @param string $url
555 * @return void
556 */
557function redirect_http( $url )
558{
559  if (ob_get_length () !== FALSE)
560  {
561    ob_clean();
562  }
563  // default url is on html format
564  $url = html_entity_decode($url);
565  header('Request-URI: '.$url);
566  header('Content-Location: '.$url);
567  header('Location: '.$url);
568  exit();
569}
570
571/**
572 * Redirects to the given URL (HTML method)
573 *
574 * Note : once this function called, the execution doesn't go further
575 * (presence of an exit() instruction.
576 *
577 * @param string $url
578 * @param string $title_msg
579 * @param integer $refreh_time
580 * @return void
581 */
582function redirect_html( $url , $msg = '', $refresh_time = 0)
583{
584  global $user, $template, $lang_info, $conf, $lang, $t2, $page, $debug;
585
586  if (!isset($lang_info))
587  {
588    $user = build_user( $conf['guest_id'], true);
589    load_language('common.lang');
590    trigger_action('loading_lang');
591    load_language('lang', PHPWG_ROOT_PATH.'local/', array('no_fallback'=>true, 'local'=>true) );
592    $template = new Template(PHPWG_ROOT_PATH.'themes', get_default_theme());
593  }
594  else
595  {
596    $template = new Template(PHPWG_ROOT_PATH.'themes', $user['theme']);
597  }
598
599  if (empty($msg))
600  {
601    $msg = nl2br(l10n('Redirection...'));
602  }
603
604  $refresh = $refresh_time;
605  $url_link = $url;
606  $title = 'redirection';
607
608  $template->set_filenames( array( 'redirect' => 'redirect.tpl' ) );
609
610  include( PHPWG_ROOT_PATH.'include/page_header.php' );
611
612  $template->set_filenames( array( 'redirect' => 'redirect.tpl' ) );
613  $template->assign('REDIRECT_MSG', $msg);
614
615  $template->parse('redirect');
616
617  include( PHPWG_ROOT_PATH.'include/page_tail.php' );
618
619  exit();
620}
621
622/**
623 * Redirects to the given URL (Switch to HTTP method or HTML method)
624 *
625 * Note : once this function called, the execution doesn't go further
626 * (presence of an exit() instruction.
627 *
628 * @param string $url
629 * @param string $title_msg
630 * @param integer $refreh_time
631 * @return void
632 */
633function redirect( $url , $msg = '', $refresh_time = 0)
634{
635  global $conf;
636
637  // with RefeshTime <> 0, only html must be used
638  if ($conf['default_redirect_method']=='http'
639      and $refresh_time==0
640      and !headers_sent()
641    )
642  {
643    redirect_http($url);
644  }
645  else
646  {
647    redirect_html($url, $msg, $refresh_time);
648  }
649}
650
651/**
652 * returns $_SERVER['QUERY_STRING'] whitout keys given in parameters
653 *
654 * @param array $rejects
655 * @param boolean $escape - if true escape & to &amp; (for html)
656 * @returns string
657 */
658function get_query_string_diff($rejects=array(), $escape=true)
659{
660  $query_string = '';
661
662  $str = $_SERVER['QUERY_STRING'];
663  parse_str($str, $vars);
664
665  $is_first = true;
666  foreach ($vars as $key => $value)
667  {
668    if (!in_array($key, $rejects))
669    {
670      $query_string.= $is_first ? '?' : ($escape ? '&amp;' : '&' );
671      $is_first = false;
672      $query_string.= $key.'='.$value;
673    }
674  }
675
676  return $query_string;
677}
678
679function url_is_remote($url)
680{
681  if ( strncmp($url, 'http://', 7)==0
682    or strncmp($url, 'https://', 8)==0 )
683  {
684    return true;
685  }
686  return false;
687}
688
689/**
690 * returns available themes
691 */
692function get_pwg_themes()
693{
694  global $conf;
695
696  $themes = array();
697
698  $query = '
699SELECT
700    id,
701    name
702  FROM '.THEMES_TABLE.'
703  ORDER BY name ASC
704;';
705  $result = pwg_query($query);
706  while ($row = pwg_db_fetch_assoc($result))
707  {
708    if (check_theme_installed($row['id']))
709    {
710      $themes[ $row['id'] ] = $row['name'];
711    }
712  }
713
714  // plugins want remove some themes based on user status maybe?
715  $themes = trigger_event('get_pwg_themes', $themes);
716
717  return $themes;
718}
719
720function check_theme_installed($theme_id)
721{
722  global $conf;
723
724  return file_exists($conf['themes_dir'].'/'.$theme_id.'/'.'themeconf.inc.php');
725}
726
727/* Returns the PATH to the thumbnail to be displayed. If the element does not
728 * have a thumbnail, the default mime image path is returned. The PATH can be
729 * used in the php script, but not sent to the browser.
730 * @param array element_info assoc array containing element info from db
731 * at least 'path', 'tn_ext' and 'id' should be present
732 */
733function get_thumbnail_path($element_info)
734{
735  $path = get_thumbnail_location($element_info);
736  if ( !url_is_remote($path) )
737  {
738    $path = PHPWG_ROOT_PATH.$path;
739  }
740  return $path;
741}
742
743/* Returns the URL of the thumbnail to be displayed. If the element does not
744 * have a thumbnail, the default mime image url is returned. The URL can be
745 * sent to the browser, but not used in the php script.
746 * @param array element_info assoc array containing element info from db
747 * at least 'path', 'tn_ext' and 'id' should be present
748 */
749function get_thumbnail_url($element_info)
750{
751  $path = get_thumbnail_location($element_info);
752  if ( !url_is_remote($path) )
753  {
754    $path = embellish_url(get_root_url().$path);
755  }
756
757  // plugins want another url ?
758  $path = trigger_event('get_thumbnail_url', $path, $element_info);
759  return $path;
760}
761
762/* returns the relative path of the thumnail with regards to to the root
763of piwigo (not the current page!).This function is not intended to be
764called directly from code.*/
765function get_thumbnail_location($element_info)
766{
767  global $conf;
768  if ( !empty( $element_info['tn_ext'] ) )
769  {
770    $path = substr_replace(
771      get_filename_wo_extension($element_info['path']),
772      '/'.$conf['dir_thumbnail'].'/'.$conf['prefix_thumbnail'],
773      strrpos($element_info['path'],'/'),
774      1
775      );
776    $path.= '.'.$element_info['tn_ext'];
777  }
778  else
779  {
780    $path = get_themeconf('mime_icon_dir')
781        .strtolower(get_extension($element_info['path'])).'.png';
782  }
783
784  // plugins want another location ?
785  $path = trigger_event( 'get_thumbnail_location', $path, $element_info);
786  return $path;
787}
788
789/* returns the title of the thumnail */
790function get_thumbnail_title($element_info)
791{
792  // message in title for the thumbnail
793  if (isset($element_info['file']))
794  {
795    $thumbnail_title = $element_info['file'];
796  }
797  else
798  {
799    $thumbnail_title = '';
800  }
801
802  if (!empty($element_info['filesize']))
803  {
804    $thumbnail_title .= ' : '.sprintf(l10n('%d Kb'), $element_info['filesize']);
805  }
806
807  return $thumbnail_title;
808}
809
810/**
811 * fill the current user caddie with given elements, if not already in
812 * caddie
813 *
814 * @param array elements_id
815 */
816function fill_caddie($elements_id)
817{
818  global $user;
819
820  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
821
822  $query = '
823SELECT element_id
824  FROM '.CADDIE_TABLE.'
825  WHERE user_id = '.$user['id'].'
826;';
827  $in_caddie = array_from_query($query, 'element_id');
828
829  $caddiables = array_diff($elements_id, $in_caddie);
830
831  $datas = array();
832
833  foreach ($caddiables as $caddiable)
834  {
835    array_push($datas, array('element_id' => $caddiable,
836                             'user_id' => $user['id']));
837  }
838
839  if (count($caddiables) > 0)
840  {
841    mass_inserts(CADDIE_TABLE, array('element_id','user_id'), $datas);
842  }
843}
844
845/**
846 * returns the element name from its filename
847 *
848 * @param string filename
849 * @return string name
850 */
851function get_name_from_file($filename)
852{
853  return str_replace('_',' ',get_filename_wo_extension($filename));
854}
855
856/**
857 * returns the corresponding value from $lang if existing. Else, the key is
858 * returned
859 *
860 * @param string key
861 * @return string
862 */
863function l10n($key, $textdomain='messages')
864{
865  global $lang, $conf;
866
867  if ($conf['debug_l10n'] and !isset($lang[$key]) and !empty($key))
868  {
869    trigger_error('[l10n] language key "'.$key.'" is not defined', E_USER_WARNING);
870  }
871
872  return isset($lang[$key]) ? $lang[$key] : $key;
873}
874
875/**
876 * returns the prinft value for strings including %d
877 * return is concorded with decimal value (singular, plural)
878 *
879 * @param singular string key
880 * @param plural string key
881 * @param decimal value
882 * @return string
883 */
884function l10n_dec($singular_fmt_key, $plural_fmt_key, $decimal)
885{
886  global $lang_info;
887
888  return
889    sprintf(
890      l10n((
891        (($decimal > 1) or ($decimal == 0 and $lang_info['zero_plural']))
892          ? $plural_fmt_key
893          : $singular_fmt_key
894        )), $decimal);
895}
896
897/*
898 * returns a single element to use with l10n_args
899 *
900 * @param string key: translation key
901 * @param array/string/../number args:
902 *   arguments to use on sprintf($key, args)
903 *   if args is a array, each values are used on sprintf
904 * @return string
905 */
906function get_l10n_args($key, $args)
907{
908  if (is_array($args))
909  {
910    $key_arg = array_merge(array($key), $args);
911  }
912  else
913  {
914    $key_arg = array($key,  $args);
915  }
916  return array('key_args' => $key_arg);
917}
918
919/*
920 * returns a string with formated with l10n_args elements
921 *
922 * @param element/array $key_args: element or array of l10n_args elements
923 * @param $sep: if $key_args is array,
924 *   separator is used when translated l10n_args elements are concated
925 * @return string
926 */
927function l10n_args($key_args, $sep = "\n")
928{
929  if (is_array($key_args))
930  {
931    foreach ($key_args as $key => $element)
932    {
933      if (isset($result))
934      {
935        $result .= $sep;
936      }
937      else
938      {
939        $result = '';
940      }
941
942      if ($key === 'key_args')
943      {
944        array_unshift($element, l10n(array_shift($element)));
945        $result .= call_user_func_array('sprintf', $element);
946      }
947      else
948      {
949        $result .= l10n_args($element, $sep);
950      }
951    }
952  }
953  else
954  {
955    fatal_error('l10n_args: Invalid arguments');
956  }
957
958  return $result;
959}
960
961/**
962 * returns the corresponding value from $themeconf if existing. Else, the
963 * key is returned
964 *
965 * @param string key
966 * @return string
967 */
968function get_themeconf($key)
969{
970  global $template;
971
972  return $template->get_themeconf($key);
973}
974
975/**
976 * Returns webmaster mail address depending on $conf['webmaster_id']
977 *
978 * @return string
979 */
980function get_webmaster_mail_address()
981{
982  global $conf;
983
984  $query = '
985SELECT '.$conf['user_fields']['email'].'
986  FROM '.USERS_TABLE.'
987  WHERE '.$conf['user_fields']['id'].' = '.$conf['webmaster_id'].'
988;';
989  list($email) = pwg_db_fetch_row(pwg_query($query));
990
991  return $email;
992}
993
994/**
995 * Add configuration parameters from database to global $conf array
996 *
997 * @return void
998 */
999function load_conf_from_db($condition = '')
1000{
1001  global $conf;
1002
1003  $query = '
1004SELECT param, value
1005 FROM '.CONFIG_TABLE.'
1006 '.(!empty($condition) ? 'WHERE '.$condition : '').'
1007;';
1008  $result = pwg_query($query);
1009
1010  if ((pwg_db_num_rows($result) == 0) and !empty($condition))
1011  {
1012    fatal_error('No configuration data');
1013  }
1014
1015  while ($row = pwg_db_fetch_assoc($result))
1016  {
1017    $conf[ $row['param'] ] = isset($row['value']) ? $row['value'] : '';
1018
1019    // If the field is true or false, the variable is transformed into a
1020    // boolean value.
1021    if ($conf[$row['param']] == 'true' or $conf[$row['param']] == 'false')
1022    {
1023      $conf[ $row['param'] ] = get_boolean($conf[ $row['param'] ]);
1024    }
1025  }
1026}
1027
1028function conf_update_param($param, $value)
1029{
1030  $query = '
1031DELETE
1032  FROM '.CONFIG_TABLE.'
1033  WHERE param = \''.$param.'\'
1034;';
1035  pwg_query($query);
1036
1037  $query = '
1038INSERT
1039  INTO '.CONFIG_TABLE.'
1040  (param, value)
1041  VALUES(\''.$param.'\', \''.$value.'\')
1042;';
1043  pwg_query($query);
1044}
1045
1046/**
1047 * Prepends and appends a string at each value of the given array.
1048 *
1049 * @param array
1050 * @param string prefix to each array values
1051 * @param string suffix to each array values
1052 */
1053function prepend_append_array_items($array, $prepend_str, $append_str)
1054{
1055  array_walk(
1056    $array,
1057    create_function('&$s', '$s = "'.$prepend_str.'".$s."'.$append_str.'";')
1058    );
1059
1060  return $array;
1061}
1062
1063/**
1064 * creates an hashed based on a query, this function is a very common
1065 * pattern used here. Among the selected columns fetched, choose one to be
1066 * the key, another one to be the value.
1067 *
1068 * @param string $query
1069 * @param string $keyname
1070 * @param string $valuename
1071 * @return array
1072 */
1073function simple_hash_from_query($query, $keyname, $valuename)
1074{
1075  $array = array();
1076
1077  $result = pwg_query($query);
1078  while ($row = pwg_db_fetch_assoc($result))
1079  {
1080    $array[ $row[$keyname] ] = $row[$valuename];
1081  }
1082
1083  return $array;
1084}
1085
1086/**
1087 * creates an hashed based on a query, this function is a very common
1088 * pattern used here. The key is given as parameter, the value is an associative
1089 * array.
1090 *
1091 * @param string $query
1092 * @param string $keyname
1093 * @return array
1094 */
1095function hash_from_query($query, $keyname)
1096{
1097  $array = array();
1098  $result = pwg_query($query);
1099  while ($row = pwg_db_fetch_assoc($result))
1100  {
1101    $array[ $row[$keyname] ] = $row;
1102  }
1103  return $array;
1104}
1105
1106/**
1107 * Return basename of the current script
1108 * Lower case convertion is applied on return value
1109 * Return value is without file extention ".php"
1110 *
1111 * @param void
1112 *
1113 * @return script basename
1114 */
1115function script_basename()
1116{
1117  global $conf;
1118
1119  foreach (array('SCRIPT_NAME', 'SCRIPT_FILENAME', 'PHP_SELF') as $value)
1120  {
1121    if (!empty($_SERVER[$value]))
1122    {
1123      $filename = strtolower($_SERVER[$value]);
1124      if ($conf['php_extension_in_urls'] and get_extension($filename)!=='php')
1125        continue;
1126      $basename = basename($filename, '.php');
1127      if (!empty($basename))
1128      {
1129        return $basename;
1130      }
1131    }
1132  }
1133  return '';
1134}
1135
1136/**
1137 * Return value for the current page define on $conf['filter_pages']
1138 * Îf value is not defined, default value are returned
1139 *
1140 * @param value name
1141 *
1142 * @return filter page value
1143 */
1144function get_filter_page_value($value_name)
1145{
1146  global $conf;
1147
1148  $page_name = script_basename();
1149
1150  if (isset($conf['filter_pages'][$page_name][$value_name]))
1151  {
1152    return $conf['filter_pages'][$page_name][$value_name];
1153  }
1154  else if (isset($conf['filter_pages']['default'][$value_name]))
1155  {
1156    return $conf['filter_pages']['default'][$value_name];
1157  }
1158  else
1159  {
1160    return null;
1161  }
1162}
1163
1164/**
1165 * returns the character set of data sent to browsers / received from forms
1166 */
1167function get_pwg_charset()
1168{
1169  $pwg_charset = 'utf-8';
1170  if (defined('PWG_CHARSET'))
1171  {
1172    $pwg_charset = PWG_CHARSET;
1173  }
1174  return $pwg_charset;
1175}
1176
1177/**
1178 * includes a language file or returns the content of a language file
1179 * availability of the file
1180 *
1181 * in descending order of preference:
1182 *   param language, user language, default language
1183 * Piwigo default language.
1184 *
1185 * @param string filename
1186 * @param string dirname
1187 * @param mixed options can contain
1188 *     language - language to load (if empty uses user language)
1189 *     return - if true the file content is returned otherwise the file is evaluated as php
1190 *     target_charset -
1191 *     no_fallback - the language must be respected
1192 *     local - if true, get local language file
1193 * @return boolean success status or a string if options['return'] is true
1194 */
1195function load_language($filename, $dirname = '',
1196    $options = array() )
1197{
1198  global $user;
1199
1200  if (! @$options['return'] )
1201  {
1202    $filename .= '.php'; //MAYBE to do .. load .po and .mo localization files
1203  }
1204  if (empty($dirname))
1205  {
1206    $dirname = PHPWG_ROOT_PATH;
1207  }
1208  $dirname .= 'language/';
1209
1210  $languages = array();
1211  if ( !empty($options['language']) )
1212  {
1213    $languages[] = $options['language'];
1214  }
1215  if ( !empty($user['language']) )
1216  {
1217    $languages[] = $user['language'];
1218  }
1219  if ( ! @$options['no_fallback'] )
1220  {
1221    if ( defined('PHPWG_INSTALLED') )
1222    {
1223      $languages[] = get_default_language();
1224    }
1225    $languages[] = PHPWG_DEFAULT_LANGUAGE;
1226  }
1227
1228  $languages = array_unique($languages);
1229
1230  if ( empty($options['target_charset']) )
1231  {
1232    $target_charset = get_pwg_charset();
1233  }
1234  else
1235  {
1236    $target_charset = $options['target_charset'];
1237  }
1238  $target_charset = strtolower($target_charset);
1239  $source_file    = '';
1240  foreach ($languages as $language)
1241  {
1242    $f = @$options['local'] ?
1243      $dirname.$language.'.'.$filename:
1244      $dirname.$language.'/'.$filename;
1245
1246    if (file_exists($f))
1247    {
1248      $source_file = $f;
1249      break;
1250    }
1251  }
1252
1253  if ( !empty($source_file) )
1254  {
1255    if (! @$options['return'] )
1256    {
1257      @include($source_file);
1258      $load_lang = @$lang;
1259      $load_lang_info = @$lang_info;
1260
1261      global $lang, $lang_info;
1262      if ( !isset($lang) ) $lang=array();
1263      if ( !isset($lang_info) ) $lang_info=array();
1264
1265      if ( 'utf-8'!=$target_charset)
1266      {
1267        if ( is_array($load_lang) )
1268        {
1269          foreach ($load_lang as $k => $v)
1270          {
1271            if ( is_array($v) )
1272            {
1273              $func = create_function('$v', 'return convert_charset($v, "utf-8", "'.$target_charset.'");' );
1274              $lang[$k] = array_map($func, $v);
1275            }
1276            else
1277              $lang[$k] = convert_charset($v, 'utf-8', $target_charset);
1278          }
1279        }
1280        if ( is_array($load_lang_info) )
1281        {
1282          foreach ($load_lang_info as $k => $v)
1283          {
1284            $lang_info[$k] = convert_charset($v, 'utf-8', $target_charset);
1285          }
1286        }
1287      }
1288      else
1289      {
1290        $lang = array_merge( $lang, (array)$load_lang );
1291        $lang_info = array_merge( $lang_info, (array)$load_lang_info );
1292      }
1293      return true;
1294    }
1295    else
1296    {
1297      $content = @file_get_contents($source_file);
1298      $content = convert_charset($content, 'utf-8', $target_charset);
1299      return $content;
1300    }
1301  }
1302  return false;
1303}
1304
1305/**
1306 * converts a string from a character set to another character set
1307 * @param string str the string to be converted
1308 * @param string source_charset the character set in which the string is encoded
1309 * @param string dest_charset the destination character set
1310 */
1311function convert_charset($str, $source_charset, $dest_charset)
1312{
1313  if ($source_charset==$dest_charset)
1314    return $str;
1315  if ($source_charset=='iso-8859-1' and $dest_charset=='utf-8')
1316  {
1317    return utf8_encode($str);
1318  }
1319  if ($source_charset=='utf-8' and $dest_charset=='iso-8859-1')
1320  {
1321    return utf8_decode($str);
1322  }
1323  if (function_exists('iconv'))
1324  {
1325    return iconv($source_charset, $dest_charset, $str);
1326  }
1327  if (function_exists('mb_convert_encoding'))
1328  {
1329    return mb_convert_encoding( $str, $dest_charset, $source_charset );
1330  }
1331  return $str; //???
1332}
1333
1334/**
1335 * makes sure a index.htm protects the directory from browser file listing
1336 *
1337 * @param string dir directory
1338 */
1339function secure_directory($dir)
1340{
1341  $file = $dir.'/index.htm';
1342  if (!file_exists($file))
1343  {
1344    @file_put_contents($file, 'Not allowed!');
1345  }
1346}
1347
1348/**
1349 * returns a "secret key" that is to be sent back when a user enters a comment
1350 *
1351 * @param int image_id
1352 */
1353function get_comment_post_key($image_id)
1354{
1355  global $conf;
1356
1357  $time = time();
1358
1359  return sprintf(
1360    '%s:%s',
1361    $time,
1362    hash_hmac(
1363      'md5',
1364      $time.':'.$image_id,
1365      $conf['secret_key']
1366      )
1367    );
1368}
1369
1370/**
1371 * return an array which will be sent to template to display navigation bar
1372 */
1373function create_navigation_bar($url, $nb_element, $start, $nb_element_page, $clean_url = false)
1374{
1375  global $conf;
1376
1377  $navbar = array();
1378  $pages_around = $conf['paginate_pages_around'];
1379  $start_str = $clean_url ? '/start-' : (strpos($url, '?')===false ? '?':'&amp;').'start=';
1380
1381  if (!isset($start) or !is_numeric($start) or (is_numeric($start) and $start < 0))
1382  {
1383    $start = 0;
1384  }
1385
1386  // navigation bar useful only if more than one page to display !
1387  if ($nb_element > $nb_element_page)
1388  {
1389    $cur_page = ceil($start / $nb_element_page) + 1;
1390    $maximum = ceil($nb_element / $nb_element_page);
1391    $previous = $start - $nb_element_page;
1392    $next = $start + $nb_element_page;
1393    $last = ($maximum - 1) * $nb_element_page;
1394
1395    $navbar['CURRENT_PAGE'] = $cur_page;
1396
1397    // link to first page and previous page?
1398    if ($cur_page != 1)
1399    {
1400      $navbar['URL_FIRST'] = $url;
1401      $navbar['URL_PREV'] = $url.($previous > 0 ? $start_str.$previous : '');
1402    }
1403    // link on next page and last page?
1404    if ($cur_page != $maximum)
1405    {
1406      $navbar['URL_NEXT'] = $url.$start_str.$next;
1407      $navbar['URL_LAST'] = $url.$start_str.$last;
1408    }
1409
1410    // pages to display
1411    $navbar['pages'] = array();
1412    $navbar['pages'][1] = $url;
1413    $navbar['pages'][$maximum] = $url.$start_str.$last;
1414
1415    for ($i = max($cur_page - $pages_around , 2), $stop = min($cur_page + $pages_around + 1, $maximum);
1416         $i < $stop; $i++)
1417    {
1418      $navbar['pages'][$i] = $url.$start_str.(($i - 1) * $nb_element_page);
1419    }
1420    ksort($navbar['pages']);
1421  }
1422  return $navbar;
1423}
1424
1425/**
1426 * return an array which will be sent to template to display recent icon
1427 */
1428function get_icon($date, $is_child_date = false)
1429{
1430  global $cache, $user;
1431
1432  if (empty($date))
1433  {
1434    return false;
1435  }
1436
1437  if (!isset($cache['get_icon']['title']))
1438  {
1439    $cache['get_icon']['title'] = sprintf(
1440      l10n('images posted during the last %d days'),
1441      $user['recent_period']
1442      );
1443  }
1444
1445  $icon = array(
1446    'TITLE' => $cache['get_icon']['title'],
1447    'IS_CHILD_DATE' => $is_child_date,
1448    );
1449
1450  if (isset($cache['get_icon'][$date]))
1451  {
1452    return $cache['get_icon'][$date] ? $icon : array();
1453  }
1454
1455  if (!isset($cache['get_icon']['sql_recent_date']))
1456  {
1457    // Use MySql date in order to standardize all recent "actions/queries"
1458    $cache['get_icon']['sql_recent_date'] = pwg_db_get_recent_period($user['recent_period']);
1459  }
1460
1461  $cache['get_icon'][$date] = $date > $cache['get_icon']['sql_recent_date'];
1462
1463  return $cache['get_icon'][$date] ? $icon : array();
1464}
1465
1466/**
1467 * check token comming from form posted or get params to prevent csrf attacks
1468 * if pwg_token is empty action doesn't require token
1469 * else pwg_token is compare to server token
1470 *
1471 * @return void access denied if token given is not equal to server token
1472 */
1473function check_pwg_token()
1474{
1475  if (!empty($_REQUEST['pwg_token']))
1476  {
1477    if (get_pwg_token() != $_REQUEST['pwg_token'])
1478    {
1479      access_denied();
1480    }
1481  }
1482  else
1483    bad_request('missing token');
1484}
1485
1486function get_pwg_token()
1487{
1488  global $conf;
1489
1490  return hash_hmac('md5', session_id(), $conf['secret_key']);
1491}
1492
1493/*
1494 * breaks the script execution if the given value doesn't match the given
1495 * pattern. This should happen only during hacking attempts.
1496 *
1497 * @param string param_name
1498 * @param array param_array
1499 * @param boolean is_array
1500 * @param string pattern
1501 *
1502 * @return void
1503 */
1504function check_input_parameter($param_name, $param_array, $is_array, $pattern)
1505{
1506  $param_value = null;
1507  if (isset($param_array[$param_name]))
1508  {
1509    $param_value = $param_array[$param_name];
1510  }
1511
1512  // it's ok if the input parameter is null
1513  if (empty($param_value))
1514  {
1515    return true;
1516  }
1517
1518  if ($is_array)
1519  {
1520    if (!is_array($param_value))
1521    {
1522      fatal_error('[Hacking attempt] the input parameter "'.$param_name.'" should be an array');
1523    }
1524
1525    foreach ($param_value as $item_to_check)
1526    {
1527      if (!preg_match($pattern, $item_to_check))
1528      {
1529        fatal_error('[Hacking attempt] an item is not valid in input parameter "'.$param_name.'"');
1530      }
1531    }
1532  }
1533  else
1534  {
1535    if (!preg_match($pattern, $param_value))
1536    {
1537      fatal_error('[Hacking attempt] the input parameter "'.$param_name.'" is not valid');
1538    }
1539  }
1540}
1541
1542
1543function get_privacy_level_options()
1544{
1545  global $conf;
1546
1547  $options = array();
1548  foreach (array_reverse($conf['available_permission_levels']) as $level)
1549  {
1550    $label = null;
1551
1552    if (0 == $level)
1553    {
1554      $label = l10n('Everybody');
1555    }
1556    else
1557    {
1558      $labels = array();
1559      $sub_levels = array_reverse($conf['available_permission_levels']);
1560      foreach ($sub_levels as $sub_level)
1561      {
1562        if ($sub_level == 0 or $sub_level < $level)
1563        {
1564          break;
1565        }
1566        array_push(
1567          $labels,
1568          l10n(
1569            sprintf(
1570              'Level %d',
1571              $sub_level
1572              )
1573            )
1574          );
1575      }
1576
1577      $label = implode(', ', $labels);
1578    }
1579    $options[$level] = $label;
1580  }
1581  return $options;
1582}
1583?>
Note: See TracBrowser for help on using the repository browser.