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

Last change on this file since 1844 was 1844, checked in by plg, 17 years ago

New: non picture files are now logged in history when downloaded. The
history filter was redesigned: #history.is_high replaced by
#history.image_type = high. The filter is simpler.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 30.3 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-2007 PhpWebGallery Team - http://phpwebgallery.net |
6// +-----------------------------------------------------------------------+
7// | branch        : BSF (Best So Far)
8// | file          : $Id: functions.inc.php 1844 2007-02-20 23:40:02Z plg $
9// | last update   : $Date: 2007-02-20 23:40:02 +0000 (Tue, 20 Feb 2007) $
10// | last modifier : $Author: plg $
11// | revision      : $Revision: 1844 $
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($image_id = null, $image_type = null)
414{
415  global $conf, $user, $page;
416
417  if (!$conf['log'])
418  {
419    return false;
420  }
421
422  if (is_admin() and !$conf['history_admin'])
423  {
424    return false;
425  }
426
427  if ($user['is_the_guest'] and !$conf['history_guest'])
428  {
429    return false;
430  }
431
432  $tags_string = null;
433  if (isset($page['section']) and $page['section'] == 'tags')
434  {
435    $tag_ids = array();
436    foreach ($page['tags'] as $tag)
437    {
438      array_push($tag_ids, $tag['id']);
439    }
440
441    $tags_string = implode(',', $tag_ids);
442  }
443
444  // here we ask the database the current date and time, and we extract
445  // {year, month, day} from the current date. We could do this during the
446  // insert query with a CURDATE(), CURTIME(), DATE_FORMAT(CURDATE(), '%Y')
447  // ... but I (plg) think it would cost more than a double query and a PHP
448  // extraction.
449  $query = '
450SELECT CURDATE(), CURTIME()
451;';
452  list($curdate, $curtime) = mysql_fetch_row(pwg_query($query));
453
454  list($curyear, $curmonth, $curday) = explode('-', $curdate);
455  list($curhour) = explode(':', $curtime);
456 
457  $query = '
458INSERT INTO '.HISTORY_TABLE.'
459  (
460    date,
461    time,
462    year,
463    month,
464    day,
465    hour,
466    user_id,
467    IP,
468    section,
469    category_id,
470    image_id,
471    image_type,
472    tag_ids
473  )
474  VALUES
475  (
476    \''.$curdate.'\',
477    \''.$curtime.'\',
478    '.$curyear.',
479    '.$curmonth.',
480    '.$curday.',
481    '.$curhour.',
482    '.$user['id'].',
483    \''.$_SERVER['REMOTE_ADDR'].'\',
484    '.(isset($page['section']) ? "'".$page['section']."'" : 'NULL').',
485    '.(isset($page['category']) ? $page['category'] : 'NULL').',
486    '.(isset($image_id) ? $image_id : 'NULL').',
487    '.(isset($image_id) ? "'".$image_type."'" : 'NULL').',
488    '.(isset($tags_string) ? "'".$tags_string."'" : 'NULL').'
489  )
490;';
491  pwg_query($query);
492
493  return true;
494}
495
496// format_date returns a formatted date for display. The date given in
497// argument can be a unixdate (number of seconds since the 01.01.1970) or an
498// american format (2003-09-15). By option, you can show the time. The
499// output is internationalized.
500//
501// format_date( "2003-09-15", 'us', true ) -> "Monday 15 September 2003 21:52"
502function format_date($date, $type = 'us', $show_time = false)
503{
504  global $lang;
505
506  list($year,$month,$day,$hour,$minute,$second) = array(0,0,0,0,0,0);
507
508  switch ( $type )
509  {
510    case 'us' :
511    {
512      list($year,$month,$day) = explode('-', $date);
513      break;
514    }
515    case 'unix' :
516    {
517      list($year,$month,$day,$hour,$minute) =
518        explode('.', date('Y.n.j.G.i', $date));
519      break;
520    }
521    case 'mysql_datetime' :
522    {
523      preg_match('/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/',
524                 $date, $out);
525      list($year,$month,$day,$hour,$minute,$second) =
526        array($out[1],$out[2],$out[3],$out[4],$out[5],$out[6]);
527      break;
528    }
529  }
530  $formated_date = '';
531  // before 1970, Microsoft Windows can't mktime
532  if ($year >= 1970)
533  {
534    // we ask midday because Windows think it's prior to midnight with a
535    // zero and refuse to work
536    $formated_date.= $lang['day'][date('w', mktime(12,0,0,$month,$day,$year))];
537  }
538  $formated_date.= ' '.$day;
539  $formated_date.= ' '.$lang['month'][(int)$month];
540  $formated_date.= ' '.$year;
541  if ($show_time)
542  {
543    $formated_date.= ' '.$hour.':'.$minute;
544  }
545
546  return $formated_date;
547}
548
549function pwg_query($query)
550{
551  global $conf,$page,$debug,$t2;
552
553  $start = get_moment();
554  $result = mysql_query($query) or my_error($query."\n");
555
556  $time = get_moment() - $start;
557
558  if (!isset($page['count_queries']))
559  {
560    $page['count_queries'] = 0;
561    $page['queries_time'] = 0;
562  }
563
564  $page['count_queries']++;
565  $page['queries_time']+= $time;
566
567  if ($conf['show_queries'])
568  {
569    $output = '';
570    $output.= '<pre>['.$page['count_queries'].'] ';
571    $output.= "\n".$query;
572    $output.= "\n".'(this query time : ';
573    $output.= '<b>'.number_format($time, 3, '.', ' ').' s)</b>';
574    $output.= "\n".'(total SQL time  : ';
575    $output.= number_format($page['queries_time'], 3, '.', ' ').' s)';
576    $output.= "\n".'(total time      : ';
577    $output.= number_format( ($time+$start-$t2), 3, '.', ' ').' s)';
578    $output.= "</pre>\n";
579
580    $debug .= $output;
581  }
582
583  return $result;
584}
585
586function pwg_debug( $string )
587{
588  global $debug,$t2,$page;
589
590  $now = explode( ' ', microtime() );
591  $now2 = explode( '.', $now[0] );
592  $now2 = $now[1].'.'.$now2[1];
593  $time = number_format( $now2 - $t2, 3, '.', ' ').' s';
594  $debug .= '<p>';
595  $debug.= '['.$time.', ';
596  $debug.= $page['count_queries'].' queries] : '.$string;
597  $debug.= "</p>\n";
598}
599
600/**
601 * Redirects to the given URL (HTTP method)
602 *
603 * Note : once this function called, the execution doesn't go further
604 * (presence of an exit() instruction.
605 *
606 * @param string $url
607 * @return void
608 */
609function redirect_http( $url )
610{
611  if (ob_get_length () !== FALSE)
612  {
613    ob_clean();
614  }
615  header('Request-URI: '.$url);
616  header('Content-Location: '.$url);
617  header('Location: '.$url);
618  exit();
619}
620
621/**
622 * Redirects to the given URL (HTML method)
623 *
624 * Note : once this function called, the execution doesn't go further
625 * (presence of an exit() instruction.
626 *
627 * @param string $url
628 * @param string $title_msg
629 * @param integer $refreh_time
630 * @return void
631 */
632function redirect_html( $url , $msg = '', $refresh_time = 0)
633{
634  global $user, $template, $lang_info, $conf, $lang, $t2, $page, $debug;
635
636  if (!isset($lang_info))
637  {
638    $user = build_user( $conf['guest_id'], true);
639    include_once(get_language_filepath('common.lang.php'));
640    trigger_action('loading_lang');
641    @include_once(get_language_filepath('local.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 ( strncmp($url, 'http://', 7)==0
732    or strncmp($url, 'https://', 8)==0 )
733  {
734    return true;
735  }
736  return false;
737}
738
739/**
740 * returns available template/theme
741 */
742function get_pwg_themes()
743{
744  $themes = array();
745
746  $template_dir = PHPWG_ROOT_PATH.'template';
747
748  foreach (get_dirs($template_dir) as $template)
749  {
750    foreach (get_dirs($template_dir.'/'.$template.'/theme') as $theme)
751    {
752      array_push($themes, $template.'/'.$theme);
753    }
754  }
755
756  return $themes;
757}
758
759/* Returns the PATH to the thumbnail to be displayed. If the element does not
760 * have a thumbnail, the default mime image path is returned. The PATH can be
761 * used in the php script, but not sent to the browser.
762 * @param array element_info assoc array containing element info from db
763 * at least 'path', 'tn_ext' and 'id' should be present
764 */
765function get_thumbnail_path($element_info)
766{
767  $path = get_thumbnail_location($element_info);
768  if ( !url_is_remote($path) )
769  {
770    $path = PHPWG_ROOT_PATH.$path;
771  }
772  return $path;
773}
774
775/* Returns the URL of the thumbnail to be displayed. If the element does not
776 * have a thumbnail, the default mime image url is returned. The URL can be
777 * sent to the browser, but not used in the php script.
778 * @param array element_info assoc array containing element info from db
779 * at least 'path', 'tn_ext' and 'id' should be present
780 */
781function get_thumbnail_url($element_info)
782{
783  $path = get_thumbnail_location($element_info);
784  if ( !url_is_remote($path) )
785  {
786    $path = get_root_url().$path;
787  }
788  // plugins want another url ?
789  $path = trigger_event('get_thumbnail_url', $path, $element_info);
790  return $path;
791}
792
793/* returns the relative path of the thumnail with regards to to the root
794of phpwebgallery (not the current page!).This function is not intended to be
795called directly from code.*/
796function get_thumbnail_location($element_info)
797{
798  global $conf;
799  if ( !empty( $element_info['tn_ext'] ) )
800  {
801    $path = substr_replace(
802      get_filename_wo_extension($element_info['path']),
803      '/thumbnail/'.$conf['prefix_thumbnail'],
804      strrpos($element_info['path'],'/'),
805      1
806      );
807    $path.= '.'.$element_info['tn_ext'];
808  }
809  else
810  {
811    $path = get_themeconf('mime_icon_dir')
812        .strtolower(get_extension($element_info['path'])).'.png';
813  }
814
815  // plugins want another location ?
816  $path = trigger_event( 'get_thumbnail_location', $path, $element_info);
817  return $path;
818}
819
820
821// my_error returns (or send to standard output) the message concerning the
822// error occured for the last mysql query.
823function my_error($header)
824{
825  global $conf;
826
827  $error = '<pre>';
828  $error.= $header;
829  $error.= '[mysql error '.mysql_errno().'] ';
830  $error.= mysql_error();
831  $error.= '</pre>';
832
833  if ($conf['die_on_sql_error'])
834  {
835    die($error);
836  }
837  else
838  {
839    echo $error;
840  }
841}
842
843/**
844 * creates an array based on a query, this function is a very common pattern
845 * used here
846 *
847 * @param string $query
848 * @param string $fieldname
849 * @return array
850 */
851function array_from_query($query, $fieldname)
852{
853  $array = array();
854
855  $result = pwg_query($query);
856  while ($row = mysql_fetch_array($result))
857  {
858    array_push($array, $row[$fieldname]);
859  }
860
861  return $array;
862}
863
864/**
865 * instantiate number list for days in a template block
866 *
867 * @param string blockname
868 * @param string selection
869 */
870function get_day_list($blockname, $selection)
871{
872  global $template;
873
874  $template->assign_block_vars(
875    $blockname,
876    array(
877      'SELECTED' => '',
878      'VALUE' => 0,
879      'OPTION' => '--'
880      )
881    );
882
883  for ($i = 1; $i <= 31; $i++)
884  {
885    $selected = '';
886    if ($i == (int)$selection)
887    {
888      $selected = 'selected="selected"';
889    }
890    $template->assign_block_vars(
891      $blockname,
892      array(
893        'SELECTED' => $selected,
894        'VALUE' => $i,
895        'OPTION' => str_pad($i, 2, '0', STR_PAD_LEFT)
896        )
897      );
898  }
899}
900
901/**
902 * instantiate month list in a template block
903 *
904 * @param string blockname
905 * @param string selection
906 */
907function get_month_list($blockname, $selection)
908{
909  global $template, $lang;
910
911  $template->assign_block_vars(
912    $blockname,
913    array(
914      'SELECTED' => '',
915      'VALUE' => 0,
916      'OPTION' => '------------')
917    );
918
919  for ($i = 1; $i <= 12; $i++)
920  {
921    $selected = '';
922    if ($i == (int)$selection)
923    {
924      $selected = 'selected="selected"';
925    }
926    $template->assign_block_vars(
927      $blockname,
928      array(
929        'SELECTED' => $selected,
930        'VALUE' => $i,
931        'OPTION' => $lang['month'][$i])
932      );
933  }
934}
935
936/**
937 * fill the current user caddie with given elements, if not already in
938 * caddie
939 *
940 * @param array elements_id
941 */
942function fill_caddie($elements_id)
943{
944  global $user;
945
946  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
947
948  $query = '
949SELECT element_id
950  FROM '.CADDIE_TABLE.'
951  WHERE user_id = '.$user['id'].'
952;';
953  $in_caddie = array_from_query($query, 'element_id');
954
955  $caddiables = array_diff($elements_id, $in_caddie);
956
957  $datas = array();
958
959  foreach ($caddiables as $caddiable)
960  {
961    array_push($datas, array('element_id' => $caddiable,
962                             'user_id' => $user['id']));
963  }
964
965  if (count($caddiables) > 0)
966  {
967    mass_inserts(CADDIE_TABLE, array('element_id','user_id'), $datas);
968  }
969}
970
971/**
972 * returns the element name from its filename
973 *
974 * @param string filename
975 * @return string name
976 */
977function get_name_from_file($filename)
978{
979  return str_replace('_',' ',get_filename_wo_extension($filename));
980}
981
982/**
983 * returns the corresponding value from $lang if existing. Else, the key is
984 * returned
985 *
986 * @param string key
987 * @return string
988 */
989function l10n($key)
990{
991  global $lang, $conf;
992
993  if ($conf['debug_l10n'] and !isset($lang[$key]))
994  {
995    echo '[l10n] language key "'.$key.'" is not defined<br />';
996  }
997
998  return isset($lang[$key]) ? $lang[$key] : $key;
999}
1000
1001/**
1002 * returns the prinft value for strings including %d
1003 * return is concorded with decimal value (singular, plural)
1004 *
1005 * @param singular string key
1006 * @param plural string key
1007 * @param decimal value
1008 * @return string
1009 */
1010function l10n_dec($singular_fmt_key, $plural_fmt_key, $decimal)
1011{
1012  return sprintf(l10n(($decimal > 1 ? $plural_fmt_key :
1013                                      $singular_fmt_key)), $decimal);
1014}
1015
1016/**
1017 * Translate string in string ascii7bits
1018 * It's possible to do that with iconv_substr
1019 * but this fonction is not avaible on all the providers.
1020 *
1021 * @param string str
1022 * @return string
1023 */
1024function str_translate_to_ascii7bits($str)
1025{
1026  global $lang_table_translate_ascii7bits;
1027
1028  $src_table = array_keys($lang_table_translate_ascii7bits);
1029  $dst_table = array_values($lang_table_translate_ascii7bits);
1030
1031  return str_replace($src_table , $dst_table, $str);
1032}
1033
1034/**
1035 * returns the corresponding value from $themeconf if existing. Else, the
1036 * key is returned
1037 *
1038 * @param string key
1039 * @return string
1040 */
1041function get_themeconf($key)
1042{
1043  global $template;
1044
1045  return $template->get_themeconf($key);
1046}
1047
1048/**
1049 * Returns webmaster mail address depending on $conf['webmaster_id']
1050 *
1051 * @return string
1052 */
1053function get_webmaster_mail_address()
1054{
1055  global $conf;
1056
1057  $query = '
1058SELECT '.$conf['user_fields']['email'].'
1059  FROM '.USERS_TABLE.'
1060  WHERE '.$conf['user_fields']['id'].' = '.$conf['webmaster_id'].'
1061;';
1062  list($email) = mysql_fetch_array(pwg_query($query));
1063
1064  return $email;
1065}
1066
1067/**
1068 * which upgrades are available ?
1069 *
1070 * @return array
1071 */
1072function get_available_upgrade_ids()
1073{
1074  $upgrades_path = PHPWG_ROOT_PATH.'install/db';
1075
1076  $available_upgrade_ids = array();
1077
1078  if ($contents = opendir($upgrades_path))
1079  {
1080    while (($node = readdir($contents)) !== false)
1081    {
1082      if (is_file($upgrades_path.'/'.$node)
1083          and preg_match('/^(.*?)-database\.php$/', $node, $match))
1084      {
1085        array_push($available_upgrade_ids, $match[1]);
1086      }
1087    }
1088  }
1089  natcasesort($available_upgrade_ids);
1090
1091  return $available_upgrade_ids;
1092}
1093
1094/**
1095 * Add configuration parameters from database to global $conf array
1096 *
1097 * @return void
1098 */
1099function load_conf_from_db($condition = '')
1100{
1101  global $conf;
1102
1103  $query = '
1104SELECT param, value
1105 FROM '.CONFIG_TABLE.'
1106 '.(!empty($condition) ? 'WHERE '.$condition : '').'
1107;';
1108  $result = pwg_query($query);
1109
1110  if ((mysql_num_rows($result) == 0) and !empty($condition))
1111  {
1112    die('No configuration data');
1113  }
1114
1115  while ($row = mysql_fetch_array($result))
1116  {
1117    $conf[ $row['param'] ] = isset($row['value']) ? $row['value'] : '';
1118
1119    // If the field is true or false, the variable is transformed into a
1120    // boolean value.
1121    if ($conf[$row['param']] == 'true' or $conf[$row['param']] == 'false')
1122    {
1123      $conf[ $row['param'] ] = get_boolean($conf[ $row['param'] ]);
1124    }
1125  }
1126}
1127
1128/**
1129 * Prepends and appends a string at each value of the given array.
1130 *
1131 * @param array
1132 * @param string prefix to each array values
1133 * @param string suffix to each array values
1134 */
1135function prepend_append_array_items($array, $prepend_str, $append_str)
1136{
1137  array_walk(
1138    $array,
1139    create_function('&$s', '$s = "'.$prepend_str.'".$s."'.$append_str.'";')
1140    );
1141
1142  return $array;
1143}
1144
1145/**
1146 * creates an hashed based on a query, this function is a very common
1147 * pattern used here. Among the selected columns fetched, choose one to be
1148 * the key, another one to be the value.
1149 *
1150 * @param string $query
1151 * @param string $keyname
1152 * @param string $valuename
1153 * @return array
1154 */
1155function simple_hash_from_query($query, $keyname, $valuename)
1156{
1157  $array = array();
1158
1159  $result = pwg_query($query);
1160  while ($row = mysql_fetch_array($result))
1161  {
1162    $array[ $row[$keyname] ] = $row[$valuename];
1163  }
1164
1165  return $array;
1166}
1167
1168/**
1169 * Return basename of the current script
1170 * Lower case convertion is applied on return value
1171 * Return value is without file extention ".php"
1172 *
1173 * @param void
1174 *
1175 * @return script basename
1176 */
1177function script_basename()
1178{
1179  if (!empty($_SERVER['SCRIPT_NAME']))
1180  {
1181    $file_name = $_SERVER['SCRIPT_NAME'];
1182  }
1183  else if (!empty($_SERVER['SCRIPT_FILENAME']))
1184  {
1185    $file_name = $_SERVER['SCRIPT_FILENAME'];
1186  }
1187  else
1188  {
1189    $file_name = '';
1190  }
1191
1192  // $_SERVER return lower string following var and systems
1193  return basename(strtolower($file_name), '.php');
1194}
1195
1196/**
1197 * Return value for the current page define on $conf['filter_pages']
1198 * Îf value is not defined, default value are returned
1199 *
1200 * @param value name
1201 *
1202 * @return filter page value
1203 */
1204function get_filter_page_value($value_name)
1205{
1206  global $conf;
1207
1208  $page_name = script_basename();
1209
1210  if (isset($conf['filter_pages'][$page_name][$value_name]))
1211  {
1212    return $conf['filter_pages'][$page_name][$value_name];
1213  }
1214  else if (isset($conf['filter_pages']['default'][$value_name]))
1215  {
1216    return $conf['filter_pages']['default'][$value_name];
1217  }
1218  else
1219  {
1220    return null;
1221  }
1222}
1223
1224?>
Note: See TracBrowser for help on using the repository browser.