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

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