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

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

Issue ID 0000529 Fixed.

Problem with $_SERVERSCRIPT_FILENAME on IIS server

Merge branch-1_6 1685:1686 into BSF

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 28.6 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-2006 PhpWebGallery Team - http://phpwebgallery.net |
6// +-----------------------------------------------------------------------+
7// | branch        : BSF (Best So Far)
8// | file          : $Id: functions.inc.php 1687 2006-12-31 17:08:37Z rub $
9// | last update   : $Date: 2006-12-31 17:08:37 +0000 (Sun, 31 Dec 2006) $
10// | last modifier : $Author: rub $
11// | revision      : $Revision: 1687 $
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' );
37include_once( PHPWG_ROOT_PATH .'include/functions_webserv.inc.php' );
38
39//----------------------------------------------------------- generic functions
40
41/**
42 * returns an array containing the possible values of an enum field
43 *
44 * @param string tablename
45 * @param string fieldname
46 */
47function get_enums($table, $field)
48{
49  // retrieving the properties of the table. Each line represents a field :
50  // columns are 'Field', 'Type'
51  $result = pwg_query('desc '.$table);
52  while ($row = mysql_fetch_array($result))
53  {
54    // we are only interested in the the field given in parameter for the
55    // function
56    if ($row['Field'] == $field)
57    {
58      // retrieving possible values of the enum field
59      // enum('blue','green','black')
60      $options = explode(',', substr($row['Type'], 5, -1));
61      foreach ($options as $i => $option)
62      {
63        $options[$i] = str_replace("'", '',$option);
64      }
65    }
66  }
67  mysql_free_result($result);
68  return $options;
69}
70
71// get_boolean transforms a string to a boolean value. If the string is
72// "false" (case insensitive), then the boolean value false is returned. In
73// any other case, true is returned.
74function get_boolean( $string )
75{
76  $boolean = true;
77  if ( preg_match( '/^false$/i', $string ) )
78  {
79    $boolean = false;
80  }
81  return $boolean;
82}
83
84/**
85 * returns boolean string 'true' or 'false' if the given var is boolean
86 *
87 * @param mixed $var
88 * @return mixed
89 */
90function boolean_to_string($var)
91{
92  if (is_bool($var))
93  {
94    if ($var)
95    {
96      return 'true';
97    }
98    else
99    {
100      return 'false';
101    }
102  }
103  else
104  {
105    return $var;
106  }
107}
108
109// The function get_moment returns a float value coresponding to the number
110// of seconds since the unix epoch (1st January 1970) and the microseconds
111// are precised : e.g. 1052343429.89276600
112function get_moment()
113{
114  $t1 = explode( ' ', microtime() );
115  $t2 = explode( '.', $t1[0] );
116  $t2 = $t1[1].'.'.$t2[1];
117  return $t2;
118}
119
120// The function get_elapsed_time returns the number of seconds (with 3
121// decimals precision) between the start time and the end time given.
122function get_elapsed_time( $start, $end )
123{
124  return number_format( $end - $start, 3, '.', ' ').' s';
125}
126
127// - The replace_space function replaces space and '-' characters
128//   by their HTML equivalent  &nbsb; and &minus;
129// - The function does not replace characters in HTML tags
130// - This function was created because IE5 does not respect the
131//   CSS "white-space: nowrap;" property unless space and minus
132//   characters are replaced like this function does.
133// - Example :
134//                 <div class="foo">My friend</div>
135//               ( 01234567891111111111222222222233 )
136//               (           0123456789012345678901 )
137// becomes :
138//             <div class="foo">My&nbsp;friend</div>
139function replace_space( $string )
140{
141  //return $string;
142  $return_string = '';
143  // $remaining is the rest of the string where to replace spaces characters
144  $remaining = $string;
145  // $start represents the position of the next '<' character
146  // $end   represents the position of the next '>' character
147  $start = 0;
148  $end = 0;
149  $start = strpos ( $remaining, '<' ); // -> 0
150  $end   = strpos ( $remaining, '>' ); // -> 16
151  // as long as a '<' and his friend '>' are found, we loop
152  while ( is_numeric( $start ) and is_numeric( $end ) )
153  {
154    // $treatment is the part of the string to treat
155    // In the first loop of our example, this variable is empty, but in the
156    // second loop, it equals 'My friend'
157    $treatment = substr ( $remaining, 0, $start );
158    // Replacement of ' ' by his equivalent '&nbsp;'
159    $treatment = str_replace( ' ', '&nbsp;', $treatment );
160    $treatment = str_replace( '-', '&minus;', $treatment );
161    // composing the string to return by adding the treated string and the
162    // following HTML tag -> 'My&nbsp;friend</div>'
163    $return_string.= $treatment.substr( $remaining, $start, $end-$start+1 );
164    // the remaining string is deplaced to the part after the '>' of this
165    // loop
166    $remaining = substr ( $remaining, $end + 1, strlen( $remaining ) );
167    $start = strpos ( $remaining, '<' );
168    $end   = strpos ( $remaining, '>' );
169  }
170  $treatment = str_replace( ' ', '&nbsp;', $remaining );
171  $treatment = str_replace( '-', '&minus;', $treatment );
172  $return_string.= $treatment;
173
174  return $return_string;
175}
176
177// get_extension returns the part of the string after the last "."
178function get_extension( $filename )
179{
180  return substr( strrchr( $filename, '.' ), 1, strlen ( $filename ) );
181}
182
183// get_filename_wo_extension returns the part of the string before the last
184// ".".
185// get_filename_wo_extension( 'test.tar.gz' ) -> 'test.tar'
186function get_filename_wo_extension( $filename )
187{
188  $pos = strrpos( $filename, '.' );
189  return ($pos===false) ? $filename : substr( $filename, 0, $pos);
190}
191
192/**
193 * returns an array contening sub-directories, excluding "CVS"
194 *
195 * @param string $dir
196 * @return array
197 */
198function get_dirs($directory)
199{
200  $sub_dirs = array();
201
202  if ($opendir = opendir($directory))
203  {
204    while ($file = readdir($opendir))
205    {
206      if ($file != '.'
207          and $file != '..'
208          and is_dir($directory.'/'.$file)
209          and $file != 'CVS'
210    and $file != '.svn')
211      {
212        array_push($sub_dirs, $file);
213      }
214    }
215  }
216  return $sub_dirs;
217}
218
219/**
220 * returns thumbnail directory name of input diretoty name
221 * make thumbnail directory is necessary
222 * set error messages on array messages
223 *
224 * @param:
225 *  string $dirname
226 *  arrayy $errors
227 * @return bool false on error else string directory name
228 */
229function mkget_thumbnail_dir($dirname, &$errors)
230{
231  $tndir = $dirname.'/thumbnail';
232  if (!is_dir($tndir))
233  {
234    if (!is_writable($dirname))
235    {
236      array_push($errors,
237                 '['.$dirname.'] : '.l10n('no_write_access'));
238      return false;
239    }
240    umask(0000);
241    mkdir($tndir, 0777);
242  }
243
244  return $tndir;
245}
246
247// The get_picture_size function return an array containing :
248//      - $picture_size[0] : final width
249//      - $picture_size[1] : final height
250// The final dimensions are calculated thanks to the original dimensions and
251// the maximum dimensions given in parameters.  get_picture_size respects
252// the width/height ratio
253function get_picture_size( $original_width, $original_height,
254                           $max_width, $max_height )
255{
256  $width = $original_width;
257  $height = $original_height;
258  $is_original_size = true;
259
260  if ( $max_width != "" )
261  {
262    if ( $original_width > $max_width )
263    {
264      $width = $max_width;
265      $height = floor( ( $width * $original_height ) / $original_width );
266    }
267  }
268  if ( $max_height != "" )
269  {
270    if ( $original_height > $max_height )
271    {
272      $height = $max_height;
273      $width = floor( ( $height * $original_width ) / $original_height );
274      $is_original_size = false;
275    }
276  }
277  if ( is_numeric( $max_width ) and is_numeric( $max_height )
278       and $max_width != 0 and $max_height != 0 )
279  {
280    $ratioWidth = $original_width / $max_width;
281    $ratioHeight = $original_height / $max_height;
282    if ( ( $ratioWidth > 1 ) or ( $ratioHeight > 1 ) )
283    {
284      if ( $ratioWidth < $ratioHeight )
285      {
286        $width = floor( $original_width / $ratioHeight );
287        $height = $max_height;
288      }
289      else
290      {
291        $width = $max_width;
292        $height = floor( $original_height / $ratioWidth );
293      }
294      $is_original_size = false;
295    }
296  }
297  $picture_size = array();
298  $picture_size[0] = $width;
299  $picture_size[1] = $height;
300  return $picture_size;
301}
302
303/**
304 * simplify a string to insert it into an URL
305 *
306 * based on str2url function from Dotclear
307 *
308 * @param string
309 * @return string
310 */
311function str2url($str)
312{
313  $str = strtr(
314    $str,
315    'ÀÁÂÃÄÅàáâãäåÇçÒÓÔÕÖØòóôõöøÈÉÊËèéêëÌÍÎÏìíîïÙÚÛÜùúûü¾ÝÿýÑñ',
316    'AAAAAAaaaaaaCcOOOOOOooooooEEEEeeeeIIIIiiiiUUUUuuuuYYyyNn'
317    );
318
319  $str = str_replace('Æ', 'AE', $str);
320  $str = str_replace('æ', 'ae', $str);
321  $str = str_replace('¼', 'OE', $str);
322  $str = str_replace('½', 'oe', $str);
323
324  $str = preg_replace('/[^a-z0-9_\s\'\:\/\[\],-]/','',strtolower($str));
325  $str = preg_replace('/[\s\'\:\/\[\],-]+/',' ',trim($str));
326  $res = str_replace(' ','_',$str);
327
328  return $res;
329}
330
331//-------------------------------------------- PhpWebGallery specific functions
332
333/**
334 * returns an array with a list of {language_code => language_name}
335 *
336 * @returns array
337 */
338function get_languages()
339{
340  $dir = opendir(PHPWG_ROOT_PATH.'language');
341  $languages = array();
342
343  while ($file = readdir($dir))
344  {
345    $path = PHPWG_ROOT_PATH.'language/'.$file;
346    if (is_dir($path) and !is_link($path) and file_exists($path.'/iso.txt'))
347    {
348      list($language_name) = @file($path.'/iso.txt');
349      $languages[$file] = $language_name;
350    }
351  }
352  closedir($dir);
353  @asort($languages);
354  @reset($languages);
355
356  return $languages;
357}
358
359/**
360 * replaces the $search into <span style="$style">$search</span> in the
361 * given $string.
362 *
363 * case insensitive replacements, does not replace characters in HTML tags
364 *
365 * @param string $string
366 * @param string $search
367 * @param string $style
368 * @return string
369 */
370function add_style( $string, $search, $style )
371{
372  //return $string;
373  $return_string = '';
374  $remaining = $string;
375
376  $start = 0;
377  $end = 0;
378  $start = strpos ( $remaining, '<' );
379  $end   = strpos ( $remaining, '>' );
380  while ( is_numeric( $start ) and is_numeric( $end ) )
381  {
382    $treatment = substr ( $remaining, 0, $start );
383    $treatment = preg_replace( '/('.$search.')/i',
384                               '<span style="'.$style.'">\\0</span>',
385                               $treatment );
386    $return_string.= $treatment.substr( $remaining, $start, $end-$start+1 );
387    $remaining = substr ( $remaining, $end + 1, strlen( $remaining ) );
388    $start = strpos ( $remaining, '<' );
389    $end   = strpos ( $remaining, '>' );
390  }
391  $treatment = preg_replace( '/('.$search.')/i',
392                             '<span style="'.$style.'">\\0</span>',
393                             $remaining );
394  $return_string.= $treatment;
395
396  return $return_string;
397}
398
399// replace_search replaces a searched words array string by the search in
400// another style for the given $string.
401function replace_search( $string, $search )
402{
403  // FIXME : with new advanced search, this function needs a rewrite
404  return $string;
405
406  $words = explode( ',', $search );
407  $style = 'background-color:white;color:red;';
408  foreach ( $words as $word ) {
409    $string = add_style( $string, $word, $style );
410  }
411  return $string;
412}
413
414function pwg_log( $file, $category, $picture = '' )
415{
416  global $conf, $user;
417
418  if ( is_admin() )
419  {
420    $doit=$conf['history_admin'];
421  }
422  elseif ( $user['is_the_guest'] )
423  {
424    $doit=$conf['history_guest'];
425  }
426  else
427  {
428    $doit = $conf['log'];
429  }
430
431  if ($doit)
432  {
433    $login = ($user['id'] == $conf['guest_id'])
434      ? 'guest' : addslashes($user['username']);
435    insert_into_history($login, $file, $category, $picture);
436  }
437}
438
439function pwg_log_login( $username )
440{
441  global $conf;
442  if ( $conf['login_history'] )
443  {
444    insert_into_history($username, 'login', '', '');
445  }
446}
447
448// inserts a row in the history table
449function insert_into_history( $login, $file, $category, $picture)
450{
451  $query = '
452INSERT INTO '.HISTORY_TABLE.'
453  (date,login,IP,file,category,picture)
454  VALUES
455  (NOW(),
456  \''.$login.'\',
457  \''.$_SERVER['REMOTE_ADDR'].'\',
458  \''.addslashes($file).'\',
459  \''.addslashes(strip_tags($category)).'\',
460  \''.addslashes($picture).'\')
461;';
462  pwg_query($query);
463}
464
465// format_date returns a formatted date for display. The date given in
466// argument can be a unixdate (number of seconds since the 01.01.1970) or an
467// american format (2003-09-15). By option, you can show the time. The
468// output is internationalized.
469//
470// format_date( "2003-09-15", 'us', true ) -> "Monday 15 September 2003 21:52"
471function format_date($date, $type = 'us', $show_time = false)
472{
473  global $lang;
474
475  list($year,$month,$day,$hour,$minute,$second) = array(0,0,0,0,0,0);
476
477  switch ( $type )
478  {
479    case 'us' :
480    {
481      list($year,$month,$day) = explode('-', $date);
482      break;
483    }
484    case 'unix' :
485    {
486      list($year,$month,$day,$hour,$minute) =
487        explode('.', date('Y.n.j.G.i', $date));
488      break;
489    }
490    case 'mysql_datetime' :
491    {
492      preg_match('/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/',
493                 $date, $out);
494      list($year,$month,$day,$hour,$minute,$second) =
495        array($out[1],$out[2],$out[3],$out[4],$out[5],$out[6]);
496      break;
497    }
498  }
499  $formated_date = '';
500  // before 1970, Microsoft Windows can't mktime
501  if ($year >= 1970)
502  {
503    // we ask midday because Windows think it's prior to midnight with a
504    // zero and refuse to work
505    $formated_date.= $lang['day'][date('w', mktime(12,0,0,$month,$day,$year))];
506  }
507  $formated_date.= ' '.$day;
508  $formated_date.= ' '.$lang['month'][(int)$month];
509  $formated_date.= ' '.$year;
510  if ($show_time)
511  {
512    $formated_date.= ' '.$hour.':'.$minute;
513  }
514
515  return $formated_date;
516}
517
518function pwg_stripslashes($value)
519{
520  if (get_magic_quotes_gpc())
521  {
522    $value = stripslashes($value);
523  }
524  return $value;
525}
526
527function pwg_addslashes($value)
528{
529  if (!get_magic_quotes_gpc())
530  {
531    $value = addslashes($value);
532  }
533  return $value;
534}
535
536function pwg_quotemeta($value)
537{
538  if (get_magic_quotes_gpc()) {
539    $value = stripslashes($value);
540  }
541  if (function_exists('mysql_real_escape_string'))
542  {
543    $value = mysql_real_escape_string($value);
544  }
545  else
546  {
547    $value = mysql_escape_string($value);
548  }
549  return $value;
550}
551
552function pwg_query($query)
553{
554  global $conf,$page,$debug,$t2;
555
556  $start = get_moment();
557  $result = mysql_query($query) or my_error($query."\n");
558
559  $time = get_moment() - $start;
560
561  if (!isset($page['count_queries']))
562  {
563    $page['count_queries'] = 0;
564    $page['queries_time'] = 0;
565  }
566
567  $page['count_queries']++;
568  $page['queries_time']+= $time;
569
570  if ($conf['show_queries'])
571  {
572    $output = '';
573    $output.= '<pre>['.$page['count_queries'].'] ';
574    $output.= "\n".$query;
575    $output.= "\n".'(this query time : ';
576    $output.= '<b>'.number_format($time, 3, '.', ' ').' s)</b>';
577    $output.= "\n".'(total SQL time  : ';
578    $output.= number_format($page['queries_time'], 3, '.', ' ').' s)';
579    $output.= "\n".'(total time      : ';
580    $output.= number_format( ($time+$start-$t2), 3, '.', ' ').' s)';
581    $output.= "</pre>\n";
582
583    $debug .= $output;
584  }
585
586  return $result;
587}
588
589function pwg_debug( $string )
590{
591  global $debug,$t2,$page;
592
593  $now = explode( ' ', microtime() );
594  $now2 = explode( '.', $now[0] );
595  $now2 = $now[1].'.'.$now2[1];
596  $time = number_format( $now2 - $t2, 3, '.', ' ').' s';
597  $debug .= '<p>';
598  $debug.= '['.$time.', ';
599  $debug.= $page['count_queries'].' queries] : '.$string;
600  $debug.= "</p>\n";
601}
602
603/**
604 * Redirects to the given URL (HTTP method)
605 *
606 * Note : once this function called, the execution doesn't go further
607 * (presence of an exit() instruction.
608 *
609 * @param string $url
610 * @return void
611 */
612function redirect_http( $url )
613{
614  if (ob_get_length () !== FALSE)
615  {
616    ob_clean();
617  }
618  header('Request-URI: '.$url);
619  header('Content-Location: '.$url);
620  header('Location: '.$url);
621  exit();
622}
623
624/**
625 * Redirects to the given URL (HTML method)
626 *
627 * Note : once this function called, the execution doesn't go further
628 * (presence of an exit() instruction.
629 *
630 * @param string $url
631 * @param string $title_msg
632 * @param integer $refreh_time
633 * @return void
634 */
635function redirect_html( $url , $msg = '', $refresh_time = 0)
636{
637  global $user, $template, $lang_info, $conf, $lang, $t2, $page, $debug;
638
639  if (!isset($lang_info))
640  {
641    $user = build_user( $conf['guest_id'], true);
642    include_once(get_language_filepath('common.lang.php'));
643    @include_once(get_language_filepath('local.lang.php'));
644    list($tmpl, $thm) = explode('/', $conf['default_template']);
645    $template = new Template(PHPWG_ROOT_PATH.'template/'.$tmpl, $thm);
646  }
647  else
648  {
649    $template = new Template(PHPWG_ROOT_PATH.'template/'.$user['template'], $user['theme']);
650  }
651
652  if (empty($msg))
653  {
654    $redirect_msg = l10n('redirect_msg');
655  }
656  else
657  {
658    $redirect_msg = $msg;
659  }
660  $redirect_msg = nl2br($redirect_msg);
661
662  $refresh = $refresh_time;
663  $url_link = $url;
664  $title = 'redirection';
665
666  $template->set_filenames( array( 'redirect' => 'redirect.tpl' ) );
667
668  include( PHPWG_ROOT_PATH.'include/page_header.php' );
669
670  $template->set_filenames( array( 'redirect' => 'redirect.tpl' ) );
671  $template->parse('redirect');
672
673  include( PHPWG_ROOT_PATH.'include/page_tail.php' );
674
675  exit();
676}
677
678/**
679 * Redirects to the given URL (Switch to HTTP method or HTML method)
680 *
681 * Note : once this function called, the execution doesn't go further
682 * (presence of an exit() instruction.
683 *
684 * @param string $url
685 * @param string $title_msg
686 * @param integer $refreh_time
687 * @return void
688 */
689function redirect( $url , $msg = '', $refresh_time = 0)
690{
691  global $conf;
692
693  // with RefeshTime <> 0, only html must be used
694  if (($conf['default_redirect_method'] == 'http') and ($refresh_time == 0))
695  {
696    redirect_http($url);
697  }
698  else
699  {
700    redirect_html($url, $msg, $refresh_time);
701  }
702}
703
704/**
705 * returns $_SERVER['QUERY_STRING'] whitout keys given in parameters
706 *
707 * @param array $rejects
708 * @returns string
709 */
710function get_query_string_diff($rejects = array())
711{
712  $query_string = '';
713
714  $str = $_SERVER['QUERY_STRING'];
715  parse_str($str, $vars);
716
717  $is_first = true;
718  foreach ($vars as $key => $value)
719  {
720    if (!in_array($key, $rejects))
721    {
722      $query_string.= $is_first ? '?' : '&amp;';
723      $is_first = false;
724      $query_string.= $key.'='.$value;
725    }
726  }
727
728  return $query_string;
729}
730
731function url_is_remote($url)
732{
733  if (preg_match('/^https?:\/\/[~\/\.\w-]+$/', $url))
734  {
735    return true;
736  }
737  return false;
738}
739
740/**
741 * returns available template/theme
742 */
743function get_pwg_themes()
744{
745  $themes = array();
746
747  $template_dir = PHPWG_ROOT_PATH.'template';
748
749  foreach (get_dirs($template_dir) as $template)
750  {
751    foreach (get_dirs($template_dir.'/'.$template.'/theme') as $theme)
752    {
753      array_push($themes, $template.'/'.$theme);
754    }
755  }
756
757  return $themes;
758}
759
760/* Returns the PATH to the thumbnail to be displayed. If the element does not
761 * have a thumbnail, the default mime image path is returned. The PATH can be
762 * used in the php script, but not sent to the browser.
763 * @param array element_info assoc array containing element info from db
764 * at least 'path', 'tn_ext' and 'id' should be present
765 */
766function get_thumbnail_path($element_info)
767{
768  $path = get_thumbnail_location($element_info);
769  if ( !url_is_remote($path) )
770  {
771    $path = PHPWG_ROOT_PATH.$path;
772  }
773  return $path;
774}
775
776/* Returns the URL of the thumbnail to be displayed. If the element does not
777 * have a thumbnail, the default mime image url is returned. The URL can be
778 * sent to the browser, but not used in the php script.
779 * @param array element_info assoc array containing element info from db
780 * at least 'path', 'tn_ext' and 'id' should be present
781 */
782function get_thumbnail_url($element_info)
783{
784  $path = get_thumbnail_location($element_info);
785  if ( !url_is_remote($path) )
786  {
787    $path = get_root_url().$path;
788  }
789  // plugins want another url ?
790  $path = trigger_event('get_thumbnail_url', $path, $element_info);
791  return $path;
792}
793
794/* returns the relative path of the thumnail with regards to to the root
795of phpwebgallery (not the current page!).This function is not intended to be
796called directly from code.*/
797function get_thumbnail_location($element_info)
798{
799  global $conf;
800  if ( !empty( $element_info['tn_ext'] ) )
801  {
802    $path = substr_replace(
803      get_filename_wo_extension($element_info['path']),
804      '/thumbnail/'.$conf['prefix_thumbnail'],
805      strrpos($element_info['path'],'/'),
806      1
807      );
808    $path.= '.'.$element_info['tn_ext'];
809  }
810  else
811  {
812    $path = get_themeconf('mime_icon_dir')
813        .strtolower(get_extension($element_info['path'])).'.png';
814  }
815
816  // plugins want another location ?
817  $path = trigger_event( 'get_thumbnail_location', $path, $element_info);
818  return $path;
819}
820
821
822// my_error returns (or send to standard output) the message concerning the
823// error occured for the last mysql query.
824function my_error($header)
825{
826  global $conf;
827
828  $error = '<pre>';
829  $error.= $header;
830  $error.= '[mysql error '.mysql_errno().'] ';
831  $error.= mysql_error();
832  $error.= '</pre>';
833
834  if ($conf['die_on_sql_error'])
835  {
836    die($error);
837  }
838  else
839  {
840    echo $error;
841  }
842}
843
844/**
845 * creates an array based on a query, this function is a very common pattern
846 * used here
847 *
848 * @param string $query
849 * @param string $fieldname
850 * @return array
851 */
852function array_from_query($query, $fieldname)
853{
854  $array = array();
855
856  $result = pwg_query($query);
857  while ($row = mysql_fetch_array($result))
858  {
859    array_push($array, $row[$fieldname]);
860  }
861
862  return $array;
863}
864
865/**
866 * instantiate number list for days in a template block
867 *
868 * @param string blockname
869 * @param string selection
870 */
871function get_day_list($blockname, $selection)
872{
873  global $template;
874
875  $template->assign_block_vars(
876    $blockname, array('SELECTED' => '', 'VALUE' => 0, 'OPTION' => '--'));
877
878  for ($i = 1; $i <= 31; $i++)
879  {
880    $selected = '';
881    if ($i == (int)$selection)
882    {
883      $selected = 'selected="selected"';
884    }
885    $template->assign_block_vars(
886      $blockname, array('SELECTED' => $selected,
887                        'VALUE' => $i,
888                        'OPTION' => str_pad($i, 2, '0', STR_PAD_LEFT)));
889  }
890}
891
892/**
893 * instantiate month list in a template block
894 *
895 * @param string blockname
896 * @param string selection
897 */
898function get_month_list($blockname, $selection)
899{
900  global $template, $lang;
901
902  $template->assign_block_vars(
903    $blockname, array('SELECTED' => '',
904                      'VALUE' => 0,
905                      'OPTION' => '------------'));
906
907  for ($i = 1; $i <= 12; $i++)
908  {
909    $selected = '';
910    if ($i == (int)$selection)
911    {
912      $selected = 'selected="selected"';
913    }
914    $template->assign_block_vars(
915      $blockname, array('SELECTED' => $selected,
916                        'VALUE' => $i,
917                        'OPTION' => $lang['month'][$i]));
918  }
919}
920
921/**
922 * fill the current user caddie with given elements, if not already in
923 * caddie
924 *
925 * @param array elements_id
926 */
927function fill_caddie($elements_id)
928{
929  global $user;
930
931  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
932
933  $query = '
934SELECT element_id
935  FROM '.CADDIE_TABLE.'
936  WHERE user_id = '.$user['id'].'
937;';
938  $in_caddie = array_from_query($query, 'element_id');
939
940  $caddiables = array_diff($elements_id, $in_caddie);
941
942  $datas = array();
943
944  foreach ($caddiables as $caddiable)
945  {
946    array_push($datas, array('element_id' => $caddiable,
947                             'user_id' => $user['id']));
948  }
949
950  if (count($caddiables) > 0)
951  {
952    mass_inserts(CADDIE_TABLE, array('element_id','user_id'), $datas);
953  }
954}
955
956/**
957 * returns the element name from its filename
958 *
959 * @param string filename
960 * @return string name
961 */
962function get_name_from_file($filename)
963{
964  return str_replace('_',' ',get_filename_wo_extension($filename));
965}
966
967/**
968 * returns the corresponding value from $lang if existing. Else, the key is
969 * returned
970 *
971 * @param string key
972 * @return string
973 */
974function l10n($key)
975{
976  global $lang, $conf;
977
978  if ($conf['debug_l10n'] and !isset($lang[$key]))
979  {
980    echo '[l10n] language key "'.$key.'" is not defined<br />';
981  }
982
983  return isset($lang[$key]) ? $lang[$key] : $key;
984}
985
986/**
987 * returns the prinft value for strings including %d
988 * return is concorded with decimal value (singular, plural)
989 *
990 * @param singular string key
991 * @param plural string key
992 * @param decimal value
993 * @return string
994 */
995function l10n_dec($singular_fmt_key, $plural_fmt_key, $decimal)
996{
997  return sprintf(l10n(($decimal > 1 ? $plural_fmt_key : 
998                                      $singular_fmt_key)), $decimal);
999}
1000
1001/**
1002 * Translate string in string ascii7bits
1003 * It's possible to do that with iconv_substr
1004 * but this fonction is not avaible on all the providers.
1005 *
1006 * @param string str
1007 * @return string
1008 */
1009function str_translate_to_ascii7bits($str)
1010{
1011  global $lang_table_translate_ascii7bits;
1012
1013  $src_table = array_keys($lang_table_translate_ascii7bits);
1014  $dst_table = array_values($lang_table_translate_ascii7bits);
1015
1016  return str_replace($src_table , $dst_table, $str);
1017}
1018
1019/**
1020 * returns the corresponding value from $themeconf if existing. Else, the
1021 * key is returned
1022 *
1023 * @param string key
1024 * @return string
1025 */
1026function get_themeconf($key)
1027{
1028  global $template;
1029
1030  return $template->get_themeconf($key);
1031}
1032
1033/**
1034 * Returns webmaster mail address depending on $conf['webmaster_id']
1035 *
1036 * @return string
1037 */
1038function get_webmaster_mail_address()
1039{
1040  global $conf;
1041
1042  $query = '
1043SELECT '.$conf['user_fields']['email'].'
1044  FROM '.USERS_TABLE.'
1045  WHERE '.$conf['user_fields']['id'].' = '.$conf['webmaster_id'].'
1046;';
1047  list($email) = mysql_fetch_array(pwg_query($query));
1048
1049  return $email;
1050}
1051
1052/**
1053 * which upgrades are available ?
1054 *
1055 * @return array
1056 */
1057function get_available_upgrade_ids()
1058{
1059  $upgrades_path = PHPWG_ROOT_PATH.'install/db';
1060
1061  $available_upgrade_ids = array();
1062
1063  if ($contents = opendir($upgrades_path))
1064  {
1065    while (($node = readdir($contents)) !== false)
1066    {
1067      if (is_file($upgrades_path.'/'.$node)
1068          and preg_match('/^(.*?)-database\.php$/', $node, $match))
1069      {
1070        array_push($available_upgrade_ids, $match[1]);
1071      }
1072    }
1073  }
1074  natcasesort($available_upgrade_ids);
1075
1076  return $available_upgrade_ids;
1077}
1078
1079/**
1080 * Add configuration parameters from database to global $conf array
1081 *
1082 * @return void
1083 */
1084function load_conf_from_db()
1085{
1086  global $conf;
1087
1088  $query = '
1089SELECT param,value
1090 FROM '.CONFIG_TABLE.'
1091;';
1092  $result = pwg_query($query);
1093
1094  if (mysql_num_rows($result) == 0)
1095  {
1096    die('No configuration data');
1097  }
1098
1099  while ($row = mysql_fetch_array($result))
1100  {
1101    $conf[ $row['param'] ] = isset($row['value']) ? $row['value'] : '';
1102
1103    // If the field is true or false, the variable is transformed into a
1104    // boolean value.
1105    if ($conf[$row['param']] == 'true' or $conf[$row['param']] == 'false')
1106    {
1107      $conf[ $row['param'] ] = get_boolean($conf[ $row['param'] ]);
1108    }
1109  }
1110}
1111
1112/**
1113 * Return basename of the current script
1114 * Return value are chnage to loawer case
1115 *
1116 * @param void
1117 *
1118 * @return script basename
1119 */
1120function script_basename()
1121{
1122  if (!empty($_SERVER['SCRIPT_NAME']))
1123  {
1124    $file_name = $_SERVER['SCRIPT_NAME'];
1125  }
1126  else if (!empty($_SERVER['PHP_SELF']))
1127  {
1128    $file_name = $_SERVER['PHP_SELF'];
1129  }
1130  else if (!empty($_SERVER['SCRIPT_FILENAME']))
1131  {
1132    $file_name = $_SERVER['SCRIPT_FILENAME'];
1133  }
1134  else if (!empty($_SERVER['PATH_TRANSLATED']))
1135  {
1136    $file_name = $_SERVER['PATH_TRANSLATED'];
1137  }
1138  else
1139  {
1140    $file_name = '';
1141  }
1142
1143  // $_SERVER return lower string following var ans systems
1144  return basename(strtolower($file_name));
1145}
1146
1147?>
Note: See TracBrowser for help on using the repository browser.