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

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