Subversion Repositories svnkaklik

Rev

Go to most recent revision | Details | Last modification | View Log

Rev Author Line No. Line
6 kaklik 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: functions.inc.php,v $
9
// | last update   : $Date: 2005/05/02 20:44:27 $
10
// | last modifier : $Author: plg $
11
// | revision      : $Revision: 1.55.2.1 $
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
 
28
include_once( PHPWG_ROOT_PATH .'include/functions_user.inc.php' );
29
include_once( PHPWG_ROOT_PATH .'include/functions_session.inc.php' );
30
include_once( PHPWG_ROOT_PATH .'include/functions_category.inc.php' );
31
include_once( PHPWG_ROOT_PATH .'include/functions_xml.inc.php' );
32
include_once( PHPWG_ROOT_PATH .'include/functions_group.inc.php' );
33
include_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.
40
function 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
 */
56
function 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.
77
function 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
89
function 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.
99
function 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>
116
function 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 "."
155
function 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'
163
function 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
 */
174
function 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
200
function 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
 */
256
function get_languages()
257
{
258
  $dir = opendir(PHPWG_ROOT_PATH.'language');
259
  $languages = array();
260
 
261
  while ($file = readdir($dir))
262
  {
263
    $path = 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
 */
288
function 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.
319
function 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
 
332
function pwg_log( $file, $category, $picture = '' )
333
{
334
  global $conf, $user;
335
 
336
  if ($conf['log'])
337
  {
338
    $query = '
339
INSERT INTO '.HISTORY_TABLE.'
340
  (date,login,IP,file,category,picture)
341
  VALUES
342
  (NOW(),
343
  \''.(($user['id'] == 2) ? 'guest' : addslashes($user['username'])).'\',
344
  \''.$_SERVER['REMOTE_ADDR'].'\',
345
  \''.addslashes($file).'\',
346
  \''.addslashes($category).'\',
347
  \''.addslashes($picture).'\')
348
;';
349
    pwg_query($query);
350
  }
351
}
352
 
353
// format_date returns a formatted date for display. The date given in
354
// argument can be a unixdate (number of seconds since the 01.01.1970) or an
355
// american format (2003-09-15). By option, you can show the time. The
356
// output is internationalized.
357
//
358
// format_date( "2003-09-15", 'us', true ) -> "Monday 15 September 2003 21:52"
359
function format_date($date, $type = 'us', $show_time = false)
360
{
361
  global $lang;
362
 
363
  list($year,$month,$day,$hour,$minute,$second) = array(0,0,0,0,0,0);
364
 
365
  switch ( $type )
366
  {
367
    case 'us' :
368
    {
369
      list($year,$month,$day) = explode('-', $date);
370
      break;
371
    }
372
    case 'unix' :
373
    {
374
      list($year,$month,$day,$hour,$minute) =
375
        explode('.', date('Y.n.j.G.i', $date));
376
      break;
377
    }
378
    case 'mysql_datetime' :
379
    {
380
      preg_match('/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/',
381
                 $date, $out);
382
      list($year,$month,$day,$hour,$minute,$second) =
383
        array($out[1],$out[2],$out[3],$out[4],$out[5],$out[6]);
384
      break;
385
    }
386
  }
387
  $formated_date = '';
388
  // before 1970, Microsoft Windows can't mktime
389
  if ($year >= 1970)
390
  {
391
    // we ask midday because Windows think it's prior to midnight with a
392
    // zero and refuse to work
393
    $formated_date.= $lang['day'][date('w', mktime(12,0,0,$month,$day,$year))];
394
  }
395
  $formated_date.= ' '.$day;
396
  $formated_date.= ' '.$lang['month'][(int)$month];
397
  $formated_date.= ' '.$year;
398
  if ($show_time)
399
  {
400
    $formated_date.= ' '.$hour.':'.$minute;
401
  }
402
 
403
  return $formated_date;
404
}
405
 
406
// notify sends a email to every admin of the gallery
407
function notify( $type, $infos = '' )
408
{
409
  global $conf;
410
 
411
  $headers = 'From: <'.$conf['mail_webmaster'].'>'."\n";
412
  $headers.= 'Reply-To: '.$conf['mail_webmaster']."\n";
413
  $headers.= 'X-Mailer: PhpWebGallery, PHP '.phpversion();
414
 
415
  $options = '-f '.$conf['mail_webmaster'];
416
  // retrieving all administrators
417
  $query = 'SELECT username,mail_address,language';
418
  $query.= ' FROM '.USERS_TABLE;
419
  $query.= " WHERE status = 'admin'";
420
  $query.= ' AND mail_address IS NOT NULL';
421
  $query.= ';';
422
  $result = pwg_query( $query );
423
  while ( $row = mysql_fetch_array( $result ) )
424
  {
425
    $to = $row['mail_address'];
426
    include( PHPWG_ROOT_PATH.'language/'.$row['language'].'/common.lang.php' );
427
    $content = $lang['mail_hello']."\n\n";
428
    switch ( $type )
429
    {
430
    case 'upload' :
431
      $subject = $lang['mail_new_upload_subject'];
432
      $content.= $lang['mail_new_upload_content'];
433
      break;
434
    case 'comment' :
435
      $subject = $lang['mail_new_comment_subject'];
436
      $content.= $lang['mail_new_comment_content'];
437
      break;
438
    }
439
    $infos = str_replace( '&nbsp;',  ' ', $infos );
440
    $infos = str_replace( '&minus;', '-', $infos );
441
    $content.= "\n\n".$infos;
442
    $content.= "\n\n-- \nPhpWebGallery ".PHPWG_VERSION;
443
    $content = wordwrap( $content, 72 );
444
    @mail( $to, $subject, $content, $headers, $options );
445
  }
446
}
447
 
448
function pwg_write_debug()
449
{
450
  global $debug;
451
 
452
  $fp = @fopen( './log/debug.log', 'a+' );
453
  fwrite( $fp, "\n\n" );
454
  fwrite( $fp, $debug );
455
  fclose( $fp );
456
}
457
 
458
function pwg_query($query)
459
{
460
  global $conf,$page;
461
 
462
  $start = get_moment();
463
  $result = mysql_query($query) or my_error($query."\n");
464
 
465
  $time = get_moment() - $start;
466
 
467
  if (!isset($page['count_queries']))
468
  {
469
    $page['count_queries'] = 0;
470
    $page['queries_time'] = 0;
471
  }
472
 
473
  $page['count_queries']++;
474
  $page['queries_time']+= $time;
475
 
476
  if ($conf['show_queries'])
477
  {
478
    $output = '';
479
    $output.= '<pre>['.$page['count_queries'].'] ';
480
    $output.= "\n".$query;
481
    $output.= "\n".'(this query time : ';
482
    $output.= number_format($time, 3, '.', ' ').' s)</b>';
483
    $output.= "\n".'(total SQL time  : ';
484
    $output.= number_format($page['queries_time'], 3, '.', ' ').' s)';
485
    $output.= '</pre>';
486
 
487
    echo $output;
488
  }
489
 
490
  return $result;
491
}
492
 
493
function pwg_debug( $string )
494
{
495
  global $debug,$t2,$count_queries;
496
 
497
  $now = explode( ' ', microtime() );
498
  $now2 = explode( '.', $now[0] );
499
  $now2 = $now[1].'.'.$now2[1];
500
  $time = number_format( $now2 - $t2, 3, '.', ' ').' s';
501
  $debug.= '['.$time.', ';
502
  $debug.= $count_queries.' queries] : '.$string;
503
  $debug.= "\n";
504
}
505
 
506
/**
507
 * Redirects to the given URL
508
 *
509
 * Note : once this function called, the execution doesn't go further
510
 * (presence of an exit() instruction.
511
 *
512
 * @param string $url
513
 * @return void
514
 */
515
function redirect( $url )
516
{
517
  global $user, $template, $lang_info, $conf, $lang, $t2, $page;
518
 
519
  // $refresh, $url_link and $title are required for creating an automated
520
  // refresh page in header.tpl
521
  $refresh = 0;
522
  $url_link = $url;
523
  $title = 'redirection';
524
 
525
  include( PHPWG_ROOT_PATH.'include/page_header.php' );
526
 
527
  $template->set_filenames( array( 'redirect' => 'redirect.tpl' ) );
528
  $template->parse('redirect');
529
 
530
  include( PHPWG_ROOT_PATH.'include/page_tail.php' );
531
 
532
  exit();
533
}
534
 
535
/**
536
 * returns $_SERVER['QUERY_STRING'] whitout keys given in parameters
537
 *
538
 * @param array $rejects
539
 * @returns string
540
 */
541
function get_query_string_diff($rejects = array())
542
{
543
  $query_string = '';
544
 
545
  $str = $_SERVER['QUERY_STRING'];
546
  parse_str($str, $vars);
547
 
548
  $is_first = true;
549
  foreach ($vars as $key => $value)
550
  {
551
    if (!in_array($key, $rejects))
552
    {
553
      if ($is_first)
554
      {
555
        $query_string.= '?';
556
        $is_first = false;
557
      }
558
      else
559
      {
560
        $query_string.= '&amp;';
561
      }
562
      $query_string.= $key.'='.$value;
563
    }
564
  }
565
 
566
  return $query_string;
567
}
568
 
569
/**
570
 * returns available templates
571
 */
572
function get_templates()
573
{
574
  return get_dirs(PHPWG_ROOT_PATH.'template');
575
}
576
 
577
/**
578
 * returns thumbnail filepath (or distant URL if thumbnail is remote) for a
579
 * given element
580
 *
581
 * the returned string can represente the filepath of the thumbnail or the
582
 * filepath to the corresponding icon for non picture elements
583
 *
584
 * @param string path
585
 * @param string tn_ext
586
 * @return string
587
 */
588
function get_thumbnail_src($path, $tn_ext = '')
589
{
590
  global $conf, $user;
591
 
592
  if ($tn_ext != '')
593
  {
594
    $src = substr_replace(get_filename_wo_extension($path),
595
                          '/thumbnail/'.$conf['prefix_thumbnail'],
596
                          strrpos($path,'/'),
597
                          1);
598
    $src.= '.'.$tn_ext;
599
  }
600
  else
601
  {
602
    $src = PHPWG_ROOT_PATH;
603
    $src.= 'template/'.$user['template'].'/mimetypes/';
604
    $src.= strtolower(get_extension($path)).'.png';
605
  }
606
 
607
  return $src;
608
}
609
 
610
// my_error returns (or send to standard output) the message concerning the
611
// error occured for the last mysql query.
612
function my_error($header)
613
{
614
  $error = '<pre>';
615
  $error.= $header;
616
  $error.= '[mysql error '.mysql_errno().'] ';
617
  $error.= mysql_error();
618
  $error.= '</pre>';
619
  die ($error);
620
}
621
?>