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

Last change on this file since 537 was 537, checked in by gweltas, 20 years ago

-First draft of history display

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 16.4 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// |                           functions.inc.php                           |
4// +-----------------------------------------------------------------------+
5// | application   : PhpWebGallery <http://phpwebgallery.net>              |
6// | branch        : BSF (Best So Far)                                     |
7// +-----------------------------------------------------------------------+
8// | file          : $RCSfile$
9// | last update   : $Date: 2004-09-26 21:24:49 +0000 (Sun, 26 Sep 2004) $
10// | last modifier : $Author: gweltas $
11// | revision      : $Revision: 537 $
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=mysql_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// array_remove removes a value from the given array if the value existed in
89// this array.
90function array_remove( $array, $value )
91{
92  $output = array();
93  foreach ( $array as $v ) {
94    if ( $v != $value ) array_push( $output, $v );
95  }
96  return $output;
97}
98
99// The function get_moment returns a float value coresponding to the number
100// of seconds since the unix epoch (1st January 1970) and the microseconds
101// are precised : e.g. 1052343429.89276600
102function get_moment()
103{
104  $t1 = explode( ' ', microtime() );
105  $t2 = explode( '.', $t1[0] );
106  $t2 = $t1[1].'.'.$t2[1];
107  return $t2;
108}
109
110// The function get_elapsed_time returns the number of seconds (with 3
111// decimals precision) between the start time and the end time given.
112function get_elapsed_time( $start, $end )
113{
114  return number_format( $end - $start, 3, '.', ' ').' s';
115}
116
117// - The replace_space function replaces space and '-' characters
118//   by their HTML equivalent  &nbsb; and &minus;
119// - The function does not replace characters in HTML tags
120// - This function was created because IE5 does not respect the
121//   CSS "white-space: nowrap;" property unless space and minus
122//   characters are replaced like this function does.
123// - Example :
124//                 <div class="foo">My friend</div>
125//               ( 01234567891111111111222222222233 )
126//               (           0123456789012345678901 )
127// becomes :
128//             <div class="foo">My&nbsp;friend</div>
129function replace_space( $string )
130{
131  //return $string;
132  $return_string = '';
133  // $remaining is the rest of the string where to replace spaces characters
134  $remaining = $string;
135  // $start represents the position of the next '<' character
136  // $end   represents the position of the next '>' character
137  $start = 0;
138  $end = 0;
139  $start = strpos ( $remaining, '<' ); // -> 0
140  $end   = strpos ( $remaining, '>' ); // -> 16
141  // as long as a '<' and his friend '>' are found, we loop
142  while ( is_numeric( $start ) and is_numeric( $end ) )
143  {
144    // $treatment is the part of the string to treat
145    // In the first loop of our example, this variable is empty, but in the
146    // second loop, it equals 'My friend'
147    $treatment = substr ( $remaining, 0, $start );
148    // Replacement of ' ' by his equivalent '&nbsp;'
149    $treatment = str_replace( ' ', '&nbsp;', $treatment );
150    $treatment = str_replace( '-', '&minus;', $treatment );
151    // composing the string to return by adding the treated string and the
152    // following HTML tag -> 'My&nbsp;friend</div>'
153    $return_string.= $treatment.substr( $remaining, $start, $end-$start+1 );
154    // the remaining string is deplaced to the part after the '>' of this
155    // loop
156    $remaining = substr ( $remaining, $end + 1, strlen( $remaining ) );
157    $start = strpos ( $remaining, '<' );
158    $end   = strpos ( $remaining, '>' );
159  }
160  $treatment = str_replace( ' ', '&nbsp;', $remaining );
161  $treatment = str_replace( '-', '&minus;', $treatment );
162  $return_string.= $treatment;
163
164  return $return_string;
165}
166
167// get_extension returns the part of the string after the last "."
168function get_extension( $filename )
169{
170  return substr( strrchr( $filename, '.' ), 1, strlen ( $filename ) );
171}
172
173// get_filename_wo_extension returns the part of the string before the last
174// ".".
175// get_filename_wo_extension( 'test.tar.gz' ) -> 'test.tar'
176function get_filename_wo_extension( $filename )
177{
178  return substr( $filename, 0, strrpos( $filename, '.' ) );
179}
180
181/**
182 * returns an array contening sub-directories, excluding "CVS"
183 *
184 * @param string $dir
185 * @return array
186 */
187function get_dirs($directory)
188{
189  $sub_dirs = array();
190
191  if ($opendir = opendir($directory))
192  {
193    while ($file = readdir($opendir))
194    {
195      if ($file != '.'
196          and $file != '..'
197          and is_dir($directory.'/'.$file)
198          and $file != 'CVS')
199      {
200        array_push($sub_dirs, $file);
201      }
202    }
203  }
204  return $sub_dirs;
205}
206
207// The get_picture_size function return an array containing :
208//      - $picture_size[0] : final width
209//      - $picture_size[1] : final height
210// The final dimensions are calculated thanks to the original dimensions and
211// the maximum dimensions given in parameters.  get_picture_size respects
212// the width/height ratio
213function get_picture_size( $original_width, $original_height,
214                           $max_width, $max_height )
215{
216  $width = $original_width;
217  $height = $original_height;
218  $is_original_size = true;
219               
220  if ( $max_width != "" )
221  {
222    if ( $original_width > $max_width )
223    {
224      $width = $max_width;
225      $height = floor( ( $width * $original_height ) / $original_width );
226    }
227  }
228  if ( $max_height != "" )
229  {
230    if ( $original_height > $max_height )
231    {
232      $height = $max_height;
233      $width = floor( ( $height * $original_width ) / $original_height );
234      $is_original_size = false;
235    }
236  }
237  if ( is_numeric( $max_width ) and is_numeric( $max_height )
238       and $max_width != 0 and $max_height != 0 )
239  {
240    $ratioWidth = $original_width / $max_width;
241    $ratioHeight = $original_height / $max_height;
242    if ( ( $ratioWidth > 1 ) or ( $ratioHeight > 1 ) )
243    {
244      if ( $ratioWidth < $ratioHeight )
245      { 
246        $width = floor( $original_width / $ratioHeight );
247        $height = $max_height;
248      }
249      else
250      { 
251        $width = $max_width; 
252        $height = floor( $original_height / $ratioWidth );
253      }
254      $is_original_size = false;
255    }
256  }
257  $picture_size = array();
258  $picture_size[0] = $width;
259  $picture_size[1] = $height;
260  return $picture_size;
261}
262//-------------------------------------------- PhpWebGallery specific functions
263
264/**
265 * returns an array with a list of {language_code => language_name}
266 *
267 * @returns array
268 */
269function get_languages()
270{
271  $dir = opendir(PHPWG_ROOT_PATH.'language');
272  $languages = array();
273
274  while ($file = readdir($dir))
275  {
276    $path = realpath(PHPWG_ROOT_PATH.'language/'.$file);
277    if (is_dir($path) and !is_link($path) and file_exists($path.'/iso.txt'))
278    {
279      list($language_name) = @file($path.'/iso.txt');
280      $languages[$file] = $language_name;
281    }
282  }
283  closedir($dir);
284  @asort($languages);
285  @reset($languages);
286
287  return $languages;
288}
289
290/**
291 * replaces the $search into <span style="$style">$search</span> in the
292 * given $string.
293 *
294 * case insensitive replacements, does not replace characters in HTML tags
295 *
296 * @param string $string
297 * @param string $search
298 * @param string $style
299 * @return string
300 */
301function add_style( $string, $search, $style )
302{
303  //return $string;
304  $return_string = '';
305  $remaining = $string;
306
307  $start = 0;
308  $end = 0;
309  $start = strpos ( $remaining, '<' );
310  $end   = strpos ( $remaining, '>' );
311  while ( is_numeric( $start ) and is_numeric( $end ) )
312  {
313    $treatment = substr ( $remaining, 0, $start );
314    $treatment = preg_replace( '/('.$search.')/i',
315                               '<span style="'.$style.'">\\0</span>',
316                               $treatment );
317    $return_string.= $treatment.substr( $remaining, $start, $end-$start+1 );
318    $remaining = substr ( $remaining, $end + 1, strlen( $remaining ) );
319    $start = strpos ( $remaining, '<' );
320    $end   = strpos ( $remaining, '>' );
321  }
322  $treatment = preg_replace( '/('.$search.')/i',
323                             '<span style="'.$style.'">\\0</span>',
324                             $remaining );
325  $return_string.= $treatment;
326               
327  return $return_string;
328}
329
330// replace_search replaces a searched words array string by the search in
331// another style for the given $string.
332function replace_search( $string, $search )
333{
334  $words = explode( ',', $search );
335  $style = 'background-color:white;color:red;';
336  foreach ( $words as $word ) {
337    $string = add_style( $string, $word, $style );
338  }
339  return $string;
340}
341
342function pwg_log( $file, $category, $picture = '' )
343{
344  global $conf, $user;
345
346  if ( $conf['log'] )
347  {
348    $query = 'insert into '.HISTORY_TABLE;
349    $query.= ' (date,login,IP,file,category,picture) values';
350    $query.= " (NOW(), '".$user['username']."'";
351    $query.= ",'".$_SERVER['REMOTE_ADDR']."'";
352    $query.= ",'".$file."','".$category."','".$picture."');";
353    mysql_query( $query );
354  }
355}
356
357// format_date returns a formatted date for display. The date given in
358// argument can be a unixdate (number of seconds since the 01.01.1970) or an
359// american format (2003-09-15). By option, you can show the time. The
360// output is internationalized.
361//
362// format_date( "2003-09-15", 'us', true ) -> "Monday 15 September 2003 21:52"
363function format_date( $date, $type = 'us', $show_time = false )
364{
365  global $lang;
366
367  switch ( $type )
368  {
369  case 'us' :
370    list( $year,$month,$day ) = explode( '-', $date );
371    $unixdate = mktime(0,0,0,$month,$day,$year);
372    break;
373  case 'unix' :
374    $unixdate = $date;
375    break;
376  case 'mysql_datetime' :
377    preg_match( '/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/',
378                $date, $matches );
379    $unixdate = mktime($matches[4],$matches[5],$matches[6],
380                       $matches[2],$matches[3],$matches[1]);
381    break;
382  }
383  $formated_date = $lang['day'][date( "w", $unixdate )];
384  $formated_date.= date( " j ", $unixdate );
385  $formated_date.= $lang['month'][date( "n", $unixdate )];
386  $formated_date.= date( ' Y', $unixdate );
387  if ( $show_time )
388  {
389    $formated_date.= date( ' G:i', $unixdate );
390  }
391
392  return $formated_date;
393}
394
395// notify sends a email to every admin of the gallery
396function notify( $type, $infos = '' )
397{
398  global $conf;
399
400  $headers = 'From: '.$conf['webmaster'].' <'.$conf['mail_webmaster'].'>'."\n";
401  $headers.= 'Reply-To: '.$conf['mail_webmaster']."\n";
402  $headers.= 'X-Mailer: PhpWebGallery, PHP '.phpversion();
403
404  $options = '-f '.$conf['mail_webmaster'];
405  // retrieving all administrators
406  $query = 'SELECT username,mail_address,language';
407  $query.= ' FROM '.USERS_TABLE;
408  $query.= " WHERE status = 'admin'";
409  $query.= ' AND mail_address IS NOT NULL';
410  $query.= ';';
411  $result = mysql_query( $query );
412  while ( $row = mysql_fetch_array( $result ) )
413  {
414    $to = $row['mail_address'];
415    include( PHPWG_ROOT_PATH.'language/'.$row['language'].'/common.lang.php' );
416    $content = $lang['mail_hello']."\n\n";
417    switch ( $type )
418    {
419    case 'upload' :
420      $subject = $lang['mail_new_upload_subject'];
421      $content.= $lang['mail_new_upload_content'];
422      break;
423    case 'comment' :
424      $subject = $lang['mail_new_comment_subject'];
425      $content.= $lang['mail_new_comment_content'];
426      break;
427    }
428    $infos = str_replace( '&nbsp;',  ' ', $infos );
429    $infos = str_replace( '&minus;', '-', $infos );
430    $content.= "\n\n".$infos;
431    $content.= "\n\n-- \nPhpWebGallery ".$conf['version'];
432    $content = wordwrap( $content, 72 );
433    @mail( $to, $subject, $content, $headers, $options );
434  }
435}
436
437function pwg_write_debug()
438{
439  global $debug;
440 
441  $fp = @fopen( './log/debug.log', 'a+' );
442  fwrite( $fp, "\n\n" );
443  fwrite( $fp, $debug );
444  fclose( $fp );
445}
446
447function pwg_query( $query )
448{
449  global $count_queries,$queries_time;
450
451  $start = get_moment();
452  $output = '';
453 
454  $count_queries++;
455  $output.= '<br /><br />['.$count_queries.'] '.$query;
456  $result = mysql_query( $query );
457  $time = get_moment() - $start;
458  $queries_time+= $time;
459  $output.= '<b>('.number_format( $time, 3, '.', ' ').' s)</b>';
460  $output.= '('.number_format( $queries_time, 3, '.', ' ').' s)';
461
462  // echo $output;
463 
464  return $result;
465}
466
467function pwg_debug( $string )
468{
469  global $debug,$t2,$count_queries;
470
471  $now = explode( ' ', microtime() );
472  $now2 = explode( '.', $now[0] );
473  $now2 = $now[1].'.'.$now2[1];
474  $time = number_format( $now2 - $t2, 3, '.', ' ').' s';
475  $debug.= '['.$time.', ';
476  $debug.= $count_queries.' queries] : '.$string;
477  $debug.= "\n";
478}
479
480/**
481 * Redirects to the given URL
482 *
483 * Note : once this function called, the execution doesn't go further
484 * (presence of an exit() instruction.
485 *
486 * @param string $url
487 * @return void
488 */
489function redirect( $url )
490{
491  global $user, $template, $lang_info, $conf, $lang, $t2;
492
493  // $refresh, $url_link and $title are required for creating an automated
494  // refresh page in header.tpl
495  $refresh = 1;
496  $url_link = $url;
497  $title = 'redirection';
498  include( PHPWG_ROOT_PATH.'include/page_header.php' );
499 
500  $template->set_filenames( array( 'redirect' => 'redirect.tpl' ) );
501  $template->pparse('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      if ($is_first)
527      {
528        $query_string.= '?';
529        $is_first = false;
530      }
531      else
532      {
533        $query_string.= '&amp;';
534      }
535      $query_string.= $key.'='.$value;
536    }
537  }
538
539  return $query_string;
540}
541
542/**
543 * returns available templates
544 */
545function get_templates()
546{
547  return get_dirs(PHPWG_ROOT_PATH.'template');
548}
549?>
Note: See TracBrowser for help on using the repository browser.