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

Last change on this file since 2917 was 2917, checked in by plg, 15 years ago

merge r2916 from branch 2.0 to trunk

bug 904 fixed: an index.htm is created in directories created by
pwg.images.add web API method, only directories that contains pictures.

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