Merge to trunk everything in img_metadata branch.
[lhc/web/wiklou.git] / includes / media / JpegMetadataExtractor.php
1 <?php
2 /**
3 * Class for reading jpegs and extracting metadata.
4 * see also BitmapMetadataHandler.
5 *
6 * Based somewhat on GIFMetadataExtrator.
7 */
8 class JpegMetadataExtractor {
9 const MAX_JPEG_SEGMENTS = 200;
10 // the max segment is a sanity check.
11 // A jpeg file should never even remotely have
12 // that many segments. Your average file has about 10.
13
14 /** Function to extract metadata segments of interest from jpeg files
15 * based on GIFMetadataExtractor.
16 *
17 * we can almost use getimagesize to do this
18 * but gis doesn't support having multiple app1 segments
19 * and those can't extract xmp on files containing both exif and xmp data
20 *
21 * @param String $filename name of jpeg file
22 * @return Array of interesting segments.
23 * @throws MWException if given invalid file.
24 */
25 static function segmentSplitter ( $filename ) {
26 $showXMP = function_exists( 'xml_parser_create_ns' );
27
28 $segmentCount = 0;
29
30 $segments = Array( 'XMP_ext' => array(), 'COM' => array() );
31
32 if ( !$filename ) throw new MWException( "No filename specified for " . __METHOD__ );
33 if ( !file_exists( $filename ) || is_dir( $filename ) ) throw new MWException( "Invalid file $filename passed to " . __METHOD__ );
34
35 $fh = fopen( $filename, "rb" );
36
37 if ( !$fh ) throw new MWException( "Could not open file $filename" );
38
39 $buffer = fread( $fh, 2 );
40 if ( $buffer !== "\xFF\xD8" ) throw new MWException( "Not a jpeg, no SOI" );
41 while ( !feof( $fh ) ) {
42 $buffer = fread( $fh, 1 );
43 $segmentCount++;
44 if ( $segmentCount > self::MAX_JPEG_SEGMENTS ) {
45 // this is just a sanity check
46 throw new MWException( 'Too many jpeg segments. Aborting' );
47 }
48 if ( $buffer !== "\xFF" ) {
49 throw new MWException( "Error reading jpeg file marker" );
50 }
51
52 $buffer = fread( $fh, 1 );
53 if ( $buffer === "\xFE" ) {
54
55 // COM section -- file comment
56 // First see if valid utf-8,
57 // if not try to convert it to windows-1252.
58 $com = $oldCom = trim( self::jpegExtractMarker( $fh ) );
59
60 UtfNormal::quickIsNFCVerify( $com );
61 // turns $com to valid utf-8.
62 // thus if no change, its utf-8, otherwise its something else.
63 if ( $com !== $oldCom ) {
64 $oldCom = iconv( 'windows-1252', 'UTF-8//IGNORE', $oldCom );
65 }
66 $segments["COM"][] = $oldCom;
67
68 } elseif ( $buffer === "\xE1" && $showXMP ) {
69 // APP1 section (Exif, XMP, and XMP extended)
70 // only extract if XMP is enabled.
71 $temp = self::jpegExtractMarker( $fh );
72
73 // check what type of app segment this is.
74 if ( substr( $temp, 0, 29 ) === "http://ns.adobe.com/xap/1.0/\x00" ) {
75 $segments["XMP"] = substr( $temp, 29 );
76 } elseif ( substr( $temp, 0, 35 ) === "http://ns.adobe.com/xmp/extension/\x00" ) {
77 $segments["XMP_ext"][] = substr( $temp, 35 );
78 } elseif ( substr( $temp, 0, 29 ) === "XMP\x00://ns.adobe.com/xap/1.0/\x00" ) {
79 // Some images (especially flickr images) seem to have this.
80 // I really have no idea what the deal is with them, but
81 // whatever...
82 $segments["XMP"] = substr( $temp, 29 );
83 wfDebug( __METHOD__ . ' Found XMP section with wrong app identifier '
84 . "Using anyways.\n" );
85 }
86 } elseif ( $buffer === "\xED" ) {
87 // APP13 - PSIR. IPTC and some photoshop stuff
88 $temp = self::jpegExtractMarker( $fh );
89 if ( substr( $temp, 0, 14 ) === "Photoshop 3.0\x00" ) {
90 $segments["PSIR"] = $temp;
91 }
92 } elseif ( $buffer === "\xD9" || $buffer === "\xDA" ) {
93 // EOI - end of image or SOS - start of scan. either way we're past any interesting segments
94 return $segments;
95 } else {
96 // segment we don't care about, so skip
97 $size = unpack( "nint", fread( $fh, 2 ) );
98 if ( $size['int'] <= 2 ) throw new MWException( "invalid marker size in jpeg" );
99 fseek( $fh, $size['int'] - 2, SEEK_CUR );
100 }
101
102 }
103 // shouldn't get here.
104 throw new MWException( "Reached end of jpeg file unexpectedly" );
105
106 }
107 /**
108 * Helper function for jpegSegmentSplitter
109 * @param &$fh FileHandle for jpeg file
110 * @return data content of segment.
111 */
112 private static function jpegExtractMarker( &$fh ) {
113 $size = unpack( "nint", fread( $fh, 2 ) );
114 if ( $size['int'] <= 2 ) throw new MWException( "invalid marker size in jpeg" );
115 return fread( $fh, $size['int'] - 2 );
116 }
117
118 /**
119 * This reads the photoshop image resource.
120 * Currently it only compares the iptc/iim hash
121 * with the stored hash, which is used to determine the precedence
122 * of the iptc data. In future it may extract some other info, like
123 * url of copyright license.
124 *
125 * This should generally be called by BitmapMetadataHandler::doApp13()
126 *
127 * @param String $app13 photoshop psir app13 block from jpg.
128 * @return String if the iptc hash is good or not.
129 */
130 public static function doPSIR ( $app13 ) {
131 if ( !$app13 ) return;
132 // First compare hash with real thing
133 // 0x404 contains IPTC, 0x425 has hash
134 // This is used to determine if the iptc is newer than
135 // the xmp data, as xmp programs update the hash,
136 // where non-xmp programs don't.
137
138 $offset = 14; // skip past PHOTOSHOP 3.0 identifier. should already be checked.
139 $appLen = strlen( $app13 );
140 $realHash = "";
141 $recordedHash = "";
142
143 // the +12 is the length of an empty item.
144 while ( $offset + 12 <= $appLen ) {
145 $valid = true;
146 $id = false;
147 $lenName = false;
148 $lenData = false;
149
150 if ( substr( $app13, $offset, 4 ) !== '8BIM' ) {
151 // its supposed to be 8BIM
152 // but apparently sometimes isn't esp. in
153 // really old jpg's
154 $valid = false;
155 }
156 $offset += 4;
157 $id = substr( $app13, $offset, 2 );
158 // id is a 2 byte id number which identifies
159 // the piece of info this record contains.
160
161 $offset += 2;
162
163 // some record types can contain a name, which
164 // is a pascal string 0-padded to be an even
165 // number of bytes. Most times (and any time
166 // we care) this is empty, making it two null bytes.
167
168 $lenName = ord( substr( $app13, $offset, 1 ) ) + 1;
169 // we never use the name so skip it. +1 for length byte
170 if ( $lenName % 2 == 1 ) $lenName++; // pad to even.
171 $offset += $lenName;
172
173 // now length of data (unsigned long big endian)
174 $lenData = unpack( 'Nlen', substr( $app13, $offset, 4 ) );
175 $offset += 4; // 4bytes length field;
176
177 // this should not happen, but check.
178 if ( $lenData['len'] + $offset > $appLen ) {
179 wfDebug( __METHOD__ . " PSIR data too long.\n" );
180 return 'iptc-no-hash';
181 }
182
183 if ( $valid ) {
184 switch ( $id ) {
185 case "\x04\x04":
186 // IPTC block
187 $realHash = md5( substr( $app13, $offset, $lenData['len'] ), true );
188 break;
189 case "\x04\x25":
190 $recordedHash = substr( $app13, $offset, $lenData['len'] );
191 break;
192 }
193 }
194
195 // if odd, add 1 to length to account for
196 // null pad byte.
197 if ( $lenData['len'] % 2 == 1 ) $lenData['len']++;
198 $offset += $lenData['len'];
199
200 }
201
202 if ( !$realHash || !$recordedHash ) {
203 return 'iptc-no-hash';
204 } elseif ( $realHash === $recordedHash ) {
205 return 'iptc-good-hash';
206 } else { /*$realHash !== $recordedHash */
207 return 'iptc-bad-hash';
208 }
209
210 }
211
212 }