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

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

Implement Nikon camera's maker note ; add some Xmp tag ; fix some bugs

  • Property svn:executable set to *
File size: 18.9 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     *  'translatable'=> Boolean, allowing to know if the tag value can be
168     *                   translated
169     *  'name'        => String, the tag name translated in locale language
170     *
171     * @Param Array $options  (optional)
172     * @return Array(keyName => Array('implemented' => Boolean, 'name' => String))
173     */
174    static public function getTagList($options=Array())
175    {
176      $default=Array(
177        'filter' => self::TAGFILTER_ALL,
178        'optimizeIptcDateTime' => false,
179        'exif'  => true,
180        'iptc'  => true,
181        'xmp'   => true,
182        'maker' => true
183      );
184
185      foreach($default as $key => $val)
186      {
187        if(array_key_exists($key, $options))
188          $default[$key]=$options[$key];
189      }
190
191      $list=Array();
192      $returned=Array();
193
194      if($default['exif'])
195      {
196        $list[]="exif";
197        $list[]="gps";
198      }
199
200      if($default['maker'])
201      {
202        $list[]=MAKER_PENTAX;
203        $list[]=MAKER_NIKON;
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          case MAKER_NIKON:
240            include_once(JPEG_METADATA_DIR."TagDefinitions/NikonTags.class.php");
241            $tmp=new NikonTags();
242            $schema="exif.".MAKER_NIKON;
243            break;
244          default:
245            $tmp=null;
246            $schema="?";
247            break;
248        }
249
250        if(!is_null($tmp))
251          foreach($tmp->getTags() as $key => $tag)
252          {
253            if(self::filter(true, $tag['implemented'], $default['filter']))
254            {
255              if(array_key_exists('tagName', $tag))
256                $name=$tag['tagName'];
257              else
258                $name=$key;
259
260              if(array_key_exists('schema', $tag) and $val=="exif")
261                $subSchema=".".$tag['schema'];
262              else
263                $subSchema="";
264
265              if($val=='xmp')
266                $keyName=$schema.$subSchema.".".$key;
267              else
268                $keyName=$schema.$subSchema.".".$name;
269              $returned[$keyName]=Array(
270                'implemented' => $tag['implemented'],
271                'translatable' => $tag['translatable'],
272                'name' => $name
273              );
274            }
275          }
276      }
277
278      return($returned);
279    }
280
281
282    /**
283     * the filter function is used by the classe to determine if a tag is
284     * filtered or not
285     *
286     * @Param Boolean $known
287     * @Param Boolean $implemented
288     * @Param Integer $filter
289     *
290     */
291    static public function filter($known, $implemented, $filter)
292    {
293      return(($known and (($filter & self::TAGFILTER_KNOWN) == self::TAGFILTER_KNOWN )) or
294                ($implemented and (($filter & self::TAGFILTER_IMPLEMENTED) == self::TAGFILTER_IMPLEMENTED )));
295    }
296
297    /**
298     * the constructor need an optional filename and options
299     *
300     * if no filename is given, you can use the "load" function after the object
301     * is instancied
302     *
303     * if no options are given, the class use the default values
304     *
305     * ---------------------+---------------------------------------------------
306     * key                  | descriptions/values
307     * ---------------------+---------------------------------------------------
308     * filter               | Integer
309     *                      | This options is used to filter implemented tag
310     *                      |  JpegMetaData::TAGFILTER_ALL
311     *                      |  => returns all the tags
312     *                      |  JpegMetaData::TAGFILTER_IMPLEMENTED
313     *                      |  => returns only the implemented tags, not
314     *                      |     implemented tag are excluded
315     *                      |  JpegMetaData::TAGFILTER_KNOWN
316     *                      |  => returns only the known tags (implemented or
317     *                      |     not), unknown tag are excluded
318     *                      |
319     * optimizeIptcDateTime | Boolean
320     *                      | IPTC Date/Time are separated into 2 tags
321     *                      | if this option is set to true, only dates tags are
322     *                      | returned (in this case, time is included is the
323     *                      | date)
324     *                      |
325     * exif                 | Boolean
326     * iptc                 | If set to true, the function returns all the tags
327     * xmp                  | known for the specified type tag
328     *                      | the exif parameter include the maker tags
329     *                      |
330     * ---------------------+---------------------------------------------------
331     *
332     * @Param String $file    (optional)
333     * @Param Array  $options (optional)
334     *
335     */
336    function __construct($file = "", $options = Array())
337    {
338      $this->load($file, $options);
339    }
340
341    function __destruct()
342    {
343      $this->unsetAll();
344    }
345
346    /**
347     * load a file
348     *
349     * options values are the same than the constructor's options
350     *
351     * @Param String $file
352     * @Param Array  $options (optional)
353     *
354     */
355    public function load($file, $options = Array())
356    {
357      $this->unsetAll();
358
359      $this->initializeOptions($options);
360      $this->tags = Array();
361      $this->jpeg = new JpegReader($file);
362
363      if($this->jpeg->isLoaded() and $this->jpeg->isValid())
364      {
365        foreach($this->jpeg->getAppMarkerSegments() as $key => $appMarkerSegment)
366        {
367          if($appMarkerSegment->dataLoaded())
368          {
369            $data=$appMarkerSegment->getData();
370
371            if($data instanceof TiffReader)
372            {
373              /*
374               * Load Exifs tags from Tiff block
375               */
376              if($data->getNbIFDs()>0)
377              {
378                $this->loadIfdTags($data->getIFD(0), self::KEY_EXIF_TIFF);
379              }
380            }
381            elseif($data instanceof XmpReader)
382            {
383              /*
384               * Load Xmp tags from Xmp block
385               */
386              $this->loadTags($data->getTags(), self::KEY_XMP);
387            }
388            elseif($data instanceof IptcReader)
389            {
390              /*
391               * Load IPTC tags from IPTC block
392               */
393              if($this->options['optimizeIptcDateTime'])
394                $data->optimizeDateTime();
395
396              $this->loadTags($data->getTags(), self::KEY_IPTC);
397            }
398          }
399        }
400      }
401    }
402
403    /**
404     * This function returns an array of tags found in the loaded file
405     *
406     * It's possible to made a second selection to filter items
407     *
408     * ---------------------+---------------------------------------------------
409     * key                  | descriptions/values
410     * ---------------------+---------------------------------------------------
411     * tagFilter            | Integer
412     *                      | This options is used to filter implemented tag
413     *                      |  JpegMetaData::TAGFILTER_ALL
414     *                      |  => returns all the tags
415     *                      |  JpegMetaData::TAGFILTER_IMPLEMENTED
416     *                      |  => returns only the implemented tags, not
417     *                      |     implemented tag are excluded
418     *                      |  JpegMetaData::TAGFILTER_KNOWN
419     *                      |  => returns only the known tags (implemented or
420     *                      |     not), unknown tag are excluded
421     *                      |
422     * ---------------------+---------------------------------------------------
423     *
424     * Note, the filter is applied on loaded tags. If a filter was applied when
425     * the file was loaded, you cannot expand the tag list, only reduce
426     * example :
427     *  $jpegmd = new JpegMetadata($file, Array('filter' => JpegMetaData::TAGFILTER_IMPLEMENTED));
428     *     => the unknown tag are not loaded
429     *  $jpegmd->getTags(JpegMetaData::TAGFILTER_ALL)
430     *     => unknown tag will not be restitued because they are not loaded...
431     *
432     * the function returns an array of Tag.
433     *
434     *
435     * ===========> See the Tag.class.php to know all about a tag <=============
436     *
437     * @Param Integer $tagFilter (optional)
438     *
439     */
440    public function getTags($tagFilter = self::TAGFILTER_ALL)
441    {
442      $returned=Array();
443      foreach($this->tags as $key => $val)
444      {
445        if(self::filter($val->isKnown(), $val->isImplemented(), $tagFilter))
446        {
447          $returned[$key]=$val;
448        }
449      }
450      return($returned);
451    }
452
453    /**
454     * initialize the options...
455     *
456     * @Param Array $options (optional)
457     *
458     */
459    private function initializeOptions($options=Array())
460    {
461      $this->options = Array(
462        'filter' => self::TAGFILTER_ALL,
463        'optimizeIptcDateTime' => false,
464        'exif' => true,
465        'iptc' => true,
466        'xmp'  => true
467      );
468
469      foreach($this->options as $key => $val)
470      {
471        if(array_key_exists($key, $options))
472          $this->options[$key]=$options[$key];
473      }
474    }
475
476    /**
477     * load tags from an IFD structure
478     *
479     * see Tiff.class.php and IfdReader.class.php for more informations
480     *
481     * @Param IfdReader $ifd
482     * @Param String    $exifKey
483     *
484     */
485    private function loadIfdTags($ifd, $exifKey)
486    {
487      foreach($ifd->getTags() as $key => $tag)
488      {
489        if(self::filter($tag->getTag()->isKnown(), $tag->getTag()->isImplemented(), $this->options['filter']))
490        {
491          if($tag->getTag()->getLabel() instanceof IfdReader)
492          {
493            switch($tag->getTag()->getName())
494            {
495              case 'Exif IFD Pointer':
496                $exifKey2=self::KEY_EXIF_EXIF;
497                break;
498              case 'MakerNote':
499                $exifKey2=self::KEY_EXIF.".".$tag->getTag()->getLabel()->getMaker();
500                break;
501              case 'GPS IFD Pointer':
502                $exifKey2=self::KEY_EXIF_GPS;
503                break;
504              default:
505                $exifKey2=$exifKey;
506                break;
507            }
508            $this->loadIfdTags($tag->getTag()->getLabel(), $exifKey2);
509          }
510          else
511          {
512            $this->tags[$exifKey.".".$tag->getTag()->getName()]=$tag->getTag();
513          }
514        }
515      }
516    }
517
518    /**
519     * Used to load tags from an IPTc or XMP structure
520     *
521     * see IptcReader.class.php and XmpReader.class.php
522     *
523     * @Param Tag[]  $ifd
524     * @Param String $tagKey
525     *
526     */
527    private function loadTags($tags, $tagKey)
528    {
529      foreach($tags as $key => $tag)
530      {
531        if(self::filter($tag->isKnown(), $tag->isImplemented(), $this->options['filter']))
532        {
533          $this->tags[$tagKey.".".$tag->getName()]=$tag;
534        }
535      }
536    }
537
538    private function unsetAll()
539    {
540      unset($this->tags);
541      unset($this->jpeg);
542      unset($this->options);
543    }
544
545
546  } // class JpegMetaData
547
548?>
Note: See TracBrowser for help on using the repository browser.