source: tags/release-1_7_2/tools/create_listing_file.php @ 15555

Last change on this file since 15555 was 2459, checked in by plg, 16 years ago

New version 1.7.2 hard coded.

Stable release required modifications: don't show version and generation
time in footer, don't check the upgrade feed, don't die on sql errors.

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