source: tags/build-Alligator02/include/functions.inc.php @ 14518

Last change on this file since 14518 was 1766, checked in by rvelices, 17 years ago

bug 623: Char "+" is not supported in gallery URL (the function url_is_remote
should not check if the url is actually valid but only if it starts with http://)

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 30.2 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// | branch        : BSF (Best So Far)
8// | file          : $Id: functions.inc.php 1766 2007-01-29 20:08:24Z rvelices $
9// | last update   : $Date: 2007-01-29 20:08:24 +0000 (Mon, 29 Jan 2007) $
10// | last modifier : $Author: rvelices $
11// | revision      : $Revision: 1766 $
12// +-----------------------------------------------------------------------+
13// | This program is free software; you can redistribute it and/or modify  |
14// | it under the terms of the GNU General Public License as published by  |
15// | the Free Software Foundation                                          |
16// |                                                                       |
17// | This program is distributed in the hope that it will be useful, but   |
18// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
19// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
20// | General Public License for more details.                              |
21// |                                                                       |
22// | You should have received a copy of the GNU General Public License     |
23// | along with this program; if not, write to the Free Software           |
24// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
25// | USA.                                                                  |
26// +-----------------------------------------------------------------------+
27
28include_once( PHPWG_ROOT_PATH .'include/functions_user.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/**
303 * simplify a string to insert it into an URL
304 *
305 * based on str2url function from Dotclear
306 *
307 * @param string
308 * @return string
309 */
310function str2url($str)
311{
312  $str = strtr(
313    $str,
314    'ÀÁÂÃÄÅàáâãäåÇçÒÓÔÕÖØòóôõöøÈÉÊËèéêëÌÍÎÏìíîïÙÚÛÜùúûü¾ÝÿýÑñ',
315    'AAAAAAaaaaaaCcOOOOOOooooooEEEEeeeeIIIIiiiiUUUUuuuuYYyyNn'
316    );
317
318  $str = str_replace('Æ', 'AE', $str);
319  $str = str_replace('æ', 'ae', $str);
320  $str = str_replace('¼', 'OE', $str);
321  $str = str_replace('½', 'oe', $str);
322
323  $str = preg_replace('/[^a-z0-9_\s\'\:\/\[\],-]/','',strtolower($str));
324  $str = preg_replace('/[\s\'\:\/\[\],-]+/',' ',trim($str));
325  $res = str_replace(' ','_',$str);
326
327  return $res;
328}
329
330//-------------------------------------------- PhpWebGallery specific functions
331
332/**
333 * returns an array with a list of {language_code => language_name}
334 *
335 * @returns array
336 */
337function get_languages()
338{
339  $dir = opendir(PHPWG_ROOT_PATH.'language');
340  $languages = array();
341
342  while ($file = readdir($dir))
343  {
344    $path = PHPWG_ROOT_PATH.'language/'.$file;
345    if (is_dir($path) and !is_link($path) and file_exists($path.'/iso.txt'))
346    {
347      list($language_name) = @file($path.'/iso.txt');
348      $languages[$file] = $language_name;
349    }
350  }
351  closedir($dir);
352  @asort($languages);
353  @reset($languages);
354
355  return $languages;
356}
357
358/**
359 * replaces the $search into <span style="$style">$search</span> in the
360 * given $string.
361 *
362 * case insensitive replacements, does not replace characters in HTML tags
363 *
364 * @param string $string
365 * @param string $search
366 * @param string $style
367 * @return string
368 */
369function add_style( $string, $search, $style )
370{
371  //return $string;
372  $return_string = '';
373  $remaining = $string;
374
375  $start = 0;
376  $end = 0;
377  $start = strpos ( $remaining, '<' );
378  $end   = strpos ( $remaining, '>' );
379  while ( is_numeric( $start ) and is_numeric( $end ) )
380  {
381    $treatment = substr ( $remaining, 0, $start );
382    $treatment = preg_replace( '/('.$search.')/i',
383                               '<span style="'.$style.'">\\0</span>',
384                               $treatment );
385    $return_string.= $treatment.substr( $remaining, $start, $end-$start+1 );
386    $remaining = substr ( $remaining, $end + 1, strlen( $remaining ) );
387    $start = strpos ( $remaining, '<' );
388    $end   = strpos ( $remaining, '>' );
389  }
390  $treatment = preg_replace( '/('.$search.')/i',
391                             '<span style="'.$style.'">\\0</span>',
392                             $remaining );
393  $return_string.= $treatment;
394
395  return $return_string;
396}
397
398// replace_search replaces a searched words array string by the search in
399// another style for the given $string.
400function replace_search( $string, $search )
401{
402  // FIXME : with new advanced search, this function needs a rewrite
403  return $string;
404
405  $words = explode( ',', $search );
406  $style = 'background-color:white;color:red;';
407  foreach ( $words as $word ) {
408    $string = add_style( $string, $word, $style );
409  }
410  return $string;
411}
412
413function pwg_log($image_id = null)
414{
415  global $conf, $user, $page;
416
417  if (!$conf['log'])
418  {
419    return false;
420  }
421
422  if (is_admin() and !$conf['history_admin'])
423  {
424    return false;
425  }
426
427  if ($user['is_the_guest'] and !$conf['history_guest'])
428  {
429    return false;
430  }
431
432  $tags_string = null;
433  if (isset($page['section']) and $page['section'] == 'tags')
434  {
435    $tag_ids = array();
436    foreach ($page['tags'] as $tag)
437    {
438      array_push($tag_ids, $tag['id']);
439    }
440
441    $tags_string = implode(',', $tag_ids);
442  }
443
444  // here we ask the database the current date and time, and we extract
445  // {year, month, day} from the current date. We could do this during the
446  // insert query with a CURDATE(), CURTIME(), DATE_FORMAT(CURDATE(), '%Y')
447  // ... but I (plg) think it would cost more than a double query and a PHP
448  // extraction.
449  $query = '
450SELECT CURDATE(), CURTIME()
451;';
452  list($curdate, $curtime) = mysql_fetch_row(pwg_query($query));
453
454  list($curyear, $curmonth, $curday) = explode('-', $curdate);
455  list($curhour) = explode(':', $curtime);
456 
457  $query = '
458INSERT INTO '.HISTORY_TABLE.'
459  (
460    date,
461    time,
462    year,
463    month,
464    day,
465    hour,
466    user_id,
467    IP,
468    section,
469    category_id,
470    image_id,
471    tag_ids
472  )
473  VALUES
474  (
475    \''.$curdate.'\',
476    \''.$curtime.'\',
477    '.$curyear.',
478    '.$curmonth.',
479    '.$curday.',
480    '.$curhour.',
481    '.$user['id'].',
482    \''.$_SERVER['REMOTE_ADDR'].'\',
483    '.(isset($page['section']) ? "'".$page['section']."'" : 'NULL').',
484    '.(isset($page['category']) ? $page['category'] : 'NULL').',
485    '.(isset($image_id) ? $image_id : 'NULL').',
486    '.(isset($tags_string) ? "'".$tags_string."'" : 'NULL').'
487  )
488;';
489  pwg_query($query);
490
491  return true;
492}
493
494// format_date returns a formatted date for display. The date given in
495// argument can be a unixdate (number of seconds since the 01.01.1970) or an
496// american format (2003-09-15). By option, you can show the time. The
497// output is internationalized.
498//
499// format_date( "2003-09-15", 'us', true ) -> "Monday 15 September 2003 21:52"
500function format_date($date, $type = 'us', $show_time = false)
501{
502  global $lang;
503
504  list($year,$month,$day,$hour,$minute,$second) = array(0,0,0,0,0,0);
505
506  switch ( $type )
507  {
508    case 'us' :
509    {
510      list($year,$month,$day) = explode('-', $date);
511      break;
512    }
513    case 'unix' :
514    {
515      list($year,$month,$day,$hour,$minute) =
516        explode('.', date('Y.n.j.G.i', $date));
517      break;
518    }
519    case 'mysql_datetime' :
520    {
521      preg_match('/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/',
522                 $date, $out);
523      list($year,$month,$day,$hour,$minute,$second) =
524        array($out[1],$out[2],$out[3],$out[4],$out[5],$out[6]);
525      break;
526    }
527  }
528  $formated_date = '';
529  // before 1970, Microsoft Windows can't mktime
530  if ($year >= 1970)
531  {
532    // we ask midday because Windows think it's prior to midnight with a
533    // zero and refuse to work
534    $formated_date.= $lang['day'][date('w', mktime(12,0,0,$month,$day,$year))];
535  }
536  $formated_date.= ' '.$day;
537  $formated_date.= ' '.$lang['month'][(int)$month];
538  $formated_date.= ' '.$year;
539  if ($show_time)
540  {
541    $formated_date.= ' '.$hour.':'.$minute;
542  }
543
544  return $formated_date;
545}
546
547function pwg_query($query)
548{
549  global $conf,$page,$debug,$t2;
550
551  $start = get_moment();
552  $result = mysql_query($query) or my_error($query."\n");
553
554  $time = get_moment() - $start;
555
556  if (!isset($page['count_queries']))
557  {
558    $page['count_queries'] = 0;
559    $page['queries_time'] = 0;
560  }
561
562  $page['count_queries']++;
563  $page['queries_time']+= $time;
564
565  if ($conf['show_queries'])
566  {
567    $output = '';
568    $output.= '<pre>['.$page['count_queries'].'] ';
569    $output.= "\n".$query;
570    $output.= "\n".'(this query time : ';
571    $output.= '<b>'.number_format($time, 3, '.', ' ').' s)</b>';
572    $output.= "\n".'(total SQL time  : ';
573    $output.= number_format($page['queries_time'], 3, '.', ' ').' s)';
574    $output.= "\n".'(total time      : ';
575    $output.= number_format( ($time+$start-$t2), 3, '.', ' ').' s)';
576    $output.= "</pre>\n";
577
578    $debug .= $output;
579  }
580
581  return $result;
582}
583
584function pwg_debug( $string )
585{
586  global $debug,$t2,$page;
587
588  $now = explode( ' ', microtime() );
589  $now2 = explode( '.', $now[0] );
590  $now2 = $now[1].'.'.$now2[1];
591  $time = number_format( $now2 - $t2, 3, '.', ' ').' s';
592  $debug .= '<p>';
593  $debug.= '['.$time.', ';
594  $debug.= $page['count_queries'].' queries] : '.$string;
595  $debug.= "</p>\n";
596}
597
598/**
599 * Redirects to the given URL (HTTP method)
600 *
601 * Note : once this function called, the execution doesn't go further
602 * (presence of an exit() instruction.
603 *
604 * @param string $url
605 * @return void
606 */
607function redirect_http( $url )
608{
609  if (ob_get_length () !== FALSE)
610  {
611    ob_clean();
612  }
613  header('Request-URI: '.$url);
614  header('Content-Location: '.$url);
615  header('Location: '.$url);
616  exit();
617}
618
619/**
620 * Redirects to the given URL (HTML method)
621 *
622 * Note : once this function called, the execution doesn't go further
623 * (presence of an exit() instruction.
624 *
625 * @param string $url
626 * @param string $title_msg
627 * @param integer $refreh_time
628 * @return void
629 */
630function redirect_html( $url , $msg = '', $refresh_time = 0)
631{
632  global $user, $template, $lang_info, $conf, $lang, $t2, $page, $debug;
633
634  if (!isset($lang_info))
635  {
636    $user = build_user( $conf['guest_id'], true);
637    include_once(get_language_filepath('common.lang.php'));
638    trigger_action('loading_lang');
639    @include_once(get_language_filepath('local.lang.php'));
640    list($tmpl, $thm) = explode('/', $conf['default_template']);
641    $template = new Template(PHPWG_ROOT_PATH.'template/'.$tmpl, $thm);
642  }
643  else
644  {
645    $template = new Template(PHPWG_ROOT_PATH.'template/'.$user['template'], $user['theme']);
646  }
647
648  if (empty($msg))
649  {
650    $redirect_msg = l10n('redirect_msg');
651  }
652  else
653  {
654    $redirect_msg = $msg;
655  }
656  $redirect_msg = nl2br($redirect_msg);
657
658  $refresh = $refresh_time;
659  $url_link = $url;
660  $title = 'redirection';
661
662  $template->set_filenames( array( 'redirect' => 'redirect.tpl' ) );
663
664  include( PHPWG_ROOT_PATH.'include/page_header.php' );
665
666  $template->set_filenames( array( 'redirect' => 'redirect.tpl' ) );
667  $template->parse('redirect');
668
669  include( PHPWG_ROOT_PATH.'include/page_tail.php' );
670
671  exit();
672}
673
674/**
675 * Redirects to the given URL (Switch to HTTP method or HTML method)
676 *
677 * Note : once this function called, the execution doesn't go further
678 * (presence of an exit() instruction.
679 *
680 * @param string $url
681 * @param string $title_msg
682 * @param integer $refreh_time
683 * @return void
684 */
685function redirect( $url , $msg = '', $refresh_time = 0)
686{
687  global $conf;
688
689  // with RefeshTime <> 0, only html must be used
690  if (($conf['default_redirect_method'] == 'http') and ($refresh_time == 0))
691  {
692    redirect_http($url);
693  }
694  else
695  {
696    redirect_html($url, $msg, $refresh_time);
697  }
698}
699
700/**
701 * returns $_SERVER['QUERY_STRING'] whitout keys given in parameters
702 *
703 * @param array $rejects
704 * @returns string
705 */
706function get_query_string_diff($rejects = array())
707{
708  $query_string = '';
709
710  $str = $_SERVER['QUERY_STRING'];
711  parse_str($str, $vars);
712
713  $is_first = true;
714  foreach ($vars as $key => $value)
715  {
716    if (!in_array($key, $rejects))
717    {
718      $query_string.= $is_first ? '?' : '&amp;';
719      $is_first = false;
720      $query_string.= $key.'='.$value;
721    }
722  }
723
724  return $query_string;
725}
726
727function url_is_remote($url)
728{
729  if ( strncmp($url, 'http://', 7)==0
730    or strncmp($url, 'https://', 8)==0 )
731  {
732    return true;
733  }
734  return false;
735}
736
737/**
738 * returns available template/theme
739 */
740function get_pwg_themes()
741{
742  $themes = array();
743
744  $template_dir = PHPWG_ROOT_PATH.'template';
745
746  foreach (get_dirs($template_dir) as $template)
747  {
748    foreach (get_dirs($template_dir.'/'.$template.'/theme') as $theme)
749    {
750      array_push($themes, $template.'/'.$theme);
751    }
752  }
753
754  return $themes;
755}
756
757/* Returns the PATH to the thumbnail to be displayed. If the element does not
758 * have a thumbnail, the default mime image path is returned. The PATH can be
759 * used in the php script, but not sent to the browser.
760 * @param array element_info assoc array containing element info from db
761 * at least 'path', 'tn_ext' and 'id' should be present
762 */
763function get_thumbnail_path($element_info)
764{
765  $path = get_thumbnail_location($element_info);
766  if ( !url_is_remote($path) )
767  {
768    $path = PHPWG_ROOT_PATH.$path;
769  }
770  return $path;
771}
772
773/* Returns the URL of the thumbnail to be displayed. If the element does not
774 * have a thumbnail, the default mime image url is returned. The URL can be
775 * sent to the browser, but not used in the php script.
776 * @param array element_info assoc array containing element info from db
777 * at least 'path', 'tn_ext' and 'id' should be present
778 */
779function get_thumbnail_url($element_info)
780{
781  $path = get_thumbnail_location($element_info);
782  if ( !url_is_remote($path) )
783  {
784    $path = get_root_url().$path;
785  }
786  // plugins want another url ?
787  $path = trigger_event('get_thumbnail_url', $path, $element_info);
788  return $path;
789}
790
791/* returns the relative path of the thumnail with regards to to the root
792of phpwebgallery (not the current page!).This function is not intended to be
793called directly from code.*/
794function get_thumbnail_location($element_info)
795{
796  global $conf;
797  if ( !empty( $element_info['tn_ext'] ) )
798  {
799    $path = substr_replace(
800      get_filename_wo_extension($element_info['path']),
801      '/thumbnail/'.$conf['prefix_thumbnail'],
802      strrpos($element_info['path'],'/'),
803      1
804      );
805    $path.= '.'.$element_info['tn_ext'];
806  }
807  else
808  {
809    $path = get_themeconf('mime_icon_dir')
810        .strtolower(get_extension($element_info['path'])).'.png';
811  }
812
813  // plugins want another location ?
814  $path = trigger_event( 'get_thumbnail_location', $path, $element_info);
815  return $path;
816}
817
818
819// my_error returns (or send to standard output) the message concerning the
820// error occured for the last mysql query.
821function my_error($header)
822{
823  global $conf;
824
825  $error = '<pre>';
826  $error.= $header;
827  $error.= '[mysql error '.mysql_errno().'] ';
828  $error.= mysql_error();
829  $error.= '</pre>';
830
831  if ($conf['die_on_sql_error'])
832  {
833    die($error);
834  }
835  else
836  {
837    echo $error;
838  }
839}
840
841/**
842 * creates an array based on a query, this function is a very common pattern
843 * used here
844 *
845 * @param string $query
846 * @param string $fieldname
847 * @return array
848 */
849function array_from_query($query, $fieldname)
850{
851  $array = array();
852
853  $result = pwg_query($query);
854  while ($row = mysql_fetch_array($result))
855  {
856    array_push($array, $row[$fieldname]);
857  }
858
859  return $array;
860}
861
862/**
863 * instantiate number list for days in a template block
864 *
865 * @param string blockname
866 * @param string selection
867 */
868function get_day_list($blockname, $selection)
869{
870  global $template;
871
872  $template->assign_block_vars(
873    $blockname,
874    array(
875      'SELECTED' => '',
876      'VALUE' => 0,
877      'OPTION' => '--'
878      )
879    );
880
881  for ($i = 1; $i <= 31; $i++)
882  {
883    $selected = '';
884    if ($i == (int)$selection)
885    {
886      $selected = 'selected="selected"';
887    }
888    $template->assign_block_vars(
889      $blockname,
890      array(
891        'SELECTED' => $selected,
892        'VALUE' => $i,
893        'OPTION' => str_pad($i, 2, '0', STR_PAD_LEFT)
894        )
895      );
896  }
897}
898
899/**
900 * instantiate month list in a template block
901 *
902 * @param string blockname
903 * @param string selection
904 */
905function get_month_list($blockname, $selection)
906{
907  global $template, $lang;
908
909  $template->assign_block_vars(
910    $blockname,
911    array(
912      'SELECTED' => '',
913      'VALUE' => 0,
914      'OPTION' => '------------')
915    );
916
917  for ($i = 1; $i <= 12; $i++)
918  {
919    $selected = '';
920    if ($i == (int)$selection)
921    {
922      $selected = 'selected="selected"';
923    }
924    $template->assign_block_vars(
925      $blockname,
926      array(
927        'SELECTED' => $selected,
928        'VALUE' => $i,
929        'OPTION' => $lang['month'][$i])
930      );
931  }
932}
933
934/**
935 * fill the current user caddie with given elements, if not already in
936 * caddie
937 *
938 * @param array elements_id
939 */
940function fill_caddie($elements_id)
941{
942  global $user;
943
944  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
945
946  $query = '
947SELECT element_id
948  FROM '.CADDIE_TABLE.'
949  WHERE user_id = '.$user['id'].'
950;';
951  $in_caddie = array_from_query($query, 'element_id');
952
953  $caddiables = array_diff($elements_id, $in_caddie);
954
955  $datas = array();
956
957  foreach ($caddiables as $caddiable)
958  {
959    array_push($datas, array('element_id' => $caddiable,
960                             'user_id' => $user['id']));
961  }
962
963  if (count($caddiables) > 0)
964  {
965    mass_inserts(CADDIE_TABLE, array('element_id','user_id'), $datas);
966  }
967}
968
969/**
970 * returns the element name from its filename
971 *
972 * @param string filename
973 * @return string name
974 */
975function get_name_from_file($filename)
976{
977  return str_replace('_',' ',get_filename_wo_extension($filename));
978}
979
980/**
981 * returns the corresponding value from $lang if existing. Else, the key is
982 * returned
983 *
984 * @param string key
985 * @return string
986 */
987function l10n($key)
988{
989  global $lang, $conf;
990
991  if ($conf['debug_l10n'] and !isset($lang[$key]))
992  {
993    echo '[l10n] language key "'.$key.'" is not defined<br />';
994  }
995
996  return isset($lang[$key]) ? $lang[$key] : $key;
997}
998
999/**
1000 * returns the prinft value for strings including %d
1001 * return is concorded with decimal value (singular, plural)
1002 *
1003 * @param singular string key
1004 * @param plural string key
1005 * @param decimal value
1006 * @return string
1007 */
1008function l10n_dec($singular_fmt_key, $plural_fmt_key, $decimal)
1009{
1010  return sprintf(l10n(($decimal > 1 ? $plural_fmt_key :
1011                                      $singular_fmt_key)), $decimal);
1012}
1013
1014/**
1015 * Translate string in string ascii7bits
1016 * It's possible to do that with iconv_substr
1017 * but this fonction is not avaible on all the providers.
1018 *
1019 * @param string str
1020 * @return string
1021 */
1022function str_translate_to_ascii7bits($str)
1023{
1024  global $lang_table_translate_ascii7bits;
1025
1026  $src_table = array_keys($lang_table_translate_ascii7bits);
1027  $dst_table = array_values($lang_table_translate_ascii7bits);
1028
1029  return str_replace($src_table , $dst_table, $str);
1030}
1031
1032/**
1033 * returns the corresponding value from $themeconf if existing. Else, the
1034 * key is returned
1035 *
1036 * @param string key
1037 * @return string
1038 */
1039function get_themeconf($key)
1040{
1041  global $template;
1042
1043  return $template->get_themeconf($key);
1044}
1045
1046/**
1047 * Returns webmaster mail address depending on $conf['webmaster_id']
1048 *
1049 * @return string
1050 */
1051function get_webmaster_mail_address()
1052{
1053  global $conf;
1054
1055  $query = '
1056SELECT '.$conf['user_fields']['email'].'
1057  FROM '.USERS_TABLE.'
1058  WHERE '.$conf['user_fields']['id'].' = '.$conf['webmaster_id'].'
1059;';
1060  list($email) = mysql_fetch_array(pwg_query($query));
1061
1062  return $email;
1063}
1064
1065/**
1066 * which upgrades are available ?
1067 *
1068 * @return array
1069 */
1070function get_available_upgrade_ids()
1071{
1072  $upgrades_path = PHPWG_ROOT_PATH.'install/db';
1073
1074  $available_upgrade_ids = array();
1075
1076  if ($contents = opendir($upgrades_path))
1077  {
1078    while (($node = readdir($contents)) !== false)
1079    {
1080      if (is_file($upgrades_path.'/'.$node)
1081          and preg_match('/^(.*?)-database\.php$/', $node, $match))
1082      {
1083        array_push($available_upgrade_ids, $match[1]);
1084      }
1085    }
1086  }
1087  natcasesort($available_upgrade_ids);
1088
1089  return $available_upgrade_ids;
1090}
1091
1092/**
1093 * Add configuration parameters from database to global $conf array
1094 *
1095 * @return void
1096 */
1097function load_conf_from_db($condition = '')
1098{
1099  global $conf;
1100
1101  $query = '
1102SELECT param, value
1103 FROM '.CONFIG_TABLE.'
1104 '.(!empty($condition) ? 'WHERE '.$condition : '').'
1105;';
1106  $result = pwg_query($query);
1107
1108  if ((mysql_num_rows($result) == 0) and !empty($condition))
1109  {
1110    die('No configuration data');
1111  }
1112
1113  while ($row = mysql_fetch_array($result))
1114  {
1115    $conf[ $row['param'] ] = isset($row['value']) ? $row['value'] : '';
1116
1117    // If the field is true or false, the variable is transformed into a
1118    // boolean value.
1119    if ($conf[$row['param']] == 'true' or $conf[$row['param']] == 'false')
1120    {
1121      $conf[ $row['param'] ] = get_boolean($conf[ $row['param'] ]);
1122    }
1123  }
1124}
1125
1126/**
1127 * Prepends and appends a string at each value of the given array.
1128 *
1129 * @param array
1130 * @param string prefix to each array values
1131 * @param string suffix to each array values
1132 */
1133function prepend_append_array_items($array, $prepend_str, $append_str)
1134{
1135  array_walk(
1136    $array,
1137    create_function('&$s', '$s = "'.$prepend_str.'".$s."'.$append_str.'";')
1138    );
1139
1140  return $array;
1141}
1142
1143/**
1144 * creates an hashed based on a query, this function is a very common
1145 * pattern used here. Among the selected columns fetched, choose one to be
1146 * the key, another one to be the value.
1147 *
1148 * @param string $query
1149 * @param string $keyname
1150 * @param string $valuename
1151 * @return array
1152 */
1153function simple_hash_from_query($query, $keyname, $valuename)
1154{
1155  $array = array();
1156
1157  $result = pwg_query($query);
1158  while ($row = mysql_fetch_array($result))
1159  {
1160    $array[ $row[$keyname] ] = $row[$valuename];
1161  }
1162
1163  return $array;
1164}
1165
1166/**
1167 * Return basename of the current script
1168 * Lower case convertion is applied on return value
1169 * Return value is without file extention ".php"
1170 *
1171 * @param void
1172 *
1173 * @return script basename
1174 */
1175function script_basename()
1176{
1177  if (!empty($_SERVER['SCRIPT_NAME']))
1178  {
1179    $file_name = $_SERVER['SCRIPT_NAME'];
1180  }
1181  else if (!empty($_SERVER['SCRIPT_FILENAME']))
1182  {
1183    $file_name = $_SERVER['SCRIPT_FILENAME'];
1184  }
1185  else
1186  {
1187    $file_name = '';
1188  }
1189
1190  // $_SERVER return lower string following var and systems
1191  return basename(strtolower($file_name), '.php');
1192}
1193
1194/**
1195 * Return value for the current page define on $conf['filter_pages']
1196 * Îf value is not defined, default value are returned
1197 *
1198 * @param value name
1199 *
1200 * @return filter page value
1201 */
1202function get_filter_page_value($value_name)
1203{
1204  global $conf;
1205
1206  $page_name = script_basename();
1207
1208  if (isset($conf['filter_pages'][$page_name][$value_name]))
1209  {
1210    return $conf['filter_pages'][$page_name][$value_name];
1211  }
1212  else if (isset($conf['filter_pages']['default'][$value_name]))
1213  {
1214    return $conf['filter_pages']['default'][$value_name];
1215  }
1216  else
1217  {
1218    return null;
1219  }
1220}
1221
1222?>
Note: See TracBrowser for help on using the repository browser.