Merge "Update docs/hooks.txt for ShowSearchHitTitle"
[mediawiki.git] / includes / media / JpegMetadataExtractor.php
blob67c957adac13a75b448c54aed2779081456d24ea
1 <?php
2 /**
3 * Extraction of JPEG image metadata.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
21 * @ingroup Media
24 /**
25 * Class for reading jpegs and extracting metadata.
26 * see also BitmapMetadataHandler.
28 * Based somewhat on GIFMetadataExtractor.
30 * @ingroup Media
32 class JpegMetadataExtractor {
33 const MAX_JPEG_SEGMENTS = 200;
35 // the max segment is a sanity check.
36 // A jpeg file should never even remotely have
37 // that many segments. Your average file has about 10.
39 /** Function to extract metadata segments of interest from jpeg files
40 * based on GIFMetadataExtractor.
42 * we can almost use getimagesize to do this
43 * but gis doesn't support having multiple app1 segments
44 * and those can't extract xmp on files containing both exif and xmp data
46 * @param string $filename Name of jpeg file
47 * @return array Array of interesting segments.
48 * @throws MWException If given invalid file.
50 static function segmentSplitter( $filename ) {
51 $showXMP = XMPReader::isSupported();
53 $segmentCount = 0;
55 $segments = [
56 'XMP_ext' => [],
57 'COM' => [],
58 'PSIR' => [],
61 if ( !$filename ) {
62 throw new MWException( "No filename specified for " . __METHOD__ );
64 if ( !file_exists( $filename ) || is_dir( $filename ) ) {
65 throw new MWException( "Invalid file $filename passed to " . __METHOD__ );
68 $fh = fopen( $filename, "rb" );
70 if ( !$fh ) {
71 throw new MWException( "Could not open file $filename" );
74 $buffer = fread( $fh, 2 );
75 if ( $buffer !== "\xFF\xD8" ) {
76 throw new MWException( "Not a jpeg, no SOI" );
78 while ( !feof( $fh ) ) {
79 $buffer = fread( $fh, 1 );
80 $segmentCount++;
81 if ( $segmentCount > self::MAX_JPEG_SEGMENTS ) {
82 // this is just a sanity check
83 throw new MWException( 'Too many jpeg segments. Aborting' );
85 while ( $buffer !== "\xFF" ) {
86 // In theory JPEG files are not allowed to contain anything between the sections,
87 // but in practice they sometimes do. It's customary to ignore the garbage data.
88 $buffer = fread( $fh, 1 );
91 $buffer = fread( $fh, 1 );
92 while ( $buffer === "\xFF" && !feof( $fh ) ) {
93 // Skip through any 0xFF padding bytes.
94 $buffer = fread( $fh, 1 );
96 if ( $buffer === "\xFE" ) {
98 // COM section -- file comment
99 // First see if valid utf-8,
100 // if not try to convert it to windows-1252.
101 $com = $oldCom = trim( self::jpegExtractMarker( $fh ) );
102 UtfNormal\Validator::quickIsNFCVerify( $com );
103 // turns $com to valid utf-8.
104 // thus if no change, its utf-8, otherwise its something else.
105 if ( $com !== $oldCom ) {
106 MediaWiki\suppressWarnings();
107 $com = $oldCom = iconv( 'windows-1252', 'UTF-8//IGNORE', $oldCom );
108 MediaWiki\restoreWarnings();
110 // Try it again, if its still not a valid string, then probably
111 // binary junk or some really weird encoding, so don't extract.
112 UtfNormal\Validator::quickIsNFCVerify( $com );
113 if ( $com === $oldCom ) {
114 $segments["COM"][] = $oldCom;
115 } else {
116 wfDebug( __METHOD__ . " Ignoring JPEG comment as is garbage.\n" );
118 } elseif ( $buffer === "\xE1" ) {
119 // APP1 section (Exif, XMP, and XMP extended)
120 // only extract if XMP is enabled.
121 $temp = self::jpegExtractMarker( $fh );
122 // check what type of app segment this is.
123 if ( substr( $temp, 0, 29 ) === "http://ns.adobe.com/xap/1.0/\x00" && $showXMP ) {
124 $segments["XMP"] = substr( $temp, 29 );
125 } elseif ( substr( $temp, 0, 35 ) === "http://ns.adobe.com/xmp/extension/\x00" && $showXMP ) {
126 $segments["XMP_ext"][] = substr( $temp, 35 );
127 } elseif ( substr( $temp, 0, 29 ) === "XMP\x00://ns.adobe.com/xap/1.0/\x00" && $showXMP ) {
128 // Some images (especially flickr images) seem to have this.
129 // I really have no idea what the deal is with them, but
130 // whatever...
131 $segments["XMP"] = substr( $temp, 29 );
132 wfDebug( __METHOD__ . ' Found XMP section with wrong app identifier '
133 . "Using anyways.\n" );
134 } elseif ( substr( $temp, 0, 6 ) === "Exif\0\0" ) {
135 // Just need to find out what the byte order is.
136 // because php's exif plugin sucks...
137 // This is a II for little Endian, MM for big. Not a unicode BOM.
138 $byteOrderMarker = substr( $temp, 6, 2 );
139 if ( $byteOrderMarker === 'MM' ) {
140 $segments['byteOrder'] = 'BE';
141 } elseif ( $byteOrderMarker === 'II' ) {
142 $segments['byteOrder'] = 'LE';
143 } else {
144 wfDebug( __METHOD__ . " Invalid byte ordering?!\n" );
147 } elseif ( $buffer === "\xED" ) {
148 // APP13 - PSIR. IPTC and some photoshop stuff
149 $temp = self::jpegExtractMarker( $fh );
150 if ( substr( $temp, 0, 14 ) === "Photoshop 3.0\x00" ) {
151 $segments["PSIR"][] = $temp;
153 } elseif ( $buffer === "\xD9" || $buffer === "\xDA" ) {
154 // EOI - end of image or SOS - start of scan. either way we're past any interesting segments
155 return $segments;
156 } else {
157 // segment we don't care about, so skip
158 $size = wfUnpack( "nint", fread( $fh, 2 ), 2 );
159 if ( $size['int'] < 2 ) {
160 throw new MWException( "invalid marker size in jpeg" );
162 fseek( $fh, $size['int'] - 2, SEEK_CUR );
165 // shouldn't get here.
166 throw new MWException( "Reached end of jpeg file unexpectedly" );
170 * Helper function for jpegSegmentSplitter
171 * @param resource &$fh File handle for JPEG file
172 * @throws MWException
173 * @return string Data content of segment.
175 private static function jpegExtractMarker( &$fh ) {
176 $size = wfUnpack( "nint", fread( $fh, 2 ), 2 );
177 if ( $size['int'] < 2 ) {
178 throw new MWException( "invalid marker size in jpeg" );
180 if ( $size['int'] === 2 ) {
181 // fread( ..., 0 ) generates a warning
182 return '';
184 $segment = fread( $fh, $size['int'] - 2 );
185 if ( strlen( $segment ) !== $size['int'] - 2 ) {
186 throw new MWException( "Segment shorter than expected" );
189 return $segment;
193 * This reads the photoshop image resource.
194 * Currently it only compares the iptc/iim hash
195 * with the stored hash, which is used to determine the precedence
196 * of the iptc data. In future it may extract some other info, like
197 * url of copyright license.
199 * This should generally be called by BitmapMetadataHandler::doApp13()
201 * @param string $app13 Photoshop psir app13 block from jpg.
202 * @throws MWException (It gets caught next level up though)
203 * @return string If the iptc hash is good or not. One of 'iptc-no-hash',
204 * 'iptc-good-hash', 'iptc-bad-hash'.
206 public static function doPSIR( $app13 ) {
207 if ( !$app13 ) {
208 throw new MWException( "No App13 segment given" );
210 // First compare hash with real thing
211 // 0x404 contains IPTC, 0x425 has hash
212 // This is used to determine if the iptc is newer than
213 // the xmp data, as xmp programs update the hash,
214 // where non-xmp programs don't.
216 $offset = 14; // skip past PHOTOSHOP 3.0 identifier. should already be checked.
217 $appLen = strlen( $app13 );
218 $realHash = "";
219 $recordedHash = "";
221 // the +12 is the length of an empty item.
222 while ( $offset + 12 <= $appLen ) {
223 $valid = true;
224 if ( substr( $app13, $offset, 4 ) !== '8BIM' ) {
225 // its supposed to be 8BIM
226 // but apparently sometimes isn't esp. in
227 // really old jpg's
228 $valid = false;
230 $offset += 4;
231 $id = substr( $app13, $offset, 2 );
232 // id is a 2 byte id number which identifies
233 // the piece of info this record contains.
235 $offset += 2;
237 // some record types can contain a name, which
238 // is a pascal string 0-padded to be an even
239 // number of bytes. Most times (and any time
240 // we care) this is empty, making it two null bytes.
242 $lenName = ord( substr( $app13, $offset, 1 ) ) + 1;
243 // we never use the name so skip it. +1 for length byte
244 if ( $lenName % 2 == 1 ) {
245 $lenName++;
246 } // pad to even.
247 $offset += $lenName;
249 // now length of data (unsigned long big endian)
250 $lenData = wfUnpack( 'Nlen', substr( $app13, $offset, 4 ), 4 );
251 // PHP can take issue with very large unsigned ints and make them negative.
252 // Which should never ever happen, as this has to be inside a segment
253 // which is limited to a 16 bit number.
254 if ( $lenData['len'] < 0 ) {
255 throw new MWException( "Too big PSIR (" . $lenData['len'] . ')' );
258 $offset += 4; // 4bytes length field;
260 // this should not happen, but check.
261 if ( $lenData['len'] + $offset > $appLen ) {
262 throw new MWException( "PSIR data too long. (item length=" . $lenData['len']
263 . "; offset=$offset; total length=$appLen)" );
266 if ( $valid ) {
267 switch ( $id ) {
268 case "\x04\x04":
269 // IPTC block
270 $realHash = md5( substr( $app13, $offset, $lenData['len'] ), true );
271 break;
272 case "\x04\x25":
273 $recordedHash = substr( $app13, $offset, $lenData['len'] );
274 break;
278 // if odd, add 1 to length to account for
279 // null pad byte.
280 if ( $lenData['len'] % 2 == 1 ) {
281 $lenData['len']++;
283 $offset += $lenData['len'];
286 if ( !$realHash || !$recordedHash ) {
287 return 'iptc-no-hash';
288 } elseif ( $realHash === $recordedHash ) {
289 return 'iptc-good-hash';
290 } else { /*$realHash !== $recordedHash */
291 return 'iptc-bad-hash';