source: trunk/tools/create_listing_file.php @ 12137

Last change on this file since 12137 was 12137, checked in by plg, 13 years ago

change version number to 2.3.0RC3

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