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

Last change on this file since 868 was 868, checked in by plg, 19 years ago
  • bug 107 fixed: crash when logging visit on a category containing "'" character. Correction reported from branch 1.4
  • bug fixed: in admin/stats, incorrect SQL queries gave no result.
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 19.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-2005 PhpWebGallery Team - http://phpwebgallery.net |
6// +-----------------------------------------------------------------------+
7// | branch        : BSF (Best So Far)
8// | file          : $RCSfile$
9// | last update   : $Date: 2005-09-18 21:56:56 +0000 (Sun, 18 Sep 2005) $
10// | last modifier : $Author: plg $
11// | revision      : $Revision: 868 $
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' );
34
35//----------------------------------------------------------- generic functions
36
37/**
38 * returns an array containing the possible values of an enum field
39 *
40 * @param string tablename
41 * @param string fieldname
42 */
43function get_enums($table, $field)
44{
45  // retrieving the properties of the table. Each line represents a field :
46  // columns are 'Field', 'Type'
47  $result = pwg_query('desc '.$table);
48  while ($row = mysql_fetch_array($result))
49  {
50    // we are only interested in the the field given in parameter for the
51    // function
52    if ($row['Field'] == $field)
53    {
54      // retrieving possible values of the enum field
55      // enum('blue','green','black')
56      $options = explode(',', substr($row['Type'], 5, -1));
57      foreach ($options as $i => $option)
58      {
59        $options[$i] = str_replace("'", '',$option);
60      }
61    }
62  }
63  mysql_free_result($result);
64  return $options;
65}
66
67// get_boolean transforms a string to a boolean value. If the string is
68// "false" (case insensitive), then the boolean value false is returned. In
69// any other case, true is returned.
70function get_boolean( $string )
71{
72  $boolean = true;
73  if ( preg_match( '/^false$/i', $string ) )
74  {
75    $boolean = false;
76  }
77  return $boolean;
78}
79
80/**
81 * returns boolean string 'true' or 'false' if the given var is boolean
82 *
83 * @param mixed $var
84 * @return mixed
85 */
86function boolean_to_string($var)
87{
88  if (is_bool($var))
89  {
90    if ($var)
91    {
92      return 'true';
93    }
94    else
95    {
96      return 'false';
97    }
98  }
99  else
100  {
101    return $var;
102  }
103}
104
105// The function get_moment returns a float value coresponding to the number
106// of seconds since the unix epoch (1st January 1970) and the microseconds
107// are precised : e.g. 1052343429.89276600
108function get_moment()
109{
110  $t1 = explode( ' ', microtime() );
111  $t2 = explode( '.', $t1[0] );
112  $t2 = $t1[1].'.'.$t2[1];
113  return $t2;
114}
115
116// The function get_elapsed_time returns the number of seconds (with 3
117// decimals precision) between the start time and the end time given.
118function get_elapsed_time( $start, $end )
119{
120  return number_format( $end - $start, 3, '.', ' ').' s';
121}
122
123// - The replace_space function replaces space and '-' characters
124//   by their HTML equivalent  &nbsb; and &minus;
125// - The function does not replace characters in HTML tags
126// - This function was created because IE5 does not respect the
127//   CSS "white-space: nowrap;" property unless space and minus
128//   characters are replaced like this function does.
129// - Example :
130//                 <div class="foo">My friend</div>
131//               ( 01234567891111111111222222222233 )
132//               (           0123456789012345678901 )
133// becomes :
134//             <div class="foo">My&nbsp;friend</div>
135function replace_space( $string )
136{
137  //return $string;
138  $return_string = '';
139  // $remaining is the rest of the string where to replace spaces characters
140  $remaining = $string;
141  // $start represents the position of the next '<' character
142  // $end   represents the position of the next '>' character
143  $start = 0;
144  $end = 0;
145  $start = strpos ( $remaining, '<' ); // -> 0
146  $end   = strpos ( $remaining, '>' ); // -> 16
147  // as long as a '<' and his friend '>' are found, we loop
148  while ( is_numeric( $start ) and is_numeric( $end ) )
149  {
150    // $treatment is the part of the string to treat
151    // In the first loop of our example, this variable is empty, but in the
152    // second loop, it equals 'My friend'
153    $treatment = substr ( $remaining, 0, $start );
154    // Replacement of ' ' by his equivalent '&nbsp;'
155    $treatment = str_replace( ' ', '&nbsp;', $treatment );
156    $treatment = str_replace( '-', '&minus;', $treatment );
157    // composing the string to return by adding the treated string and the
158    // following HTML tag -> 'My&nbsp;friend</div>'
159    $return_string.= $treatment.substr( $remaining, $start, $end-$start+1 );
160    // the remaining string is deplaced to the part after the '>' of this
161    // loop
162    $remaining = substr ( $remaining, $end + 1, strlen( $remaining ) );
163    $start = strpos ( $remaining, '<' );
164    $end   = strpos ( $remaining, '>' );
165  }
166  $treatment = str_replace( ' ', '&nbsp;', $remaining );
167  $treatment = str_replace( '-', '&minus;', $treatment );
168  $return_string.= $treatment;
169
170  return $return_string;
171}
172
173// get_extension returns the part of the string after the last "."
174function get_extension( $filename )
175{
176  return substr( strrchr( $filename, '.' ), 1, strlen ( $filename ) );
177}
178
179// get_filename_wo_extension returns the part of the string before the last
180// ".".
181// get_filename_wo_extension( 'test.tar.gz' ) -> 'test.tar'
182function get_filename_wo_extension( $filename )
183{
184  return substr( $filename, 0, strrpos( $filename, '.' ) );
185}
186
187/**
188 * returns an array contening sub-directories, excluding "CVS"
189 *
190 * @param string $dir
191 * @return array
192 */
193function get_dirs($directory)
194{
195  $sub_dirs = array();
196
197  if ($opendir = opendir($directory))
198  {
199    while ($file = readdir($opendir))
200    {
201      if ($file != '.'
202          and $file != '..'
203          and is_dir($directory.'/'.$file)
204          and $file != 'CVS')
205      {
206        array_push($sub_dirs, $file);
207      }
208    }
209  }
210  return $sub_dirs;
211}
212
213// The get_picture_size function return an array containing :
214//      - $picture_size[0] : final width
215//      - $picture_size[1] : final height
216// The final dimensions are calculated thanks to the original dimensions and
217// the maximum dimensions given in parameters.  get_picture_size respects
218// the width/height ratio
219function get_picture_size( $original_width, $original_height,
220                           $max_width, $max_height )
221{
222  $width = $original_width;
223  $height = $original_height;
224  $is_original_size = true;
225               
226  if ( $max_width != "" )
227  {
228    if ( $original_width > $max_width )
229    {
230      $width = $max_width;
231      $height = floor( ( $width * $original_height ) / $original_width );
232    }
233  }
234  if ( $max_height != "" )
235  {
236    if ( $original_height > $max_height )
237    {
238      $height = $max_height;
239      $width = floor( ( $height * $original_width ) / $original_height );
240      $is_original_size = false;
241    }
242  }
243  if ( is_numeric( $max_width ) and is_numeric( $max_height )
244       and $max_width != 0 and $max_height != 0 )
245  {
246    $ratioWidth = $original_width / $max_width;
247    $ratioHeight = $original_height / $max_height;
248    if ( ( $ratioWidth > 1 ) or ( $ratioHeight > 1 ) )
249    {
250      if ( $ratioWidth < $ratioHeight )
251      { 
252        $width = floor( $original_width / $ratioHeight );
253        $height = $max_height;
254      }
255      else
256      { 
257        $width = $max_width; 
258        $height = floor( $original_height / $ratioWidth );
259      }
260      $is_original_size = false;
261    }
262  }
263  $picture_size = array();
264  $picture_size[0] = $width;
265  $picture_size[1] = $height;
266  return $picture_size;
267}
268//-------------------------------------------- PhpWebGallery specific functions
269
270/**
271 * returns an array with a list of {language_code => language_name}
272 *
273 * @returns array
274 */
275function get_languages()
276{
277  $dir = opendir(PHPWG_ROOT_PATH.'language');
278  $languages = array();
279
280  while ($file = readdir($dir))
281  {
282    $path = PHPWG_ROOT_PATH.'language/'.$file;
283    if (is_dir($path) and !is_link($path) and file_exists($path.'/iso.txt'))
284    {
285      list($language_name) = @file($path.'/iso.txt');
286      $languages[$file] = $language_name;
287    }
288  }
289  closedir($dir);
290  @asort($languages);
291  @reset($languages);
292
293  return $languages;
294}
295
296/**
297 * replaces the $search into <span style="$style">$search</span> in the
298 * given $string.
299 *
300 * case insensitive replacements, does not replace characters in HTML tags
301 *
302 * @param string $string
303 * @param string $search
304 * @param string $style
305 * @return string
306 */
307function add_style( $string, $search, $style )
308{
309  //return $string;
310  $return_string = '';
311  $remaining = $string;
312
313  $start = 0;
314  $end = 0;
315  $start = strpos ( $remaining, '<' );
316  $end   = strpos ( $remaining, '>' );
317  while ( is_numeric( $start ) and is_numeric( $end ) )
318  {
319    $treatment = substr ( $remaining, 0, $start );
320    $treatment = preg_replace( '/('.$search.')/i',
321                               '<span style="'.$style.'">\\0</span>',
322                               $treatment );
323    $return_string.= $treatment.substr( $remaining, $start, $end-$start+1 );
324    $remaining = substr ( $remaining, $end + 1, strlen( $remaining ) );
325    $start = strpos ( $remaining, '<' );
326    $end   = strpos ( $remaining, '>' );
327  }
328  $treatment = preg_replace( '/('.$search.')/i',
329                             '<span style="'.$style.'">\\0</span>',
330                             $remaining );
331  $return_string.= $treatment;
332               
333  return $return_string;
334}
335
336// replace_search replaces a searched words array string by the search in
337// another style for the given $string.
338function replace_search( $string, $search )
339{
340  // FIXME : with new advanced search, this function needs a rewrite
341  return $string;
342 
343  $words = explode( ',', $search );
344  $style = 'background-color:white;color:red;';
345  foreach ( $words as $word ) {
346    $string = add_style( $string, $word, $style );
347  }
348  return $string;
349}
350
351function pwg_log( $file, $category, $picture = '' )
352{
353  global $conf, $user;
354
355  if ($conf['log'])
356  {
357    $query = '
358INSERT INTO '.HISTORY_TABLE.'
359  (date,login,IP,file,category,picture)
360  VALUES
361  (NOW(),
362  \''.(($user['id'] == 2) ? 'guest' : addslashes($user['username'])).'\',
363  \''.$_SERVER['REMOTE_ADDR'].'\',
364  \''.addslashes($file).'\',
365  \''.addslashes($category).'\',
366  \''.addslashes($picture).'\')
367;';
368    pwg_query($query);
369  }
370}
371
372// format_date returns a formatted date for display. The date given in
373// argument can be a unixdate (number of seconds since the 01.01.1970) or an
374// american format (2003-09-15). By option, you can show the time. The
375// output is internationalized.
376//
377// format_date( "2003-09-15", 'us', true ) -> "Monday 15 September 2003 21:52"
378function format_date($date, $type = 'us', $show_time = false)
379{
380  global $lang;
381
382  list($year,$month,$day,$hour,$minute,$second) = array(0,0,0,0,0,0);
383 
384  switch ( $type )
385  {
386    case 'us' :
387    {
388      list($year,$month,$day) = explode('-', $date);
389      break;
390    }
391    case 'unix' :
392    {
393      list($year,$month,$day,$hour,$minute) =
394        explode('.', date('Y.n.j.G.i', $date));
395      break;
396    }
397    case 'mysql_datetime' :
398    {
399      preg_match('/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/',
400                 $date, $out);
401      list($year,$month,$day,$hour,$minute,$second) =
402        array($out[1],$out[2],$out[3],$out[4],$out[5],$out[6]);
403      break;
404    }
405  }
406  $formated_date = '';
407  // before 1970, Microsoft Windows can't mktime
408  if ($year >= 1970)
409  {
410    // we ask midday because Windows think it's prior to midnight with a
411    // zero and refuse to work
412    $formated_date.= $lang['day'][date('w', mktime(12,0,0,$month,$day,$year))];
413  }
414  $formated_date.= ' '.$day;
415  $formated_date.= ' '.$lang['month'][(int)$month];
416  $formated_date.= ' '.$year;
417  if ($show_time)
418  {
419    $formated_date.= ' '.$hour.':'.$minute;
420  }
421
422  return $formated_date;
423}
424
425function pwg_query($query)
426{
427  global $conf,$page;
428 
429  $start = get_moment();
430  $result = mysql_query($query) or my_error($query."\n");
431 
432  $time = get_moment() - $start;
433
434  if (!isset($page['count_queries']))
435  {
436    $page['count_queries'] = 0;
437    $page['queries_time'] = 0;
438  }
439 
440  $page['count_queries']++;
441  $page['queries_time']+= $time;
442 
443  if ($conf['show_queries'])
444  {
445    $output = '';
446    $output.= '<pre>['.$page['count_queries'].'] ';
447    $output.= "\n".$query;
448    $output.= "\n".'(this query time : ';
449    $output.= number_format($time, 3, '.', ' ').' s)</b>';
450    $output.= "\n".'(total SQL time  : ';
451    $output.= number_format($page['queries_time'], 3, '.', ' ').' s)';
452    $output.= '</pre>';
453   
454    echo $output;
455  }
456 
457  return $result;
458}
459
460function pwg_debug( $string )
461{
462  global $debug,$t2,$count_queries;
463
464  $now = explode( ' ', microtime() );
465  $now2 = explode( '.', $now[0] );
466  $now2 = $now[1].'.'.$now2[1];
467  $time = number_format( $now2 - $t2, 3, '.', ' ').' s';
468  $debug.= '['.$time.', ';
469  $debug.= $count_queries.' queries] : '.$string;
470  $debug.= "\n";
471}
472
473/**
474 * Redirects to the given URL
475 *
476 * Note : once this function called, the execution doesn't go further
477 * (presence of an exit() instruction.
478 *
479 * @param string $url
480 * @return void
481 */
482function redirect( $url )
483{
484  global $user, $template, $lang_info, $conf, $lang, $t2, $page;
485
486  // $refresh, $url_link and $title are required for creating an automated
487  // refresh page in header.tpl
488  $refresh = 0;
489  $url_link = $url;
490  $title = 'redirection';
491
492  include( PHPWG_ROOT_PATH.'include/page_header.php' );
493 
494  $template->set_filenames( array( 'redirect' => 'redirect.tpl' ) );
495  $template->parse('redirect');
496 
497  include( PHPWG_ROOT_PATH.'include/page_tail.php' );
498
499  exit();
500}
501
502/**
503 * returns $_SERVER['QUERY_STRING'] whitout keys given in parameters
504 *
505 * @param array $rejects
506 * @returns string
507 */
508function get_query_string_diff($rejects = array())
509{
510  $query_string = '';
511 
512  $str = $_SERVER['QUERY_STRING'];
513  parse_str($str, $vars);
514 
515  $is_first = true;
516  foreach ($vars as $key => $value)
517  {
518    if (!in_array($key, $rejects))
519    {
520      $query_string.= $is_first ? '?' : '&amp;';
521      $is_first = false;
522      $query_string.= $key.'='.$value;
523    }
524  }
525
526  return $query_string;
527}
528
529/**
530 * returns available templates
531 */
532function get_templates()
533{
534  return get_dirs(PHPWG_ROOT_PATH.'template');
535}
536
537/**
538 * returns thumbnail filepath (or distant URL if thumbnail is remote) for a
539 * given element
540 *
541 * the returned string can represente the filepath of the thumbnail or the
542 * filepath to the corresponding icon for non picture elements
543 *
544 * @param string path
545 * @param string tn_ext
546 * @return string
547 */
548function get_thumbnail_src($path, $tn_ext = '')
549{
550  global $conf, $user;
551
552  if ($tn_ext != '')
553  {
554    $src = substr_replace(get_filename_wo_extension($path),
555                          '/thumbnail/'.$conf['prefix_thumbnail'],
556                          strrpos($path,'/'),
557                          1);
558    $src.= '.'.$tn_ext;
559  }
560  else
561  {
562    $src = PHPWG_ROOT_PATH;
563    $src.= 'template/'.$user['template'].'/mimetypes/';
564    $src.= strtolower(get_extension($path)).'.png';
565  }
566 
567  return $src;
568}
569
570// my_error returns (or send to standard output) the message concerning the
571// error occured for the last mysql query.
572function my_error($header)
573{
574  $error = '<pre>';
575  $error.= $header;
576  $error.= '[mysql error '.mysql_errno().'] ';
577  $error.= mysql_error();
578  $error.= '</pre>';
579  die ($error);
580}
581
582/**
583 * creates an array based on a query, this function is a very common pattern
584 * used here
585 *
586 * @param string $query
587 * @param string $fieldname
588 * @return array
589 */
590function array_from_query($query, $fieldname)
591{
592  $array = array();
593 
594  $result = pwg_query($query);
595  while ($row = mysql_fetch_array($result))
596  {
597    array_push($array, $row[$fieldname]);
598  }
599
600  return $array;
601}
602
603/**
604 * instantiate number list for days in a template block
605 *
606 * @param string blockname
607 * @param string selection
608 */
609function get_day_list($blockname, $selection)
610{
611  global $template;
612 
613  $template->assign_block_vars(
614    $blockname, array('SELECTED' => '', 'VALUE' => 0, 'OPTION' => '--'));
615 
616  for ($i = 1; $i <= 31; $i++)
617  {
618    $selected = '';
619    if ($i == (int)$selection)
620    {
621      $selected = 'selected="selected"';
622    }
623    $template->assign_block_vars(
624      $blockname, array('SELECTED' => $selected,
625                        'VALUE' => $i,
626                        'OPTION' => str_pad($i, 2, '0', STR_PAD_LEFT)));
627  }
628}
629
630/**
631 * instantiate month list in a template block
632 *
633 * @param string blockname
634 * @param string selection
635 */
636function get_month_list($blockname, $selection)
637{
638  global $template, $lang;
639 
640  $template->assign_block_vars(
641    $blockname, array('SELECTED' => '',
642                      'VALUE' => 0,
643                      'OPTION' => '------------'));
644
645  for ($i = 1; $i <= 12; $i++)
646  {
647    $selected = '';
648    if ($i == (int)$selection)
649    {
650      $selected = 'selected="selected"';
651    }
652    $template->assign_block_vars(
653      $blockname, array('SELECTED' => $selected,
654                        'VALUE' => $i,
655                        'OPTION' => $lang['month'][$i]));
656  }
657}
658
659/**
660 * fill the current user caddie with given elements, if not already in
661 * caddie
662 *
663 * @param array elements_id
664 */
665function fill_caddie($elements_id)
666{
667  global $user;
668 
669  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
670 
671  $query = '
672SELECT element_id
673  FROM '.CADDIE_TABLE.'
674  WHERE user_id = '.$user['id'].'
675;';
676  $in_caddie = array_from_query($query, 'element_id');
677
678  $caddiables = array_diff($elements_id, $in_caddie);
679
680  $datas = array();
681
682  foreach ($caddiables as $caddiable)
683  {
684    array_push($datas, array('element_id' => $caddiable,
685                             'user_id' => $user['id']));
686  }
687
688  if (count($caddiables) > 0)
689  {
690    mass_inserts(CADDIE_TABLE, array('element_id','user_id'), $datas);
691  }
692}
693
694/**
695 * returns the element name from its filename
696 *
697 * @param string filename
698 * @return string name
699 */
700function get_name_from_file($filename)
701{
702  return str_replace('_',' ',get_filename_wo_extension($filename));
703}
704
705/**
706 * returns the corresponding value from $lang if existing. Else, the key is
707 * returned
708 *
709 * @param string key
710 * @return string
711 */
712function l10n($key)
713{
714  global $lang, $conf;
715
716  if ($conf['debug_l10n'] and !isset($lang[$key]))
717  {
718    echo '[l10n] language key "'.$key.'" is not defined<br />';
719  }
720 
721  return isset($lang[$key]) ? $lang[$key] : $key;
722}
723?>
Note: See TracBrowser for help on using the repository browser.