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