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

Last change on this file since 2083 was 2071, checked in by rub, 17 years ago

Resolved 0000726: script_basename returns bad result

With specific server configuration, script_basename returns bad result.

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