source: tags/release-1_7_1/include/functions.inc.php @ 4202

Last change on this file since 4202 was 2125, checked in by rvelices, 17 years ago

merge revisions 2121, 2122 and 2123 from trunk to branch-1_7

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