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

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