root/trunk/tools/create_listing_file.php @ 1867

Revision 1867, 54.3 KB (checked in by laurent_duretz, 6 years ago)

minor update : supress warning on images without IPTC metadatas

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