source: branches/1.7/tools/create_listing_file.php @ 14974

Last change on this file since 14974 was 2834, checked in by laurent_duretz, 16 years ago

Issue 899

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