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

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

[Plugin:AMetaData] Finished to comment the JpegMetaData classes and rename some methods

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