51b0ffa9d32e4103b938062046cd5b13aa803e12
[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" );
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 } else {
127 // segment we don't care about, so skip
128 $size = unpack( "nint", fread( $fh, 2 ) );
129 if ( $size['int'] <= 2 ) throw new MWException( "invalid marker size in jpeg" );
130 fseek( $fh, $size['int'] - 2, SEEK_CUR );
131 }
132
133 }
134 // shouldn't get here.
135 throw new MWException( "Reached end of jpeg file unexpectedly" );
136 }
137
138 /**
139 * Helper function for jpegSegmentSplitter
140 * @param &$fh FileHandle for jpeg file
141 * @return data content of segment.
142 */
143 private static function jpegExtractMarker( &$fh ) {
144 $size = unpack( "nint", fread( $fh, 2 ) );
145 if ( $size['int'] <= 2 ) throw new MWException( "invalid marker size in jpeg" );
146 return fread( $fh, $size['int'] - 2 );
147 }
148
149 /**
150 * This reads the photoshop image resource.
151 * Currently it only compares the iptc/iim hash
152 * with the stored hash, which is used to determine the precedence
153 * of the iptc data. In future it may extract some other info, like
154 * url of copyright license.
155 *
156 * This should generally be called by BitmapMetadataHandler::doApp13()
157 *
158 * @param String $app13 photoshop psir app13 block from jpg.
159 * @return String if the iptc hash is good or not.
160 */
161 public static function doPSIR ( $app13 ) {
162 if ( !$app13 ) {
163 return;
164 }
165 // First compare hash with real thing
166 // 0x404 contains IPTC, 0x425 has hash
167 // This is used to determine if the iptc is newer than
168 // the xmp data, as xmp programs update the hash,
169 // where non-xmp programs don't.
170
171 $offset = 14; // skip past PHOTOSHOP 3.0 identifier. should already be checked.
172 $appLen = strlen( $app13 );
173 $realHash = "";
174 $recordedHash = "";
175
176 // the +12 is the length of an empty item.
177 while ( $offset + 12 <= $appLen ) {
178 $valid = true;
179 if ( substr( $app13, $offset, 4 ) !== '8BIM' ) {
180 // its supposed to be 8BIM
181 // but apparently sometimes isn't esp. in
182 // really old jpg's
183 $valid = false;
184 }
185 $offset += 4;
186 $id = substr( $app13, $offset, 2 );
187 // id is a 2 byte id number which identifies
188 // the piece of info this record contains.
189
190 $offset += 2;
191
192 // some record types can contain a name, which
193 // is a pascal string 0-padded to be an even
194 // number of bytes. Most times (and any time
195 // we care) this is empty, making it two null bytes.
196
197 $lenName = ord( substr( $app13, $offset, 1 ) ) + 1;
198 // we never use the name so skip it. +1 for length byte
199 if ( $lenName % 2 == 1 ) {
200 $lenName++;
201 } // pad to even.
202 $offset += $lenName;
203
204 // now length of data (unsigned long big endian)
205 $lenData = unpack( 'Nlen', substr( $app13, $offset, 4 ) );
206 $offset += 4; // 4bytes length field;
207
208 // this should not happen, but check.
209 if ( $lenData['len'] + $offset > $appLen ) {
210 wfDebug( __METHOD__ . " PSIR data too long.\n" );
211 return 'iptc-no-hash';
212 }
213
214 if ( $valid ) {
215 switch ( $id ) {
216 case "\x04\x04":
217 // IPTC block
218 $realHash = md5( substr( $app13, $offset, $lenData['len'] ), true );
219 break;
220 case "\x04\x25":
221 $recordedHash = substr( $app13, $offset, $lenData['len'] );
222 break;
223 }
224 }
225
226 // if odd, add 1 to length to account for
227 // null pad byte.
228 if ( $lenData['len'] % 2 == 1 ) $lenData['len']++;
229 $offset += $lenData['len'];
230
231 }
232
233 if ( !$realHash || !$recordedHash ) {
234 return 'iptc-no-hash';
235 } elseif ( $realHash === $recordedHash ) {
236 return 'iptc-good-hash';
237 } else { /*$realHash !== $recordedHash */
238 return 'iptc-bad-hash';
239 }
240 }
241 }