source: extensions/AMetaData/JpegMetaData/JpegMetaData.class.php @ 4904

Last change on this file since 4904 was 4904, checked in by grum, 14 years ago

Optimize some memory leak and some bugged lines of code

  • Property svn:executable set to *
File size: 18.6 KB
Line 
1<?php
2/**
3 * --:: JPEG MetaDatas ::-------------------------------------------------------
4 *
5 * Version : 1.0.0
6 * Date    : 2009/12/26
7 *
8 *  Author    : Grum
9 *   email    : grum at piwigo.org
10 *   website  : http://photos.grum.fr
11 *
12 *   << May the Little SpaceFrog be with you ! >>
13 *
14 * +-----------------------------------------------------------------------+
15 * | JpegMetaData - a PHP based Jpeg Metadata manager                      |
16 * +-----------------------------------------------------------------------+
17 * | Copyright(C) 2010  Grum - http://www.grum.fr                          |
18 * +-----------------------------------------------------------------------+
19 * | This program is free software; you can redistribute it and/or modify  |
20 * | it under the terms of the GNU General Public License as published by  |
21 * | the Free Software Foundation                                          |
22 * |                                                                       |
23 * | This program is distributed in the hope that it will be useful, but   |
24 * | WITHOUT ANY WARRANTY; without even the implied warranty of            |
25 * | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
26 * | General Public License for more details.                              |
27 * |                                                                       |
28 * | You should have received a copy of the GNU General Public License     |
29 * | along with this program; if not, write to the Free Software           |
30 * | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
31 * | USA.                                                                  |
32 * +-----------------------------------------------------------------------+
33 *
34 *
35 * +-:: HISTORY ::--------+-----------------------------------------------------
36 * |         |            |
37 * | Release | Date       |
38 * +---------+------------+-----------------------------------------------------
39 * | 0.1.0a  | 2009-12-26 |
40 * |         |            |
41 * |         |            |
42 * |         |            |
43 * |         |            |
44 * |         |            |
45 * |         |            |
46 * |         |            |
47 * |         |            |
48 * |         |            |
49 * |         |            |
50 * +---------+------------+-----------------------------------------------------
51 *
52 *
53 * -----------------------------------------------------------------------------
54 *
55 * References about definition & interpretation of metadata tags :
56 *  - EXIF 2.20 Specification    => http://www.exif.org/Exif2-2.PDF
57 *  - TIFF 6.0 Specification     => http://partners.adobe.com/public/developer/en/tiff/TIFF6.pdf
58 *  - Exiftool by Phil Harvey    => http://www.sno.phy.queensu.ca/~phil/exiftool/
59 *                                  http://owl.phy.queensu.ca/~phil/exiftool/TagNames
60 *  - Exiv2 by Andreas Huggel    => http://www.exiv2.org/
61 *  - MetaData working group     => http://www.metadataworkinggroup.org/specs/
62 *  - Adobe XMP Developer Center => http://www.adobe.com/devnet/xmp/
63 *  - Gezuz                      => http://gezus.one.free.fr/?Plugin-EXIF-pour-Spip-1-9-2
64 *  - JPEG format                => http://crousseau.free.fr/imgfmt_jpeg.htm
65 *  - International Press Telecomunication Council specifications
66 *                               => http://www.iptc.org/
67 *  - IPTC headers structure     => http://www.codeproject.com/KB/graphics/iptc.aspx?msg=1014929
68 *  - CPAN                       => http://search.cpan.org/dist/Image-MetaData-JPEG/lib/Image/MetaData/JPEG/Structures.pod
69 *                               => http://search.cpan.org/~bettelli/Image-MetaData-JPEG/lib/Image/MetaData/JPEG/MakerNotes.pod
70 *
71 * -----------------------------------------------------------------------------
72 * To support internationalization the JpegMetaData package uses ".po" and ".mo"
73 * files, and use "php-gettext"
74 * ==> See files in External/php-gettext for more information about this project
75 * -----------------------------------------------------------------------------
76 *
77 * The JpegMetaData is the main class for reading metadata of a Jpeg file
78 *
79 * It provides two essentialy high level functions to read different kind of
80 * metadata (EXIF, IPTC, XMP) :
81 *  - (static) getTagList
82 *  - load
83 *  - getTags
84 *
85 * -----------------------------------------------------------------------------
86 *
87 * .. Notes ..
88 *
89 * About tags and translation in local lang
90 * With the 'getTags()' method, the JpegMetaData returns an array of Tag objects
91 * found in the jpeg file.
92 *
93 * A Tag object have 2 properties that can be translated into a local language :
94 *  - the name, getted with 'getName()'
95 *  - the valueLabel, getted with 'getLabel()'
96 *
97 * Theses properties ARE NOT translated automatically.
98 *
99 * You can translate it with the Locale class, by using the static method 'get'
100 *
101 * Example :
102 *  Locale::get($myTag->getName()) will return the translated name of the Tag
103 *  Locale::get($myTag->getLabel()) will return the translated value of the Tag
104 *
105 * ===========> See Tag.class.php to know more about the Tag class <============
106 * ========> See Locale.class.php to know more about the Locale class <=========
107 *
108 *
109 * -----------------------------------------------------------------------------
110 */
111
112  define("JPEG_METADATA_DIR", dirname(__FILE__)."/");
113
114  require_once(JPEG_METADATA_DIR."Readers/JpegReader.class.php");
115
116  class JpegMetaData
117  {
118    const TAGFILTER_KNOWN       = 0x01;
119    const TAGFILTER_IMPLEMENTED = 0x02;
120    const TAGFILTER_ALL         = 0x03;
121
122    const KEY_EXIF_TIFF = "exif.tiff";
123    const KEY_EXIF_EXIF = "exif.exif";
124    const KEY_EXIF_GPS  = "exif.gps";
125    const KEY_EXIF = "exif";
126    const KEY_IPTC = "iptc";
127    const KEY_XMP  = "xmp";
128
129    private $jpeg = null;
130    private $tags = Array();
131    private $options = Array();
132
133    /**
134     * this static function returns an array of tags definitions
135     *
136     * the only parameter is an array to determine filter options
137     *
138     * ---------------------+---------------------------------------------------
139     * key                  | descriptions/values
140     * ---------------------+---------------------------------------------------
141     * filter               | Integer
142     *                      | This options is used to filter implemented tag
143     *                      |  JpegMetaData::TAGFILTER_ALL
144     *                      |  => returns all the tags
145     *                      |  JpegMetaData::TAGFILTER_IMPLEMENTED
146     *                      |  => returns only the implemented tags
147     *                      |
148     * optimizeIptcDateTime | Boolean
149     *                      | IPTC Date/Time are separated into 2 tags
150     *                      | if this option is set to true, only dates tags are
151     *                      | returned (assuming this option is used when an
152     *                      | image file is loaded)
153     *                      |
154     * exif                 | Boolean
155     * iptc                 | If set to true, the function returns all the tags
156     *                      | known for the specified type tag
157     * xmp                  |
158     * maker                | maker => returns specifics tags from all the known
159     *                      |          makers
160     *                      |
161     * ---------------------+---------------------------------------------------
162     *
163     * returned value is an array
164     * each keys is a tag name and the associated value is a 2-level array
165     *  'implemented' => Boolean, allowing to know if the tags is implemented or
166     *                   not
167     *  'name'        => String, the tag name translated in locale language
168     *
169     * @Param Array $options  (optional)
170     * @return Array(keyName => Array(
171     *                            'implemented' => Boolean,
172     *                            'translatable' => Boolean,
173     *                            'name' => String))
174     */
175    static public function getTagList($options=Array())
176    {
177      $default=Array(
178        'filter' => self::TAGFILTER_ALL,
179        'optimizeIptcDateTime' => false,
180        'exif'  => true,
181        'iptc'  => true,
182        'xmp'   => true,
183        'maker' => true
184      );
185
186      foreach($default as $key => $val)
187      {
188        if(array_key_exists($key, $options))
189          $default[$key]=$options[$key];
190      }
191
192      $list=Array();
193      $returned=Array();
194
195      if($default['exif'])
196      {
197        $list[]="exif";
198        $list[]="gps";
199      }
200
201      if($default['maker'])
202      {
203        $list[]=MAKER_PENTAX;
204      }
205
206      if($default['iptc'])
207        $list[]="iptc";
208
209      if($default['xmp'])
210        $list[]="xmp";
211
212      foreach($list as $val)
213      {
214        unset($tmp);
215
216        switch($val)
217        {
218          case "exif":
219            $tmp=new IfdTags();
220            $schema="exif";
221            break;
222          case "gps":
223            $tmp=new GpsTags();
224            $schema="exif.gps";
225            break;
226          case "iptc":
227            $tmp=new IptcTags();
228            $schema="iptc";
229            break;
230          case "xmp":
231            $tmp=new XmpTags();
232            $schema="xmp";
233            break;
234          case MAKER_PENTAX:
235            include_once(JPEG_METADATA_DIR."TagDefinitions/PentaxTags.class.php");
236            $tmp=new PentaxTags();
237            $schema="exif.".MAKER_PENTAX;
238            break;
239          default:
240            $tmp=null;
241            $schema="?";
242            break;
243        }
244
245        if(!is_null($tmp))
246          foreach($tmp->getTags() as $key => $tag)
247          {
248            if(self::filter(true, $tag['implemented'], $default['filter']))
249            {
250              if(array_key_exists('tagName', $tag))
251                $name=$tag['tagName'];
252              else
253                $name=$key;
254
255              if(array_key_exists('schema', $tag) and $val=="exif")
256                $subSchema=".".$tag['schema'];
257              else
258                $subSchema="";
259
260              if($val=='xmp')
261                $keyName=$schema.$subSchema.".".$key;
262              else
263                $keyName=$schema.$subSchema.".".$name;
264              $returned[$keyName]=Array(
265                'implemented' => $tag['implemented'],
266                'translatable' => $tag['translatable'],
267                'name' => $name
268              );
269            }
270          }
271      }
272
273      return($returned);
274    }
275
276
277    /**
278     * the filter function is used by the classe to determine if a tag is
279     * filtered or not
280     *
281     * @Param Boolean $known
282     * @Param Boolean $implemented
283     * @Param Integer $filter
284     *
285     */
286    static public function filter($known, $implemented, $filter)
287    {
288      return(($known and (($filter & self::TAGFILTER_KNOWN) == self::TAGFILTER_KNOWN )) or
289                ($implemented and (($filter & self::TAGFILTER_IMPLEMENTED) == self::TAGFILTER_IMPLEMENTED )));
290    }
291
292    /**
293     * the constructor need an optional filename and options
294     *
295     * if no filename is given, you can use the "load" function after the object
296     * is instancied
297     *
298     * if no options are given, the class use the default values
299     *
300     * ---------------------+---------------------------------------------------
301     * key                  | descriptions/values
302     * ---------------------+---------------------------------------------------
303     * filter               | Integer
304     *                      | This options is used to filter implemented tag
305     *                      |  JpegMetaData::TAGFILTER_ALL
306     *                      |  => returns all the tags
307     *                      |  JpegMetaData::TAGFILTER_IMPLEMENTED
308     *                      |  => returns only the implemented tags, not
309     *                      |     implemented tag are excluded
310     *                      |  JpegMetaData::TAGFILTER_KNOWN
311     *                      |  => returns only the known tags (implemented or
312     *                      |     not), unknown tag are excluded
313     *                      |
314     * optimizeIptcDateTime | Boolean
315     *                      | IPTC Date/Time are separated into 2 tags
316     *                      | if this option is set to true, only dates tags are
317     *                      | returned (in this case, time is included is the
318     *                      | date)
319     *                      |
320     * exif                 | Boolean
321     * iptc                 | If set to true, the function returns all the tags
322     * xmp                  | known for the specified type tag
323     *                      | the exif parameter include the maker tags
324     *                      |
325     * ---------------------+---------------------------------------------------
326     *
327     * @Param String $file    (optional)
328     * @Param Array  $options (optional)
329     *
330     */
331    function __construct($file = "", $options = Array())
332    {
333      $this->load($file, $options);
334    }
335
336    function __destruct()
337    {
338      $this->unsetAll();
339    }
340
341    /**
342     * load a file
343     *
344     * options values are the same than the constructor's options
345     *
346     * @Param String $file
347     * @Param Array  $options (optional)
348     *
349     */
350    public function load($file, $options = Array())
351    {
352      $this->unsetAll();
353
354      $this->initializeOptions($options);
355      $this->tags = Array();
356      $this->jpeg = new JpegReader($file);
357
358      if($this->jpeg->isLoaded() and $this->jpeg->isValid())
359      {
360        foreach($this->jpeg->getAppMarkerSegments() as $key => $appMarkerSegment)
361        {
362          if($appMarkerSegment->dataLoaded())
363          {
364            $data=$appMarkerSegment->getData();
365
366            if($data instanceof TiffReader)
367            {
368              /*
369               * Load Exifs tags from Tiff block
370               */
371              if($data->getNbIFDs()>0)
372              {
373                $this->loadIfdTags($data->getIFD(0), self::KEY_EXIF_TIFF);
374              }
375            }
376            elseif($data instanceof XmpReader)
377            {
378              /*
379               * Load Xmp tags from Xmp block
380               */
381              $this->loadTags($data->getTags(), self::KEY_XMP);
382            }
383            elseif($data instanceof IptcReader)
384            {
385              /*
386               * Load IPTC tags from IPTC block
387               */
388              if($this->options['optimizeIptcDateTime'])
389                $data->optimizeDateTime();
390
391              $this->loadTags($data->getTags(), self::KEY_IPTC);
392            }
393          }
394        }
395      }
396    }
397
398    /**
399     * This function returns an array of tags found in the loaded file
400     *
401     * It's possible to made a second selection to filter items
402     *
403     * ---------------------+---------------------------------------------------
404     * key                  | descriptions/values
405     * ---------------------+---------------------------------------------------
406     * tagFilter            | Integer
407     *                      | This options is used to filter implemented tag
408     *                      |  JpegMetaData::TAGFILTER_ALL
409     *                      |  => returns all the tags
410     *                      |  JpegMetaData::TAGFILTER_IMPLEMENTED
411     *                      |  => returns only the implemented tags, not
412     *                      |     implemented tag are excluded
413     *                      |  JpegMetaData::TAGFILTER_KNOWN
414     *                      |  => returns only the known tags (implemented or
415     *                      |     not), unknown tag are excluded
416     *                      |
417     * ---------------------+---------------------------------------------------
418     *
419     * Note, the filter is applied on loaded tags. If a filter was applied when
420     * the file was loaded, you cannot expand the tag list, only reduce
421     * example :
422     *  $jpegmd = new JpegMetadata($file, Array('filter' => JpegMetaData::TAGFILTER_IMPLEMENTED));
423     *     => the unknown tag are not loaded
424     *  $jpegmd->getTags(JpegMetaData::TAGFILTER_ALL)
425     *     => unknown tag will not be restitued because they are not loaded...
426     *
427     * the function returns an array of Tag.
428     *
429     *
430     * ===========> See the Tag.class.php to know all about a tag <=============
431     *
432     * @Param Integer $tagFilter (optional)
433     *
434     */
435    public function getTags($tagFilter = self::TAGFILTER_ALL)
436    {
437      $returned=Array();
438      foreach($this->tags as $key => $val)
439      {
440        if(self::filter($val->isKnown(), $val->isImplemented(), $tagFilter))
441        {
442          $returned[$key]=$val;
443        }
444      }
445      return($returned);
446    }
447
448    /**
449     * initialize the options...
450     *
451     * @Param Array $options (optional)
452     *
453     */
454    private function initializeOptions($options=Array())
455    {
456      $this->options = Array(
457        'filter' => self::TAGFILTER_ALL,
458        'optimizeIptcDateTime' => false,
459        'exif' => true,
460        'iptc' => true,
461        'xmp'  => true
462      );
463
464      foreach($this->options as $key => $val)
465      {
466        if(array_key_exists($key, $options))
467          $this->options[$key]=$options[$key];
468      }
469    }
470
471    /**
472     * load tags from an IFD structure
473     *
474     * see Tiff.class.php and IfdReader.class.php for more informations
475     *
476     * @Param IfdReader $ifd
477     * @Param String    $exifKey
478     *
479     */
480    private function loadIfdTags($ifd, $exifKey)
481    {
482      foreach($ifd->getTags() as $key => $tag)
483      {
484        if(self::filter($tag->getTag()->isKnown(), $tag->getTag()->isImplemented(), $this->options['filter']))
485        {
486          if($tag->getTag()->getLabel() instanceof IfdReader)
487          {
488            switch($tag->getTag()->getName())
489            {
490              case 'Exif IFD Pointer':
491                $exifKey2=self::KEY_EXIF_EXIF;
492                break;
493              case 'MakerNote':
494                $exifKey2=self::KEY_EXIF.".".$tag->getTag()->getLabel()->getMaker();
495                break;
496              case 'GPS IFD Pointer':
497                $exifKey2=self::KEY_EXIF_GPS;
498                break;
499              default:
500                $exifKey2=$exifKey;
501                break;
502            }
503            $this->loadIfdTags($tag->getTag()->getLabel(), $exifKey2);
504          }
505          else
506          {
507            $this->tags[$exifKey.".".$tag->getTag()->getName()]=$tag->getTag();
508          }
509        }
510      }
511    }
512
513    /**
514     * Used to load tags from an IPTc or XMP structure
515     *
516     * see IptcReader.class.php and XmpReader.class.php
517     *
518     * @Param Tag[]  $ifd
519     * @Param String $tagKey
520     *
521     */
522    private function loadTags($tags, $tagKey)
523    {
524      foreach($tags as $key => $tag)
525      {
526        if(self::filter($tag->isKnown(), $tag->isImplemented(), $this->options['filter']))
527        {
528          $this->tags[$tagKey.".".$tag->getName()]=$tag;
529        }
530      }
531    }
532
533    private function unsetAll()
534    {
535      unset($this->tags);
536      unset($this->jpeg);
537      unset($this->options);
538    }
539
540
541  } // class JpegMetaData
542
543?>
Note: See TracBrowser for help on using the repository browser.