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