source: tags/release-1_7_0/tools/create_listing_file.php @ 8497

Last change on this file since 8497 was 2002, checked in by plg, 17 years ago

New version 1.7.0 hard coded (not replaced at release creation time).

  • Property svn:eol-style set to LF
  • Property svn:keywords set to Author Date Id Revision
File size: 54.5 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: 2007-05-04 22:43:06 +0000 (Fri, 04 May 2007) $
10// | last modifier : $Author: plg $
11// | revision      : $Revision: 2002 $
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// +-----------------------------------------------------------------------+
29// |                                User configuration                     |
30// +-----------------------------------------------------------------------+
31
32// ****** Gallery configuration ****** //
33// Script version
34$conf['version'] = '1.7.0';
35
36// URL of main gallery
37// Example : http://www.my.domain/my/directory
38$conf['gallery'] = 'http://';
39
40// prefix for thumbnails in "thumbnail" sub directories
41$conf['prefix_thumbnail'] = 'TN-';
42
43// $conf['file_ext'] lists all extensions (case insensitive) allowed
44// for your PhpWebGallery installation
45$conf['file_ext'] = array('jpg','JPG','jpeg','JPEG',
46                          'png','PNG','gif','GIF','mpg','zip',
47                          'avi','mp3','ogg');
48
49
50// $conf['picture_ext'] must be a subset of $conf['file_ext']
51$conf['picture_ext'] = array('jpg','JPG','jpeg','JPEG',
52                             'png','PNG','gif','GIF');
53
54// ****** Time limitation functionality ****** //
55// max execution time before refresh in seconds
56$conf['max_execution_time'] = (5*ini_get('max_execution_time'))/6; // 25 seconds with default PHP configuration
57
58// refresh delay is seconds
59$conf['refresh_delay'] = 0;
60
61// ****** EXIF support functionality ****** //
62// $conf['use_exif'] set to true if you want to use Exif information
63$conf['use_exif'] = true;
64
65// use_exif_mapping: same behaviour as use_iptc_mapping
66$conf['use_exif_mapping'] = array(
67  'date_creation' => 'DateTimeOriginal'
68  );
69
70// ****** IPTC support functionality ****** //
71// $conf['use_iptc'] set to true if you want to use IPTC informations of the
72// element according to get_sync_iptc_data function mapping, otherwise, set
73// to false
74$conf['use_iptc'] = false;
75
76// use_iptc_mapping : in which IPTC fields will PhpWebGallery find image
77// information ? This setting is used during metadata synchronisation. It
78// associates a phpwebgallery_images column name to a IPTC key
79$conf['use_iptc_mapping'] = array(
80  'keywords'        => '2#025',
81  'date_creation'   => '2#055',
82  'author'          => '2#122',
83  'name'            => '2#005',
84  'comment'         => '2#120');
85
86// ****** Directory protection functionality ****** //
87// Define if directories have to be protected if they are not
88$conf['protect'] = false;
89
90// index.php content for command 'protect'
91$conf['protect_content'] = '<?php header("Location: '.$conf['gallery'].'") ?>';
92
93// true/false : show/hide warnings
94$conf['protect_warnings'] = true;
95
96// ****** Thumbnails generation functionality ****** //
97// Define if images have to be reduced if they are not
98$conf['thumbnail'] = false;
99
100// Define method to generate thumbnails :
101// - fixed (width and height required);
102// - width (only width required);
103// - height (only height required);
104// - ratio (only ratio is required)
105// - exif (no other parameter required)
106$conf['thumbnail_method'] = 'ratio';
107
108// Height in pixels (greater than 0)
109$conf['thumbnail_height'] = 128;
110
111// Width in pixels (greater than 0)
112$conf['thumbnail_width'] = 128;
113
114// Ratio between original and thumbnail size (strictly between 0 and 1)
115$conf['thumbnail_ratio'] = 0.2;
116
117// Define thumbnail format : jpeg, png or gif (will be verified)
118$conf['thumbnail_format'] = 'jpeg';
119
120// ****** Directory mapping ****** //
121// directories names
122$conf['thumbs'] = 'thumbnail'; // thumbnails
123$conf['high'] = 'pwg_high'; // high resolution
124$conf['represent'] = 'pwg_representative'; // non pictures representative files
125
126// +-----------------------------------------------------------------------+
127// |                                Advanced script configuration          |
128// +-----------------------------------------------------------------------+
129
130// url of icon directory in yoga template
131$pwg_conf['icon_dir'] = $conf['gallery'].'/template/yoga/icon/';
132
133// list of actions managed by this script
134$pwg_conf['scan_action'] = array('clean', 'test', 'generate');
135
136// url of this script
137$pwg_conf['this_url'] = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'];
138
139// list of reserved directory names
140$pwg_conf['reserved_directory_names'] = array($conf['thumbs'], $conf['high'], $conf['represent'], ".", "..", ".svn");
141
142// content of index.php generated in protect action
143$pwg_conf['protect_content'] = '<?php header("Location: '.$conf['gallery'].'") ?>';
144
145// backup of PHP safe_mode INI parameter (used for time limitation)
146$pwg_conf['safe_mode'] = (ini_get('safe_mode') == '1') ? true : false;
147
148// This parameter will be fixed in pwg_init()
149$pwg_conf['gd_version_major'] = '';
150$pwg_conf['gd_version_full'] = '';
151$pwg_conf['gd_supported_format'] = array();
152
153// +-----------------------------------------------------------------------+
154// |                               Functions                               |
155// +-----------------------------------------------------------------------+
156
157/**
158 * write line in log file
159 *
160 * @param string line
161 * @return string
162 */
163function pwg_log($line)
164{
165  $log_file = fopen(__FILE__.'.log', 'a');
166  fwrite($log_file, $line);
167  fclose($log_file);
168}
169
170/**
171 * Check web server graphical capabilities
172 *
173 * @return string
174 */
175function pwg_check_graphics()
176{
177  //~ pwg_log('>>>>> pwg_check_graphics() >>>>>'."\n");
178 
179  global $conf, $pwg_conf;
180  $log = '';
181 
182  // Verify gd library for thumbnail generation
183  if ($conf['thumbnail'] and !is_callable('gd_info'))
184  {
185    $log .= '          <code class="warning">Warning -</code> Your server can not generate thumbnails. Thumbnail creation switched off.<br />'."\n";
186    // Switch off thumbnail generation
187    $conf['thumbnail'] = false;
188    return $log;
189  }
190 
191  // Verify thumnail format
192  if ($conf['thumbnail'])
193  {
194    $info = gd_info();
195   
196    // Backup GD major version
197    $pwg_conf['gd_version_full'] = ereg_replace('[[:alpha:][:space:]()]+', '', $info['GD Version']);
198    list($pwg_conf['gd_version_major']) = preg_split('/[.]+/', $pwg_conf['gd_version_full']);
199   
200    // Backup input/output format support
201    array_push($pwg_conf['gd_supported_format'], $info['JPG Support'] ? 'jpeg' : NULL);
202    array_push($pwg_conf['gd_supported_format'], $info['PNG Support'] ? 'png' : NULL);
203    array_push($pwg_conf['gd_supported_format'], ($info['GIF Read Support'] and $info['GIF Create Support']) ? 'gif' : NULL);
204   
205    // Check output format support
206    if (!in_array($conf['thumbnail_format'], $pwg_conf['gd_supported_format']))
207    {
208      $log .= '          <code class="warning">Warning -</code> Your server does not support thumbnail\'s <code>';
209      $log .= $conf['thumbnail_format'].'</code> format. Thumbnail creation switched off.<br />'."\n";
210    }
211   
212    switch ($conf['thumbnail_method'])
213    {
214      case 'exif':
215      {
216        // exif_thumbnail() must be callable
217        if (!is_callable('exif_thumbnail'))
218        {
219          $log .= '          <code class="warning">Warning -</code> Your server does not support thumbnail creation through EXIF datas. Thumbnail creation switched off.<br />'."\n";
220        }
221        break;
222      }
223      case 'fixed':
224      {
225        // $conf['thumbnail_width'] > 0
226        if (!is_numeric($conf['thumbnail_width']) or $conf['thumbnail_width'] <= 0)
227        {
228          $log .= '          <code class="failure">Failure -</code> Bad value <code>thumbnail_width = ';
229          $log .= var_export($conf['thumbnail_width'], true).'</code>. Thumbnail creation switched off.<br />'."\n";
230        }
231        // $conf['thumbnail_height'] > 0
232        if (!is_numeric($conf['thumbnail_height']) or $conf['thumbnail_height'] <= 0)
233        {
234          $log .= '          <code class="failure">Failure -</code> Bad value <code>thumbnail_height = ';
235          $log .= var_export($conf['thumbnail_height'], true).'</code>. Thumbnail creation switched off.<br />'."\n";
236        }
237        break;
238      }
239      case 'ratio':
240      {
241        // 0 < $conf['thumbnail_ratio'] < 1
242        if (!is_numeric($conf['thumbnail_ratio']) or $conf['thumbnail_ratio'] <= 0 or $conf['thumbnail_ratio'] >= 1)
243        {
244          $log .= '          <code class="failure">Failure -</code> Bad value <code>thumbnail_ratio = ';
245          $log .= var_export($conf['thumbnail_ratio'], true).'</code>. Thumbnail creation switched off.<br />'."\n";
246        }
247        break;
248      }
249      case 'width':
250      {
251        // $conf['thumbnail_width'] > 0
252        if (!is_numeric($conf['thumbnail_width']) or $conf['thumbnail_width'] <= 0)
253        {
254          $log .= '          <code class="failure">Failure -</code> Bad value <code>thumbnail_width = ';
255          $log .= var_export($conf['thumbnail_width'], true).'</code>. Thumbnail creation switched off.<br />'."\n";
256        }
257        break;
258      }
259      case 'height':
260      {
261        // $conf['thumbnail_height'] > 0
262        if (!is_numeric($conf['thumbnail_height']) or $conf['thumbnail_height'] <= 0)
263        {
264          $log .= '          <code class="failure">Failure -</code> Bad value <code>thumbnail_height = ';
265          $log .= var_export($conf['thumbnail_height'], true).'</code>. Thumbnail creation switched off.<br />'."\n";
266        }
267        break;
268      }
269      default:
270      {
271        // unknown method
272          $log .= '          <code class="failure">Failure -</code> Bad value <code>thumbnail_method = ';
273          $log .= var_export($conf['thumbnail_method'], true).'</code>. Thumbnail creation switched off.<br />'."\n";
274        break;
275      }
276    }
277   
278    if (strlen($log))
279    {
280      $conf['thumbnail'] = false;
281    }
282  }
283 
284  //~ pwg_log('<<<<< pwg_check_graphics() returns '.var_export($log, TRUE).' <<<<<'."\n");
285  return $log;
286}
287
288/**
289 * returns xml </dirX> lines
290 *
291 * @param integer $dir_start
292 * @param integer $dir_number
293 * @return string
294 */
295function pwg_close_level($dir_start, $dir_number)
296{
297  //~ pwg_log('>>>>> pwg_close_level($dir_start = '.var_export($dir_start, TRUE).', $dir_number = '.var_export($dir_number, TRUE).') >>>>>'."\n");
298 
299  $lines ='';
300  do
301  {
302    $lines .= str_repeat(' ', 2*$dir_start).'</dir'.$dir_start.">\n";
303    $dir_number--;
304    $dir_start--;
305  }
306  while(($dir_number > 0) && ($dir_start >= 0));
307 
308  //~ pwg_log('<<<<< pwg_close_level returns '.var_export($lines, TRUE).' <<<<<'."\n");
309  return $lines;
310}
311
312/**
313 * return a cleaned IPTC value
314 *
315 * @param string value
316 * @return string
317 */
318function pwg_clean_iptc_value($value)
319{
320  //~ pwg_log('>>>>> pwg_clean_iptc_value ($value = '.var_export($value, TRUE).') >>>>>'."\n");
321 
322  // strip leading zeros (weird Kodak Scanner software)
323  while (isset($value[0]) and $value[0] == chr(0))
324  {
325    $value = substr($value, 1);
326  }
327  // remove binary nulls
328  $value = str_replace(chr(0x00), ' ', $value);
329
330  //~ pwg_log('<<<<< pwg_clean_iptc_value() returns '.var_export($value, TRUE).' <<<<<'."\n");
331  return $value;
332}
333
334/**
335 * returns informations from IPTC metadata, mapping is done at the beginning
336 * of the function
337 *
338 * @param string $filename
339 * @param string $map
340 * @return array
341 */
342function pwg_get_iptc_data($filename, $map)
343{
344  //~ pwg_log('>>>>> pwg_get_iptc_data ($filename = '.var_export($filename, TRUE).', $map = '.var_export($map, TRUE).') >>>>>'."\n");
345 
346  $result = array();
347
348  // Read IPTC data
349  $iptc = array();
350
351  $imginfo = array();
352  getimagesize($filename, $imginfo);
353
354  if (isset($imginfo['APP13']))
355  {
356    $iptc = iptcparse($imginfo['APP13']);
357    if (is_array($iptc))
358    {
359      $rmap = array_flip($map);
360      foreach (array_keys($rmap) as $iptc_key)
361      {
362        if (isset($iptc[$iptc_key][0]))
363        {
364          if ($iptc_key == '2#025')
365          {
366            $value = implode(',', array_map('pwg_clean_iptc_value', $iptc[$iptc_key]));
367          }
368          else
369          {
370            $value = pwg_clean_iptc_value($iptc[$iptc_key][0]);
371          }
372
373          foreach (array_keys($map, $iptc_key) as $pwg_key)
374          {
375            $result[$pwg_key] = $value;
376          }
377        }
378      }
379    }
380  }
381 
382  //~ pwg_log('<<<<< pwg_get_iptc_data() returns '.var_export($result, TRUE).' <<<<<'."\n");
383  return $result;
384}
385
386/**
387 * returns informations from IPTC metadata
388 *
389 * @param string $file
390 * @return array iptc
391 */
392function pwg_get_sync_iptc_data($file)
393{
394  //~ pwg_log('>>>>> pwg_get_sync_iptc_data ($file = '.var_export($file, TRUE).') >>>>>'."\n");
395
396  global $conf;
397
398  $map = $conf['use_iptc_mapping'];
399  $datefields = array('date_creation', 'date_available');
400
401  $iptc = pwg_get_iptc_data($file, $map);
402
403  foreach ($iptc as $pwg_key => $value)
404  {
405    if (in_array($pwg_key, $datefields))
406    {
407      if ( preg_match('/(\d{4})(\d{2})(\d{2})/', $value, $matches))
408      {
409        $value = $matches[1].'-'.$matches[2].'-'.$matches[3];
410      }
411    }
412    if ($pwg_key == 'keywords')
413    {
414      // official keywords separator is the comma
415      $value = preg_replace('/[.;]/', ',', $value);
416      $value = preg_replace('/^,+|,+$/', '', $value);
417    }
418    $iptc[$pwg_key] = htmlentities($value);
419  }
420
421  $iptc['keywords'] = isset($iptc['keywords']) ? implode(',', array_unique(explode(',', $iptc['keywords']))) : NULL;
422
423  //~ pwg_log('<<<<< pwg_get_sync_iptc_data() returns '.var_export($iptc, TRUE).' <<<<<'."\n");
424  return $iptc;
425}
426
427/**
428 * return extension of the representative file
429 *
430 * @param string $file_dir
431 * @param string $file_short
432 * @return string
433 */
434function pwg_get_representative_ext($file_dir, $file_short)
435{
436  //~ pwg_log('>>>>> pwg_get_representative_ext($file_dir = '.var_export($file_dir, TRUE).', $file_short = '.var_export($file_short, TRUE).') >>>>>'."\n");
437 
438  global $conf;
439 
440  $rep_ext = '';
441  foreach ($conf['picture_ext'] as $ext)
442  {
443    if (file_exists($file_dir.'/'.$conf['represent'].'/'.$file_short.'.'.$ext))
444    {
445      $rep_ext = $ext;
446      break;
447    }
448  }
449 
450  //~ pwg_log('<<<<< pwg_get_representative_ext() returns '.var_export($rep_ext, TRUE).' <<<<<'."\n");
451  return $rep_ext; 
452}
453
454/**
455 * return 'true' if high resolution picture exists else ''
456 *
457 * @param string $file_dir
458 * @param string $file_base
459 * @return boolean
460 */
461function pwg_get_high($file_dir, $file_base)
462{
463  //~ pwg_log('>>>>> pwg_get_high($file = '.var_export($file_dir, TRUE).', $line = '.var_export($file_base, TRUE).') >>>>>'."\n");
464 
465  global $conf;
466 
467  $high = false;
468  if (file_exists($file_dir.'/'.$conf['high'].'/'.$file_base))
469  {
470    $high = true;
471  }
472 
473  //~ pwg_log('<<<<< pwg_get_high() returns '.var_export($high, TRUE).' <<<<<'."\n");
474  return $high; 
475}
476
477/**
478 * return filename without extension
479 *
480 * @param string $filename
481 * @return string
482 */
483function pwg_get_filename_wo_extension($filename)
484{
485  //~ pwg_log('>>>>> _get_filename_wo_extension($filename = '.var_export($filename, TRUE).') >>>>>'."\n");
486 
487  $short_name = substr($filename, 0, strrpos($filename, '.'));
488 
489  //~ pwg_log('<<<<< _get_filename_wo_extension() returns '.var_export($short_name, TRUE).' <<<<<'."\n");
490  return $short_name;
491}
492
493/**
494 * return extension of the thumbnail and complete error_log
495 *
496 * @param string $file_dir
497 * @param string $file_short
498 * @param string $file_ext
499 * @param string &$error_log
500 * @return string
501 */
502function pwg_get_thumbnail_ext($file_dir, $file_short, $file_ext, &$error_log)
503{
504  //~ pwg_log('>>>>> pwg_get_thumbnail_ext($file_dir = '.var_export($file_dir, TRUE).', $file_short = '.var_export($file_short, TRUE).') >>>>>'."\n");
505 
506  global $conf;
507 
508  $thumb_ext = '';
509  foreach ($conf['picture_ext'] as $ext)
510  {
511    if (file_exists($file_dir.'/'.$conf['thumbs'].'/'.$conf['prefix_thumbnail'].$file_short.'.'.$ext))
512    {
513      $thumb_ext = $ext;
514      break;
515    }
516  }
517 
518  if ($thumb_ext == '')
519  {
520    if ($conf['thumbnail'])
521    {
522      $log = pwg_icon_file($file_dir, $file_short, $file_ext);
523      if (strpos($log, 'success'))
524      {
525        $thumb_ext = $conf['thumbnail_format'];
526      }
527      $error_log .= $log; 
528    }
529  }
530 
531  //~ pwg_log('<<<<< pwg_get_thumbnail_ext() returns '.var_export($thumb_ext, TRUE).' <<<<<'."\n");
532  return $thumb_ext; 
533}
534
535
536/**
537 * return error logs
538 *
539 * @param string $file_dir
540 * @param string $file_short
541 * @param string $file_ext
542 * @return string
543 */
544function pwg_icon_file($file_dir, $file_short, $file_ext)
545{
546  //~ pwg_log('>>>>> pwg_icon_file($file_dir = '.var_export($file_dir, TRUE).', $file_short = '.var_export($file_short, TRUE).') >>>>>'."\n");
547 
548  global $conf, $pwg_conf;
549 
550  $error_log = '';
551 
552  // Get original properties (width, height)
553  if ($image_size = getimagesize($file_dir.'/'.$file_short.'.'.$file_ext))
554  {
555    $src_width = $image_size[0];
556    $src_height = $image_size[1];
557  }
558  else
559  {
560    $error_log .= '          <code class="failure">Failure -</code> Can not generate icon for <code>';
561    $error_log .= $file_dir.'/'.$file_short.'.'.$file_ext.'</code>';
562    $error_log .= ' <img src="'.$pwg_conf['icon_dir'].'add_tag.png" title="width/height are unreadable" /><br />'."\n";
563    return $error_log;
564  }
565 
566  // Check input format
567  $dst_format = $conf['thumbnail_format'];
568  $src_format = ($file_ext == 'jpg' or $file_ext == 'JPG') ? 'jpeg' : strtolower($file_ext);
569  if (!in_array($src_format, $pwg_conf['gd_supported_format']))
570  {
571    $error_log .= '          <code class="failure">Failure -</code> Can not generate icon for <code>';
572    $error_log .= $file_dir.'/'.$file_short.'.'.$file_ext.'</code>';
573    $error_log .= ' <img src="'.$pwg_conf['icon_dir'].'add_tag.png" title="format not supported" /><br />'."\n";
574    return $error_log;
575  }
576 
577  // Calculate icon properties (width, height)
578  switch ($conf['thumbnail_method'])
579  {
580    case 'fixed':
581    {
582      $dst_width  = $conf['thumbnail_width'];
583      $dst_height = $conf['thumbnail_height'];
584      break;
585    }
586    case 'width':
587    {
588      $dst_width  = $conf['thumbnail_width'];
589      $dst_height = $dst_width * $src_height / $src_width;
590      break;
591    }
592    case 'height':
593    {
594      $dst_height = $conf['thumbnail_height'];
595      $dst_width  = $dst_height * $src_width / $src_height;
596      break;
597    }
598    case 'ratio':
599    {
600      $dst_width  = round($src_width * $conf['thumbnail_ratio']);
601      $dst_height = round($src_height * $conf['thumbnail_ratio']);
602      break;
603    }
604    case 'exif':
605    default:
606    {
607      // Nothing to do
608    }
609  }
610 
611  // Creating icon
612  if ($conf['thumbnail_method'] == 'exif')
613  {
614    $src = exif_thumbnail($file_dir.'/'.$file_short.'.'.$file_ext, $width, $height, $imagetype);
615    if ($src === false)
616    {
617      $error_log .= '          <code class="failure">Failure -</code> No EXIF thumbnail in <code>';
618      $error_log .= $file_dir.'/'.$file_short.'.'.$file_ext.'</code><br />'."\n";
619      return $error_log;
620    }
621    $dst = imagecreatefromstring($src);
622    if ($src === false)
623    {
624      $error_log .= '          <code class="failure">Failure -</code> EXIF thumbnail format not supported in <code>';
625      $error_log .= $file_dir.'/'.$file_short.'.'.$file_ext.'</code><br />'."\n";
626      return $error_log;
627    }
628  }
629  else
630  {
631    if (($pwg_conf['gd_version_major'] != 2)) // or ($conf['thumbnail_format'] == 'gif'))
632    {
633      $dst = imagecreate($dst_width, $dst_height);
634    }
635    else
636    {
637      $dst = imagecreatetruecolor($dst_width, $dst_height);
638    }
639    $src = call_user_func('imagecreatefrom'.$src_format, $file_dir.'/'.$file_short.'.'.$file_ext);
640    if (!$src)
641    {
642      $error_log .= '          <code class="failure">Failure -</code> Internal error for <code>imagecreatefrom'.$src_format.'()</code>';
643      $error_log .= 'with <code>'.$file_dir.'/'.$file_short.'.'.$file_ext.'</code><br />'."\n";
644      return $error_log;
645    }
646     
647    if (($pwg_conf['gd_version_major'] != 2))
648    {
649      if (!imagecopyresized($dst, $src, 0, 0, 0, 0, $dst_width, $dst_height, $src_width, $src_height))
650      {
651        $error_log .= '          <code class="failure">Failure -</code> Internal error for <code>imagecopyresized()</code>';
652        $error_log .= 'with <code>'.$file_dir.'/'.$file_short.'.'.$file_ext.'</code><br />'."\n";
653        return $error_log;
654      }
655    }
656    else
657    {
658      if (!imagecopyresampled($dst, $src, 0, 0, 0, 0, $dst_width, $dst_height, $src_width, $src_height))
659      {
660        $error_log .= '          <code class="failure">Failure -</code> Internal error for <code>imagecopyresampled()</code>';
661        $error_log .= 'with <code>'.$file_dir.'/'.$file_short.'.'.$file_ext.'</code><br />'."\n";
662        return $error_log;
663      }
664    }
665  }
666 
667  if (!call_user_func('image'.$dst_format, $dst, $file_dir.'/'.$conf['thumbs'].'/'.$conf['prefix_thumbnail'].$file_short.'.'.$conf['thumbnail_format']))
668  {
669    $error_log .= '          <code class="failure">Failure -</code> Can not write <code>';
670    $error_log .= $file_dir.'/'.$conf['thumbs'].'/'.$conf['prefix_thumbnail'].$file_short.'.'.$file_ext.'</code> to generate thumbnail<br />'."\n";
671    return $error_log;
672  }
673 
674  $error_log .= '          <code class="success">Success -</code> Thumbnail generated for <code>';
675  $error_log .= $file_dir.'/'.$file_short.'.'.$file_ext.'</code><br />'."\n";
676
677  //~ pwg_log('<<<<< pwg_icon_file() returns '.var_export($error_log, TRUE).' <<<<<'."\n");
678  return $error_log; 
679}
680
681/**
682 * completes xml line <element .../> and returns error log
683 *
684 * @param string $file
685 * @param string &$line
686 * @return string
687 */
688function pwg_scan_file($file_full, &$line)
689{
690  //~ pwg_log('>>>>> pwg_scan_file($file = '.var_export($file_full, TRUE).', $line = '.var_export($line, TRUE).') >>>>>'."\n");
691 
692  global $conf, $pwg_conf;
693 
694  $error_log ='';
695 
696  $file_base  = basename($file_full);
697  $file_short = pwg_get_filename_wo_extension($file_base);
698  $file_ext   = pwg_get_file_extension($file_base);
699  $file_dir   = dirname($file_full);
700
701  $element['file'] = $file_base;
702  $element['path'] = 'http://'.dirname($_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF']).substr($file_dir, 1).'/'.$file_base;
703 
704  if (in_array($file_ext, $conf['picture_ext']))
705  {
706    // Here we scan a picture : thumbnail is mandatory, high is optionnal, representative is not scanned
707    $element['tn_ext'] = pwg_get_thumbnail_ext($file_dir, $file_short, $file_ext, $error_log);
708    if ($element['tn_ext'] != '')
709    {
710      // picture has a thumbnail, get image width, heigth, size in Mo
711      $element['filesize'] = floor(filesize($file_full) / 1024);
712      if ($image_size = getimagesize($file_full))
713      {
714        $element['width'] = $image_size[0];
715        $element['height'] = $image_size[1];
716      }
717     
718      // get high resolution
719      if (pwg_get_high($file_dir, $file_base))
720      {
721        $element['has_high'] = 'true';
722       
723        $high_file = $file_dir.'/'.$conf['high'].'/'.$file_base;
724        $element['high_filesize'] = floor(filesize($high_file) / 1024);
725      }
726     
727      // get EXIF meta datas
728      if ($conf['use_exif'])
729      {
730        // Verify activation of exif module
731        if (extension_loaded('exif'))
732        {
733          if ($exif = read_exif_data($file_full))
734          {
735            foreach ($conf['use_exif_mapping'] as $pwg_key => $exif_key )
736            {
737              if (isset($exif[$exif_key]))
738              {
739                if ( in_array($pwg_key, array('date_creation','date_available') ) )
740                {
741                  if (preg_match('/^(\d{4}):(\d{2}):(\d{2})/', $exif[$exif_key], $matches))
742                    {
743                      $element[$pwg_key] = $matches[1].'-'.$matches[2].'-'.$matches[3];
744                    }
745                }
746                else
747                {
748                  $element[$pwg_key] = $exif[$exif_key];
749                }
750              }
751            }
752          }
753        }
754      }
755     
756      // get IPTC meta datas
757      if ($conf['use_iptc'])
758      {
759        $iptc = pwg_get_sync_iptc_data($file_full);
760        if (count($iptc) > 0)
761        {
762          foreach (array_keys($iptc) as $key)
763          {
764            $element[$key] = addslashes($iptc[$key]);
765          }
766        }
767      }
768     
769    }
770    else
771    {
772      $error_log .= '          <code class="failure">Failure -</code> Thumbnail is missing for <code>'.$file_dir.'/'.$file_base.'</code>';
773      $error_log .= ' <img src="'.$pwg_conf['icon_dir'].'add_tag.png" title="'.$file_dir.'/thumbnail/'.$conf['prefix_thumbnail'].$file_short;
774      $error_log .= '.xxx ('.implode(', ', $conf['picture_ext']).')" /><br />'."\n";
775    }
776  }
777  else
778  {
779    // Here we scan a non picture file : thumbnail and high are unused, representative is optionnal
780    $ext = pwg_get_representative_ext($file_dir, $file_short);
781    if ($ext != '')
782    {
783      $element['representative_ext'] = $ext;
784    }
785  }
786 
787  if (strlen($error_log) == 0)
788  {
789    $line = pwg_get_indent('element').'<element ';
790    foreach($element as $key => $value)
791    {
792      $line .= $key.'="'.$value.'" ';
793    }
794    $line .= '/>'."\n";
795  }
796 
797  //~ pwg_log('<<<<< pwg_scan_file() returns '.var_export($error_log, TRUE).' <<<<<'."\n");
798  return $error_log;
799}
800
801/**
802 * returns current level in tree
803 *
804 * @return integer
805 */
806function pwg_get_level($dir)
807{
808  //~ pwg_log('>>>>> pwg_get_level($dir = '.var_export($dir, TRUE).') >>>>>'."\n");
809 
810  $level = substr_count($dir, '/') - 1; // -1 because of ./ at the beginning of path
811 
812  //~ pwg_log('<<<<< pwg_get_level() returns '.var_export($level, TRUE).' <<<<<'."\n");
813  return $level;
814}
815
816/**
817 * returns indentation of element
818 *
819 * @param string $element_type : 'root', 'element', 'dir'
820 * @return string
821 */
822function pwg_get_indent($element_type)
823{
824  //~ pwg_log('>>>>> pwg_get_indent($element_type = '.var_export($element_type, TRUE).') >>>>>'."\n");
825 
826  $level = substr_count($_SESSION['scan_list_fold'][0], '/') - 1; // because of ./ at the beginning
827  switch($element_type)
828  {
829    case 'dir' :
830    {
831      $indent = str_repeat(' ', 2*pwg_get_level($_SESSION['scan_list_fold'][0]));
832      break;
833    }
834    case 'root' :
835    {
836      $indent = str_repeat(' ', 2*pwg_get_level($_SESSION['scan_list_fold'][0])+2);
837      break;
838    }
839    case 'element' :
840    {
841      $indent = str_repeat(' ', 2*pwg_get_level($_SESSION['scan_list_fold'][0])+4);
842      break;
843    }
844    default :
845    {
846      $indent = '';
847      break;
848    }
849  }
850 
851  //~ pwg_log('<<<<< pwg_get_indent() returns '.var_export(strlen($indent), TRUE).' spaces <<<<<'."\n");
852  return $indent;
853}
854
855/**
856 * create index.php in directory and reserved sub_directories, return logs
857 *
858 * @param string dir
859 * @return string
860 */
861function pwg_protect_directories($directory)
862{
863  //~ pwg_log('>>>>> pwg_protect_directories($directory = '.var_export($directory, true).') >>>>>'."\n");
864 
865  global $conf;
866 
867  $error_log = '';
868  $dirlist = array($directory, $directory.'/'.$conf['thumbs'], $directory.'/'.$conf['high'], $directory.'/'.$conf['represent']);
869 
870  foreach ($dirlist as $dir)
871  {
872    if (file_exists($dir))
873    {
874      if (!file_exists($dir.'/index.php'))
875      {
876        $file = @fopen($dir.'/index.php', 'w');
877        if ($file != false)
878        {
879          fwrite($file, $conf['protect_content']); // the return code should be verified
880          $error_log .= '          <code class="success">Success -</code> index.php created in directory <a href="'.$dir.'">'.$dir."</a><br />\n";
881        }
882        else
883        {
884          $error_log .= '          <code class="failure">Failure -</code> Can not create index.php in directory <code>'.$dir."</code><br />\n";
885        }
886      }
887      else
888      {
889        if ($conf['protect_warnings'])
890        {
891          $error_log .= '          <code class="warning">Warning -</code> index.php already exists in directory <a href="'.$dir.'">'.$dir."</a><br />\n";
892        }
893      }
894    }
895  }
896 
897  //~ pwg_log('<<<<< pwg_protect_directories() returns '.var_export($error_log, true).' <<<<<'."\n");
898  return $error_log;
899}
900
901/**
902 * returns file extension (.xxx)
903 *
904 * @param string $file
905 * @return string
906 */
907function pwg_get_file_extension($file)
908{
909  //~ pwg_log('>>>>> pwg_get_file_extension($file = '.var_export($file, true).') >>>>>'."\n");
910 
911  $ext = substr(strrchr($file, '.'), 1, strlen ($file));
912 
913  //~ pwg_log('<<<<< pwg_get_file_extension() returns '.var_export($ext, true).' <<<<<'."\n");
914  return $ext;
915}
916
917/**
918 * completes directory list of supported files and returns error logs
919 *
920 * @param string $directory
921 * @return string
922 */
923function pwg_get_file_list($directory)
924{
925  //~ pwg_log('>>>>> pwg_get_file_list($directory = '.var_export($directory, true).') >>>>>'."\n");
926 
927  global $conf, $pwg_conf;
928
929  $errorLog = '';
930  $dir = opendir($directory);
931  while (($file = readdir($dir)) !== false)
932  {
933    switch (filetype($directory."/".$file))
934    {
935      case 'file' :
936      {
937        if (in_array(pwg_get_file_extension($file), $conf['file_ext']))
938        {
939          // The file pointed is a regular file with a supported extension
940          array_push($_SESSION['scan_list_file'], $directory.'/'.$file);
941          //~ pwg_log('--->> Push in $_SESSION[scan_list_file] value "'.$directory.'/'.$file.'"'."\n");
942          if (!preg_match('/^[a-zA-Z0-9-_.]+$/', $file))
943          {
944            $errorLog .= '          <code class="failure">Failure -</code> Invalid file name for <code>'.$file.'</code> in <code>'.$directory.'</code>';
945            $errorLog .= ' <img src="'.$pwg_conf['icon_dir'].'add_tag.png"';
946            $errorLog .= ' title="Name should be composed of letters, figures, -, _ or . ONLY" /><br />'."\n";
947          }
948        }
949        break; // End of filetype FILE
950      }
951      case 'dir' :
952      {
953        if(!in_array($file, $pwg_conf['reserved_directory_names']))
954        {
955          // The file pointed is a directory but neither system directory nor reserved by PWG
956          array_push($_SESSION['scan_list_fold'], $directory.'/'.$file);
957          //~ pwg_log('--->> Push in $_SESSION[scan_list_fold] value "'.$directory.'/'.$file.'"'."\n");
958          if (!preg_match('/^[a-zA-Z0-9-_.]+$/', $file))
959          {
960            $errorLog .= '          <code class="failure">Failure -</code> Invalid directory name for <code>'.$directory.'/'.$file.'</code>';
961            $errorLog .= ' <img src="'.$pwg_conf['icon_dir'].'add_tag.png"';
962            $errorLog .= ' title="Name should be composed of letters, figures, -, _ or . ONLY" /><br />'."\n";
963          }
964        }
965        break; // End of filetype DIR
966      }
967      case 'fifo' :
968      case 'char' :
969      case 'block' :
970      case 'link' :
971      case 'unknown':
972      default :
973      {
974        // PWG does not manage these cases
975        break;
976      }
977    }
978  }
979  closedir($dir);
980 
981  //~ pwg_log('<<<<< pwg_get_file_list() returns '.var_export($errorLog, true).' <<<<<'."\n");
982
983  return $errorLog;
984}
985
986/**
987 * returns a float value coresponding to the number of seconds since the
988 * unix epoch (1st January 1970) and the microseconds are precised :
989 * e.g. 1052343429.89276600
990 *
991 * @return float
992 */
993function pwg_get_moment()
994{
995  //~ pwg_log('>>>>> pwg_get_moment() >>>>>'."\n");
996 
997  $t1 = explode(' ', microtime());
998  $t2 = explode('.', $t1[0]);
999  $t2 = $t1[1].'.'.$t2[1];
1000
1001  //~ pwg_log('<<<<< pwg_get_moment() returns '.var_export($t2, true).' <<<<<'."\n");
1002  return $t2;
1003}
1004
1005/**
1006 * return true if HTTP_REFERER and PHP_SELF are similar
1007 *
1008 * return boolean
1009 */
1010function pwg_referer_is_me()
1011{
1012  //~ pwg_log('>>>>> pwg_referer_is_me() >>>>>'."\n");
1013 
1014  $response = false;
1015  $server = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'];
1016  $caller = (isset($_SERVER['HTTP_REFERER'])) ? $_SERVER['HTTP_REFERER'] : '';
1017
1018  if (strcasecmp($server, $caller) == 0) {
1019    $response = true;
1020  }
1021
1022  //~ pwg_log('<<<<< pwg_referer_is_me() returns '.var_export($response, true).' <<<<<'."\n");
1023  return $response;
1024}
1025
1026// +-----------------------------------------------------------------------+
1027// |                                pwg_<ACTION>_<STEP> Functions          |
1028// +-----------------------------------------------------------------------+
1029
1030function pwg_test_start()
1031{
1032  //~ pwg_log('>>>>> pwg_test_start() >>>>>'."\n");
1033
1034  global $g_message, $conf;
1035 
1036  if (isset($_REQUEST['version']))
1037  {
1038    if ($_REQUEST['version'] != $conf['version'])
1039    {
1040      $g_message = '0';
1041    }
1042    else
1043    {
1044      $g_message = '1';
1045    }
1046  }
1047  else
1048  {
1049    $g_message  = '1';
1050  }
1051  $_SESSION['scan_step'] = 'exit';
1052 
1053  //~ pwg_log('<<<<< pwg_test_start() <<<<<'."\n");
1054}
1055
1056function pwg_test_exit()
1057{
1058  //~ pwg_log('>>>>> pwg_test_exit() >>>>>'."\n");
1059
1060  global $g_header, $g_message, $g_footer, $conf, $pwg_conf;
1061 
1062  if (pwg_referer_is_me())
1063  {
1064    $g_header  = ' : <span class="success">Test</span>'."\n";
1065    $g_footer  = '<a href="'.$pwg_conf['this_url'].'" title="Main menu"><img src="'.$pwg_conf['icon_dir'].'up.png" /></a>'."\n";
1066   
1067    // Write version
1068    $g_message  = '        <h3>Script version</h3>'."\n";
1069    $g_message .= '        This script is tagged : <code class="failure">'.$conf['version'].'</code>'."\n";
1070    // write GD support
1071    if (!is_callable('gd_info'))
1072    {
1073      $g_message .= '        <code class="failure">Failure -</code> Your server can not generate imagess<br />'."\n";
1074    }
1075    else
1076    {
1077      $info = gd_info();
1078      $gd_full_version = ereg_replace('[[:alpha:][:space:]()]+', '', $info['GD Version']);
1079      list($gd_version) = preg_split('/[.]+/', $gd_full_version);
1080     
1081      $g_message .= '        <h3>Image generation</h3>'."\n";
1082      $g_message .= '        <code class="success">Success -</code> Your server can generate images<br />'."\n";
1083      $g_message .= '        <code class="warning">Warning -</code> Your server support GD'.$gd_version.' (v'.$gd_full_version.')<br />'."\n";
1084      $format_list = array();
1085      $format = ($info['GIF Create Support']) ? '<code>gif</code>' : NULL;
1086      array_push($format_list, $format);
1087      $format = ($info['JPG Support']) ? '<code>jpg</code>' : NULL;
1088      array_push($format_list, $format);
1089      $format = ($info['PNG Support']) ? '<code>png</code>' : NULL;
1090      array_push($format_list, $format);
1091      $g_message .= '        <code class="warning">Warning -</code> Your server support format: '.implode(', ', $format_list)."\n";
1092    }
1093   
1094    $g_message .= '        <h3>Directory parsing</h3>'."\n";
1095    if ($pwg_conf['safe_mode'])
1096    {
1097      $g_message .= '        <code class="warning">Warning -</code> Your server does not support to resize execution time'."\n";
1098    }
1099    else
1100    {
1101      $g_message .= '        <code class="success">Success -</code> Your server supports to resize execution time'."\n";
1102    }
1103  }
1104  else
1105  {
1106    // compare version in GET parameter with $conf['version']
1107    if ($g_message == '1')
1108    {
1109      exit('<pre>PWG-INFO-2: test successful</pre>');
1110    }
1111    else
1112    {
1113      exit('<pre>PWG-ERROR-4: PhpWebGallery versions differs</pre>');
1114    }
1115  }
1116 
1117  //~ pwg_log('<<<<< pwg_test_exit() <<<<<'."\n");
1118}
1119
1120function pwg_clean_start()
1121{
1122  //~ pwg_log('>>>>> pwg_clean_start() >>>>>'."\n");
1123 
1124  global $g_message;
1125 
1126  if(@unlink('./listing.xml'))
1127  {
1128    $g_message = '1';
1129  }
1130  else
1131  {
1132    $g_message = '0';
1133  }
1134
1135  $_SESSION['scan_step'] = 'exit';
1136 
1137  //~ pwg_log('<<<<< pwg_clean_start() <<<<<'."\n");
1138}
1139
1140function pwg_clean_exit()
1141{
1142  //~ pwg_log('>>>>> pwg_clean_exit() >>>>>'."\n");
1143
1144  global $g_header, $g_message, $g_footer, $conf, $pwg_conf;
1145 
1146  if(pwg_referer_is_me())
1147  {
1148    $g_header = ' : <span class="success">Clean</span>';
1149    if ($g_message == '1')
1150    {
1151      $g_message = '        <code class="success">Success -</code> <code>listing.xml</code> file deleted'."\n";
1152    }
1153    else
1154    {
1155      $g_message = '        <code class="failure">Failure -</code> <code>listing.xml</code> does not exist or is read only'."\n";
1156    }
1157    $g_footer = '<a href="'.$pwg_conf['this_url'].'" title="Main menu"><img src="'.$pwg_conf['icon_dir'].'up.png" /></a>';
1158  }
1159  else
1160  {
1161    if ($g_message == '1')
1162    {
1163      exit('<pre>PWG-INFO-3 : listing.xml file deleted</pre>');
1164    }
1165    else
1166    {
1167      exit('<pre>PWG-ERROR-3 : listing.xml does not exist</pre>');
1168    }
1169  }
1170 
1171  //~ pwg_log('<<<<< pwg_clean_exit() <<<<<'."\n");
1172}
1173
1174function pwg_generate_start()
1175{
1176  //~ pwg_log('>>>>> pwg_generate_start() >>>>>'."\n");
1177  //~ pwg_log("GENARATE start >>>\n".var_export($_SESSION['scan_list_fold'], true)."\n".var_export($_SESSION['scan_list_file'], true)."\nGENERATE start >>>\n");
1178
1179  global $g_listing, $conf;
1180 
1181  // Flush line <informations>
1182  $xml_header_url = 'http://'.dirname($_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF']).'/';
1183  $xml_header_date = date('Y-m-d');
1184  $xml_header_version = htmlentities($conf['version']);
1185 
1186  $attrs = array();
1187  if ($conf['use_iptc'])
1188  {
1189    $attrs = array_merge($attrs, array_keys($conf['use_iptc_mapping']) );
1190  }
1191  if ($conf['use_exif'])
1192  {
1193    $attrs = array_merge($attrs, array_keys($conf['use_exif_mapping']) );
1194  }
1195  $xml_header_metadata = implode(',',array_unique($attrs));
1196 
1197  $xml_header = '<informations';
1198  $xml_header .= ' generation_date="'.$xml_header_date.'"';
1199  $xml_header .= ' phpwg_version="'.$xml_header_version.'"';
1200  $xml_header .= ' metadata="'.$xml_header_metadata.'"';
1201  $xml_header .= ' url="'.$xml_header_url.'"';
1202  $xml_header .= '>'."\n";
1203 
1204  fwrite($g_listing, $xml_header);
1205 
1206  // Initialization of directory and file lists
1207  $_SESSION['scan_list_fold'] = array();
1208  $_SESSION['scan_list_file'] = array();
1209  $_SESSION['scan_logs'] .= pwg_get_file_list('.');
1210  sort($_SESSION['scan_list_fold']);
1211         
1212  // Erase first file list because root directory does not contain images.
1213  $_SESSION['scan_list_file'] = array();
1214           
1215  // What are we doing at next step
1216  if(count($_SESSION['scan_list_fold']) > 0)
1217  {
1218    $_SESSION['scan_step'] = 'list';
1219  }
1220  else
1221  {
1222    $_SESSION['scan_step'] = 'stop';
1223  }
1224 
1225  //~ pwg_log("GENARATE start <<<\n".var_export($_SESSION['scan_list_fold'], true)."\n".var_export($_SESSION['scan_list_file'], true)."\nGENERATE start <<<\n");
1226  //~ pwg_log('<<<<< pwg_generate_start() <<<<<'."\n");
1227}
1228
1229function pwg_generate_list()
1230{
1231  //~ pwg_log('>>>>> pwg_generate_list() >>>>>'."\n");
1232  //~ pwg_log("GENARATE list >>>\n".var_export($_SESSION['scan_list_fold'], true)."\n".var_export($_SESSION['scan_list_file'], true)."\nGENERATE list >>>\n");
1233 
1234  global $g_listing;
1235 
1236  // Flush line <dirX name=""> in xml file
1237  $dirname = basename($_SESSION['scan_list_fold'][0]);
1238  $line = pwg_get_indent('dir').'<dir'.pwg_get_level($_SESSION['scan_list_fold'][0]).' name="'.$dirname.'">'."\n";
1239  fwrite($g_listing, $line);
1240 
1241  // Get list of files and directories
1242  $_SESSION['scan_logs'] .= pwg_get_file_list($_SESSION['scan_list_fold'][0]);
1243  sort($_SESSION['scan_list_fold']); // Mandatory to keep the tree order
1244  sort($_SESSION['scan_list_file']); // Easier to read when sorted
1245 
1246  // Flush line <root>
1247  $line = pwg_get_indent('root').'<root>'."\n";
1248  fwrite($g_listing, $line);
1249 
1250  // What are we doing at next step
1251  $_SESSION['scan_step'] = 'scan';
1252 
1253  //~ pwg_log("GENARATE list <<<\n".var_export($_SESSION['scan_list_fold'], true)."\n".var_export($_SESSION['scan_list_file'], true)."\nGENERATE list <<<\n");
1254  //~ pwg_log('<<<<< pwg_generate_list() <<<<<'."\n");
1255}
1256
1257function pwg_generate_scan()
1258{
1259  //~ pwg_log('>>>>> pwg_generate_scan() >>>>>'."\n");
1260  //~ pwg_log("GENARATE scan >>>\n".var_export($_SESSION['scan_list_fold'], true)."\n".var_export($_SESSION['scan_list_file'], true)."\nGENERATE scan >>>\n");
1261 
1262  global $g_listing, $conf;
1263 
1264  while (pwg_continue() and count($_SESSION['scan_list_file']) > 0)
1265  {
1266    $line = '';
1267    $_SESSION['scan_logs'] .= pwg_scan_file($_SESSION['scan_list_file'][0], $line);
1268   
1269    if (strlen($line) > 0)
1270    {
1271      fwrite($g_listing, $line);
1272    }
1273    //~ pwg_log('---<< Pull of $_SESSION[scan_list_file] value "'.$_SESSION['scan_list_file'][0].'"'."\n");
1274    array_shift($_SESSION['scan_list_file']);
1275    $_SESSION['scan_cnt_file']++;
1276  }
1277         
1278  if (count($_SESSION['scan_list_file']) <= 0)
1279  {
1280    $_SESSION['scan_step'] = 'prot';
1281  }
1282 
1283  //~ pwg_log("GENERATE scan <<<\n".var_export($_SESSION['scan_list_fold'], true)."\n".var_export($_SESSION['scan_list_file'], true)."\nGENERATE scan <<<\n");
1284  //~ pwg_log('<<<<< pwg_generate_scan() <<<<<'."\n");
1285}
1286
1287function pwg_generate_prot()
1288{
1289  //~ pwg_log('>>>>> pwg_generate_prot() >>>>>'."\n");
1290  //~ pwg_log("GENARATE prot >>>\n".var_export($_SESSION['scan_list_fold'], true)."\n".var_export($_SESSION['scan_list_file'], true)."\nGENERATE prot >>>\n");
1291 
1292  global $conf, $g_listing;
1293 
1294  // Flush line </root>
1295  $line = pwg_get_indent('root').'</root>'."\n";
1296  fwrite($g_listing, $line);
1297 
1298  if ($conf['protect'])
1299  {
1300    $_SESSION['scan_logs'] .= pwg_protect_directories($_SESSION['scan_list_fold'][0]);
1301  }
1302 
1303  // How many directories to close
1304  $current_level = pwg_get_level($_SESSION['scan_list_fold'][0]);
1305  if (isset($_SESSION['scan_list_fold'][1]))
1306  {
1307    //~ pwg_log('---<< Pull of $_SESSION[scan_list_fold] value "'.$_SESSION['scan_list_fold'][0].'"'."\n");
1308    array_shift($_SESSION['scan_list_fold']);
1309    $_SESSION['scan_cnt_fold']++;
1310    $next_level = pwg_get_level($_SESSION['scan_list_fold'][0]);
1311    $_SESSION['scan_step'] = 'list';
1312  }
1313  else
1314  {
1315    $next_level = -1;
1316    $_SESSION['scan_cnt_fold']++;
1317    $_SESSION['scan_step'] = 'stop';
1318  }
1319 
1320  if ($current_level == $next_level)
1321  {
1322    fwrite($g_listing, pwg_close_level($current_level, 1));
1323  }
1324  else
1325  {
1326    if (($current_level > $next_level))
1327    {
1328      fwrite($g_listing, pwg_close_level($current_level, $current_level-$next_level+1));
1329    } // Nothing to do if current_level < next_level
1330  }
1331
1332  //~ pwg_log("GENERATE prot <<<\n".var_export($_SESSION['scan_list_fold'], true)."\n".var_export($_SESSION['scan_list_file'], true)."\nGENERATE prot <<<\n");
1333  //~ pwg_log('<<<<< pwg_generate_prot() <<<<<'."\n");
1334}
1335
1336function pwg_generate_stop()
1337{
1338  //~ pwg_log('>>>>> pwg_generate_stop() >>>>>'."\n");
1339  //~ pwg_log("GENARATE stop >>>\n".var_export($_SESSION['scan_list_fold'], true)."\n".var_export($_SESSION['scan_list_file'], true)."\nGENERATE stop >>>\n");
1340 
1341  global $pwg_conf, $g_listing, $g_header, $g_message, $g_footer;
1342 
1343  // Flush line </informations>
1344  fwrite($g_listing, '</informations>'."\n");
1345 
1346  // backup error log before cleaning session
1347  $time_elapsed = number_format(pwg_get_moment() - $_SESSION['scan_time'], 3, '.', ' ');
1348 
1349  $g_header   = ' : <span class="success">Generate</span>';
1350  $g_message  = '        <div>'."\n".$_SESSION['scan_logs'].'        </div>'."\n";
1351  $g_message .= '        <div><code class="success">'.$_SESSION['scan_cnt_fold'].'</code> directories parsed<br />'."\n";
1352  $g_message .= '        <code class="success">'.$_SESSION['scan_cnt_file'].'</code> files scanned</div>'."\n";
1353  $g_message .= '        <div>View <a href="listing.xml">listing.xml</a></div>'."\n";
1354  $g_message .= '        <div style="{text-align: right;}">Listing generated in : <code>'.$time_elapsed.' s</code></div>';
1355  $g_footer   = '<a href="'.$pwg_conf['this_url'].'" title="Main menu"><img src="'.$pwg_conf['icon_dir'].'up.png" /></a>';
1356     
1357  // What are we doing at next step
1358  $_SESSION['scan_step'] = 'exit';
1359 
1360  //~ pwg_log("GENARATE stop <<<\n".var_export($_SESSION['scan_list_fold'], true)."\n".var_export($_SESSION['scan_list_file'], true)."\nGENERATE stop <<<\n");
1361  //~ pwg_log('<<<<< pwg_generate_stop() <<<<<'."\n");
1362}
1363
1364// +-----------------------------------------------------------------------+
1365// |                                ALWAYS CALLED FUNCTIONS                |
1366// +-----------------------------------------------------------------------+
1367
1368/**
1369 * This function check step and time ellapsed to determine end of loop
1370 *
1371 * @return bool
1372 */
1373function pwg_continue()
1374{
1375  //~ pwg_log('>>>>> pwg_continue() >>>>>'."\n");
1376 
1377  global $conf, $pwg_conf, $g_refresh, $g_header, $g_message, $g_footer, $start_time;
1378 
1379  if (!isset($_SESSION['scan_step']) or $_SESSION['scan_step'] == 'exit')
1380  {
1381    // evident end of process
1382    $return = false;
1383  }
1384  else
1385  {
1386    if ($pwg_conf['safe_mode'])
1387    {
1388      // can not reset the time
1389      $time_elapsed = pwg_get_moment() - $start_time;
1390      if ($time_elapsed < $conf['max_execution_time'])
1391      {
1392        $return = true;
1393      }
1394      else
1395      {
1396        $start_time = $_SESSION['scan_time'];
1397        $formated_time = number_format(pwg_get_moment() - $start_time, 3, '.', ' ');
1398
1399        $g_refresh = '<meta http-equiv="Refresh" content="'.$conf['refresh_delay'].'">'."\n";
1400        $g_header  = ' : <span class="success">'.ucfirst($_SESSION['scan_action']).'</span>';
1401        $g_message = '';
1402        if ($_SESSION['scan_cnt_fold'] != 0)
1403        {
1404          $g_message .= '<code class="success">'.$_SESSION['scan_cnt_fold'].'</code> directories scanned<br />'."\n";
1405        }
1406        if ($_SESSION['scan_cnt_file'] != 0)
1407        {
1408          $g_message .= '<code class="success">'.$_SESSION['scan_cnt_file'].'</code> files scanned<br />'."\n";
1409        }
1410        $nb = count($_SESSION['scan_list_fold']);
1411        if ($nb > 0)
1412        {
1413          $g_message .= '<code class="warning">'.$nb.'</code> directories to scan<br />'."\n";
1414        }
1415        $nb = count($_SESSION['scan_list_file']);
1416        if ($nb > 0)
1417        {
1418          $g_message .= '<code class="warning">'.$nb.'</code> files to scan<br />'."\n";
1419        }
1420        $g_message .= '        <div style="{text-align: right;}">Time elapsed : <code>'.$formated_time.' s</code></div>';
1421        $g_footer  = '<a href="'.$pwg_conf['this_url'].'?action='.$_SESSION['scan_action'].'" title="Continue"><img src="'.$pwg_conf['icon_dir'].'right.png" /></a>'."\n";
1422       
1423        $return = false;
1424      }
1425    }
1426    else
1427    {
1428      // reset the time
1429      set_time_limit(intval(ini_get('max_execution_time')));
1430      $return = true;
1431    }
1432  }
1433  //~ pwg_log('<<<<< pwg_continue() returns '.var_export($return, true).' <<<<<'."\n");
1434 
1435  return $return;
1436}
1437
1438/**
1439 * This function :
1440 * -> Verify the script call
1441 * -> Lock the script
1442 * -> Open listing.xml if action is 'generate'
1443 * -> Initialize output and session variables
1444 *
1445 * @return nothing
1446 */
1447function pwg_init()
1448{
1449  //~ pwg_log('>>>>> pwg_init() >>>>>'."\n");
1450
1451  global $g_message, $g_listing, $g_footer, $conf, $pwg_conf, $start_time;
1452  $init_message = '';
1453 
1454  // Lock other script sessions, this lock will be remove during 'exit' step
1455  if (!isset($_SESSION['scan_step']))
1456  {
1457    $fp = @fopen(__FILE__.'.lock', 'x+'); // return false if __FILE__.lock exists or if cannot create
1458    if ($fp == false)
1459    {
1460      $g_header   = $_SESSION['scan_action'];
1461      $g_message  = '        <code class="failure">Failure -</code> Another script is running';
1462      $g_message .= ' <img src="'.$pwg_conf['icon_dir'].'add_tag.png" title="Delete file '.__FILE__.'.lock and retry" />';
1463      $g_message .= "\n";
1464      $g_footer   = '<a href="'.$pwg_conf['this_url'].'" title="Main menu"><img src="'.$pwg_conf['icon_dir'].'up.png" /></a>'."\n";
1465      $_SESSION['scan_step'] = 'exit';
1466      //~ pwg_log('<<<<< pwg_init() failure <<<<<'."\n");
1467      return;
1468    }
1469    else
1470    {
1471      fwrite($fp, session_id()); // Writing session_id to trace lock
1472      fclose($fp);
1473      $_SESSION['scan_step'] = 'init';
1474    }
1475  }
1476 
1477  // Verify and backup parameter action. This backup will be removed during step 'exit'
1478  if (isset($_REQUEST['action']))
1479  {
1480    if (in_array($_REQUEST['action'], $pwg_conf['scan_action']))
1481    {
1482      if (isset($_SESSION['scan_action']))
1483      {
1484        if ($_SESSION['scan_action'] != $_REQUEST['action'])
1485        {
1486          // Fatal error
1487          $g_message  = '        <code class="failure">Failure -</code> Parameter <code>action</code> differs between url and session';
1488          $g_message .= "\n";
1489          $g_footer   = '<a href="'.$pwg_conf['this_url'].'" title="Main menu"><img src="'.$pwg_conf['icon_dir'].'up.png" /></a>'."\n";
1490          $_SESSION['scan_step'] = 'exit';
1491          //~ pwg_log('<<<<< pwg_init() failure <<<<<'."\n");
1492          return;
1493        }
1494      }
1495      else
1496      {
1497        $_SESSION['scan_action'] = $_REQUEST['action'];
1498      }
1499    }
1500    else
1501    {
1502      // Fatal error
1503      $g_message  = '        <code class="failure">Failure -</code> Problem with <code>action</code> parameter';
1504      $g_message .= ' <img src="'.$pwg_conf['icon_dir'].'add_tag.png" title="empty, '.implode(', ', $pwg_conf['scan_action']).'" />';
1505      $g_message .= "\n";
1506      $g_footer   = '<a href="'.$pwg_conf['this_url'].'" title="Main menu"><img src="'.$pwg_conf['icon_dir'].'up.png" /></a>'."\n";
1507      $_SESSION['scan_step'] = 'exit';
1508      //~ pwg_log('<<<<< pwg_init() failure <<<<<'."\n");
1509      return;
1510    }
1511  }
1512  else
1513  {
1514    // Here we are on welcome page
1515    $g_message  = '        <ul>'."\n";
1516    $g_message .= '          <li><a href="'.$pwg_conf['this_url'].'?action=test" title="Display/Compare script version">Test</a></li>'."\n";
1517    $g_message .= '          <li><a href="'.$pwg_conf['this_url'].'?action=clean" title="Delete listing.xml if exists">Clean</a></li>'."\n";
1518    $g_message .= '          <li><a href="'.$pwg_conf['this_url'].'?action=generate" title="Scan all images from this directory and write informations in listing.xml">Listing</a></li>'."\n";
1519    $g_message .= '        </ul>'."\n";
1520    $g_footer   = '<a href="'.$conf['gallery'].'/admin.php?page=site_manager" title="Main gallery :: site manager">';
1521    $g_footer  .= '<img src="'.$pwg_conf['icon_dir'].'home.png" /></a>'."\n";
1522    $_SESSION['scan_step'] = 'exit';
1523    $_SESSION['scan_action'] = '';
1524  }
1525 
1526  // Actions to do at the init of generate
1527  if ($_SESSION['scan_action'] == 'generate')
1528  {
1529    // Open XML file
1530    $mode = ($_SESSION['scan_step'] == 'init') ? 'w' : 'a'; // Erase old listing.xml at the beginning of generation (mode w)
1531    $g_listing = @fopen('listing.xml', $mode);
1532    if ($g_listing === false)
1533    {
1534      $g_header   = $_SESSION['scan_action'];
1535      $g_message  = '        <code class="failure">Failure -</code> Can not write file <code>listing.xml</code>';
1536      $g_message .= "\n";
1537      $g_footer   = '<a href="'.$pwg_conf['this_url'].'" title="Main menu"><img src="'.$pwg_conf['icon_dir'].'up.png" /></a>'."\n";
1538      $_SESSION['scan_step'] = 'exit';
1539      //~ pwg_log('<<<<< pwg_init() failure <<<<<'."\n");
1540      return;
1541    }
1542   
1543    // Check graphical capabilities
1544    $init_message = pwg_check_graphics();
1545  }
1546   
1547  // Initializing session counters. This counters will be completely unset during step 'exit'
1548  if ($_SESSION['scan_step'] == 'init')
1549  {
1550    $_SESSION['scan_list_file'] = array();
1551    $_SESSION['scan_list_fold'] = array();
1552    $_SESSION['scan_cnt_file'] = 0;
1553    $_SESSION['scan_cnt_fold'] = 0;
1554    $_SESSION['scan_time'] = $start_time;
1555    $_SESSION['scan_step'] = 'start';
1556    $_SESSION['scan_logs'] = $init_message;
1557  }
1558 
1559  //~ pwg_log('<<<<< pwg_init() success <<<<<'."\n");
1560}
1561
1562/**
1563 * This function :
1564 * -> Close listing.xml if action is 'generate'
1565 * -> Unlock the script
1566 * -> Erase session variables
1567 *
1568 * @return nothing
1569 */
1570function pwg_exit()
1571{
1572  //~ pwg_log('>>>>> pwg_exit() >>>>>'."\n");
1573 
1574  global $g_listing;
1575 
1576  // Close XML file
1577  if ($_SESSION['scan_action'] == 'generate' and $g_listing != false)
1578  {
1579    fclose($g_listing);
1580  }
1581 
1582  // Unlock script
1583  unlink(__FILE__.'.lock');
1584 
1585  // Erase session counters
1586  unset($_SESSION['scan_list_file']);
1587  unset($_SESSION['scan_list_fold']);
1588  unset($_SESSION['scan_cnt_file']);
1589  unset($_SESSION['scan_cnt_fold']);
1590  unset($_SESSION['scan_time']);
1591  unset($_SESSION['scan_step']);
1592  $local_action = $_SESSION['scan_action'];
1593  unset($_SESSION['scan_action']);
1594  unset($_SESSION['scan_logs']);
1595  session_destroy();
1596 
1597  // Call specific action post process
1598  if (is_callable('pwg_'.$local_action.'_exit'))
1599  {
1600    call_user_func('pwg_'.$local_action.'_exit');
1601  }
1602 
1603  //~ pwg_log('<<<<< pwg_exit() <<<<<'."\n");
1604}
1605
1606// +-----------------------------------------------------------------------+
1607// |                                Script                                 |
1608// +-----------------------------------------------------------------------+
1609session_save_path('.');
1610session_start();
1611
1612$start_time = pwg_get_moment();
1613
1614// Initializing message for web page
1615$g_refresh = '';
1616$g_header  = '';
1617$g_message = '';
1618$g_footer  = '';
1619$g_listing = '';
1620
1621pwg_init();
1622
1623while(pwg_continue())
1624{
1625  if (is_callable('pwg_'.$_SESSION['scan_action'].'_'.$_SESSION['scan_step']))
1626  {
1627    call_user_func('pwg_'.$_SESSION['scan_action'].'_'.$_SESSION['scan_step']); // Run the step : start, list, scan, stop are available
1628  }
1629  else
1630  {
1631    $g_header   = $_SESSION['scan_action'];
1632    $g_message  = '        <code class="failure">Failure -</code> INTERNAL STEP ERROR : <code>pwg_'.$_SESSION['scan_action'].'_'.$_SESSION['scan_step'].'()</code> undefined';
1633    $g_message .= "\n";
1634    $g_footer   = '<a href="'.$pwg_conf['this_url'].'" title="Main menu"><img src="'.$pwg_conf['icon_dir'].'up.png" /></a>'."\n";
1635    $_SESSION['scan_step'] = 'exit';
1636  }
1637}
1638
1639if ($_SESSION['scan_step'] == 'exit')
1640{
1641  pwg_exit();
1642}
1643
1644?>
1645<html>
1646  <head>
1647  <?php echo $g_refresh; ?>
1648  <title>Manage remote gallery</title>
1649  </head>
1650    <style type="text/css">
1651      code {font-weight: bold}
1652      img {border-style: none; vertical-align: middle}
1653      ul {list-style-image: url(<?php echo $pwg_conf['icon_dir']; ?>add_tag.png)}     
1654      .success {color: green}
1655      .warning {color: orange}
1656      .failure {color: red}
1657      .header {text-align: center; font-variant: small-caps; font-weight: bold;}
1658      .p {color: #F93;}
1659      .w {color: #ccc;}
1660      .g {color: #69C;}
1661      .pwg {text-decoration: none; border-bottom-style: dotted; border-bottom-width: 1px;}
1662      .content {width: 75%; position: absolute; top: 10%; left: 12%;}
1663      .footer {text-align: right;}
1664      .pwg_block {float: left;}
1665    </style>
1666  <body>
1667    <div class="content">
1668      <fieldset class="header">
1669        <span class="p">Php</span>
1670        <span class="w">Web</span>
1671        <span class="g">Gallery</span>
1672        &nbsp;remote site<? echo $g_header; ?>
1673      </fieldset>
1674      <fieldset>
1675<?php echo $g_message; ?>
1676      </fieldset>
1677      <fieldset class="footer">
1678        <div class="pwg_block">
1679          Powered by <a href="http://www.phpwebgallery.net" class="pwg"><span class="p">Php</span><span class="w">Web</span><span class="g">Gallery</span></a>
1680        </div>
1681        <?php echo $g_footer; ?>
1682      </fieldset>
1683    </div>
1684  </body>
1685</html>
Note: See TracBrowser for help on using the repository browser.