source: tags/release-1_7_1/tools/create_listing_file.php @ 2196

Last change on this file since 2196 was 2196, checked in by mathiasm, 16 years ago

New version 1.7.1 hard coded

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

Missed version update in tools/create_listing_file.php

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