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

Last change on this file since 359 was 351, checked in by gweltas, 21 years ago

Template modification
Split of the french language file

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