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

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

Remove "TODO" on picture display showed on the caddie...

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 31.2 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// | file          : $Id: functions.inc.php 1868 2007-03-04 09:36:30Z rub $
8// | last update   : $Date: 2007-03-04 09:36:30 +0000 (Sun, 04 Mar 2007) $
9// | last modifier : $Author: rub $
10// | revision      : $Revision: 1868 $
11// +-----------------------------------------------------------------------+
12// | This program is free software; you can redistribute it and/or modify  |
13// | it under the terms of the GNU General Public License as published by  |
14// | the Free Software Foundation                                          |
15// |                                                                       |
16// | This program is distributed in the hope that it will be useful, but   |
17// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
18// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
19// | General Public License for more details.                              |
20// |                                                                       |
21// | You should have received a copy of the GNU General Public License     |
22// | along with this program; if not, write to the Free Software           |
23// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
24// | USA.                                                                  |
25// +-----------------------------------------------------------------------+
26
27include_once( PHPWG_ROOT_PATH .'include/functions_user.inc.php' );
28include_once( PHPWG_ROOT_PATH .'include/functions_session.inc.php' );
29include_once( PHPWG_ROOT_PATH .'include/functions_category.inc.php' );
30include_once( PHPWG_ROOT_PATH .'include/functions_xml.inc.php' );
31include_once( PHPWG_ROOT_PATH .'include/functions_group.inc.php' );
32include_once( PHPWG_ROOT_PATH .'include/functions_html.inc.php' );
33include_once( PHPWG_ROOT_PATH .'include/functions_tag.inc.php' );
34include_once( PHPWG_ROOT_PATH .'include/functions_url.inc.php' );
35include_once( PHPWG_ROOT_PATH .'include/functions_plugins.inc.php' );
36
37//----------------------------------------------------------- generic functions
38
39/**
40 * returns an array containing the possible values of an enum field
41 *
42 * @param string tablename
43 * @param string fieldname
44 */
45function get_enums($table, $field)
46{
47  // retrieving the properties of the table. Each line represents a field :
48  // columns are 'Field', 'Type'
49  $result = pwg_query('desc '.$table);
50  while ($row = mysql_fetch_array($result))
51  {
52    // we are only interested in the the field given in parameter for the
53    // function
54    if ($row['Field'] == $field)
55    {
56      // retrieving possible values of the enum field
57      // enum('blue','green','black')
58      $options = explode(',', substr($row['Type'], 5, -1));
59      foreach ($options as $i => $option)
60      {
61        $options[$i] = str_replace("'", '',$option);
62      }
63    }
64  }
65  mysql_free_result($result);
66  return $options;
67}
68
69// get_boolean transforms a string to a boolean value. If the string is
70// "false" (case insensitive), then the boolean value false is returned. In
71// any other case, true is returned.
72function get_boolean( $string )
73{
74  $boolean = true;
75  if ( preg_match( '/^false$/i', $string ) )
76  {
77    $boolean = false;
78  }
79  return $boolean;
80}
81
82/**
83 * returns boolean string 'true' or 'false' if the given var is boolean
84 *
85 * @param mixed $var
86 * @return mixed
87 */
88function boolean_to_string($var)
89{
90  if (is_bool($var))
91  {
92    if ($var)
93    {
94      return 'true';
95    }
96    else
97    {
98      return 'false';
99    }
100  }
101  else
102  {
103    return $var;
104  }
105}
106
107// The function get_moment returns a float value coresponding to the number
108// of seconds since the unix epoch (1st January 1970) and the microseconds
109// are precised : e.g. 1052343429.89276600
110function get_moment()
111{
112  $t1 = explode( ' ', microtime() );
113  $t2 = explode( '.', $t1[0] );
114  $t2 = $t1[1].'.'.$t2[1];
115  return $t2;
116}
117
118// The function get_elapsed_time returns the number of seconds (with 3
119// decimals precision) between the start time and the end time given.
120function get_elapsed_time( $start, $end )
121{
122  return number_format( $end - $start, 3, '.', ' ').' s';
123}
124
125// - The replace_space function replaces space and '-' characters
126//   by their HTML equivalent  &nbsb; and &minus;
127// - The function does not replace characters in HTML tags
128// - This function was created because IE5 does not respect the
129//   CSS "white-space: nowrap;" property unless space and minus
130//   characters are replaced like this function does.
131// - Example :
132//                 <div class="foo">My friend</div>
133//               ( 01234567891111111111222222222233 )
134//               (           0123456789012345678901 )
135// becomes :
136//             <div class="foo">My&nbsp;friend</div>
137function replace_space( $string )
138{
139  //return $string;
140  $return_string = '';
141  // $remaining is the rest of the string where to replace spaces characters
142  $remaining = $string;
143  // $start represents the position of the next '<' character
144  // $end   represents the position of the next '>' character
145  $start = 0;
146  $end = 0;
147  $start = strpos ( $remaining, '<' ); // -> 0
148  $end   = strpos ( $remaining, '>' ); // -> 16
149  // as long as a '<' and his friend '>' are found, we loop
150  while ( is_numeric( $start ) and is_numeric( $end ) )
151  {
152    // $treatment is the part of the string to treat
153    // In the first loop of our example, this variable is empty, but in the
154    // second loop, it equals 'My friend'
155    $treatment = substr ( $remaining, 0, $start );
156    // Replacement of ' ' by his equivalent '&nbsp;'
157    $treatment = str_replace( ' ', '&nbsp;', $treatment );
158    $treatment = str_replace( '-', '&minus;', $treatment );
159    // composing the string to return by adding the treated string and the
160    // following HTML tag -> 'My&nbsp;friend</div>'
161    $return_string.= $treatment.substr( $remaining, $start, $end-$start+1 );
162    // the remaining string is deplaced to the part after the '>' of this
163    // loop
164    $remaining = substr ( $remaining, $end + 1, strlen( $remaining ) );
165    $start = strpos ( $remaining, '<' );
166    $end   = strpos ( $remaining, '>' );
167  }
168  $treatment = str_replace( ' ', '&nbsp;', $remaining );
169  $treatment = str_replace( '-', '&minus;', $treatment );
170  $return_string.= $treatment;
171
172  return $return_string;
173}
174
175// get_extension returns the part of the string after the last "."
176function get_extension( $filename )
177{
178  return substr( strrchr( $filename, '.' ), 1, strlen ( $filename ) );
179}
180
181// get_filename_wo_extension returns the part of the string before the last
182// ".".
183// get_filename_wo_extension( 'test.tar.gz' ) -> 'test.tar'
184function get_filename_wo_extension( $filename )
185{
186  $pos = strrpos( $filename, '.' );
187  return ($pos===false) ? $filename : substr( $filename, 0, $pos);
188}
189
190/**
191 * returns an array contening sub-directories, excluding "CVS"
192 *
193 * @param string $dir
194 * @return array
195 */
196function get_dirs($directory)
197{
198  $sub_dirs = array();
199
200  if ($opendir = opendir($directory))
201  {
202    while ($file = readdir($opendir))
203    {
204      if ($file != '.'
205          and $file != '..'
206          and is_dir($directory.'/'.$file)
207          and $file != 'CVS'
208    and $file != '.svn')
209      {
210        array_push($sub_dirs, $file);
211      }
212    }
213  }
214  return $sub_dirs;
215}
216
217/**
218 * returns thumbnail directory name of input diretoty name
219 * make thumbnail directory is necessary
220 * set error messages on array messages
221 *
222 * @param:
223 *  string $dirname
224 *  arrayy $errors
225 * @return bool false on error else string directory name
226 */
227function mkget_thumbnail_dir($dirname, &$errors)
228{
229  $tndir = $dirname.'/thumbnail';
230  if (!is_dir($tndir))
231  {
232    if (!is_writable($dirname))
233    {
234      array_push($errors,
235                 '['.$dirname.'] : '.l10n('no_write_access'));
236      return false;
237    }
238    umask(0000);
239    mkdir($tndir, 0777);
240  }
241
242  return $tndir;
243}
244
245// The get_picture_size function return an array containing :
246//      - $picture_size[0] : final width
247//      - $picture_size[1] : final height
248// The final dimensions are calculated thanks to the original dimensions and
249// the maximum dimensions given in parameters.  get_picture_size respects
250// the width/height ratio
251function get_picture_size( $original_width, $original_height,
252                           $max_width, $max_height )
253{
254  $width = $original_width;
255  $height = $original_height;
256  $is_original_size = true;
257
258  if ( $max_width != "" )
259  {
260    if ( $original_width > $max_width )
261    {
262      $width = $max_width;
263      $height = floor( ( $width * $original_height ) / $original_width );
264    }
265  }
266  if ( $max_height != "" )
267  {
268    if ( $original_height > $max_height )
269    {
270      $height = $max_height;
271      $width = floor( ( $height * $original_width ) / $original_height );
272      $is_original_size = false;
273    }
274  }
275  if ( is_numeric( $max_width ) and is_numeric( $max_height )
276       and $max_width != 0 and $max_height != 0 )
277  {
278    $ratioWidth = $original_width / $max_width;
279    $ratioHeight = $original_height / $max_height;
280    if ( ( $ratioWidth > 1 ) or ( $ratioHeight > 1 ) )
281    {
282      if ( $ratioWidth < $ratioHeight )
283      {
284        $width = floor( $original_width / $ratioHeight );
285        $height = $max_height;
286      }
287      else
288      {
289        $width = $max_width;
290        $height = floor( $original_height / $ratioWidth );
291      }
292      $is_original_size = false;
293    }
294  }
295  $picture_size = array();
296  $picture_size[0] = $width;
297  $picture_size[1] = $height;
298  return $picture_size;
299}
300
301/**
302 * simplify a string to insert it into an URL
303 *
304 * based on str2url function from Dotclear
305 *
306 * @param string
307 * @return string
308 */
309function str2url($str)
310{
311  $str = strtr(
312    $str,
313    'ÀÁÂÃÄÅàáâãäåÇçÒÓÔÕÖØòóôõöøÈÉÊËèéêëÌÍÎÏìíîïÙÚÛÜùúûü¾ÝÿýÑñ',
314    'AAAAAAaaaaaaCcOOOOOOooooooEEEEeeeeIIIIiiiiUUUUuuuuYYyyNn'
315    );
316
317  $str = str_replace('Æ', 'AE', $str);
318  $str = str_replace('æ', 'ae', $str);
319  $str = str_replace('¼', 'OE', $str);
320  $str = str_replace('½', 'oe', $str);
321
322  $str = preg_replace('/[^a-z0-9_\s\'\:\/\[\],-]/','',strtolower($str));
323  $str = preg_replace('/[\s\'\:\/\[\],-]+/',' ',trim($str));
324  $res = str_replace(' ','_',$str);
325
326  return $res;
327}
328
329//-------------------------------------------- PhpWebGallery specific functions
330
331/**
332 * returns an array with a list of {language_code => language_name}
333 *
334 * @returns array
335 */
336function get_languages()
337{
338  $dir = opendir(PHPWG_ROOT_PATH.'language');
339  $languages = array();
340
341  while ($file = readdir($dir))
342  {
343    $path = PHPWG_ROOT_PATH.'language/'.$file;
344    if (is_dir($path) and !is_link($path) and file_exists($path.'/iso.txt'))
345    {
346      list($language_name) = @file($path.'/iso.txt');
347      $languages[$file] = $language_name;
348    }
349  }
350  closedir($dir);
351  @asort($languages);
352  @reset($languages);
353
354  return $languages;
355}
356
357/**
358 * replaces the $search into <span style="$style">$search</span> in the
359 * given $string.
360 *
361 * case insensitive replacements, does not replace characters in HTML tags
362 *
363 * @param string $string
364 * @param string $search
365 * @param string $style
366 * @return string
367 */
368function add_style( $string, $search, $style )
369{
370  //return $string;
371  $return_string = '';
372  $remaining = $string;
373
374  $start = 0;
375  $end = 0;
376  $start = strpos ( $remaining, '<' );
377  $end   = strpos ( $remaining, '>' );
378  while ( is_numeric( $start ) and is_numeric( $end ) )
379  {
380    $treatment = substr ( $remaining, 0, $start );
381    $treatment = preg_replace( '/('.$search.')/i',
382                               '<span style="'.$style.'">\\0</span>',
383                               $treatment );
384    $return_string.= $treatment.substr( $remaining, $start, $end-$start+1 );
385    $remaining = substr ( $remaining, $end + 1, strlen( $remaining ) );
386    $start = strpos ( $remaining, '<' );
387    $end   = strpos ( $remaining, '>' );
388  }
389  $treatment = preg_replace( '/('.$search.')/i',
390                             '<span style="'.$style.'">\\0</span>',
391                             $remaining );
392  $return_string.= $treatment;
393
394  return $return_string;
395}
396
397// replace_search replaces a searched words array string by the search in
398// another style for the given $string.
399function replace_search( $string, $search )
400{
401  // FIXME : with new advanced search, this function needs a rewrite
402  return $string;
403
404  $words = explode( ',', $search );
405  $style = 'background-color:white;color:red;';
406  foreach ( $words as $word ) {
407    $string = add_style( $string, $word, $style );
408  }
409  return $string;
410}
411
412function pwg_log($image_id = null, $image_type = null)
413{
414  global $conf, $user, $page;
415
416  if (!$conf['log'])
417  {
418    return false;
419  }
420
421  if (is_admin() and !$conf['history_admin'])
422  {
423    return false;
424  }
425
426  if ($user['is_the_guest'] and !$conf['history_guest'])
427  {
428    return false;
429  }
430
431  $tags_string = null;
432  if (isset($page['section']) and $page['section'] == 'tags')
433  {
434    $tag_ids = array();
435    foreach ($page['tags'] as $tag)
436    {
437      array_push($tag_ids, $tag['id']);
438    }
439
440    $tags_string = implode(',', $tag_ids);
441  }
442
443  // here we ask the database the current date and time, and we extract
444  // {year, month, day} from the current date. We could do this during the
445  // insert query with a CURDATE(), CURTIME(), DATE_FORMAT(CURDATE(), '%Y')
446  // ... but I (plg) think it would cost more than a double query and a PHP
447  // extraction.
448  $query = '
449SELECT CURDATE(), CURTIME()
450;';
451  list($curdate, $curtime) = mysql_fetch_row(pwg_query($query));
452
453  list($curyear, $curmonth, $curday) = explode('-', $curdate);
454  list($curhour) = explode(':', $curtime);
455 
456  $query = '
457INSERT INTO '.HISTORY_TABLE.'
458  (
459    date,
460    time,
461    year,
462    month,
463    day,
464    hour,
465    user_id,
466    IP,
467    section,
468    category_id,
469    image_id,
470    image_type,
471    tag_ids
472  )
473  VALUES
474  (
475    \''.$curdate.'\',
476    \''.$curtime.'\',
477    '.$curyear.',
478    '.$curmonth.',
479    '.$curday.',
480    '.$curhour.',
481    '.$user['id'].',
482    \''.$_SERVER['REMOTE_ADDR'].'\',
483    '.(isset($page['section']) ? "'".$page['section']."'" : 'NULL').',
484    '.(isset($page['category']) ? $page['category']['id'] : 'NULL').',
485    '.(isset($image_id) ? $image_id : 'NULL').',
486    '.(isset($image_id) ? "'".$image_type."'" : 'NULL').',
487    '.(isset($tags_string) ? "'".$tags_string."'" : 'NULL').'
488  )
489;';
490  pwg_query($query);
491
492  return true;
493}
494
495// format_date returns a formatted date for display. The date given in
496// argument can be a unixdate (number of seconds since the 01.01.1970) or an
497// american format (2003-09-15). By option, you can show the time. The
498// output is internationalized.
499//
500// format_date( "2003-09-15", 'us', true ) -> "Monday 15 September 2003 21:52"
501function format_date($date, $type = 'us', $show_time = false)
502{
503  global $lang;
504
505  list($year,$month,$day,$hour,$minute,$second) = array(0,0,0,0,0,0);
506
507  switch ( $type )
508  {
509    case 'us' :
510    {
511      list($year,$month,$day) = explode('-', $date);
512      break;
513    }
514    case 'unix' :
515    {
516      list($year,$month,$day,$hour,$minute) =
517        explode('.', date('Y.n.j.G.i', $date));
518      break;
519    }
520    case 'mysql_datetime' :
521    {
522      preg_match('/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/',
523                 $date, $out);
524      list($year,$month,$day,$hour,$minute,$second) =
525        array($out[1],$out[2],$out[3],$out[4],$out[5],$out[6]);
526      break;
527    }
528  }
529  $formated_date = '';
530  // before 1970, Microsoft Windows can't mktime
531  if ($year >= 1970)
532  {
533    // we ask midday because Windows think it's prior to midnight with a
534    // zero and refuse to work
535    $formated_date.= $lang['day'][date('w', mktime(12,0,0,$month,$day,$year))];
536  }
537  $formated_date.= ' '.$day;
538  $formated_date.= ' '.$lang['month'][(int)$month];
539  $formated_date.= ' '.$year;
540  if ($show_time)
541  {
542    $formated_date.= ' '.$hour.':'.$minute;
543  }
544
545  return $formated_date;
546}
547
548function pwg_query($query)
549{
550  global $conf,$page,$debug,$t2;
551
552  $start = get_moment();
553  $result = mysql_query($query) or my_error($query."\n");
554
555  $time = get_moment() - $start;
556
557  if (!isset($page['count_queries']))
558  {
559    $page['count_queries'] = 0;
560    $page['queries_time'] = 0;
561  }
562
563  $page['count_queries']++;
564  $page['queries_time']+= $time;
565
566  if ($conf['show_queries'])
567  {
568    $output = '';
569    $output.= '<pre>['.$page['count_queries'].'] ';
570    $output.= "\n".$query;
571    $output.= "\n".'(this query time : ';
572    $output.= '<b>'.number_format($time, 3, '.', ' ').' s)</b>';
573    $output.= "\n".'(total SQL time  : ';
574    $output.= number_format($page['queries_time'], 3, '.', ' ').' s)';
575    $output.= "\n".'(total time      : ';
576    $output.= number_format( ($time+$start-$t2), 3, '.', ' ').' s)';
577    $output.= "</pre>\n";
578
579    $debug .= $output;
580  }
581
582  return $result;
583}
584
585function pwg_debug( $string )
586{
587  global $debug,$t2,$page;
588
589  $now = explode( ' ', microtime() );
590  $now2 = explode( '.', $now[0] );
591  $now2 = $now[1].'.'.$now2[1];
592  $time = number_format( $now2 - $t2, 3, '.', ' ').' s';
593  $debug .= '<p>';
594  $debug.= '['.$time.', ';
595  $debug.= $page['count_queries'].' queries] : '.$string;
596  $debug.= "</p>\n";
597}
598
599/**
600 * Redirects to the given URL (HTTP method)
601 *
602 * Note : once this function called, the execution doesn't go further
603 * (presence of an exit() instruction.
604 *
605 * @param string $url
606 * @return void
607 */
608function redirect_http( $url )
609{
610  if (ob_get_length () !== FALSE)
611  {
612    ob_clean();
613  }
614  header('Request-URI: '.$url);
615  header('Content-Location: '.$url);
616  header('Location: '.$url);
617  exit();
618}
619
620/**
621 * Redirects to the given URL (HTML method)
622 *
623 * Note : once this function called, the execution doesn't go further
624 * (presence of an exit() instruction.
625 *
626 * @param string $url
627 * @param string $title_msg
628 * @param integer $refreh_time
629 * @return void
630 */
631function redirect_html( $url , $msg = '', $refresh_time = 0)
632{
633  global $user, $template, $lang_info, $conf, $lang, $t2, $page, $debug;
634
635  if (!isset($lang_info))
636  {
637    $user = build_user( $conf['guest_id'], true);
638    include_once(get_language_filepath('common.lang.php'));
639    trigger_action('loading_lang');
640    @include_once(get_language_filepath('local.lang.php'));
641    list($tmpl, $thm) = explode('/', $conf['default_template']);
642    $template = new Template(PHPWG_ROOT_PATH.'template/'.$tmpl, $thm);
643  }
644  else
645  {
646    $template = new Template(PHPWG_ROOT_PATH.'template/'.$user['template'], $user['theme']);
647  }
648
649  if (empty($msg))
650  {
651    $redirect_msg = l10n('redirect_msg');
652  }
653  else
654  {
655    $redirect_msg = $msg;
656  }
657  $redirect_msg = nl2br($redirect_msg);
658
659  $refresh = $refresh_time;
660  $url_link = $url;
661  $title = 'redirection';
662
663  $template->set_filenames( array( 'redirect' => 'redirect.tpl' ) );
664
665  include( PHPWG_ROOT_PATH.'include/page_header.php' );
666
667  $template->set_filenames( array( 'redirect' => 'redirect.tpl' ) );
668  $template->parse('redirect');
669
670  include( PHPWG_ROOT_PATH.'include/page_tail.php' );
671
672  exit();
673}
674
675/**
676 * Redirects to the given URL (Switch to HTTP method or HTML method)
677 *
678 * Note : once this function called, the execution doesn't go further
679 * (presence of an exit() instruction.
680 *
681 * @param string $url
682 * @param string $title_msg
683 * @param integer $refreh_time
684 * @return void
685 */
686function redirect( $url , $msg = '', $refresh_time = 0)
687{
688  global $conf;
689
690  // with RefeshTime <> 0, only html must be used
691  if ($conf['default_redirect_method']=='http'
692      and $refresh_time==0
693      and !headers_sent()
694    )
695  {
696    redirect_http($url);
697  }
698  else
699  {
700    redirect_html($url, $msg, $refresh_time);
701  }
702}
703
704/**
705 * returns $_SERVER['QUERY_STRING'] whitout keys given in parameters
706 *
707 * @param array $rejects
708 * @returns string
709 */
710function get_query_string_diff($rejects = array())
711{
712  $query_string = '';
713
714  $str = $_SERVER['QUERY_STRING'];
715  parse_str($str, $vars);
716
717  $is_first = true;
718  foreach ($vars as $key => $value)
719  {
720    if (!in_array($key, $rejects))
721    {
722      $query_string.= $is_first ? '?' : '&amp;';
723      $is_first = false;
724      $query_string.= $key.'='.$value;
725    }
726  }
727
728  return $query_string;
729}
730
731function url_is_remote($url)
732{
733  if ( strncmp($url, 'http://', 7)==0
734    or strncmp($url, 'https://', 8)==0 )
735  {
736    return true;
737  }
738  return false;
739}
740
741/**
742 * returns available template/theme
743 */
744function get_pwg_themes()
745{
746  $themes = array();
747
748  $template_dir = PHPWG_ROOT_PATH.'template';
749
750  foreach (get_dirs($template_dir) as $template)
751  {
752    foreach (get_dirs($template_dir.'/'.$template.'/theme') as $theme)
753    {
754      array_push($themes, $template.'/'.$theme);
755    }
756  }
757
758  return $themes;
759}
760
761/* Returns the PATH to the thumbnail to be displayed. If the element does not
762 * have a thumbnail, the default mime image path is returned. The PATH can be
763 * used in the php script, but not sent to the browser.
764 * @param array element_info assoc array containing element info from db
765 * at least 'path', 'tn_ext' and 'id' should be present
766 */
767function get_thumbnail_path($element_info)
768{
769  $path = get_thumbnail_location($element_info);
770  if ( !url_is_remote($path) )
771  {
772    $path = PHPWG_ROOT_PATH.$path;
773  }
774  return $path;
775}
776
777/* Returns the URL of the thumbnail to be displayed. If the element does not
778 * have a thumbnail, the default mime image url is returned. The URL can be
779 * sent to the browser, but not used in the php script.
780 * @param array element_info assoc array containing element info from db
781 * at least 'path', 'tn_ext' and 'id' should be present
782 */
783function get_thumbnail_url($element_info)
784{
785  $path = get_thumbnail_location($element_info);
786  if ( !url_is_remote($path) )
787  {
788    $path = get_root_url().$path;
789  }
790  // plugins want another url ?
791  $path = trigger_event('get_thumbnail_url', $path, $element_info);
792  return $path;
793}
794
795/* returns the relative path of the thumnail with regards to to the root
796of phpwebgallery (not the current page!).This function is not intended to be
797called directly from code.*/
798function get_thumbnail_location($element_info)
799{
800  global $conf;
801  if ( !empty( $element_info['tn_ext'] ) )
802  {
803    $path = substr_replace(
804      get_filename_wo_extension($element_info['path']),
805      '/thumbnail/'.$conf['prefix_thumbnail'],
806      strrpos($element_info['path'],'/'),
807      1
808      );
809    $path.= '.'.$element_info['tn_ext'];
810  }
811  else
812  {
813    $path = get_themeconf('mime_icon_dir')
814        .strtolower(get_extension($element_info['path'])).'.png';
815  }
816
817  // plugins want another location ?
818  $path = trigger_event( 'get_thumbnail_location', $path, $element_info);
819  return $path;
820}
821
822/* returns the title of the thumnail */
823function get_thumbnail_title($element_info)
824{
825  // message in title for the thumbnail
826  if (isset($element_info['file']))
827  {
828    $thumbnail_title = $element_info['file'];
829  }
830  else
831  {
832    $thumbnail_title = '';
833  }
834 
835  if (!empty($element_info['filesize']))
836  {
837    $thumbnail_title .= ' : '.$element_info['filesize'].' KB';
838  }
839
840  return $thumbnail_title;
841}
842
843// my_error returns (or send to standard output) the message concerning the
844// error occured for the last mysql query.
845function my_error($header)
846{
847  global $conf;
848
849  $error = '<pre>';
850  $error.= $header;
851  $error.= '[mysql error '.mysql_errno().'] ';
852  $error.= mysql_error();
853  $error.= '</pre>';
854
855  if ($conf['die_on_sql_error'])
856  {
857    die($error);
858  }
859  else
860  {
861    echo $error;
862  }
863}
864
865/**
866 * creates an array based on a query, this function is a very common pattern
867 * used here
868 *
869 * @param string $query
870 * @param string $fieldname
871 * @return array
872 */
873function array_from_query($query, $fieldname)
874{
875  $array = array();
876
877  $result = pwg_query($query);
878  while ($row = mysql_fetch_array($result))
879  {
880    array_push($array, $row[$fieldname]);
881  }
882
883  return $array;
884}
885
886/**
887 * instantiate number list for days in a template block
888 *
889 * @param string blockname
890 * @param string selection
891 */
892function get_day_list($blockname, $selection)
893{
894  global $template;
895
896  $template->assign_block_vars(
897    $blockname,
898    array(
899      'SELECTED' => '',
900      'VALUE' => 0,
901      'OPTION' => '--'
902      )
903    );
904
905  for ($i = 1; $i <= 31; $i++)
906  {
907    $selected = '';
908    if ($i == (int)$selection)
909    {
910      $selected = 'selected="selected"';
911    }
912    $template->assign_block_vars(
913      $blockname,
914      array(
915        'SELECTED' => $selected,
916        'VALUE' => $i,
917        'OPTION' => str_pad($i, 2, '0', STR_PAD_LEFT)
918        )
919      );
920  }
921}
922
923/**
924 * instantiate month list in a template block
925 *
926 * @param string blockname
927 * @param string selection
928 */
929function get_month_list($blockname, $selection)
930{
931  global $template, $lang;
932
933  $template->assign_block_vars(
934    $blockname,
935    array(
936      'SELECTED' => '',
937      'VALUE' => 0,
938      'OPTION' => '------------')
939    );
940
941  for ($i = 1; $i <= 12; $i++)
942  {
943    $selected = '';
944    if ($i == (int)$selection)
945    {
946      $selected = 'selected="selected"';
947    }
948    $template->assign_block_vars(
949      $blockname,
950      array(
951        'SELECTED' => $selected,
952        'VALUE' => $i,
953        'OPTION' => $lang['month'][$i])
954      );
955  }
956}
957
958/**
959 * fill the current user caddie with given elements, if not already in
960 * caddie
961 *
962 * @param array elements_id
963 */
964function fill_caddie($elements_id)
965{
966  global $user;
967
968  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
969
970  $query = '
971SELECT element_id
972  FROM '.CADDIE_TABLE.'
973  WHERE user_id = '.$user['id'].'
974;';
975  $in_caddie = array_from_query($query, 'element_id');
976
977  $caddiables = array_diff($elements_id, $in_caddie);
978
979  $datas = array();
980
981  foreach ($caddiables as $caddiable)
982  {
983    array_push($datas, array('element_id' => $caddiable,
984                             'user_id' => $user['id']));
985  }
986
987  if (count($caddiables) > 0)
988  {
989    mass_inserts(CADDIE_TABLE, array('element_id','user_id'), $datas);
990  }
991}
992
993/**
994 * returns the element name from its filename
995 *
996 * @param string filename
997 * @return string name
998 */
999function get_name_from_file($filename)
1000{
1001  return str_replace('_',' ',get_filename_wo_extension($filename));
1002}
1003
1004/**
1005 * returns the corresponding value from $lang if existing. Else, the key is
1006 * returned
1007 *
1008 * @param string key
1009 * @return string
1010 */
1011function l10n($key)
1012{
1013  global $lang, $conf;
1014
1015  if ($conf['debug_l10n'] and !isset($lang[$key]))
1016  {
1017    echo '[l10n] language key "'.$key.'" is not defined<br />';
1018  }
1019
1020  return isset($lang[$key]) ? $lang[$key] : $key;
1021}
1022
1023/**
1024 * returns the prinft value for strings including %d
1025 * return is concorded with decimal value (singular, plural)
1026 *
1027 * @param singular string key
1028 * @param plural string key
1029 * @param decimal value
1030 * @return string
1031 */
1032function l10n_dec($singular_fmt_key, $plural_fmt_key, $decimal)
1033{
1034  global $lang_info;
1035
1036  return
1037    sprintf(
1038      l10n((
1039        (($decimal > 1) or ($decimal == 0 and $lang_info['zero_plural']))
1040          ? $plural_fmt_key
1041          : $singular_fmt_key
1042        )), $decimal);
1043}
1044
1045/**
1046 * Translate string in string ascii7bits
1047 * It's possible to do that with iconv_substr
1048 * but this fonction is not avaible on all the providers.
1049 *
1050 * @param string str
1051 * @return string
1052 */
1053function str_translate_to_ascii7bits($str)
1054{
1055  global $lang_table_translate_ascii7bits;
1056
1057  $src_table = array_keys($lang_table_translate_ascii7bits);
1058  $dst_table = array_values($lang_table_translate_ascii7bits);
1059
1060  return str_replace($src_table , $dst_table, $str);
1061}
1062
1063/**
1064 * returns the corresponding value from $themeconf if existing. Else, the
1065 * key is returned
1066 *
1067 * @param string key
1068 * @return string
1069 */
1070function get_themeconf($key)
1071{
1072  global $template;
1073
1074  return $template->get_themeconf($key);
1075}
1076
1077/**
1078 * Returns webmaster mail address depending on $conf['webmaster_id']
1079 *
1080 * @return string
1081 */
1082function get_webmaster_mail_address()
1083{
1084  global $conf;
1085
1086  $query = '
1087SELECT '.$conf['user_fields']['email'].'
1088  FROM '.USERS_TABLE.'
1089  WHERE '.$conf['user_fields']['id'].' = '.$conf['webmaster_id'].'
1090;';
1091  list($email) = mysql_fetch_array(pwg_query($query));
1092
1093  return $email;
1094}
1095
1096/**
1097 * which upgrades are available ?
1098 *
1099 * @return array
1100 */
1101function get_available_upgrade_ids()
1102{
1103  $upgrades_path = PHPWG_ROOT_PATH.'install/db';
1104
1105  $available_upgrade_ids = array();
1106
1107  if ($contents = opendir($upgrades_path))
1108  {
1109    while (($node = readdir($contents)) !== false)
1110    {
1111      if (is_file($upgrades_path.'/'.$node)
1112          and preg_match('/^(.*?)-database\.php$/', $node, $match))
1113      {
1114        array_push($available_upgrade_ids, $match[1]);
1115      }
1116    }
1117  }
1118  natcasesort($available_upgrade_ids);
1119
1120  return $available_upgrade_ids;
1121}
1122
1123/**
1124 * Add configuration parameters from database to global $conf array
1125 *
1126 * @return void
1127 */
1128function load_conf_from_db($condition = '')
1129{
1130  global $conf;
1131
1132  $query = '
1133SELECT param, value
1134 FROM '.CONFIG_TABLE.'
1135 '.(!empty($condition) ? 'WHERE '.$condition : '').'
1136;';
1137  $result = pwg_query($query);
1138
1139  if ((mysql_num_rows($result) == 0) and !empty($condition))
1140  {
1141    die('No configuration data');
1142  }
1143
1144  while ($row = mysql_fetch_array($result))
1145  {
1146    $conf[ $row['param'] ] = isset($row['value']) ? $row['value'] : '';
1147
1148    // If the field is true or false, the variable is transformed into a
1149    // boolean value.
1150    if ($conf[$row['param']] == 'true' or $conf[$row['param']] == 'false')
1151    {
1152      $conf[ $row['param'] ] = get_boolean($conf[ $row['param'] ]);
1153    }
1154  }
1155}
1156
1157/**
1158 * Prepends and appends a string at each value of the given array.
1159 *
1160 * @param array
1161 * @param string prefix to each array values
1162 * @param string suffix to each array values
1163 */
1164function prepend_append_array_items($array, $prepend_str, $append_str)
1165{
1166  array_walk(
1167    $array,
1168    create_function('&$s', '$s = "'.$prepend_str.'".$s."'.$append_str.'";')
1169    );
1170
1171  return $array;
1172}
1173
1174/**
1175 * creates an hashed based on a query, this function is a very common
1176 * pattern used here. Among the selected columns fetched, choose one to be
1177 * the key, another one to be the value.
1178 *
1179 * @param string $query
1180 * @param string $keyname
1181 * @param string $valuename
1182 * @return array
1183 */
1184function simple_hash_from_query($query, $keyname, $valuename)
1185{
1186  $array = array();
1187
1188  $result = pwg_query($query);
1189  while ($row = mysql_fetch_array($result))
1190  {
1191    $array[ $row[$keyname] ] = $row[$valuename];
1192  }
1193
1194  return $array;
1195}
1196
1197/**
1198 * creates an hashed based on a query, this function is a very common
1199 * pattern used here. The key is given as parameter, the value is an associative
1200 * array.
1201 *
1202 * @param string $query
1203 * @param string $keyname
1204 * @return array
1205 */
1206function hash_from_query($query, $keyname)
1207{
1208  $array = array();
1209  $result = pwg_query($query);
1210  while ($row = mysql_fetch_assoc($result))
1211  {
1212    $array[ $row[$keyname] ] = $row;
1213  }
1214  return $array;
1215}
1216
1217/**
1218 * Return basename of the current script
1219 * Lower case convertion is applied on return value
1220 * Return value is without file extention ".php"
1221 *
1222 * @param void
1223 *
1224 * @return script basename
1225 */
1226function script_basename()
1227{
1228  if (!empty($_SERVER['SCRIPT_NAME']))
1229  {
1230    $file_name = $_SERVER['SCRIPT_NAME'];
1231  }
1232  else if (!empty($_SERVER['SCRIPT_FILENAME']))
1233  {
1234    $file_name = $_SERVER['SCRIPT_FILENAME'];
1235  }
1236  else
1237  {
1238    $file_name = '';
1239  }
1240
1241  // $_SERVER return lower string following var and systems
1242  return basename(strtolower($file_name), '.php');
1243}
1244
1245/**
1246 * Return value for the current page define on $conf['filter_pages']
1247 * Îf value is not defined, default value are returned
1248 *
1249 * @param value name
1250 *
1251 * @return filter page value
1252 */
1253function get_filter_page_value($value_name)
1254{
1255  global $conf;
1256
1257  $page_name = script_basename();
1258
1259  if (isset($conf['filter_pages'][$page_name][$value_name]))
1260  {
1261    return $conf['filter_pages'][$page_name][$value_name];
1262  }
1263  else if (isset($conf['filter_pages']['default'][$value_name]))
1264  {
1265    return $conf['filter_pages']['default'][$value_name];
1266  }
1267  else
1268  {
1269    return null;
1270  }
1271}
1272
1273?>
Note: See TracBrowser for help on using the repository browser.