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

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

Feature Issue ID 0000602: Redirect must be done by html or http

Redirect it's only done by the html method but must be done too with http method.
Creation of two functions redirect_http and redirect_html.
Function redirect calls one or other functions follow $conf or parameters.

$conf value are true on BSF, in order to check modifications.
Must be set to false on RC.

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