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

Last change on this file since 1589 was 1589, checked in by rvelices, 18 years ago

fix: get_filename_wo_extension (check for ===false) and template make_filename
improvement: can retrieve template output outside the template

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 24.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-2006 PhpWebGallery Team - http://phpwebgallery.net |
6// +-----------------------------------------------------------------------+
7// | branch        : BSF (Best So Far)
8// | file          : $Id: functions.inc.php 1589 2006-11-01 05:04:24Z rvelices $
9// | last update   : $Date: 2006-11-01 05:04:24 +0000 (Wed, 01 Nov 2006) $
10// | last modifier : $Author: rvelices $
11// | revision      : $Revision: 1589 $
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// The get_picture_size function return an array containing :
219//      - $picture_size[0] : final width
220//      - $picture_size[1] : final height
221// The final dimensions are calculated thanks to the original dimensions and
222// the maximum dimensions given in parameters.  get_picture_size respects
223// the width/height ratio
224function get_picture_size( $original_width, $original_height,
225                           $max_width, $max_height )
226{
227  $width = $original_width;
228  $height = $original_height;
229  $is_original_size = true;
230
231  if ( $max_width != "" )
232  {
233    if ( $original_width > $max_width )
234    {
235      $width = $max_width;
236      $height = floor( ( $width * $original_height ) / $original_width );
237    }
238  }
239  if ( $max_height != "" )
240  {
241    if ( $original_height > $max_height )
242    {
243      $height = $max_height;
244      $width = floor( ( $height * $original_width ) / $original_height );
245      $is_original_size = false;
246    }
247  }
248  if ( is_numeric( $max_width ) and is_numeric( $max_height )
249       and $max_width != 0 and $max_height != 0 )
250  {
251    $ratioWidth = $original_width / $max_width;
252    $ratioHeight = $original_height / $max_height;
253    if ( ( $ratioWidth > 1 ) or ( $ratioHeight > 1 ) )
254    {
255      if ( $ratioWidth < $ratioHeight )
256      {
257        $width = floor( $original_width / $ratioHeight );
258        $height = $max_height;
259      }
260      else
261      {
262        $width = $max_width;
263        $height = floor( $original_height / $ratioWidth );
264      }
265      $is_original_size = false;
266    }
267  }
268  $picture_size = array();
269  $picture_size[0] = $width;
270  $picture_size[1] = $height;
271  return $picture_size;
272}
273
274/**
275 * simplify a string to insert it into an URL
276 *
277 * based on str2url function from Dotclear
278 *
279 * @param string
280 * @return string
281 */
282function str2url($str)
283{
284  $str = strtr(
285    $str,
286    'ÀÁÂÃÄÅàáâãäåÇçÒÓÔÕÖØòóôõöøÈÉÊËèéêëÌÍÎÏìíîïÙÚÛÜùúûü¾ÝÿýÑñ',
287    'AAAAAAaaaaaaCcOOOOOOooooooEEEEeeeeIIIIiiiiUUUUuuuuYYyyNn'
288    );
289
290  $str = str_replace('Æ', 'AE', $str);
291  $str = str_replace('æ', 'ae', $str);
292  $str = str_replace('¼', 'OE', $str);
293  $str = str_replace('½', 'oe', $str);
294
295  $str = preg_replace('/[^a-z0-9_\s\'\:\/\[\],-]/','',strtolower($str));
296  $str = preg_replace('/[\s\'\:\/\[\],-]+/',' ',trim($str));
297  $res = str_replace(' ','_',$str);
298
299  return $res;
300}
301
302//-------------------------------------------- PhpWebGallery specific functions
303
304/**
305 * returns an array with a list of {language_code => language_name}
306 *
307 * @returns array
308 */
309function get_languages()
310{
311  $dir = opendir(PHPWG_ROOT_PATH.'language');
312  $languages = array();
313
314  while ($file = readdir($dir))
315  {
316    $path = PHPWG_ROOT_PATH.'language/'.$file;
317    if (is_dir($path) and !is_link($path) and file_exists($path.'/iso.txt'))
318    {
319      list($language_name) = @file($path.'/iso.txt');
320      $languages[$file] = $language_name;
321    }
322  }
323  closedir($dir);
324  @asort($languages);
325  @reset($languages);
326
327  return $languages;
328}
329
330/**
331 * replaces the $search into <span style="$style">$search</span> in the
332 * given $string.
333 *
334 * case insensitive replacements, does not replace characters in HTML tags
335 *
336 * @param string $string
337 * @param string $search
338 * @param string $style
339 * @return string
340 */
341function add_style( $string, $search, $style )
342{
343  //return $string;
344  $return_string = '';
345  $remaining = $string;
346
347  $start = 0;
348  $end = 0;
349  $start = strpos ( $remaining, '<' );
350  $end   = strpos ( $remaining, '>' );
351  while ( is_numeric( $start ) and is_numeric( $end ) )
352  {
353    $treatment = substr ( $remaining, 0, $start );
354    $treatment = preg_replace( '/('.$search.')/i',
355                               '<span style="'.$style.'">\\0</span>',
356                               $treatment );
357    $return_string.= $treatment.substr( $remaining, $start, $end-$start+1 );
358    $remaining = substr ( $remaining, $end + 1, strlen( $remaining ) );
359    $start = strpos ( $remaining, '<' );
360    $end   = strpos ( $remaining, '>' );
361  }
362  $treatment = preg_replace( '/('.$search.')/i',
363                             '<span style="'.$style.'">\\0</span>',
364                             $remaining );
365  $return_string.= $treatment;
366
367  return $return_string;
368}
369
370// replace_search replaces a searched words array string by the search in
371// another style for the given $string.
372function replace_search( $string, $search )
373{
374  // FIXME : with new advanced search, this function needs a rewrite
375  return $string;
376
377  $words = explode( ',', $search );
378  $style = 'background-color:white;color:red;';
379  foreach ( $words as $word ) {
380    $string = add_style( $string, $word, $style );
381  }
382  return $string;
383}
384
385function pwg_log( $file, $category, $picture = '' )
386{
387  global $conf, $user;
388
389  if ( is_admin() )
390  {
391    $doit=$conf['history_admin'];
392  }
393  elseif ( $user['is_the_guest'] )
394  {
395    $doit=$conf['history_guest'];
396  }
397  else
398  {
399    $doit = $conf['log'];
400  }
401
402  if ($doit)
403  {
404    $login = ($user['id'] == $conf['guest_id'])
405      ? 'guest' : addslashes($user['username']);
406    insert_into_history($login, $file, $category, $picture);
407  }
408}
409
410function pwg_log_login( $username )
411{
412  global $conf;
413  if ( $conf['login_history'] )
414  {
415    insert_into_history($username, 'login', '', '');
416  }
417}
418
419// inserts a row in the history table
420function insert_into_history( $login, $file, $category, $picture)
421{
422  $query = '
423INSERT INTO '.HISTORY_TABLE.'
424  (date,login,IP,file,category,picture)
425  VALUES
426  (NOW(),
427  \''.$login.'\',
428  \''.$_SERVER['REMOTE_ADDR'].'\',
429  \''.addslashes($file).'\',
430  \''.addslashes(strip_tags($category)).'\',
431  \''.addslashes($picture).'\')
432;';
433  pwg_query($query);
434}
435
436// format_date returns a formatted date for display. The date given in
437// argument can be a unixdate (number of seconds since the 01.01.1970) or an
438// american format (2003-09-15). By option, you can show the time. The
439// output is internationalized.
440//
441// format_date( "2003-09-15", 'us', true ) -> "Monday 15 September 2003 21:52"
442function format_date($date, $type = 'us', $show_time = false)
443{
444  global $lang;
445
446  list($year,$month,$day,$hour,$minute,$second) = array(0,0,0,0,0,0);
447
448  switch ( $type )
449  {
450    case 'us' :
451    {
452      list($year,$month,$day) = explode('-', $date);
453      break;
454    }
455    case 'unix' :
456    {
457      list($year,$month,$day,$hour,$minute) =
458        explode('.', date('Y.n.j.G.i', $date));
459      break;
460    }
461    case 'mysql_datetime' :
462    {
463      preg_match('/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/',
464                 $date, $out);
465      list($year,$month,$day,$hour,$minute,$second) =
466        array($out[1],$out[2],$out[3],$out[4],$out[5],$out[6]);
467      break;
468    }
469  }
470  $formated_date = '';
471  // before 1970, Microsoft Windows can't mktime
472  if ($year >= 1970)
473  {
474    // we ask midday because Windows think it's prior to midnight with a
475    // zero and refuse to work
476    $formated_date.= $lang['day'][date('w', mktime(12,0,0,$month,$day,$year))];
477  }
478  $formated_date.= ' '.$day;
479  $formated_date.= ' '.$lang['month'][(int)$month];
480  $formated_date.= ' '.$year;
481  if ($show_time)
482  {
483    $formated_date.= ' '.$hour.':'.$minute;
484  }
485
486  return $formated_date;
487}
488
489function pwg_stripslashes($value)
490{
491  if (get_magic_quotes_gpc())
492  {
493    $value = stripslashes($value);
494  }
495  return $value;
496}
497
498function pwg_addslashes($value)
499{
500  if (!get_magic_quotes_gpc())
501  {
502    $value = addslashes($value);
503  }
504  return $value;
505}
506
507function pwg_quotemeta($value)
508{
509  if (get_magic_quotes_gpc()) {
510    $value = stripslashes($value);
511  }
512  if (function_exists('mysql_real_escape_string'))
513  {
514    $value = mysql_real_escape_string($value);
515  }
516  else
517  {
518    $value = mysql_escape_string($value);
519  }
520  return $value;
521}
522
523function pwg_query($query)
524{
525  global $conf,$page,$debug,$t2;
526
527  $start = get_moment();
528  $result = mysql_query($query) or my_error($query."\n");
529
530  $time = get_moment() - $start;
531
532  if (!isset($page['count_queries']))
533  {
534    $page['count_queries'] = 0;
535    $page['queries_time'] = 0;
536  }
537
538  $page['count_queries']++;
539  $page['queries_time']+= $time;
540
541  if ($conf['show_queries'])
542  {
543    $output = '';
544    $output.= '<pre>['.$page['count_queries'].'] ';
545    $output.= "\n".$query;
546    $output.= "\n".'(this query time : ';
547    $output.= '<b>'.number_format($time, 3, '.', ' ').' s)</b>';
548    $output.= "\n".'(total SQL time  : ';
549    $output.= number_format($page['queries_time'], 3, '.', ' ').' s)';
550    $output.= "\n".'(total time      : ';
551    $output.= number_format( ($time+$start-$t2), 3, '.', ' ').' s)';
552    $output.= "</pre>\n";
553
554    $debug .= $output;
555  }
556
557  return $result;
558}
559
560function pwg_debug( $string )
561{
562  global $debug,$t2,$page;
563
564  $now = explode( ' ', microtime() );
565  $now2 = explode( '.', $now[0] );
566  $now2 = $now[1].'.'.$now2[1];
567  $time = number_format( $now2 - $t2, 3, '.', ' ').' s';
568  $debug .= '<p>';
569  $debug.= '['.$time.', ';
570  $debug.= $page['count_queries'].' queries] : '.$string;
571  $debug.= "</p>\n";
572}
573
574/**
575 * Redirects to the given URL
576 *
577 * Note : once this function called, the execution doesn't go further
578 * (presence of an exit() instruction.
579 *
580 * @param string $url
581 * @param string $title_msg
582 * @param integer $refreh_time
583 * @return void
584 */
585function redirect( $url , $msg = '', $refresh_time = 0)
586{
587  global $user, $template, $lang_info, $conf, $lang, $t2, $page, $debug;
588
589  if (!isset($lang_info))
590  {
591    $user = build_user( $conf['guest_id'], true);
592    include_once(get_language_filepath('common.lang.php'));
593    list($tmpl, $thm) = explode('/', $conf['default_template']);
594    $template = new Template(PHPWG_ROOT_PATH.'template/'.$tmpl, $thm);
595  }
596  else
597  {
598    $template = new Template(PHPWG_ROOT_PATH.'template/'.$user['template'], $user['theme']);
599  }
600
601  if (empty($msg))
602  {
603    $redirect_msg = l10n('redirect_msg');
604  }
605  else
606  {
607    $redirect_msg = $msg;
608  }
609  $redirect_msg = nl2br($redirect_msg);
610
611  $refresh = $refresh_time;
612  $url_link = $url;
613  $title = 'redirection';
614
615  $template->set_filenames( array( 'redirect' => 'redirect.tpl' ) );
616
617  include( PHPWG_ROOT_PATH.'include/page_header.php' );
618
619  $template->set_filenames( array( 'redirect' => 'redirect.tpl' ) );
620  $template->parse('redirect');
621
622  include( PHPWG_ROOT_PATH.'include/page_tail.php' );
623
624  exit();
625}
626
627/**
628 * returns $_SERVER['QUERY_STRING'] whitout keys given in parameters
629 *
630 * @param array $rejects
631 * @returns string
632 */
633function get_query_string_diff($rejects = array())
634{
635  $query_string = '';
636
637  $str = $_SERVER['QUERY_STRING'];
638  parse_str($str, $vars);
639
640  $is_first = true;
641  foreach ($vars as $key => $value)
642  {
643    if (!in_array($key, $rejects))
644    {
645      $query_string.= $is_first ? '?' : '&amp;';
646      $is_first = false;
647      $query_string.= $key.'='.$value;
648    }
649  }
650
651  return $query_string;
652}
653
654function url_is_remote($url)
655{
656  if (preg_match('/^https?:\/\/[~\/\.\w-]+$/', $url))
657  {
658    return true;
659  }
660  return false;
661}
662
663/**
664 * returns available template/theme
665 */
666function get_pwg_themes()
667{
668  $themes = array();
669
670  $template_dir = PHPWG_ROOT_PATH.'template';
671
672  foreach (get_dirs($template_dir) as $template)
673  {
674    foreach (get_dirs($template_dir.'/'.$template.'/theme') as $theme)
675    {
676      array_push($themes, $template.'/'.$theme);
677    }
678  }
679
680  return $themes;
681}
682
683/**
684 * returns thumbnail filepath (or distant URL if thumbnail is remote) for a
685 * given element
686 *
687 * the returned string can represente the filepath of the thumbnail or the
688 * filepath to the corresponding icon for non picture elements
689 *
690 * @param string path
691 * @param string tn_ext
692 * @param bool with_rewrite if true returned path can't be used from the script
693 * @return string
694 */
695function get_thumbnail_src($path, $tn_ext = '', $with_rewrite = true)
696{
697  global $conf, $user;
698
699  if ($tn_ext != '')
700  {
701    $src = substr_replace(
702      get_filename_wo_extension($path),
703      '/thumbnail/'.$conf['prefix_thumbnail'],
704      strrpos($path,'/'),
705      1
706      );
707    $src.= '.'.$tn_ext;
708    if ($with_rewrite==true and !url_is_remote($src) )
709    {
710      $src = get_root_url().$src;
711    }
712  }
713  else
714  {
715    $src = ($with_rewrite==true) ? get_root_url() : '';
716    $src .= get_themeconf('mime_icon_dir');
717    $src.= strtolower(get_extension($path)).'.png';
718  }
719
720  return $src;
721}
722
723// my_error returns (or send to standard output) the message concerning the
724// error occured for the last mysql query.
725function my_error($header)
726{
727  global $conf;
728
729  $error = '<pre>';
730  $error.= $header;
731  $error.= '[mysql error '.mysql_errno().'] ';
732  $error.= mysql_error();
733  $error.= '</pre>';
734
735  if ($conf['die_on_sql_error'])
736  {
737    die($error);
738  }
739  else
740  {
741    echo $error;
742  }
743}
744
745/**
746 * creates an array based on a query, this function is a very common pattern
747 * used here
748 *
749 * @param string $query
750 * @param string $fieldname
751 * @return array
752 */
753function array_from_query($query, $fieldname)
754{
755  $array = array();
756
757  $result = pwg_query($query);
758  while ($row = mysql_fetch_array($result))
759  {
760    array_push($array, $row[$fieldname]);
761  }
762
763  return $array;
764}
765
766/**
767 * instantiate number list for days in a template block
768 *
769 * @param string blockname
770 * @param string selection
771 */
772function get_day_list($blockname, $selection)
773{
774  global $template;
775
776  $template->assign_block_vars(
777    $blockname, array('SELECTED' => '', 'VALUE' => 0, 'OPTION' => '--'));
778
779  for ($i = 1; $i <= 31; $i++)
780  {
781    $selected = '';
782    if ($i == (int)$selection)
783    {
784      $selected = 'selected="selected"';
785    }
786    $template->assign_block_vars(
787      $blockname, array('SELECTED' => $selected,
788                        'VALUE' => $i,
789                        'OPTION' => str_pad($i, 2, '0', STR_PAD_LEFT)));
790  }
791}
792
793/**
794 * instantiate month list in a template block
795 *
796 * @param string blockname
797 * @param string selection
798 */
799function get_month_list($blockname, $selection)
800{
801  global $template, $lang;
802
803  $template->assign_block_vars(
804    $blockname, array('SELECTED' => '',
805                      'VALUE' => 0,
806                      'OPTION' => '------------'));
807
808  for ($i = 1; $i <= 12; $i++)
809  {
810    $selected = '';
811    if ($i == (int)$selection)
812    {
813      $selected = 'selected="selected"';
814    }
815    $template->assign_block_vars(
816      $blockname, array('SELECTED' => $selected,
817                        'VALUE' => $i,
818                        'OPTION' => $lang['month'][$i]));
819  }
820}
821
822/**
823 * fill the current user caddie with given elements, if not already in
824 * caddie
825 *
826 * @param array elements_id
827 */
828function fill_caddie($elements_id)
829{
830  global $user;
831
832  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
833
834  $query = '
835SELECT element_id
836  FROM '.CADDIE_TABLE.'
837  WHERE user_id = '.$user['id'].'
838;';
839  $in_caddie = array_from_query($query, 'element_id');
840
841  $caddiables = array_diff($elements_id, $in_caddie);
842
843  $datas = array();
844
845  foreach ($caddiables as $caddiable)
846  {
847    array_push($datas, array('element_id' => $caddiable,
848                             'user_id' => $user['id']));
849  }
850
851  if (count($caddiables) > 0)
852  {
853    mass_inserts(CADDIE_TABLE, array('element_id','user_id'), $datas);
854  }
855}
856
857/**
858 * returns the element name from its filename
859 *
860 * @param string filename
861 * @return string name
862 */
863function get_name_from_file($filename)
864{
865  return str_replace('_',' ',get_filename_wo_extension($filename));
866}
867
868/**
869 * returns the corresponding value from $lang if existing. Else, the key is
870 * returned
871 *
872 * @param string key
873 * @return string
874 */
875function l10n($key)
876{
877  global $lang, $conf;
878
879  if ($conf['debug_l10n'] and !isset($lang[$key]))
880  {
881    echo '[l10n] language key "'.$key.'" is not defined<br />';
882  }
883
884  return isset($lang[$key]) ? $lang[$key] : $key;
885}
886
887/**
888 * Translate string in string ascii7bits
889 * It's possible to do that with iconv_substr
890 * but this fonction is not avaible on all the providers.
891 *
892 * @param string str
893 * @return string
894 */
895function str_translate_to_ascii7bits($str)
896{
897  global $lang_table_translate_ascii7bits;
898
899  $src_table = array_keys($lang_table_translate_ascii7bits);
900  $dst_table = array_values($lang_table_translate_ascii7bits);
901
902  return str_replace($src_table , $dst_table, $str);
903}
904
905/**
906 * returns the corresponding value from $themeconf if existing. Else, the
907 * key is returned
908 *
909 * @param string key
910 * @return string
911 */
912function get_themeconf($key)
913{
914  global $template;
915
916  return $template->get_themeconf($key);
917}
918
919/**
920 * Returns webmaster mail address depending on $conf['webmaster_id']
921 *
922 * @return string
923 */
924function get_webmaster_mail_address()
925{
926  global $conf;
927
928  $query = '
929SELECT '.$conf['user_fields']['email'].'
930  FROM '.USERS_TABLE.'
931  WHERE '.$conf['user_fields']['id'].' = '.$conf['webmaster_id'].'
932;';
933  list($email) = mysql_fetch_array(pwg_query($query));
934
935  return $email;
936}
937
938/**
939 * which upgrades are available ?
940 *
941 * @return array
942 */
943function get_available_upgrade_ids()
944{
945  $upgrades_path = PHPWG_ROOT_PATH.'install/db';
946
947  $available_upgrade_ids = array();
948
949  if ($contents = opendir($upgrades_path))
950  {
951    while (($node = readdir($contents)) !== false)
952    {
953      if (is_file($upgrades_path.'/'.$node)
954          and preg_match('/^(.*?)-database\.php$/', $node, $match))
955      {
956        array_push($available_upgrade_ids, $match[1]);
957      }
958    }
959  }
960  natcasesort($available_upgrade_ids);
961
962  return $available_upgrade_ids;
963}
964
965/**
966 * Add configuration parameters from database to global $conf array
967 *
968 * @return void
969 */
970function load_conf_from_db()
971{
972  global $conf;
973
974  $query = '
975SELECT param,value
976 FROM '.CONFIG_TABLE.'
977;';
978  $result = pwg_query($query);
979
980  if (mysql_num_rows($result) == 0)
981  {
982    die('No configuration data');
983  }
984
985  while ($row = mysql_fetch_array($result))
986  {
987    $conf[ $row['param'] ] = isset($row['value']) ? $row['value'] : '';
988
989    // If the field is true or false, the variable is transformed into a
990    // boolean value.
991    if ($conf[$row['param']] == 'true' or $conf[$row['param']] == 'false')
992    {
993      $conf[ $row['param'] ] = get_boolean($conf[ $row['param'] ]);
994    }
995  }
996}
997?>
Note: See TracBrowser for help on using the repository browser.