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

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

plugins: first prototype version

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