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

Last change on this file since 1596 was 1596, checked in by rvelices, 17 years ago
  • deprecated get_thumbnail_src (still there for compatibility). use rather

get_thumbnail_path or get_thumbnail_url (these allow plugins to override)

  • plugins can hook into index thumbnail display (items only so far)
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 26.1 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 1596 2006-11-07 03:37:57Z rvelices $
9// | last update   : $Date: 2006-11-07 03:37:57 +0000 (Tue, 07 Nov 2006) $
10// | last modifier : $Author: rvelices $
11// | revision      : $Revision: 1596 $
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/**
684DEPRECATED use get_thumbnail_path or get_thumbnail_url
685 */
686function get_thumbnail_src($path, $tn_ext = '', $with_rewrite = true)
687{
688  if ($with_rewrite)
689    return get_thumbnail_url( array('path'=>$path, 'tn_ext'=>$tn_ext) );
690  else
691    return get_thumbnail_path( array('path'=>$path, 'tn_ext'=>$tn_ext) );
692}
693
694/* Returns the PATH to the thumbnail to be displayed. If the element does not
695 * have a thumbnail, the default mime image path is returned. The PATH can be
696 * used in the php script, but not sent to the browser.
697 * @param array element_info assoc array containing element info from db
698 * at least 'path', 'tn_ext' and 'id' should be present
699 */
700function get_thumbnail_path($element_info)
701{
702  $path = get_thumbnail_location($element_info);
703  if ( !url_is_remote($path) )
704  {
705    $path = PHPWG_ROOT_PATH.$path;
706  }
707  return $path;
708}
709
710/* Returns the URL of the thumbnail to be displayed. If the element does not
711 * have a thumbnail, the default mime image url is returned. The URL can be
712 * sent to the browser, but not used in the php script.
713 * @param array element_info assoc array containing element info from db
714 * at least 'path', 'tn_ext' and 'id' should be present
715 */
716function get_thumbnail_url($element_info)
717{
718  $path = get_thumbnail_location($element_info);
719  if ( !url_is_remote($path) )
720  {
721    $path = get_root_url().$path;
722  }
723  // plugins want another url ?
724  $path = trigger_event('get_thumbnail_url', $path, $element_info);
725  return $path;
726}
727
728/* returns the relative path of the thumnail with regards to to the root
729of phpwebgallery (not the current page!).This function is not intended to be
730called directly from code.*/
731function get_thumbnail_location($element_info)
732{
733  global $conf;
734  if ( !empty( $element_info['tn_ext'] ) )
735  {
736    $path = substr_replace(
737      get_filename_wo_extension($element_info['path']),
738      '/thumbnail/'.$conf['prefix_thumbnail'],
739      strrpos($element_info['path'],'/'),
740      1
741      );
742    $path.= '.'.$element_info['tn_ext'];
743  }
744  else
745  {
746    $path = get_themeconf('mime_icon_dir')
747        .strtolower(get_extension($element_info['path'])).'.png';
748  }
749
750  // plugins want another location ?
751  $path = trigger_event( 'get_thumbnail_location', $path, $element_info);
752  return $path;
753}
754
755
756// my_error returns (or send to standard output) the message concerning the
757// error occured for the last mysql query.
758function my_error($header)
759{
760  global $conf;
761
762  $error = '<pre>';
763  $error.= $header;
764  $error.= '[mysql error '.mysql_errno().'] ';
765  $error.= mysql_error();
766  $error.= '</pre>';
767
768  if ($conf['die_on_sql_error'])
769  {
770    die($error);
771  }
772  else
773  {
774    echo $error;
775  }
776}
777
778/**
779 * creates an array based on a query, this function is a very common pattern
780 * used here
781 *
782 * @param string $query
783 * @param string $fieldname
784 * @return array
785 */
786function array_from_query($query, $fieldname)
787{
788  $array = array();
789
790  $result = pwg_query($query);
791  while ($row = mysql_fetch_array($result))
792  {
793    array_push($array, $row[$fieldname]);
794  }
795
796  return $array;
797}
798
799/**
800 * instantiate number list for days in a template block
801 *
802 * @param string blockname
803 * @param string selection
804 */
805function get_day_list($blockname, $selection)
806{
807  global $template;
808
809  $template->assign_block_vars(
810    $blockname, array('SELECTED' => '', 'VALUE' => 0, 'OPTION' => '--'));
811
812  for ($i = 1; $i <= 31; $i++)
813  {
814    $selected = '';
815    if ($i == (int)$selection)
816    {
817      $selected = 'selected="selected"';
818    }
819    $template->assign_block_vars(
820      $blockname, array('SELECTED' => $selected,
821                        'VALUE' => $i,
822                        'OPTION' => str_pad($i, 2, '0', STR_PAD_LEFT)));
823  }
824}
825
826/**
827 * instantiate month list in a template block
828 *
829 * @param string blockname
830 * @param string selection
831 */
832function get_month_list($blockname, $selection)
833{
834  global $template, $lang;
835
836  $template->assign_block_vars(
837    $blockname, array('SELECTED' => '',
838                      'VALUE' => 0,
839                      'OPTION' => '------------'));
840
841  for ($i = 1; $i <= 12; $i++)
842  {
843    $selected = '';
844    if ($i == (int)$selection)
845    {
846      $selected = 'selected="selected"';
847    }
848    $template->assign_block_vars(
849      $blockname, array('SELECTED' => $selected,
850                        'VALUE' => $i,
851                        'OPTION' => $lang['month'][$i]));
852  }
853}
854
855/**
856 * fill the current user caddie with given elements, if not already in
857 * caddie
858 *
859 * @param array elements_id
860 */
861function fill_caddie($elements_id)
862{
863  global $user;
864
865  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
866
867  $query = '
868SELECT element_id
869  FROM '.CADDIE_TABLE.'
870  WHERE user_id = '.$user['id'].'
871;';
872  $in_caddie = array_from_query($query, 'element_id');
873
874  $caddiables = array_diff($elements_id, $in_caddie);
875
876  $datas = array();
877
878  foreach ($caddiables as $caddiable)
879  {
880    array_push($datas, array('element_id' => $caddiable,
881                             'user_id' => $user['id']));
882  }
883
884  if (count($caddiables) > 0)
885  {
886    mass_inserts(CADDIE_TABLE, array('element_id','user_id'), $datas);
887  }
888}
889
890/**
891 * returns the element name from its filename
892 *
893 * @param string filename
894 * @return string name
895 */
896function get_name_from_file($filename)
897{
898  return str_replace('_',' ',get_filename_wo_extension($filename));
899}
900
901/**
902 * returns the corresponding value from $lang if existing. Else, the key is
903 * returned
904 *
905 * @param string key
906 * @return string
907 */
908function l10n($key)
909{
910  global $lang, $conf;
911
912  if ($conf['debug_l10n'] and !isset($lang[$key]))
913  {
914    echo '[l10n] language key "'.$key.'" is not defined<br />';
915  }
916
917  return isset($lang[$key]) ? $lang[$key] : $key;
918}
919
920/**
921 * Translate string in string ascii7bits
922 * It's possible to do that with iconv_substr
923 * but this fonction is not avaible on all the providers.
924 *
925 * @param string str
926 * @return string
927 */
928function str_translate_to_ascii7bits($str)
929{
930  global $lang_table_translate_ascii7bits;
931
932  $src_table = array_keys($lang_table_translate_ascii7bits);
933  $dst_table = array_values($lang_table_translate_ascii7bits);
934
935  return str_replace($src_table , $dst_table, $str);
936}
937
938/**
939 * returns the corresponding value from $themeconf if existing. Else, the
940 * key is returned
941 *
942 * @param string key
943 * @return string
944 */
945function get_themeconf($key)
946{
947  global $template;
948
949  return $template->get_themeconf($key);
950}
951
952/**
953 * Returns webmaster mail address depending on $conf['webmaster_id']
954 *
955 * @return string
956 */
957function get_webmaster_mail_address()
958{
959  global $conf;
960
961  $query = '
962SELECT '.$conf['user_fields']['email'].'
963  FROM '.USERS_TABLE.'
964  WHERE '.$conf['user_fields']['id'].' = '.$conf['webmaster_id'].'
965;';
966  list($email) = mysql_fetch_array(pwg_query($query));
967
968  return $email;
969}
970
971/**
972 * which upgrades are available ?
973 *
974 * @return array
975 */
976function get_available_upgrade_ids()
977{
978  $upgrades_path = PHPWG_ROOT_PATH.'install/db';
979
980  $available_upgrade_ids = array();
981
982  if ($contents = opendir($upgrades_path))
983  {
984    while (($node = readdir($contents)) !== false)
985    {
986      if (is_file($upgrades_path.'/'.$node)
987          and preg_match('/^(.*?)-database\.php$/', $node, $match))
988      {
989        array_push($available_upgrade_ids, $match[1]);
990      }
991    }
992  }
993  natcasesort($available_upgrade_ids);
994
995  return $available_upgrade_ids;
996}
997
998/**
999 * Add configuration parameters from database to global $conf array
1000 *
1001 * @return void
1002 */
1003function load_conf_from_db()
1004{
1005  global $conf;
1006
1007  $query = '
1008SELECT param,value
1009 FROM '.CONFIG_TABLE.'
1010;';
1011  $result = pwg_query($query);
1012
1013  if (mysql_num_rows($result) == 0)
1014  {
1015    die('No configuration data');
1016  }
1017
1018  while ($row = mysql_fetch_array($result))
1019  {
1020    $conf[ $row['param'] ] = isset($row['value']) ? $row['value'] : '';
1021
1022    // If the field is true or false, the variable is transformed into a
1023    // boolean value.
1024    if ($conf[$row['param']] == 'true' or $conf[$row['param']] == 'false')
1025    {
1026      $conf[ $row['param'] ] = get_boolean($conf[ $row['param'] ]);
1027    }
1028  }
1029}
1030?>
Note: See TracBrowser for help on using the repository browser.