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

Last change on this file since 362 was 362, checked in by z0rglub, 20 years ago

header global refactoring

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 15.9 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-02-11 23:20:38 +0000 (Wed, 11 Feb 2004) $
10// | last modifier : $Author: z0rglub $
11// | revision      : $Revision: 362 $
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// +-----------------------------------------------------------------------+
27include( PREFIX_INCLUDE.'./include/functions_user.inc.php' );
28include( PREFIX_INCLUDE.'./include/functions_session.inc.php' );
29include( PREFIX_INCLUDE.'./include/functions_category.inc.php' );
30include( PREFIX_INCLUDE.'./include/functions_xml.inc.php' );
31include( PREFIX_INCLUDE.'./include/functions_group.inc.php' );
32
33//----------------------------------------------------------- generic functions
34
35/**
36 * possible values of an "enum" field
37 *
38 * get_enums returns an array containing the possible values of a enum field
39 * in a table of the database.
40 *
41 * @param string table in the database
42 * @param string field name in this table
43 * @uses str_replace
44 * @uses explode
45 * @uses sizeof
46 * @uses substr
47 */
48function get_enums( $table, $field )
49{
50  // retrieving the properties of the table. Each line represents a field :
51  // columns are 'Field', 'Type'
52  $result=mysql_query("desc $table");
53  while ( $row = mysql_fetch_array( $result ) ) 
54  {
55    // we are only interested in the the field given in parameter for the
56    // function
57    if ( $row['Field']==$field )
58    {
59      // retrieving possible values of the enum field
60      // enum('blue','green','black')
61      $option = explode( ',', substr($row['Type'], 5, -1 ) );
62      for ( $i = 0; $i < sizeof( $option ); $i++ )
63      {
64        // deletion of quotation marks
65        $option[$i] = str_replace( "'", '',$option[$i] );
66      }                 
67    }
68  }
69  mysql_free_result( $result );
70  return $option;
71}
72
73// get_boolean transforms a string to a boolean value. If the string is
74// "false" (case insensitive), then the boolean value false is returned. In
75// any other case, true is returned.
76function get_boolean( $string )
77{
78  $boolean = true;
79  if ( preg_match( '/^false$/i', $string ) )
80  {
81    $boolean = false;
82  }
83  return $boolean;
84}
85
86// array_remove removes a value from the given array if the value existed in
87// this array.
88function array_remove( $array, $value )
89{
90  $output = array();
91  foreach ( $array as $v ) {
92    if ( $v != $value ) array_push( $output, $v );
93  }
94  return $output;
95}
96
97// The function get_moment returns a float value coresponding to the number
98// of seconds since the unix epoch (1st January 1970) and the microseconds
99// are precised : e.g. 1052343429.89276600
100function get_moment()
101{
102  $t1 = explode( ' ', microtime() );
103  $t2 = explode( '.', $t1[0] );
104  $t2 = $t1[1].'.'.$t2[1];
105  return $t2;
106}
107
108// The function get_elapsed_time returns the number of seconds (with 3
109// decimals precision) between the start time and the end time given.
110function get_elapsed_time( $start, $end )
111{
112  return number_format( $end - $start, 3, '.', ' ').' s';
113}
114
115// - The replace_space function replaces space and '-' characters
116//   by their HTML equivalent  &nbsb; and &minus;
117// - The function does not replace characters in HTML tags
118// - This function was created because IE5 does not respect the
119//   CSS "white-space: nowrap;" property unless space and minus
120//   characters are replaced like this function does.
121// - Example :
122//                 <div class="foo">My friend</div>
123//               ( 01234567891111111111222222222233 )
124//               (           0123456789012345678901 )
125// becomes :
126//             <div class="foo">My&nbsp;friend</div>
127function replace_space( $string )
128{
129  //return $string;
130  $return_string = '';
131  // $remaining is the rest of the string where to replace spaces characters
132  $remaining = $string;
133  // $start represents the position of the next '<' character
134  // $end   represents the position of the next '>' character
135  $start = 0;
136  $end = 0;
137  $start = strpos ( $remaining, '<' ); // -> 0
138  $end   = strpos ( $remaining, '>' ); // -> 16
139  // as long as a '<' and his friend '>' are found, we loop
140  while ( is_numeric( $start ) and is_numeric( $end ) )
141  {
142    // $treatment is the part of the string to treat
143    // In the first loop of our example, this variable is empty, but in the
144    // second loop, it equals 'My friend'
145    $treatment = substr ( $remaining, 0, $start );
146    // Replacement of ' ' by his equivalent '&nbsp;'
147    $treatment = str_replace( ' ', '&nbsp;', $treatment );
148    $treatment = str_replace( '-', '&minus;', $treatment );
149    // composing the string to return by adding the treated string and the
150    // following HTML tag -> 'My&nbsp;friend</div>'
151    $return_string.= $treatment.substr( $remaining, $start, $end-$start+1 );
152    // the remaining string is deplaced to the part after the '>' of this
153    // loop
154    $remaining = substr ( $remaining, $end + 1, strlen( $remaining ) );
155    $start = strpos ( $remaining, '<' );
156    $end   = strpos ( $remaining, '>' );
157  }
158  $treatment = str_replace( ' ', '&nbsp;', $remaining );
159  $treatment = str_replace( '-', '&minus;', $treatment );
160  $return_string.= $treatment;
161
162  return $return_string;
163}
164
165// get_extension returns the part of the string after the last "."
166function get_extension( $filename )
167{
168  return substr( strrchr( $filename, '.' ), 1, strlen ( $filename ) );
169}
170
171// get_filename_wo_extension returns the part of the string before the last
172// ".".
173// get_filename_wo_extension( 'test.tar.gz' ) -> 'test.tar'
174function get_filename_wo_extension( $filename )
175{
176  return substr( $filename, 0, strrpos( $filename, '.' ) );
177}
178
179/**
180 * returns an array contening sub-directories
181 *
182 * @param string $dir
183 * @return array
184 */
185function get_dirs( $directory )
186{
187  $sub_dirs = array();
188
189  if ( $opendir = opendir( $directory ) )
190  {
191    while ( $file = readdir ( $opendir ) )
192    {
193      if ( $file != '.' and $file != '..' and is_dir ( $directory.'/'.$file ) )
194      {
195        array_push( $sub_dirs, $file );
196      }
197    }
198  }
199  return $sub_dirs;
200}
201
202// The get_picture_size function return an array containing :
203//      - $picture_size[0] : final width
204//      - $picture_size[1] : final height
205// The final dimensions are calculated thanks to the original dimensions and
206// the maximum dimensions given in parameters.  get_picture_size respects
207// the width/height ratio
208function get_picture_size( $original_width, $original_height,
209                           $max_width, $max_height )
210{
211  $width = $original_width;
212  $height = $original_height;
213  $is_original_size = true;
214               
215  if ( $max_width != "" )
216  {
217    if ( $original_width > $max_width )
218    {
219      $width = $max_width;
220      $height = floor( ( $width * $original_height ) / $original_width );
221    }
222  }
223  if ( $max_height != "" )
224  {
225    if ( $original_height > $max_height )
226    {
227      $height = $max_height;
228      $width = floor( ( $height * $original_width ) / $original_height );
229      $is_original_size = false;
230    }
231  }
232  if ( is_numeric( $max_width ) and is_numeric( $max_height )
233       and $max_width != 0 and $max_height != 0 )
234  {
235    $ratioWidth = $original_width / $max_width;
236    $ratioHeight = $original_height / $max_height;
237    if ( ( $ratioWidth > 1 ) or ( $ratioHeight > 1 ) )
238    {
239      if ( $ratioWidth < $ratioHeight )
240      { 
241        $width = floor( $original_width / $ratioHeight );
242        $height = $max_height;
243      }
244      else
245      { 
246        $width = $max_width; 
247        $height = floor( $original_height / $ratioWidth );
248      }
249      $is_original_size = false;
250    }
251  }
252  $picture_size = array();
253  $picture_size[0] = $width;
254  $picture_size[1] = $height;
255  return $picture_size;
256}
257//-------------------------------------------- PhpWebGallery specific functions
258
259// get_languages retourne un tableau contenant tous les languages
260// disponibles pour PhpWebGallery
261function get_languages( $rep_language )
262{
263  $languages = array();
264  $i = 0;
265  if ( $opendir = opendir ( $rep_language ) )
266  {
267    while ( $file = readdir ( $opendir ) )
268    {
269      if ( is_dir ( $rep_language.$file )&& !substr_count($file,'.') )
270      {
271        $languages[$i++] =$file;
272      }
273    }
274  }
275  return $languages;
276}
277
278// - add_style replaces the
279//         $search  into <span style="$style">$search</span>
280// in the given $string.
281// - The function does not replace characters in HTML tags
282function add_style( $string, $search, $style )
283{
284  //return $string;
285  $return_string = '';
286  $remaining = $string;
287
288  $start = 0;
289  $end = 0;
290  $start = strpos ( $remaining, '<' );
291  $end   = strpos ( $remaining, '>' );
292  while ( is_numeric( $start ) and is_numeric( $end ) )
293  {
294    $treatment = substr ( $remaining, 0, $start );
295    $treatment = str_replace( $search, '<span style="'.$style.'">'.
296                              $search.'</span>', $treatment );
297    $return_string.= $treatment.substr( $remaining, $start, $end-$start+1 );
298    $remaining = substr ( $remaining, $end + 1, strlen( $remaining ) );
299    $start = strpos ( $remaining, '<' );
300    $end   = strpos ( $remaining, '>' );
301  }
302  $treatment = str_replace( $search, '<span style="'.$style.'">'.
303                            $search.'</span>', $remaining );
304  $return_string.= $treatment;
305               
306  return $return_string;
307}
308
309// replace_search replaces a searched words array string by the search in
310// another style for the given $string.
311function replace_search( $string, $search )
312{
313  $words = explode( ',', $search );
314  $style = 'background-color:white;color:red;';
315  foreach ( $words as $word ) {
316    $string = add_style( $string, $word, $style );
317  }
318  return $string;
319}
320
321function pwg_log( $file, $category, $picture = '' )
322{
323  global $conf, $user;
324
325  if ( $conf['log'] )
326  {
327    $query = 'insert into '.PREFIX_TABLE.'history';
328    $query.= ' (date,login,IP,file,category,picture) values';
329    $query.= " (".time().", '".$user['username']."'";
330    $query.= ",'".$_SERVER['REMOTE_ADDR']."'";
331    $query.= ",'".$file."','".$category."','".$picture."');";
332    mysql_query( $query );
333  }
334}
335
336function templatize_array( $array, $global_array_name, $handle )
337{
338  global $vtp, $lang, $page, $user, $conf;
339
340  foreach ( $array as $value ) {
341  if (isset(${$global_array_name}[$value]))
342    $vtp->setGlobalVar( $handle, $value, ${$global_array_name}[$value] );
343  }
344}
345
346// format_date returns a formatted date for display. The date given in
347// argument can be a unixdate (number of seconds since the 01.01.1970) or an
348// american format (2003-09-15). By option, you can show the time. The
349// output is internationalized.
350//
351// format_date( "2003-09-15", 'us', true ) -> "Monday 15 September 2003 21:52"
352function format_date( $date, $type = 'us', $show_time = false )
353{
354  global $lang;
355
356  switch ( $type )
357  {
358  case 'us' :
359    list( $year,$month,$day ) = explode( '-', $date );
360    $unixdate = mktime(0,0,0,$month,$day,$year);
361    break;
362  case 'unix' :
363    $unixdate = $date;
364    break;
365  }
366  $formated_date = $lang['day'][date( "w", $unixdate )];
367  $formated_date.= date( " j ", $unixdate );
368  $formated_date.= $lang['month'][date( "n", $unixdate )];
369  $formated_date.= date( ' Y', $unixdate );
370  if ( $show_time )
371  {
372    $formated_date.= date( ' G:i', $unixdate );
373  }
374
375  return $formated_date;
376}
377
378// notify sends a email to every admin of the gallery
379function notify( $type, $infos = '' )
380{
381  global $conf;
382
383  $headers = 'From: '.$conf['webmaster'].' <'.$conf['mail_webmaster'].'>'."\n";
384  $headers.= 'Reply-To: '.$conf['mail_webmaster']."\n";
385  $headers.= 'X-Mailer: PhpWebGallery, PHP '.phpversion();
386
387  $options = '-f '.$conf['mail_webmaster'];
388  // retrieving all administrators
389  $query = 'SELECT username,mail_address,language';
390  $query.= ' FROM '.PREFIX_TABLE.'users';
391  $query.= " WHERE status = 'admin'";
392  $query.= ' AND mail_address IS NOT NULL';
393  $query.= ';';
394  $result = mysql_query( $query );
395  while ( $row = mysql_fetch_array( $result ) )
396  {
397    $to = $row['mail_address'];
398    include( PREFIX_INCLUDE.'./language/'.$row['language'].'.php' );
399    $content = $lang['mail_hello']."\n\n";
400    switch ( $type )
401    {
402    case 'upload' :
403      $subject = $lang['mail_new_upload_subject'];
404      $content.= $lang['mail_new_upload_content'];
405      break;
406    case 'comment' :
407      $subject = $lang['mail_new_comment_subject'];
408      $content.= $lang['mail_new_comment_content'];
409      break;
410    }
411    $infos = str_replace( '&nbsp;',  ' ', $infos );
412    $infos = str_replace( '&minus;', '-', $infos );
413    $content.= "\n\n".$infos;
414    $content.= "\n\n-- \nPhpWebGallery ".$conf['version'];
415    $content = wordwrap( $content, 72 );
416    @mail( $to, $subject, $content, $headers, $options );
417  }
418}
419
420function pwg_write_debug()
421{
422  global $debug;
423 
424  $fp = @fopen( './log/debug.log', 'a+' );
425  fwrite( $fp, "\n\n" );
426  fwrite( $fp, $debug );
427  fclose( $fp );
428}
429
430function pwg_query( $query )
431{
432  global $count_queries,$queries_time;
433
434  $start = get_moment();
435  $output = '';
436 
437  $count_queries++;
438  $output.= '<br /><br />['.$count_queries.'] '.$query;
439  $result = mysql_query( $query );
440  $time = get_moment() - $start;
441  $queries_time+= $time;
442  $output.= '<b>('.number_format( $time, 3, '.', ' ').' s)</b>';
443  $output.= '('.number_format( $queries_time, 3, '.', ' ').' s)';
444
445  // echo $output;
446 
447  return $result;
448}
449
450function pwg_debug( $string )
451{
452  global $debug,$t2,$count_queries;
453
454  $now = explode( ' ', microtime() );
455  $now2 = explode( '.', $now[0] );
456  $now2 = $now[1].'.'.$now2[1];
457  $time = number_format( $now2 - $t2, 3, '.', ' ').' s';
458  $debug.= '['.$time.', ';
459  $debug.= $count_queries.' queries] : '.$string;
460  $debug.= "\n";
461}
462
463//
464// Initialise user settings on page load
465function init_userprefs($userdata)
466{
467        global $conf, $template, $lang, $phpwg_root_path;
468       
469        $style = $conf['default_style'];
470        if ( !$userdata['is_the_guest'] )
471        {
472                if ( !empty($userdata['language']))
473                {
474                        $conf['default_lang'] = $userdata['language'];
475                }
476                if ( !empty($userdata['template']))
477                {
478                        $style = $userdata['template'];
479                }
480        }
481
482        if ( !file_exists(@realpath($phpwg_root_path . 'language/' . $conf['default_lang'] . '/lang_main.php')) )
483        {
484                $conf['default_lang'] = 'english';
485        }
486       
487        include_once($phpwg_root_path . 'language/' . $conf['default_lang'] . '/lang_main.php');
488        $template= setup_style($style);
489
490        return;
491}
492
493function setup_style($style)
494{
495        global $phpwg_root_path;
496
497        $template_path = 'template/' ;
498        $template_name = $style ;
499
500        $template = new Template($phpwg_root_path . $template_path . $template_name);
501        return $template;
502}
503
504function encode_ip($dotquad_ip)
505{
506        $ip_sep = explode('.', $dotquad_ip);
507        return sprintf('%02x%02x%02x%02x', $ip_sep[0], $ip_sep[1], $ip_sep[2], $ip_sep[3]);
508}
509
510function decode_ip($int_ip)
511{
512        $hexipbang = explode('.', chunk_split($int_ip, 2, '.'));
513        return hexdec($hexipbang[0]). '.' . hexdec($hexipbang[1]) . '.' . hexdec($hexipbang[2]) . '.' . hexdec($hexipbang[3]);
514}
515
516?>
Note: See TracBrowser for help on using the repository browser.