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

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

Issue 578
User guest must be real user

Step 1: guest is a real user

On next commit, I finish installation and use of guest of user list and group

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