source: trunk/tools/create_listing_file.php @ 1088

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

fix: remote site decodes html entities from xml and addslashes

fix: picture displays "image rank/total" images even for non numeric categories

fix: category comment not transformed with nl2br if allow_html_descriptions and
comment already looks like html

  • 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-02-17 02:41:57 +0000 (Fri, 17 Feb 2006) $
10// | last modifier : $Author: rvelices $
11// | revision      : $Revision: 1046 $
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 htmlentities($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        $iptc[$pwg_key] = $matches[1].'-'.$matches[2].'-'.$matches[3];
158      }
159    }
160  }
161
162  if (isset($iptc['keywords']))
163  {
164    // keywords separator is the comma, nothing else. Allowed characters in
165    // keywords : [A-Za-z0-9], "-" and "_". All other characters will be
166    // considered as separators
167    $iptc['keywords'] = preg_replace('/[^\w-]+/', ',', $iptc['keywords']);
168    $iptc['keywords'] = preg_replace('/^,+|,+$/', '', $iptc['keywords']);
169  }
170
171  return $iptc;
172}
173
174/**
175 * returns a float value coresponding to the number of seconds since the
176 * unix epoch (1st January 1970) and the microseconds are precised :
177 * e.g. 1052343429.89276600
178 *
179 * @return float
180 */
181function get_moment()
182{
183  $t1 = explode(' ', microtime());
184  $t2 = explode('.', $t1[0]);
185  $t2 = $t1[1].'.'.$t2[1];
186  return $t2;
187}
188
189/**
190 * returns the number of seconds (with 3 decimals precision) between the
191 * start time and the end time given.
192 *
193 * @param float start
194 * @param float end
195 * @return void
196 */
197function get_elapsed_time($start, $end)
198{
199  return number_format($end - $start, 3, '.', ' ').' s';
200}
201
202/**
203 * returns an array with all picture files according to $conf['file_ext']
204 *
205 * @param string $dir
206 * @return array
207 */
208function get_pwg_files($dir)
209{
210  global $conf;
211
212  $pictures = array();
213  if ($opendir = opendir($dir))
214  {
215    while ($file = readdir($opendir))
216    {
217      if (in_array(get_extension($file), $conf['file_ext']))
218      {
219        array_push($pictures, $file);
220        if (!preg_match('/^[a-zA-Z0-9-_.]+$/', $file))
221        {
222          echo 'PWG-WARNING-2: "'.$file.'" : ';
223          echo 'The name of the file should be composed of ';
224          echo 'letters, figures, "-", "_" or "." ONLY';
225          echo "\n";
226        }
227      }
228    }
229  }
230  return $pictures;
231}
232
233/**
234 * returns an array with all thumbnails according to $conf['picture_ext']
235 * and $conf['prefix_thumbnail']
236 *
237 * @param string $dir
238 * @return array
239 */
240function get_thumb_files($dir)
241{
242  global $conf;
243
244  $prefix_length = strlen($conf['prefix_thumbnail']);
245 
246  $thumbnails = array();
247  if ($opendir = @opendir($dir.'/thumbnail'))
248  {
249    while ($file = readdir($opendir))
250    {
251      if (in_array(get_extension($file), $conf['picture_ext'])
252          and substr($file,0,$prefix_length) == $conf['prefix_thumbnail'])
253      {
254        array_push($thumbnails, $file);
255      }
256    }
257  }
258  return $thumbnails;
259}
260
261/**
262 * returns an array with representative picture files of a directory
263 * according to $conf['picture_ext']
264 *
265 * @param string $dir
266 * @return array
267 */
268function get_representative_files($dir)
269{
270  global $conf;
271
272  $pictures = array();
273  if ($opendir = @opendir($dir.'/pwg_representative'))
274  {
275    while ($file = readdir($opendir))
276    {
277      if (in_array(get_extension($file), $conf['picture_ext']))
278      {
279        array_push($pictures, $file);
280      }
281    }
282  }
283  return $pictures;
284}
285
286/**
287 * returns an array with high quality/resolution picture files of a directory
288 * according to $conf['picture_ext']
289 *
290 * @param string $dir
291 * @return array
292 */
293function get_high_files($dir)
294{
295  global $conf;
296
297  $pictures = array();
298  if ($opendir = @opendir($dir.'/pwg_high'))
299  {
300    while ($file = readdir($opendir))
301    {
302      if (in_array(get_extension($file), $conf['picture_ext']))
303      {
304        array_push($pictures, $file);
305      }
306    }
307  }
308  return $pictures;
309}
310
311/**
312 * search in $basedir the sub-directories and calls get_pictures
313 *
314 * @return void
315 */
316function get_dirs($basedir, $indent, $level)
317{
318  $fs_dirs = array();
319  $dirs = "";
320
321  if ($opendir = opendir($basedir))
322  {
323    while ($file = readdir($opendir))
324    {
325      if ($file != '.'
326          and $file != '..'
327          and $file != '.svn'
328          and $file != 'thumbnail'
329          and $file != 'pwg_high'
330          and $file != 'pwg_representative'
331          and is_dir ($basedir.'/'.$file))
332      {
333        array_push($fs_dirs, $file);
334        if (!preg_match('/^[a-zA-Z0-9-_.]+$/', $file))
335        {
336          echo 'PWG-WARNING-1: "'.$file.'" : ';
337          echo 'The name of the directory should be composed of ';
338          echo 'letters, figures, "-", "_" or "." ONLY';
339          echo "\n";
340        }
341      }
342    }
343  }
344  // write of the dirs
345  foreach ($fs_dirs as $fs_dir)
346  {
347    $dirs.= "\n".$indent.'<dir'.$level.' name="'.$fs_dir.'">';
348    $dirs.= get_pictures($basedir.'/'.$fs_dir, $indent.'  ');
349    $dirs.= get_dirs($basedir.'/'.$fs_dir, $indent.'  ', $level + 1);
350    $dirs.= "\n".$indent.'</dir'.$level.'>';
351  }
352  return $dirs;   
353}
354
355// get_extension returns the part of the string after the last "."
356function get_extension($filename)
357{
358  return substr(strrchr($filename, '.'), 1, strlen ($filename));
359}
360
361// get_filename_wo_extension returns the part of the string before the last
362// ".".
363// get_filename_wo_extension('test.tar.gz') -> 'test.tar'
364function get_filename_wo_extension($filename)
365{
366  return substr($filename, 0, strrpos($filename, '.'));
367}
368
369function get_pictures($dir, $indent)
370{
371  global $conf, $page;
372 
373  // fs means FileSystem : $fs_files contains files in the filesystem found
374  // in $dir that can be managed by PhpWebGallery (see get_pwg_files
375  // function), $fs_thumbnails contains thumbnails, $fs_representatives
376  // contains potentially representative pictures for non picture files
377  $fs_files = get_pwg_files($dir);
378  $fs_thumbnails = get_thumb_files($dir);
379  $fs_representatives = get_representative_files($dir);
380  $fs_highs = get_high_files($dir);
381
382  $elements = array();
383
384  $print_dir = preg_replace('/^\.\//', '', $dir);
385  $print_dir = preg_replace('/\/*$/', '/', $print_dir);
386 
387  foreach ($fs_files as $fs_file)
388  {
389    $element = array();
390    $element['file'] = $fs_file;
391    $element['path'] = $page['url'].$print_dir.$fs_file;
392    $element['filesize'] = floor(filesize($dir.'/'.$fs_file) / 1024);
393   
394    $file_wo_ext = get_filename_wo_extension($fs_file);
395
396    foreach ($conf['picture_ext'] as $ext)
397    {
398      $test = $conf['prefix_thumbnail'].$file_wo_ext.'.'.$ext;
399      if (!in_array($test, $fs_thumbnails))
400      {
401        continue;
402      }
403      else
404      {
405        $element['tn_ext'] = $ext;
406        break;
407      }
408    }
409
410    // 2 cases : the element is a picture or not. Indeed, for a picture
411    // thumbnail is mandatory, high is optional and for non picture element,
412    // thumbnail and representative is optionnal
413    if (in_array(get_extension($fs_file), $conf['picture_ext']))
414    {
415      // if we found a thumnbnail corresponding to our picture...
416      if (isset($element['tn_ext']))
417      {
418        if ($image_size = @getimagesize($dir.'/'.$fs_file))
419        {
420          $element['width'] = $image_size[0];
421          $element['height'] = $image_size[1];
422        }
423       
424        if ( in_array($fs_file, $fs_highs) )
425        {
426          $element['has_high'] = 'true';
427        }
428
429        if ($conf['use_exif'])
430        {
431          if ($exif = @read_exif_data($dir.'/'.$fs_file))
432          {
433            foreach ($conf['use_exif_mapping'] as $pwg_key => $exif_key )
434            {
435              if (isset($exif[$exif_key]))
436              {
437                if ( in_array($pwg_key, array('date_creation','date_available') ) )
438                {
439                   if (preg_match('/^(\d{4}):(\d{2}):(\d{2})/'
440                         ,$exif[$exif_key]
441                         ,$matches))
442                   {
443                     $element[$pwg_key] =
444                        $matches[1].'-'.$matches[2].'-'.$matches[3];
445                   }
446                }
447                else
448                {
449                  $element[$pwg_key] = $exif[$exif_key];
450                }
451              }
452            }
453          }
454        }
455
456        if ($conf['use_iptc'])
457        {
458          $iptc = get_sync_iptc_data($dir.'/'.$fs_file);
459          if (count($iptc) > 0)
460          {
461            foreach (array_keys($iptc) as $key)
462            {
463              $element[$key] = $iptc[$key];
464            }
465          }
466        }
467       
468        array_push($elements, $element);
469      }
470      else
471      {
472        echo 'PWG-ERROR-1: The thumbnail is missing for '.$dir.'/'.$fs_file;
473        echo '-> '.$dir.'/thumbnail/';
474        echo $conf['prefix_thumbnail'].$file_wo_ext.'.xxx';
475        echo ' ("xxx" can be : ';
476        echo implode(', ', $conf['picture_ext']);
477        echo ')'."\n";
478      }
479    }
480    else
481    {
482      foreach ($conf['picture_ext'] as $ext)
483      {
484        $candidate = $file_wo_ext.'.'.$ext;
485        if (!in_array($candidate, $fs_representatives))
486        {
487          continue;
488        }
489        else
490        {
491          $element['representative_ext'] = $ext;
492          break;
493        }
494      }
495     
496      array_push($elements, $element);
497    }
498  }
499
500  $xml = "\n".$indent.'<root>';
501  $attributes = array('file','tn_ext','representative_ext','filesize',
502                      'width','height','date_creation','author','keywords',
503                      'name','comment','has_high', 'path');
504  foreach ($elements as $element)
505  {
506    $xml.= "\n".$indent.'  ';
507    $xml.= '<element';
508    foreach ($attributes as $attribute)
509    {
510      if (isset($element{$attribute}))
511      {
512        $xml.= ' '.$attribute.'="'.$element{$attribute}.'"';
513      }
514    }
515    $xml.= ' />';
516  }
517  $xml.= "\n".$indent.'</root>';
518
519  return $xml;
520}
521
522// +-----------------------------------------------------------------------+
523// |                                script                                 |
524// +-----------------------------------------------------------------------+
525if (isset($_GET['action']))
526{
527  $page['action'] = $_GET['action'];
528}
529else
530{
531  $page['action'] = '';
532}
533
534echo '<pre>';
535switch ($page['action'])
536{
537  case 'generate' :
538  {
539    $start = get_moment();
540   
541    $listing = '<informations';
542    $listing.= ' generation_date="'.date('Y-m-d').'"';
543    $listing.= ' phpwg_version="'.htmlentities($conf{'version'}).'"';
544   
545    $attrs=array();
546    if ($conf['use_iptc'])
547    {
548      $attrs = array_merge($attrs, array_keys($conf['use_iptc_mapping']) );
549    }
550    if ($conf['use_exif'])
551    {
552      $attrs = array_merge($attrs, array_keys($conf['use_exif_mapping']) );
553    }
554    $listing.= ' metadata="'.implode(',',array_unique($attrs)).'"';
555   
556    $end = strrpos($_SERVER['PHP_SELF'], '/') + 1;
557    $local_folder = substr($_SERVER['PHP_SELF'], 0, $end);
558    $page['url'] = 'http://'.$_SERVER['HTTP_HOST'].$local_folder;
559   
560    $listing.= ' url="'.$page['url'].'"';
561    $listing.= '/>'."\n";
562   
563    $listing.= get_dirs('.', '', 0);
564   
565    if ($fp = @fopen("./listing.xml","w"))
566    {
567      fwrite($fp, $listing);
568      fclose($fp);
569      echo 'PWG-INFO-1: listing.xml created in ';
570      echo get_elapsed_time($start, get_moment());
571      echo "\n";
572    }
573    else
574    {
575      echo "PWG-ERROR-2: I can't write the file listing.xml"."\n";
576    }
577    break;
578  }
579  case 'test' :
580  {
581    if (isset($_GET['version']))
582    {
583      if ($_GET['version'] != $conf['version'])
584      {
585        echo 'PWG-ERROR-4: PhpWebGallery versions differs'."\n";
586      }
587      else
588      {
589        echo 'PWG-INFO-2: test successful'."\n";
590      }
591    }
592    else
593    {
594      echo 'PWG-INFO-2: test successful'."\n";
595    }
596    break;
597  }
598  case 'clean' :
599  {
600    if( @unlink('./listing.xml'))
601    {
602      echo 'PWG-INFO-3 : listing.xml file deleted'."\n";
603    }
604    else
605    {
606      echo 'PWG-ERROR-3 : listing.xml does not exist'."\n";
607    }
608    break;
609  }
610  default :
611  {
612    // Menu de lancement pour la mise à jour manuel des sites distant
613    echo '</pre>
614<ul>
615  <li>
616    <a href="create_listing_file.php?action=generate">Generate listing.xml</a>
617  </li>
618
619  <li>
620    <a href="create_listing_file.php?action=test">Test</a>
621  </li>
622
623  <li>
624    <a href="create_listing_file.php?action=clean">Clean</a>
625  </li>
626</ul>
627<pre>';
628  }
629}
630echo '</pre>';
631?>
Note: See TracBrowser for help on using the repository browser.