source: trunk/tools/create_listing_file.php @ 1486

Last change on this file since 1486 was 1486, checked in by rvelices, 18 years ago

merge -r1484:1485 from branch 1.6 to trunk (bug 481: Incorrect tag generation
in listing.xml for accentuated letters)

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 16.7 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: 2006-07-20 23:55:08 +0000 (Thu, 20 Jul 2006) $
10// | last modifier : $Author: rvelices $
11// | revision      : $Revision: 1486 $
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// |                              parameters                               |
30// +-----------------------------------------------------------------------+
31
32// prefix for thumbnails in "thumbnail" sub directories
33$conf['prefix_thumbnail'] = 'TN-';
34
35// $conf['file_ext'] lists all extensions (case insensitive) allowed for
36// your PhpWebGallery installation
37$conf['file_ext'] = array('jpg','JPG','png','PNG','gif','GIF','mpg','zip',
38                          'avi','mp3','ogg');
39
40// $conf['picture_ext'] must be a subset of $conf['file_ext']
41$conf['picture_ext'] = array('jpg','JPG','png','PNG','gif','GIF');
42
43// $conf['version'] is used to verify the compatibility of the generated
44// listing.xml file and the PhpWebGallery version you're running
45$conf['version'] = '%PWGVERSION%';
46
47// $conf['use_exif'] set to true if you want to use Exif information
48$conf['use_exif'] = true;
49
50// use_exif_mapping: same behaviour as use_iptc_mapping
51$conf['use_exif_mapping'] = array(
52  'date_creation' => 'DateTimeOriginal'
53  );
54
55// $conf['use_iptc'] set to true if you want to use IPTC informations of the
56// element according to get_sync_iptc_data function mapping, otherwise, set
57// to false
58$conf['use_iptc'] = false;
59
60// use_iptc_mapping : in which IPTC fields will PhpWebGallery find image
61// information ? This setting is used during metadata synchronisation. It
62// associates a phpwebgallery_images column name to a IPTC key
63$conf['use_iptc_mapping'] = array(
64  'keywords'        => '2#025',
65  'date_creation'   => '2#055',
66  'author'          => '2#122',
67  'name'            => '2#005',
68  'comment'         => '2#120'
69  );
70
71// +-----------------------------------------------------------------------+
72// |                               functions                               |
73// +-----------------------------------------------------------------------+
74
75/**
76 * returns informations from IPTC metadata, mapping is done at the beginning
77 * of the function
78 *
79 * @param string $filename
80 * @return array
81 */
82function get_iptc_data($filename, $map)
83{
84  $result = array();
85
86  // Read IPTC data
87  $iptc = array();
88
89  $imginfo = array();
90  getimagesize($filename, $imginfo);
91
92  if (isset($imginfo['APP13']))
93  {
94    $iptc = iptcparse($imginfo['APP13']);
95    if (is_array($iptc))
96    {
97      $rmap = array_flip($map);
98      foreach (array_keys($rmap) as $iptc_key)
99      {
100        if (isset($iptc[$iptc_key][0]))
101        {
102          if ($iptc_key == '2#025')
103          {
104            $value = implode(',',
105                             array_map('clean_iptc_value',$iptc[$iptc_key]));
106          }
107          else
108          {
109            $value = clean_iptc_value($iptc[$iptc_key][0]);
110          }
111
112          foreach (array_keys($map, $iptc_key) as $pwg_key)
113          {
114            $result[$pwg_key] = $value;
115          }
116        }
117      }
118    }
119  }
120  return $result;
121}
122
123/**
124 * return a cleaned IPTC value
125 *
126 * @param string value
127 * @return string
128 */
129function clean_iptc_value($value)
130{
131  // strip leading zeros (weird Kodak Scanner software)
132  while ($value[0] == chr(0))
133  {
134    $value = substr($value, 1);
135  }
136  // remove binary nulls
137  $value = str_replace(chr(0x00), ' ', $value);
138
139  return $value;
140}
141
142function get_sync_iptc_data($file)
143{
144  global $conf;
145
146  $map = $conf['use_iptc_mapping'];
147  $datefields = array('date_creation', 'date_available');
148
149  $iptc = get_iptc_data($file, $map);
150
151  foreach ($iptc as $pwg_key => $value)
152  {
153    if (in_array($pwg_key, $datefields))
154    {
155      if ( preg_match('/(\d{4})(\d{2})(\d{2})/', $value, $matches))
156      {
157        $value = $matches[1].'-'.$matches[2].'-'.$matches[3];
158      }
159    }
160    if ($pwg_key == 'keywords')
161    {
162      // official keywords separator is the comma
163      $value = preg_replace('/[.;]/', ',', $value);
164      $value = preg_replace('/^,+|,+$/', '', $value);
165    }
166    $iptc[$pwg_key] = htmlentities($value);
167  }
168
169  $iptc['keywords'] = implode(
170               ',',
171               array_unique(
172                 explode(
173                   ',',
174                   $iptc['keywords']
175                   )
176                 )
177               );
178  return $iptc;
179}
180
181/**
182 * returns a float value coresponding to the number of seconds since the
183 * unix epoch (1st January 1970) and the microseconds are precised :
184 * e.g. 1052343429.89276600
185 *
186 * @return float
187 */
188function get_moment()
189{
190  $t1 = explode(' ', microtime());
191  $t2 = explode('.', $t1[0]);
192  $t2 = $t1[1].'.'.$t2[1];
193  return $t2;
194}
195
196/**
197 * returns the number of seconds (with 3 decimals precision) between the
198 * start time and the end time given.
199 *
200 * @param float start
201 * @param float end
202 * @return void
203 */
204function get_elapsed_time($start, $end)
205{
206  return number_format($end - $start, 3, '.', ' ').' s';
207}
208
209/**
210 * returns an array with all picture files according to $conf['file_ext']
211 *
212 * @param string $dir
213 * @return array
214 */
215function get_pwg_files($dir)
216{
217  global $conf;
218
219  $pictures = array();
220  if ($opendir = opendir($dir))
221  {
222    while ($file = readdir($opendir))
223    {
224      if (in_array(get_extension($file), $conf['file_ext']))
225      {
226        array_push($pictures, $file);
227        if (!preg_match('/^[a-zA-Z0-9-_.]+$/', $file))
228        {
229          echo 'PWG-WARNING-2: "'.$file.'" : ';
230          echo 'The name of the file should be composed of ';
231          echo 'letters, figures, "-", "_" or "." ONLY';
232          echo "\n";
233        }
234      }
235    }
236  }
237  return $pictures;
238}
239
240/**
241 * returns an array with all thumbnails according to $conf['picture_ext']
242 * and $conf['prefix_thumbnail']
243 *
244 * @param string $dir
245 * @return array
246 */
247function get_thumb_files($dir)
248{
249  global $conf;
250
251  $prefix_length = strlen($conf['prefix_thumbnail']);
252
253  $thumbnails = array();
254  if ($opendir = @opendir($dir.'/thumbnail'))
255  {
256    while ($file = readdir($opendir))
257    {
258      if (in_array(get_extension($file), $conf['picture_ext'])
259          and substr($file,0,$prefix_length) == $conf['prefix_thumbnail'])
260      {
261        array_push($thumbnails, $file);
262      }
263    }
264  }
265  return $thumbnails;
266}
267
268/**
269 * returns an array with representative picture files of a directory
270 * according to $conf['picture_ext']
271 *
272 * @param string $dir
273 * @return array
274 */
275function get_representative_files($dir)
276{
277  global $conf;
278
279  $pictures = array();
280  if ($opendir = @opendir($dir.'/pwg_representative'))
281  {
282    while ($file = readdir($opendir))
283    {
284      if (in_array(get_extension($file), $conf['picture_ext']))
285      {
286        array_push($pictures, $file);
287      }
288    }
289  }
290  return $pictures;
291}
292
293/**
294 * returns an array with high quality/resolution picture files of a directory
295 * according to $conf['picture_ext']
296 *
297 * @param string $dir
298 * @return array
299 */
300function get_high_files($dir)
301{
302  global $conf;
303
304  $pictures = array();
305  if ($opendir = @opendir($dir.'/pwg_high'))
306  {
307    while ($file = readdir($opendir))
308    {
309      if (in_array(get_extension($file), $conf['picture_ext']))
310      {
311        array_push($pictures, $file);
312      }
313    }
314  }
315  return $pictures;
316}
317
318/**
319 * search in $basedir the sub-directories and calls get_pictures
320 *
321 * @return void
322 */
323function get_dirs($basedir, $indent, $level)
324{
325  $fs_dirs = array();
326  $dirs = "";
327
328  if ($opendir = opendir($basedir))
329  {
330    while ($file = readdir($opendir))
331    {
332      if ($file != '.'
333          and $file != '..'
334          and $file != '.svn'
335          and $file != 'thumbnail'
336          and $file != 'pwg_high'
337          and $file != 'pwg_representative'
338          and is_dir ($basedir.'/'.$file))
339      {
340        array_push($fs_dirs, $file);
341        if (!preg_match('/^[a-zA-Z0-9-_.]+$/', $file))
342        {
343          echo 'PWG-WARNING-1: "'.$file.'" : ';
344          echo 'The name of the directory should be composed of ';
345          echo 'letters, figures, "-", "_" or "." ONLY';
346          echo "\n";
347        }
348      }
349    }
350  }
351  // write of the dirs
352  foreach ($fs_dirs as $fs_dir)
353  {
354    $dirs.= "\n".$indent.'<dir'.$level.' name="'.$fs_dir.'">';
355    $dirs.= get_pictures($basedir.'/'.$fs_dir, $indent.'  ');
356    $dirs.= get_dirs($basedir.'/'.$fs_dir, $indent.'  ', $level + 1);
357    $dirs.= "\n".$indent.'</dir'.$level.'>';
358  }
359  return $dirs;
360}
361
362// get_extension returns the part of the string after the last "."
363function get_extension($filename)
364{
365  return substr(strrchr($filename, '.'), 1, strlen ($filename));
366}
367
368// get_filename_wo_extension returns the part of the string before the last
369// ".".
370// get_filename_wo_extension('test.tar.gz') -> 'test.tar'
371function get_filename_wo_extension($filename)
372{
373  return substr($filename, 0, strrpos($filename, '.'));
374}
375
376function get_pictures($dir, $indent)
377{
378  global $conf, $page;
379
380  // fs means FileSystem : $fs_files contains files in the filesystem found
381  // in $dir that can be managed by PhpWebGallery (see get_pwg_files
382  // function), $fs_thumbnails contains thumbnails, $fs_representatives
383  // contains potentially representative pictures for non picture files
384  $fs_files = get_pwg_files($dir);
385  $fs_thumbnails = get_thumb_files($dir);
386  $fs_representatives = get_representative_files($dir);
387  $fs_highs = get_high_files($dir);
388
389  $elements = array();
390
391  $print_dir = preg_replace('/^\.\//', '', $dir);
392  $print_dir = preg_replace('/\/*$/', '/', $print_dir);
393
394  foreach ($fs_files as $fs_file)
395  {
396    $element = array();
397    $element['file'] = $fs_file;
398    $element['path'] = $page['url'].$print_dir.$fs_file;
399    $element['filesize'] = floor(filesize($dir.'/'.$fs_file) / 1024);
400
401    $file_wo_ext = get_filename_wo_extension($fs_file);
402
403    foreach ($conf['picture_ext'] as $ext)
404    {
405      $test = $conf['prefix_thumbnail'].$file_wo_ext.'.'.$ext;
406      if (!in_array($test, $fs_thumbnails))
407      {
408        continue;
409      }
410      else
411      {
412        $element['tn_ext'] = $ext;
413        break;
414      }
415    }
416
417    // 2 cases : the element is a picture or not. Indeed, for a picture
418    // thumbnail is mandatory, high is optional and for non picture element,
419    // thumbnail and representative is optionnal
420    if (in_array(get_extension($fs_file), $conf['picture_ext']))
421    {
422      // if we found a thumnbnail corresponding to our picture...
423      if (isset($element['tn_ext']))
424      {
425        if ($image_size = @getimagesize($dir.'/'.$fs_file))
426        {
427          $element['width'] = $image_size[0];
428          $element['height'] = $image_size[1];
429        }
430
431        if ( in_array($fs_file, $fs_highs) )
432        {
433          $element['has_high'] = 'true';
434        }
435
436        if ($conf['use_exif'])
437        {
438          if ($exif = @read_exif_data($dir.'/'.$fs_file))
439          {
440            foreach ($conf['use_exif_mapping'] as $pwg_key => $exif_key )
441            {
442              if (isset($exif[$exif_key]))
443              {
444                if ( in_array($pwg_key, array('date_creation','date_available') ) )
445                {
446                   if (preg_match('/^(\d{4}):(\d{2}):(\d{2})/'
447                         ,$exif[$exif_key]
448                         ,$matches))
449                   {
450                     $element[$pwg_key] =
451                        $matches[1].'-'.$matches[2].'-'.$matches[3];
452                   }
453                }
454                else
455                {
456                  $element[$pwg_key] = $exif[$exif_key];
457                }
458              }
459            }
460          }
461        }
462
463        if ($conf['use_iptc'])
464        {
465          $iptc = get_sync_iptc_data($dir.'/'.$fs_file);
466          if (count($iptc) > 0)
467          {
468            foreach (array_keys($iptc) as $key)
469            {
470              $element[$key] = $iptc[$key];
471            }
472          }
473        }
474
475        array_push($elements, $element);
476      }
477      else
478      {
479        echo 'PWG-ERROR-1: The thumbnail is missing for '.$dir.'/'.$fs_file;
480        echo '-> '.$dir.'/thumbnail/';
481        echo $conf['prefix_thumbnail'].$file_wo_ext.'.xxx';
482        echo ' ("xxx" can be : ';
483        echo implode(', ', $conf['picture_ext']);
484        echo ')'."\n";
485      }
486    }
487    else
488    {
489      foreach ($conf['picture_ext'] as $ext)
490      {
491        $candidate = $file_wo_ext.'.'.$ext;
492        if (!in_array($candidate, $fs_representatives))
493        {
494          continue;
495        }
496        else
497        {
498          $element['representative_ext'] = $ext;
499          break;
500        }
501      }
502
503      array_push($elements, $element);
504    }
505  }
506
507  $xml = "\n".$indent.'<root>';
508  $attributes = array('file','tn_ext','representative_ext','filesize',
509                      'width','height','date_creation','author','keywords',
510                      'name','comment','has_high', 'path');
511  foreach ($elements as $element)
512  {
513    $xml.= "\n".$indent.'  ';
514    $xml.= '<element';
515    foreach ($attributes as $attribute)
516    {
517      if (isset($element{$attribute}))
518      {
519        $xml.= ' '.$attribute.'="'.$element{$attribute}.'"';
520      }
521    }
522    $xml.= ' />';
523  }
524  $xml.= "\n".$indent.'</root>';
525
526  return $xml;
527}
528
529// +-----------------------------------------------------------------------+
530// |                                script                                 |
531// +-----------------------------------------------------------------------+
532if (isset($_GET['action']))
533{
534  $page['action'] = $_GET['action'];
535}
536else
537{
538  $page['action'] = '';
539}
540
541echo '<pre>';
542switch ($page['action'])
543{
544  case 'generate' :
545  {
546    $start = get_moment();
547
548    $listing = '<informations';
549    $listing.= ' generation_date="'.date('Y-m-d').'"';
550    $listing.= ' phpwg_version="'.htmlentities($conf{'version'}).'"';
551
552    $attrs=array();
553    if ($conf['use_iptc'])
554    {
555      $attrs = array_merge($attrs, array_keys($conf['use_iptc_mapping']) );
556    }
557    if ($conf['use_exif'])
558    {
559      $attrs = array_merge($attrs, array_keys($conf['use_exif_mapping']) );
560    }
561    $listing.= ' metadata="'.implode(',',array_unique($attrs)).'"';
562
563    $end = strrpos($_SERVER['PHP_SELF'], '/') + 1;
564    $local_folder = substr($_SERVER['PHP_SELF'], 0, $end);
565    $page['url'] = 'http://'.$_SERVER['HTTP_HOST'].$local_folder;
566
567    $listing.= ' url="'.$page['url'].'"';
568    $listing.= '/>'."\n";
569
570    $listing.= get_dirs('.', '', 0);
571
572    if ($fp = @fopen("./listing.xml","w"))
573    {
574      fwrite($fp, $listing);
575      fclose($fp);
576      echo 'PWG-INFO-1: listing.xml created in ';
577      echo get_elapsed_time($start, get_moment());
578      echo "\n";
579    }
580    else
581    {
582      echo "PWG-ERROR-2: I can't write the file listing.xml"."\n";
583    }
584    break;
585  }
586  case 'test' :
587  {
588    if (isset($_GET['version']))
589    {
590      if ($_GET['version'] != $conf['version'])
591      {
592        echo 'PWG-ERROR-4: PhpWebGallery versions differs'."\n";
593      }
594      else
595      {
596        echo 'PWG-INFO-2: test successful'."\n";
597      }
598    }
599    else
600    {
601      echo 'PWG-INFO-2: test successful'."\n";
602    }
603    break;
604  }
605  case 'clean' :
606  {
607    if( @unlink('./listing.xml'))
608    {
609      echo 'PWG-INFO-3 : listing.xml file deleted'."\n";
610    }
611    else
612    {
613      echo 'PWG-ERROR-3 : listing.xml does not exist'."\n";
614    }
615    break;
616  }
617  default :
618  {
619    // Menu de lancement pour la mise à jour manuel des sites distant
620    echo '</pre>
621<ul>
622  <li>
623    <a href="create_listing_file.php?action=generate">Generate listing.xml</a>
624  </li>
625
626  <li>
627    <a href="create_listing_file.php?action=test">Test</a>
628  </li>
629
630  <li>
631    <a href="create_listing_file.php?action=clean">Clean</a>
632  </li>
633</ul>
634<pre>';
635  }
636}
637echo '</pre>';
638?>
Note: See TracBrowser for help on using the repository browser.