source: tags/release-1_7_3/include/functions.inc.php @ 20547

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