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

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