source: tags/2.1.0RC1/tools/create_listing_file.php @ 5412

Last change on this file since 5412 was 5412, checked in by plg, 14 years ago

release number 2.1.0RC1 hard coded

File size: 55.4 KB
Line 
1<?php
2// +-----------------------------------------------------------------------+
3// | Piwigo - a PHP based picture gallery                                  |
4// +-----------------------------------------------------------------------+
5// | Copyright(C) 2008-2010 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.1.0RC1';
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     
743      // get EXIF meta datas
744      if ($conf['use_exif'])
745      {
746        // Verify activation of exif module
747        if (extension_loaded('exif'))
748        {
749          if ($exif = read_exif_data($file_full))
750          {
751            foreach ($conf['use_exif_mapping'] as $pwg_key => $exif_key )
752            {
753              if (isset($exif[$exif_key]))
754              {
755                if ( in_array($pwg_key, array('date_creation','date_available') ) )
756                {
757                  if (preg_match('/^(\d{4}):(\d{2}):(\d{2})/', $exif[$exif_key], $matches))
758                    {
759                      $element[$pwg_key] = $matches[1].'-'.$matches[2].'-'.$matches[3];
760                    }
761                }
762                else
763                {
764                  $element[$pwg_key] = $exif[$exif_key];
765                }
766              }
767            }
768          }
769        }
770      }
771     
772      // get IPTC meta datas
773      if ($conf['use_iptc'])
774      {
775        $iptc = pwg_get_sync_iptc_data($file_full);
776        if (count($iptc) > 0)
777        {
778          foreach (array_keys($iptc) as $key)
779          {
780            $element[$key] = addslashes($iptc[$key]);
781          }
782        }
783      }
784     
785    }
786    else
787    {
788      $error_log .= '          <code class="failure">Failure -</code> Thumbnail is missing for <code>'.$file_dir.'/'.$file_base.'</code>';
789      $error_log .= ' <img src="'.$pwg_conf['icon_dir'].'add_tag.png" title="'.$file_dir.'/thumbnail/'.$conf['prefix_thumbnail'].$file_short;
790      $error_log .= '.xxx ('.implode(', ', $conf['picture_ext']).')" /><br />'."\n";
791    }
792  }
793  else
794  {
795    // Here we scan a non picture file : thumbnail and high are unused, representative is optionnal
796    $element['tn_ext'] = pwg_get_thumbnail_ext($file_dir, $file_short, $file_ext, $log);
797    $ext = pwg_get_representative_ext($file_dir, $file_short);
798    if ($ext != '')
799    {
800      $element['representative_ext'] = $ext;
801    }
802    $element['filesize'] = floor(filesize($file_full) / 1024);
803  }
804 
805  if (strlen($error_log) == 0)
806  {
807    $line = pwg_get_indent('element').'<element ';
808    foreach($element as $key => $value)
809    {
810      $line .= $key.'="'.$value.'" ';
811    }
812    $line .= '/>'."\n";
813  }
814
815  // Adding Icon generation log to message
816  $error_log .= $icon_log;
817
818  //~ pwg_log('<<<<< pwg_scan_file() returns '.var_export($error_log, TRUE).' <<<<<'."\n");
819  return $error_log;
820}
821
822/**
823 * returns current level in tree
824 *
825 * @return integer
826 */
827function pwg_get_level($dir)
828{
829  //~ pwg_log('>>>>> pwg_get_level($dir = '.var_export($dir, TRUE).') >>>>>'."\n");
830 
831  $level = substr_count($dir, '/') - 1; // -1 because of ./ at the beginning of path
832 
833  //~ pwg_log('<<<<< pwg_get_level() returns '.var_export($level, TRUE).' <<<<<'."\n");
834  return $level;
835}
836
837/**
838 * returns indentation of element
839 *
840 * @param string $element_type : 'root', 'element', 'dir'
841 * @return string
842 */
843function pwg_get_indent($element_type)
844{
845  //~ pwg_log('>>>>> pwg_get_indent($element_type = '.var_export($element_type, TRUE).') >>>>>'."\n");
846 
847  $level = substr_count($_SESSION['scan_list_fold'][0], '/') - 1; // because of ./ at the beginning
848  switch($element_type)
849  {
850    case 'dir' :
851    {
852      $indent = str_repeat(' ', 2*pwg_get_level($_SESSION['scan_list_fold'][0]));
853      break;
854    }
855    case 'root' :
856    {
857      $indent = str_repeat(' ', 2*pwg_get_level($_SESSION['scan_list_fold'][0])+2);
858      break;
859    }
860    case 'element' :
861    {
862      $indent = str_repeat(' ', 2*pwg_get_level($_SESSION['scan_list_fold'][0])+4);
863      break;
864    }
865    default :
866    {
867      $indent = '';
868      break;
869    }
870  }
871 
872  //~ pwg_log('<<<<< pwg_get_indent() returns '.var_export(strlen($indent), TRUE).' spaces <<<<<'."\n");
873  return $indent;
874}
875
876/**
877 * create index.php in directory and reserved sub_directories, return logs
878 *
879 * @param string dir
880 * @return string
881 */
882function pwg_protect_directories($directory)
883{
884  //~ pwg_log('>>>>> pwg_protect_directories($directory = '.var_export($directory, true).') >>>>>'."\n");
885 
886  global $conf;
887 
888  $error_log = '';
889  $dirlist = array($directory, $directory.'/'.$conf['thumbs'], $directory.'/'.$conf['high'], $directory.'/'.$conf['represent']);
890 
891  foreach ($dirlist as $dir)
892  {
893    if (file_exists($dir))
894    {
895      if (!file_exists($dir.'/index.php'))
896      {
897        $file = @fopen($dir.'/index.php', 'w');
898        if ($file != false)
899        {
900          fwrite($file, $pwg_conf['protect_content']); // the return code should be verified
901          $error_log .= '          <code class="success">Success -</code> index.php created in directory <a href="'.$dir.'">'.$dir."</a><br />\n";
902        }
903        else
904        {
905          $error_log .= '          <code class="failure">Failure -</code> Can not create index.php in directory <code>'.$dir."</code><br />\n";
906        }
907      }
908      else
909      {
910        if ($conf['protect_warnings'])
911        {
912          $error_log .= '          <code class="warning">Warning -</code> index.php already exists in directory <a href="'.$dir.'">'.$dir."</a><br />\n";
913        }
914      }
915    }
916  }
917 
918  //~ pwg_log('<<<<< pwg_protect_directories() returns '.var_export($error_log, true).' <<<<<'."\n");
919  return $error_log;
920}
921
922/**
923 * returns file extension (.xxx)
924 *
925 * @param string $file
926 * @return string
927 */
928function pwg_get_file_extension($file)
929{
930  //~ pwg_log('>>>>> pwg_get_file_extension($file = '.var_export($file, true).') >>>>>'."\n");
931 
932  $ext = substr(strrchr($file, '.'), 1, strlen ($file));
933 
934  //~ pwg_log('<<<<< pwg_get_file_extension() returns '.var_export($ext, true).' <<<<<'."\n");
935  return $ext;
936}
937
938/**
939 * completes directory list of supported files and returns error logs
940 *
941 * @param string $directory
942 * @return string
943 */
944function pwg_get_file_list($directory)
945{
946  //~ pwg_log('>>>>> pwg_get_file_list($directory = '.var_export($directory, true).') >>>>>'."\n");
947 
948  global $conf, $pwg_conf;
949
950  $errorLog = '';
951  $dir = opendir($directory);
952  while (($file = readdir($dir)) !== false)
953  {
954    switch (filetype($directory."/".$file))
955    {
956      case 'file' :
957      {
958        if (in_array(pwg_get_file_extension($file), $conf['file_ext']))
959        {
960          // The file pointed is a regular file with a supported extension
961          array_push($_SESSION['scan_list_file'], $directory.'/'.$file);
962          //~ pwg_log('--->> Push in $_SESSION[scan_list_file] value "'.$directory.'/'.$file.'"'."\n");
963          if (!preg_match('/^[a-zA-Z0-9-_.]+$/', $file))
964          {
965            $errorLog .= '          <code class="failure">Failure -</code> Invalid file name for <code>'.$file.'</code> in <code>'.$directory.'</code>';
966            $errorLog .= ' <img src="'.$pwg_conf['icon_dir'].'add_tag.png"';
967            $errorLog .= ' title="Name should be composed of letters, figures, -, _ or . ONLY" /><br />'."\n";
968          }
969        }
970        break; // End of filetype FILE
971      }
972      case 'dir' :
973      {
974        if(!in_array($file, $pwg_conf['reserved_directory_names']))
975        {
976          // The file pointed is a directory but neither system directory nor reserved by PWG
977          array_push($_SESSION['scan_list_fold'], $directory.'/'.$file);
978          //~ pwg_log('--->> Push in $_SESSION[scan_list_fold] value "'.$directory.'/'.$file.'"'."\n");
979          if (!preg_match('/^[a-zA-Z0-9-_.]+$/', $file))
980          {
981            $errorLog .= '          <code class="failure">Failure -</code> Invalid directory name for <code>'.$directory.'/'.$file.'</code>';
982            $errorLog .= ' <img src="'.$pwg_conf['icon_dir'].'add_tag.png"';
983            $errorLog .= ' title="Name should be composed of letters, figures, -, _ or . ONLY" /><br />'."\n";
984          }
985        }
986        break; // End of filetype DIR
987      }
988      case 'fifo' :
989      case 'char' :
990      case 'block' :
991      case 'link' :
992      case 'unknown':
993      default :
994      {
995        // PWG does not manage these cases
996        break;
997      }
998    }
999  }
1000  closedir($dir);
1001 
1002  //~ pwg_log('<<<<< pwg_get_file_list() returns '.var_export($errorLog, true).' <<<<<'."\n");
1003
1004  return $errorLog;
1005}
1006
1007/**
1008 * returns a float value coresponding to the number of seconds since the
1009 * unix epoch (1st January 1970) and the microseconds are precised :
1010 * e.g. 1052343429.89276600
1011 *
1012 * @return float
1013 */
1014function pwg_get_moment()
1015{
1016  //~ pwg_log('>>>>> pwg_get_moment() >>>>>'."\n");
1017 
1018  $t1 = explode(' ', microtime());
1019  $t2 = explode('.', $t1[0]);
1020  $t2 = $t1[1].'.'.$t2[1];
1021
1022  //~ pwg_log('<<<<< pwg_get_moment() returns '.var_export($t2, true).' <<<<<'."\n");
1023  return $t2;
1024}
1025
1026/**
1027 * return true if HTTP_REFERER and PHP_SELF are similar
1028 *
1029 * return boolean
1030 */
1031function pwg_referer_is_me()
1032{
1033  global $pwg_conf;
1034
1035  //~ pwg_log('>>>>> pwg_referer_is_me() >>>>>'."\n");
1036 
1037  $response = false;
1038  $caller = (isset($_SERVER['HTTP_REFERER'])) ? $_SERVER['HTTP_REFERER'] : '';
1039
1040  if (strcasecmp($pwg_conf['this_url'], $caller) == 0) {
1041    $response = true;
1042  }
1043
1044  //~ pwg_log('<<<<< pwg_referer_is_me() returns '.var_export($response, true).' <<<<<'."\n");
1045  return $response;
1046}
1047
1048// +-----------------------------------------------------------------------+
1049// |                                pwg_<ACTION>_<STEP> Functions          |
1050// +-----------------------------------------------------------------------+
1051
1052function pwg_test_start()
1053{
1054  //~ pwg_log('>>>>> pwg_test_start() >>>>>'."\n");
1055
1056  global $g_message, $conf;
1057 
1058  if (isset($_REQUEST['version']))
1059  {
1060    if ($_REQUEST['version'] != $conf['version'])
1061    {
1062      $g_message = '0';
1063    }
1064    else
1065    {
1066      $g_message = '1';
1067    }
1068  }
1069  else
1070  {
1071    $g_message  = '1';
1072  }
1073  $_SESSION['scan_step'] = 'exit';
1074 
1075  //~ pwg_log('<<<<< pwg_test_start() <<<<<'."\n");
1076}
1077
1078function pwg_test_exit()
1079{
1080  //~ pwg_log('>>>>> pwg_test_exit() >>>>>'."\n");
1081
1082  global $g_header, $g_message, $g_footer, $conf, $pwg_conf;
1083 
1084  if (pwg_referer_is_me())
1085  {
1086    $g_header  = ' : <span class="success">Test</span>'."\n";
1087    $g_footer  = '<a href="'.$pwg_conf['this_url'].'" title="Main menu"><img src="'.$pwg_conf['icon_dir'].'up.png" /></a>'."\n";
1088   
1089    // Write version
1090    $g_message  = '        <h3>Script version</h3>'."\n";
1091    $g_message .= '        This script is tagged : <code class="failure">'.$conf['version'].'</code>'."\n";
1092    // write GD support
1093    if (!is_callable('gd_info'))
1094    {
1095      $g_message .= '        <code class="failure">Failure -</code> Your server can not generate imagess<br />'."\n";
1096    }
1097    else
1098    {
1099      $info = gd_info();
1100      $gd_full_version = preg_replace('/[[:alpha:][:space:]()]+/', '', $info['GD Version']);
1101      list($gd_version) = preg_split('/[.]+/', $gd_full_version);
1102     
1103      $g_message .= '        <h3>Image generation</h3>'."\n";
1104      $g_message .= '        <code class="success">Success -</code> Your server can generate images<br />'."\n";
1105      $g_message .= '        <code class="warning">Warning -</code> Your server support GD'.$gd_version.' (v'.$gd_full_version.')<br />'."\n";
1106      $format_list = array();
1107      $format = ($info['GIF Create Support']) ? '<code>gif</code>' : NULL;
1108      array_push($format_list, $format);
1109      $format = ((isset($info['JPG Support']) and $info['JPG Support']) or (isset($info['JPEG Support']) and $info['JPEG Support'])) ? '<code>jpg</code>' : NULL;
1110      array_push($format_list, $format);
1111      $format = ($info['PNG Support']) ? '<code>png</code>' : NULL;
1112      array_push($format_list, $format);
1113      $g_message .= '        <code class="warning">Warning -</code> Your server support format: '.implode(', ', $format_list)."\n";
1114    }
1115   
1116    $g_message .= '        <h3>Directory parsing</h3>'."\n";
1117    if ($pwg_conf['safe_mode'])
1118    {
1119      $g_message .= '        <code class="warning">Warning -</code> Your server does not support to resize execution time'."\n";
1120    }
1121    else
1122    {
1123      $g_message .= '        <code class="success">Success -</code> Your server supports to resize execution time'."\n";
1124    }
1125  }
1126  else
1127  {
1128    // compare version in GET parameter with $conf['version']
1129    if ($g_message == '1')
1130    {
1131      exit('<pre>PWG-INFO-2: test successful</pre>');
1132    }
1133    else
1134    {
1135      exit('<pre>PWG-ERROR-4: Piwigo versions differs</pre>');
1136    }
1137  }
1138 
1139  //~ pwg_log('<<<<< pwg_test_exit() <<<<<'."\n");
1140}
1141
1142function pwg_clean_start()
1143{
1144  //~ pwg_log('>>>>> pwg_clean_start() >>>>>'."\n");
1145 
1146  global $g_message;
1147 
1148  if(@unlink('./listing.xml'))
1149  {
1150    $g_message = '1';
1151  }
1152  else
1153  {
1154    $g_message = '0';
1155  }
1156
1157  $_SESSION['scan_step'] = 'exit';
1158 
1159  //~ pwg_log('<<<<< pwg_clean_start() <<<<<'."\n");
1160}
1161
1162function pwg_clean_exit()
1163{
1164  //~ pwg_log('>>>>> pwg_clean_exit() >>>>>'."\n");
1165
1166  global $g_header, $g_message, $g_footer, $conf, $pwg_conf;
1167 
1168  if(pwg_referer_is_me())
1169  {
1170    $g_header = ' : <span class="success">Clean</span>';
1171    if ($g_message == '1')
1172    {
1173      $g_message = '        <code class="success">Success -</code> <code>listing.xml</code> file deleted'."\n";
1174    }
1175    else
1176    {
1177      $g_message = '        <code class="failure">Failure -</code> <code>listing.xml</code> does not exist or is read only'."\n";
1178    }
1179    $g_footer = '<a href="'.$pwg_conf['this_url'].'" title="Main menu"><img src="'.$pwg_conf['icon_dir'].'up.png" /></a>';
1180  }
1181  else
1182  {
1183    if ($g_message == '1')
1184    {
1185      exit('<pre>PWG-INFO-3 : listing.xml file deleted</pre>');
1186    }
1187    else
1188    {
1189      exit('<pre>PWG-ERROR-3 : listing.xml does not exist</pre>');
1190    }
1191  }
1192 
1193  //~ pwg_log('<<<<< pwg_clean_exit() <<<<<'."\n");
1194}
1195
1196function pwg_generate_start()
1197{
1198  //~ pwg_log('>>>>> pwg_generate_start() >>>>>'."\n");
1199  //~ pwg_log("GENARATE start >>>\n".var_export($_SESSION['scan_list_fold'], true)."\n".var_export($_SESSION['scan_list_file'], true)."\nGENERATE start >>>\n");
1200
1201  global $g_listing, $pwg_conf, $conf;
1202 
1203  // Flush line <informations>
1204  $xml_header_url = dirname($pwg_conf['this_url']);
1205  $xml_header_date = date('Y-m-d');
1206  $xml_header_version = htmlentities($conf['version']);
1207 
1208  $attrs = array();
1209  if ($conf['use_iptc'])
1210  {
1211    $attrs = array_merge($attrs, array_keys($conf['use_iptc_mapping']) );
1212  }
1213  if ($conf['use_exif'])
1214  {
1215    $attrs = array_merge($attrs, array_keys($conf['use_exif_mapping']) );
1216  }
1217  $xml_header_metadata = implode(',',array_unique($attrs));
1218 
1219  $xml_header = '<informations';
1220  $xml_header .= ' generation_date="'.$xml_header_date.'"';
1221  $xml_header .= ' phpwg_version="'.$xml_header_version.'"';
1222  $xml_header .= ' metadata="'.$xml_header_metadata.'"';
1223  $xml_header .= ' url="'.$xml_header_url.'/"';
1224  $xml_header .= '>'."\n";
1225 
1226  fwrite($g_listing, $xml_header);
1227 
1228  // Initialization of directory and file lists
1229  $_SESSION['scan_list_fold'] = array();
1230  $_SESSION['scan_list_file'] = array();
1231  $_SESSION['scan_logs'] .= pwg_get_file_list('.');
1232  sort($_SESSION['scan_list_fold']);
1233         
1234  // Erase first file list because root directory does not contain images.
1235  $_SESSION['scan_list_file'] = array();
1236           
1237  // What are we doing at next step
1238  if(count($_SESSION['scan_list_fold']) > 0)
1239  {
1240    $_SESSION['scan_step'] = 'list';
1241  }
1242  else
1243  {
1244    $_SESSION['scan_step'] = 'stop';
1245  }
1246 
1247  //~ pwg_log("GENARATE start <<<\n".var_export($_SESSION['scan_list_fold'], true)."\n".var_export($_SESSION['scan_list_file'], true)."\nGENERATE start <<<\n");
1248  //~ pwg_log('<<<<< pwg_generate_start() <<<<<'."\n");
1249}
1250
1251function pwg_generate_list()
1252{
1253  //~ pwg_log('>>>>> pwg_generate_list() >>>>>'."\n");
1254  //~ pwg_log("GENARATE list >>>\n".var_export($_SESSION['scan_list_fold'], true)."\n".var_export($_SESSION['scan_list_file'], true)."\nGENERATE list >>>\n");
1255 
1256  global $g_listing;
1257 
1258  // Flush line <dirX name=""> in xml file
1259  $dirname = basename($_SESSION['scan_list_fold'][0]);
1260  $line = pwg_get_indent('dir').'<dir'.pwg_get_level($_SESSION['scan_list_fold'][0]).' name="'.$dirname.'">'."\n";
1261  fwrite($g_listing, $line);
1262 
1263  // Get list of files and directories
1264  $_SESSION['scan_logs'] .= pwg_get_file_list($_SESSION['scan_list_fold'][0]);
1265  sort($_SESSION['scan_list_fold']); // Mandatory to keep the tree order
1266  sort($_SESSION['scan_list_file']); // Easier to read when sorted
1267 
1268  // Flush line <root>
1269  $line = pwg_get_indent('root').'<root>'."\n";
1270  fwrite($g_listing, $line);
1271 
1272  // What are we doing at next step
1273  $_SESSION['scan_step'] = 'scan';
1274 
1275  //~ pwg_log("GENARATE list <<<\n".var_export($_SESSION['scan_list_fold'], true)."\n".var_export($_SESSION['scan_list_file'], true)."\nGENERATE list <<<\n");
1276  //~ pwg_log('<<<<< pwg_generate_list() <<<<<'."\n");
1277}
1278
1279function pwg_generate_scan()
1280{
1281  //~ pwg_log('>>>>> pwg_generate_scan() >>>>>'."\n");
1282  //~ pwg_log("GENARATE scan >>>\n".var_export($_SESSION['scan_list_fold'], true)."\n".var_export($_SESSION['scan_list_file'], true)."\nGENERATE scan >>>\n");
1283 
1284  global $g_listing, $conf;
1285 
1286  while (pwg_continue() and count($_SESSION['scan_list_file']) > 0)
1287  {
1288    $line = '';
1289    $_SESSION['scan_logs'] .= pwg_scan_file($_SESSION['scan_list_file'][0], $line);
1290   
1291    if (strlen($line) > 0)
1292    {
1293      fwrite($g_listing, $line);
1294    }
1295    //~ pwg_log('---<< Pull of $_SESSION[scan_list_file] value "'.$_SESSION['scan_list_file'][0].'"'."\n");
1296    array_shift($_SESSION['scan_list_file']);
1297    $_SESSION['scan_cnt_file']++;
1298  }
1299         
1300  if (count($_SESSION['scan_list_file']) <= 0)
1301  {
1302    $_SESSION['scan_step'] = 'prot';
1303  }
1304 
1305  //~ pwg_log("GENERATE scan <<<\n".var_export($_SESSION['scan_list_fold'], true)."\n".var_export($_SESSION['scan_list_file'], true)."\nGENERATE scan <<<\n");
1306  //~ pwg_log('<<<<< pwg_generate_scan() <<<<<'."\n");
1307}
1308
1309function pwg_generate_prot()
1310{
1311  //~ pwg_log('>>>>> pwg_generate_prot() >>>>>'."\n");
1312  //~ pwg_log("GENARATE prot >>>\n".var_export($_SESSION['scan_list_fold'], true)."\n".var_export($_SESSION['scan_list_file'], true)."\nGENERATE prot >>>\n");
1313 
1314  global $conf, $g_listing;
1315 
1316  // Flush line </root>
1317  $line = pwg_get_indent('root').'</root>'."\n";
1318  fwrite($g_listing, $line);
1319 
1320  if ($conf['protect'])
1321  {
1322    $_SESSION['scan_logs'] .= pwg_protect_directories($_SESSION['scan_list_fold'][0]);
1323  }
1324 
1325  // How many directories to close
1326  $current_level = pwg_get_level($_SESSION['scan_list_fold'][0]);
1327  if (isset($_SESSION['scan_list_fold'][1]))
1328  {
1329    //~ pwg_log('---<< Pull of $_SESSION[scan_list_fold] value "'.$_SESSION['scan_list_fold'][0].'"'."\n");
1330    array_shift($_SESSION['scan_list_fold']);
1331    $_SESSION['scan_cnt_fold']++;
1332    $next_level = pwg_get_level($_SESSION['scan_list_fold'][0]);
1333    $_SESSION['scan_step'] = 'list';
1334  }
1335  else
1336  {
1337    $next_level = -1;
1338    $_SESSION['scan_cnt_fold']++;
1339    $_SESSION['scan_step'] = 'stop';
1340  }
1341 
1342  if ($current_level == $next_level)
1343  {
1344    fwrite($g_listing, pwg_close_level($current_level, 1));
1345  }
1346  else
1347  {
1348    if (($current_level > $next_level))
1349    {
1350      fwrite($g_listing, pwg_close_level($current_level, $current_level-$next_level+1));
1351    } // Nothing to do if current_level < next_level
1352  }
1353
1354  //~ pwg_log("GENERATE prot <<<\n".var_export($_SESSION['scan_list_fold'], true)."\n".var_export($_SESSION['scan_list_file'], true)."\nGENERATE prot <<<\n");
1355  //~ pwg_log('<<<<< pwg_generate_prot() <<<<<'."\n");
1356}
1357
1358function pwg_generate_stop()
1359{
1360  //~ pwg_log('>>>>> pwg_generate_stop() >>>>>'."\n");
1361  //~ pwg_log("GENARATE stop >>>\n".var_export($_SESSION['scan_list_fold'], true)."\n".var_export($_SESSION['scan_list_file'], true)."\nGENERATE stop >>>\n");
1362 
1363  global $pwg_conf, $g_listing, $g_header, $g_message, $g_footer;
1364 
1365  // Flush line </informations>
1366  fwrite($g_listing, '</informations>'."\n");
1367 
1368  // backup error log before cleaning session
1369  $time_elapsed = number_format(pwg_get_moment() - $_SESSION['scan_time'], 3, '.', ' ');
1370 
1371  $g_header   = ' : <span class="success">Generate</span>';
1372  $g_message  = '        <div>'."\n".$_SESSION['scan_logs'].'        </div>'."\n";
1373  $g_message .= '        <div><code class="success">'.$_SESSION['scan_cnt_fold'].'</code> directories parsed<br />'."\n";
1374  $g_message .= '        <code class="success">'.$_SESSION['scan_cnt_file'].'</code> files scanned</div>'."\n";
1375  $g_message .= '        <div>View <a href="listing.xml">listing.xml</a></div>'."\n";
1376  $g_message .= '        <div style="{text-align: right;}">Listing generated in : <code>'.$time_elapsed.' s</code></div>';
1377  $g_footer   = '<a href="'.$pwg_conf['this_url'].'" title="Main menu"><img src="'.$pwg_conf['icon_dir'].'up.png" /></a>';
1378     
1379  // What are we doing at next step
1380  $_SESSION['scan_step'] = 'exit';
1381 
1382  //~ pwg_log("GENARATE stop <<<\n".var_export($_SESSION['scan_list_fold'], true)."\n".var_export($_SESSION['scan_list_file'], true)."\nGENERATE stop <<<\n");
1383  //~ pwg_log('<<<<< pwg_generate_stop() <<<<<'."\n");
1384}
1385
1386// +-----------------------------------------------------------------------+
1387// |                                ALWAYS CALLED FUNCTIONS                |
1388// +-----------------------------------------------------------------------+
1389
1390/**
1391 * This function check step and time ellapsed to determine end of loop
1392 *
1393 * @return bool
1394 */
1395function pwg_continue()
1396{
1397  //~ pwg_log('>>>>> pwg_continue() >>>>>'."\n");
1398 
1399  global $conf, $pwg_conf, $g_refresh, $g_header, $g_message, $g_footer, $start_time;
1400 
1401  if (!isset($_SESSION['scan_step']) or $_SESSION['scan_step'] == 'exit')
1402  {
1403    // evident end of process
1404    $return = false;
1405  }
1406  else
1407  {
1408    if ($pwg_conf['safe_mode'] or $conf['force_refresh_method'])
1409    {
1410      // can not reset the time
1411      $time_elapsed = pwg_get_moment() - $start_time;
1412      if ($time_elapsed < $conf['max_execution_time'])
1413      {
1414        $return = true;
1415      }
1416      else
1417      {
1418        $start_time = $_SESSION['scan_time'];
1419        $formated_time = number_format(pwg_get_moment() - $start_time, 3, '.', ' ');
1420
1421        $g_refresh = '<meta http-equiv="Refresh" content="'.$conf['refresh_delay'].'">'."\n";
1422        $g_header  = ' : <span class="success">'.ucfirst($_SESSION['scan_action']).'</span>';
1423        $g_message = '';
1424        if ($_SESSION['scan_cnt_fold'] != 0)
1425        {
1426          $g_message .= '<code class="success">'.$_SESSION['scan_cnt_fold'].'</code> directories scanned<br />'."\n";
1427        }
1428        if ($_SESSION['scan_cnt_file'] != 0)
1429        {
1430          $g_message .= '<code class="success">'.$_SESSION['scan_cnt_file'].'</code> files scanned<br />'."\n";
1431        }
1432        $nb = count($_SESSION['scan_list_fold']);
1433        if ($nb > 0)
1434        {
1435          $g_message .= '<code class="warning">'.$nb.'</code> directories to scan<br />'."\n";
1436        }
1437        $nb = count($_SESSION['scan_list_file']);
1438        if ($nb > 0)
1439        {
1440          $g_message .= '<code class="warning">'.$nb.'</code> files to scan<br />'."\n";
1441        }
1442        $g_message .= '        <div style="{text-align: right;}">Time elapsed : <code>'.$formated_time.' s</code></div>';
1443        $g_footer  = '<a href="'.$pwg_conf['this_url'].'?action='.$_SESSION['scan_action'].'" title="Continue"><img src="'.$pwg_conf['icon_dir'].'right.png" /></a>'."\n";
1444       
1445        $return = false;
1446      }
1447    }
1448    else
1449    {
1450      // reset the time
1451      set_time_limit(intval(ini_get('max_execution_time')));
1452      $return = true;
1453    }
1454  }
1455  //~ pwg_log('<<<<< pwg_continue() returns '.var_export($return, true).' <<<<<'."\n");
1456 
1457  return $return;
1458}
1459
1460/**
1461 * This function :
1462 * -> Verify the script call
1463 * -> Lock the script
1464 * -> Open listing.xml if action is 'generate'
1465 * -> Initialize output and session variables
1466 *
1467 * @return nothing
1468 */
1469function pwg_init()
1470{
1471  //~ pwg_log('>>>>> pwg_init() >>>>>'."\n");
1472
1473  global $g_message, $g_listing, $g_footer, $conf, $pwg_conf, $start_time;
1474  $init_message = '';
1475 
1476  // Lock other script sessions, this lock will be remove during 'exit' step
1477  if (!isset($_SESSION['scan_step']))
1478  {
1479    $fp = @fopen(__FILE__.'.lock', 'x+'); // return false if __FILE__.lock exists or if cannot create
1480    if ($fp == false)
1481    {
1482      $g_header   = $_SESSION['scan_action'];
1483      $g_message  = '        <code class="failure">Failure -</code> Another script is running';
1484      $g_message .= ' <img src="'.$pwg_conf['icon_dir'].'add_tag.png" title="Delete file '.__FILE__.'.lock and retry" />';
1485      $g_message .= "\n";
1486      $g_footer   = '<a href="'.$pwg_conf['this_url'].'" title="Main menu"><img src="'.$pwg_conf['icon_dir'].'up.png" /></a>'."\n";
1487      $_SESSION['scan_step'] = 'exit';
1488      //~ pwg_log('<<<<< pwg_init() failure <<<<<'."\n");
1489      return;
1490    }
1491    else
1492    {
1493      fwrite($fp, session_id()); // Writing session_id to trace lock
1494      fclose($fp);
1495      $_SESSION['scan_step'] = 'init';
1496    }
1497  }
1498 
1499  // Verify and backup parameter action. This backup will be removed during step 'exit'
1500  if (isset($_REQUEST['action']))
1501  {
1502    if (in_array($_REQUEST['action'], $pwg_conf['scan_action']))
1503    {
1504      if (isset($_SESSION['scan_action']))
1505      {
1506        if ($_SESSION['scan_action'] != $_REQUEST['action'])
1507        {
1508          // Fatal error
1509          $g_message  = '        <code class="failure">Failure -</code> Parameter <code>action</code> differs between url and session';
1510          $g_message .= "\n";
1511          $g_footer   = '<a href="'.$pwg_conf['this_url'].'" title="Main menu"><img src="'.$pwg_conf['icon_dir'].'up.png" /></a>'."\n";
1512          $_SESSION['scan_step'] = 'exit';
1513          //~ pwg_log('<<<<< pwg_init() failure <<<<<'."\n");
1514          return;
1515        }
1516      }
1517      else
1518      {
1519        $_SESSION['scan_action'] = $_REQUEST['action'];
1520      }
1521    }
1522    else
1523    {
1524      // Fatal error
1525      $g_message  = '        <code class="failure">Failure -</code> Problem with <code>action</code> parameter';
1526      $g_message .= ' <img src="'.$pwg_conf['icon_dir'].'add_tag.png" title="empty, '.implode(', ', $pwg_conf['scan_action']).'" />';
1527      $g_message .= "\n";
1528      $g_footer   = '<a href="'.$pwg_conf['this_url'].'" title="Main menu"><img src="'.$pwg_conf['icon_dir'].'up.png" /></a>'."\n";
1529      $_SESSION['scan_step'] = 'exit';
1530      //~ pwg_log('<<<<< pwg_init() failure <<<<<'."\n");
1531      return;
1532    }
1533  }
1534  else
1535  {
1536    // Here we are on welcome page
1537    $g_message  = '        <ul>'."\n";
1538    $g_message .= '          <li><a href="'.$pwg_conf['this_url'].'?action=test" title="Display/Compare script version">Test</a></li>'."\n";
1539    $g_message .= '          <li><a href="'.$pwg_conf['this_url'].'?action=clean" title="Delete listing.xml if exists">Clean</a></li>'."\n";
1540    $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";
1541    $g_message .= '        </ul>'."\n";
1542    $g_footer   = '<a href="'.$conf['gallery'].'/admin.php?page=site_manager" title="Main gallery :: site manager">';
1543    $g_footer  .= '<img src="'.$pwg_conf['icon_dir'].'home.png" /></a>'."\n";
1544    $_SESSION['scan_step'] = 'exit';
1545    $_SESSION['scan_action'] = '';
1546  }
1547 
1548  // Actions to do at the init of generate
1549  if ($_SESSION['scan_action'] == 'generate')
1550  {
1551    // Open XML file
1552    $mode = ($_SESSION['scan_step'] == 'init') ? 'w' : 'a'; // Erase old listing.xml at the beginning of generation (mode w)
1553    $g_listing = @fopen('listing.xml', $mode);
1554    if ($g_listing === false)
1555    {
1556      $g_header   = $_SESSION['scan_action'];
1557      $g_message  = '        <code class="failure">Failure -</code> Can not write file <code>listing.xml</code>';
1558      $g_message .= "\n";
1559      $g_footer   = '<a href="'.$pwg_conf['this_url'].'" title="Main menu"><img src="'.$pwg_conf['icon_dir'].'up.png" /></a>'."\n";
1560      $_SESSION['scan_step'] = 'exit';
1561      //~ pwg_log('<<<<< pwg_init() failure <<<<<'."\n");
1562      return;
1563    }
1564   
1565    // Check graphical capabilities
1566    $init_message = pwg_check_graphics();
1567  }
1568   
1569  // Initializing session counters. This counters will be completely unset during step 'exit'
1570  if ($_SESSION['scan_step'] == 'init')
1571  {
1572    $_SESSION['scan_list_file'] = array();
1573    $_SESSION['scan_list_fold'] = array();
1574    $_SESSION['scan_cnt_file'] = 0;
1575    $_SESSION['scan_cnt_fold'] = 0;
1576    $_SESSION['scan_time'] = $start_time;
1577    $_SESSION['scan_step'] = 'start';
1578    $_SESSION['scan_logs'] = $init_message;
1579  }
1580 
1581  //~ pwg_log('<<<<< pwg_init() success <<<<<'."\n");
1582}
1583
1584/**
1585 * This function :
1586 * -> Close listing.xml if action is 'generate'
1587 * -> Unlock the script
1588 * -> Erase session variables
1589 *
1590 * @return nothing
1591 */
1592function pwg_exit()
1593{
1594  //~ pwg_log('>>>>> pwg_exit() >>>>>'."\n");
1595 
1596  global $g_listing;
1597 
1598  // Close XML file
1599  if ($_SESSION['scan_action'] == 'generate' and $g_listing != false)
1600  {
1601    fclose($g_listing);
1602  }
1603 
1604  // Unlock script
1605  unlink(__FILE__.'.lock');
1606 
1607  // Erase session counters
1608  unset($_SESSION['scan_list_file']);
1609  unset($_SESSION['scan_list_fold']);
1610  unset($_SESSION['scan_cnt_file']);
1611  unset($_SESSION['scan_cnt_fold']);
1612  unset($_SESSION['scan_time']);
1613  unset($_SESSION['scan_step']);
1614  $local_action = $_SESSION['scan_action'];
1615  unset($_SESSION['scan_action']);
1616  unset($_SESSION['scan_logs']);
1617  session_destroy();
1618 
1619  // Call specific action post process
1620  if (is_callable('pwg_'.$local_action.'_exit'))
1621  {
1622    call_user_func('pwg_'.$local_action.'_exit');
1623  }
1624 
1625  //~ pwg_log('<<<<< pwg_exit() <<<<<'."\n");
1626}
1627
1628// +-----------------------------------------------------------------------+
1629// |                                Script                                 |
1630// +-----------------------------------------------------------------------+
1631session_save_path('.');
1632session_start();
1633
1634$start_time = pwg_get_moment();
1635
1636// Initializing message for web page
1637$g_refresh = '';
1638$g_header  = '';
1639$g_message = '';
1640$g_footer  = '';
1641$g_listing = '';
1642
1643pwg_init();
1644
1645while(pwg_continue())
1646{
1647  if (is_callable('pwg_'.$_SESSION['scan_action'].'_'.$_SESSION['scan_step']))
1648  {
1649    call_user_func('pwg_'.$_SESSION['scan_action'].'_'.$_SESSION['scan_step']); // Run the step : start, list, scan, stop are available
1650  }
1651  else
1652  {
1653    $g_header   = $_SESSION['scan_action'];
1654    $g_message  = '        <code class="failure">Failure -</code> INTERNAL STEP ERROR : <code>pwg_'.$_SESSION['scan_action'].'_'.$_SESSION['scan_step'].'()</code> undefined';
1655    $g_message .= "\n";
1656    $g_footer   = '<a href="'.$pwg_conf['this_url'].'" title="Main menu"><img src="'.$pwg_conf['icon_dir'].'up.png" /></a>'."\n";
1657    $_SESSION['scan_step'] = 'exit';
1658  }
1659}
1660
1661if ($_SESSION['scan_step'] == 'exit')
1662{
1663  pwg_exit();
1664}
1665
1666?>
1667<html>
1668  <head>
1669  <?php echo $g_refresh; ?>
1670  <title>Manage remote gallery</title>
1671  </head>
1672    <style type="text/css">
1673      code {font-weight: bold}
1674      img {border-style: none; vertical-align: middle}
1675      ul {list-style-image: url(<?php echo $pwg_conf['icon_dir']; ?>add_tag.png)}
1676      .success {color: green}
1677      .warning {color: orange}
1678      .failure {color: red}
1679      .header {text-align: center; font-variant: small-caps; font-weight: bold;}
1680      .p {color: #F93;}
1681      .w {color: #ccc;}
1682      .g {color: #69C;}
1683      .pwg {text-decoration: none; border-bottom-style: dotted; border-bottom-width: 1px;}
1684      .content {width: 75%; position: absolute; top: 10%; left: 12%;}
1685      .footer {text-align: right;}
1686      .pwg_block {float: left;}
1687    </style>
1688  <body>
1689    <div class="content">
1690      <fieldset class="header">
1691        <span class="p">Pi</span>
1692        <span class="w">wi</span>
1693        <span class="g">go</span>
1694        &nbsp;remote site<? echo $g_header; ?>
1695      </fieldset>
1696      <fieldset>
1697<?php echo $g_message; ?>
1698      </fieldset>
1699      <fieldset class="footer">
1700        <div class="pwg_block">
1701          Powered by <a href="http://piwigo.org" class="pwg">Piwigo</a>
1702        </div>
1703        <?php echo $g_footer; ?>
1704      </fieldset>
1705    </div>
1706  </body>
1707</html>
Note: See TracBrowser for help on using the repository browser.