source: tags/release-1_4_0RC2/include/functions.inc.php @ 16883

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