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

Last change on this file since 894 was 894, checked in by volcom, 19 years ago
  • new: history details by month,day
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 19.5 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-10-17 07:21:30 +0000 (Mon, 17 Oct 2005) $
10// | last modifier : $Author: volcom $
11// | revision      : $Revision: 894 $
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   if ( ($conf['history_admin'] ) or  ( (! $conf['history_admin'])  and ($user['status'] != 'admin')  ) )
358          {
359    $login = ($user['id'] == $conf['guest_id'])
360      ? 'guest' : addslashes($user['username']);
361   
362    $query = '
363INSERT INTO '.HISTORY_TABLE.'
364  (date,login,IP,file,category,picture)
365  VALUES
366  (NOW(),
367  \''.$login.'\',
368  \''.$_SERVER['REMOTE_ADDR'].'\',
369  \''.addslashes($file).'\',
370  \''.addslashes(strip_tags($category)).'\',
371  \''.addslashes($picture).'\')
372;';
373    pwg_query($query);
374  }
375  }
376}
377
378// format_date returns a formatted date for display. The date given in
379// argument can be a unixdate (number of seconds since the 01.01.1970) or an
380// american format (2003-09-15). By option, you can show the time. The
381// output is internationalized.
382//
383// format_date( "2003-09-15", 'us', true ) -> "Monday 15 September 2003 21:52"
384function format_date($date, $type = 'us', $show_time = false)
385{
386  global $lang;
387
388  list($year,$month,$day,$hour,$minute,$second) = array(0,0,0,0,0,0);
389 
390  switch ( $type )
391  {
392    case 'us' :
393    {
394      list($year,$month,$day) = explode('-', $date);
395      break;
396    }
397    case 'unix' :
398    {
399      list($year,$month,$day,$hour,$minute) =
400        explode('.', date('Y.n.j.G.i', $date));
401      break;
402    }
403    case 'mysql_datetime' :
404    {
405      preg_match('/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/',
406                 $date, $out);
407      list($year,$month,$day,$hour,$minute,$second) =
408        array($out[1],$out[2],$out[3],$out[4],$out[5],$out[6]);
409      break;
410    }
411  }
412  $formated_date = '';
413  // before 1970, Microsoft Windows can't mktime
414  if ($year >= 1970)
415  {
416    // we ask midday because Windows think it's prior to midnight with a
417    // zero and refuse to work
418    $formated_date.= $lang['day'][date('w', mktime(12,0,0,$month,$day,$year))];
419  }
420  $formated_date.= ' '.$day;
421  $formated_date.= ' '.$lang['month'][(int)$month];
422  $formated_date.= ' '.$year;
423  if ($show_time)
424  {
425    $formated_date.= ' '.$hour.':'.$minute;
426  }
427
428  return $formated_date;
429}
430
431function pwg_query($query)
432{
433  global $conf,$page;
434 
435  $start = get_moment();
436  $result = mysql_query($query) or my_error($query."\n");
437 
438  $time = get_moment() - $start;
439
440  if (!isset($page['count_queries']))
441  {
442    $page['count_queries'] = 0;
443    $page['queries_time'] = 0;
444  }
445 
446  $page['count_queries']++;
447  $page['queries_time']+= $time;
448 
449  if ($conf['show_queries'])
450  {
451    $output = '';
452    $output.= '<pre>['.$page['count_queries'].'] ';
453    $output.= "\n".$query;
454    $output.= "\n".'(this query time : ';
455    $output.= number_format($time, 3, '.', ' ').' s)</b>';
456    $output.= "\n".'(total SQL time  : ';
457    $output.= number_format($page['queries_time'], 3, '.', ' ').' s)';
458    $output.= '</pre>';
459   
460    echo $output;
461  }
462 
463  return $result;
464}
465
466function pwg_debug( $string )
467{
468  global $debug,$t2,$count_queries;
469
470  $now = explode( ' ', microtime() );
471  $now2 = explode( '.', $now[0] );
472  $now2 = $now[1].'.'.$now2[1];
473  $time = number_format( $now2 - $t2, 3, '.', ' ').' s';
474  $debug.= '['.$time.', ';
475  $debug.= $count_queries.' queries] : '.$string;
476  $debug.= "\n";
477}
478
479/**
480 * Redirects to the given URL
481 *
482 * Note : once this function called, the execution doesn't go further
483 * (presence of an exit() instruction.
484 *
485 * @param string $url
486 * @return void
487 */
488function redirect( $url )
489{
490  global $user, $template, $lang_info, $conf, $lang, $t2, $page;
491
492  // $refresh, $url_link and $title are required for creating an automated
493  // refresh page in header.tpl
494  $refresh = 0;
495  $url_link = $url;
496  $title = 'redirection';
497
498  include( PHPWG_ROOT_PATH.'include/page_header.php' );
499 
500  $template->set_filenames( array( 'redirect' => 'redirect.tpl' ) );
501  $template->parse('redirect');
502 
503  include( PHPWG_ROOT_PATH.'include/page_tail.php' );
504
505  exit();
506}
507
508/**
509 * returns $_SERVER['QUERY_STRING'] whitout keys given in parameters
510 *
511 * @param array $rejects
512 * @returns string
513 */
514function get_query_string_diff($rejects = array())
515{
516  $query_string = '';
517 
518  $str = $_SERVER['QUERY_STRING'];
519  parse_str($str, $vars);
520 
521  $is_first = true;
522  foreach ($vars as $key => $value)
523  {
524    if (!in_array($key, $rejects))
525    {
526      $query_string.= $is_first ? '?' : '&amp;';
527      $is_first = false;
528      $query_string.= $key.'='.$value;
529    }
530  }
531
532  return $query_string;
533}
534
535/**
536 * returns available templates
537 */
538function get_templates()
539{
540  return get_dirs(PHPWG_ROOT_PATH.'template');
541}
542
543/**
544 * returns thumbnail filepath (or distant URL if thumbnail is remote) for a
545 * given element
546 *
547 * the returned string can represente the filepath of the thumbnail or the
548 * filepath to the corresponding icon for non picture elements
549 *
550 * @param string path
551 * @param string tn_ext
552 * @return string
553 */
554function get_thumbnail_src($path, $tn_ext = '')
555{
556  global $conf, $user;
557
558  if ($tn_ext != '')
559  {
560    $src = substr_replace(get_filename_wo_extension($path),
561                          '/thumbnail/'.$conf['prefix_thumbnail'],
562                          strrpos($path,'/'),
563                          1);
564    $src.= '.'.$tn_ext;
565  }
566  else
567  {
568    $src = PHPWG_ROOT_PATH;
569    $src.= 'template/'.$user['template'].'/mimetypes/';
570    $src.= strtolower(get_extension($path)).'.png';
571  }
572 
573  return $src;
574}
575
576// my_error returns (or send to standard output) the message concerning the
577// error occured for the last mysql query.
578function my_error($header)
579{
580  $error = '<pre>';
581  $error.= $header;
582  $error.= '[mysql error '.mysql_errno().'] ';
583  $error.= mysql_error();
584  $error.= '</pre>';
585  die ($error);
586}
587
588/**
589 * creates an array based on a query, this function is a very common pattern
590 * used here
591 *
592 * @param string $query
593 * @param string $fieldname
594 * @return array
595 */
596function array_from_query($query, $fieldname)
597{
598  $array = array();
599 
600  $result = pwg_query($query);
601  while ($row = mysql_fetch_array($result))
602  {
603    array_push($array, $row[$fieldname]);
604  }
605
606  return $array;
607}
608
609/**
610 * instantiate number list for days in a template block
611 *
612 * @param string blockname
613 * @param string selection
614 */
615function get_day_list($blockname, $selection)
616{
617  global $template;
618 
619  $template->assign_block_vars(
620    $blockname, array('SELECTED' => '', 'VALUE' => 0, 'OPTION' => '--'));
621 
622  for ($i = 1; $i <= 31; $i++)
623  {
624    $selected = '';
625    if ($i == (int)$selection)
626    {
627      $selected = 'selected="selected"';
628    }
629    $template->assign_block_vars(
630      $blockname, array('SELECTED' => $selected,
631                        'VALUE' => $i,
632                        'OPTION' => str_pad($i, 2, '0', STR_PAD_LEFT)));
633  }
634}
635
636/**
637 * instantiate month list in a template block
638 *
639 * @param string blockname
640 * @param string selection
641 */
642function get_month_list($blockname, $selection)
643{
644  global $template, $lang;
645 
646  $template->assign_block_vars(
647    $blockname, array('SELECTED' => '',
648                      'VALUE' => 0,
649                      'OPTION' => '------------'));
650
651  for ($i = 1; $i <= 12; $i++)
652  {
653    $selected = '';
654    if ($i == (int)$selection)
655    {
656      $selected = 'selected="selected"';
657    }
658    $template->assign_block_vars(
659      $blockname, array('SELECTED' => $selected,
660                        'VALUE' => $i,
661                        'OPTION' => $lang['month'][$i]));
662  }
663}
664
665/**
666 * fill the current user caddie with given elements, if not already in
667 * caddie
668 *
669 * @param array elements_id
670 */
671function fill_caddie($elements_id)
672{
673  global $user;
674 
675  include_once(PHPWG_ROOT_PATH.'admin/include/functions.php');
676 
677  $query = '
678SELECT element_id
679  FROM '.CADDIE_TABLE.'
680  WHERE user_id = '.$user['id'].'
681;';
682  $in_caddie = array_from_query($query, 'element_id');
683
684  $caddiables = array_diff($elements_id, $in_caddie);
685
686  $datas = array();
687
688  foreach ($caddiables as $caddiable)
689  {
690    array_push($datas, array('element_id' => $caddiable,
691                             'user_id' => $user['id']));
692  }
693
694  if (count($caddiables) > 0)
695  {
696    mass_inserts(CADDIE_TABLE, array('element_id','user_id'), $datas);
697  }
698}
699
700/**
701 * returns the element name from its filename
702 *
703 * @param string filename
704 * @return string name
705 */
706function get_name_from_file($filename)
707{
708  return str_replace('_',' ',get_filename_wo_extension($filename));
709}
710
711/**
712 * returns the corresponding value from $lang if existing. Else, the key is
713 * returned
714 *
715 * @param string key
716 * @return string
717 */
718function l10n($key)
719{
720  global $lang, $conf;
721
722  if ($conf['debug_l10n'] and !isset($lang[$key]))
723  {
724    echo '[l10n] language key "'.$key.'" is not defined<br />';
725  }
726 
727  return isset($lang[$key]) ? $lang[$key] : $key;
728}
729?>
Note: See TracBrowser for help on using the repository browser.