Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
80.31% covered (warning)
80.31%
102 / 127
0.00% covered (danger)
0.00%
0 / 3
CRAP
0.00% covered (danger)
0.00%
0 / 1
JpegMetadataExtractor
80.31% covered (warning)
80.31%
102 / 127
0.00% covered (danger)
0.00%
0 / 3
74.43
0.00% covered (danger)
0.00%
0 / 1
 segmentSplitter
84.00% covered (warning)
84.00%
63 / 75
0.00% covered (danger)
0.00%
0 / 1
37.46
 jpegExtractMarker
54.55% covered (warning)
54.55%
6 / 11
0.00% covered (danger)
0.00%
0 / 1
7.35
 doPSIR
80.49% covered (warning)
80.49%
33 / 41
0.00% covered (danger)
0.00%
0 / 1
16.67
1<?php
2/**
3 * Extraction of JPEG image metadata.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 * @ingroup Media
22 */
23
24use MediaWiki\Libs\UnpackFailedException;
25use Wikimedia\AtEase\AtEase;
26use Wikimedia\StringUtils\StringUtils;
27use Wikimedia\XMPReader\Reader as XMPReader;
28
29/**
30 * Class for reading jpegs and extracting metadata.
31 * see also BitmapMetadataHandler.
32 *
33 * Based somewhat on GIFMetadataExtractor.
34 *
35 * @ingroup Media
36 */
37class JpegMetadataExtractor {
38    /**
39     * The max segment is a safety check. A JPEG file should never even remotely have
40     * that many segments. Your average file has about 10.
41     */
42    private const MAX_JPEG_SEGMENTS = 200;
43
44    /** Function to extract metadata segments of interest from jpeg files
45     * based on GIFMetadataExtractor.
46     *
47     * we can almost use getimagesize to do this
48     * but gis doesn't support having multiple app1 segments
49     * and those can't extract xmp on files containing both exif and xmp data
50     *
51     * @param string $filename Name of jpeg file
52     * @return array Array of interesting segments.
53     * @throws InvalidJpegException
54     */
55    public static function segmentSplitter( $filename ) {
56        $showXMP = XMPReader::isSupported();
57
58        $segmentCount = 0;
59
60        $segments = [
61            'XMP_ext' => [],
62            'COM' => [],
63            'PSIR' => [],
64        ];
65
66        if ( !$filename ) {
67            throw new InvalidJpegException( "No filename specified for " . __METHOD__ );
68        }
69        if ( !file_exists( $filename ) || is_dir( $filename ) ) {
70            throw new InvalidJpegException( "Invalid file $filename passed to " . __METHOD__ );
71        }
72
73        $fh = fopen( $filename, "rb" );
74
75        if ( !$fh ) {
76            throw new InvalidJpegException( "Could not open file $filename" );
77        }
78
79        $buffer = fread( $fh, 2 );
80        if ( $buffer !== "\xFF\xD8" ) {
81            throw new InvalidJpegException( "Not a jpeg, no SOI" );
82        }
83        while ( !feof( $fh ) ) {
84            $buffer = fread( $fh, 1 );
85            $segmentCount++;
86            if ( $segmentCount > self::MAX_JPEG_SEGMENTS ) {
87                throw new InvalidJpegException( 'Too many jpeg segments. Aborting' );
88            }
89            while ( $buffer !== "\xFF" && !feof( $fh ) ) {
90                // In theory JPEG files are not allowed to contain anything between the sections,
91                // but in practice they sometimes do. It's customary to ignore the garbage data.
92                $buffer = fread( $fh, 1 );
93            }
94
95            $buffer = fread( $fh, 1 );
96            while ( $buffer === "\xFF" && !feof( $fh ) ) {
97                // Skip through any 0xFF padding bytes.
98                $buffer = fread( $fh, 1 );
99            }
100            if ( $buffer === "\xFE" ) {
101                // COM section -- file comment
102                // First see if valid utf-8,
103                // if not try to convert it to windows-1252.
104                $com = $oldCom = trim( self::jpegExtractMarker( $fh ) );
105                UtfNormal\Validator::quickIsNFCVerify( $com );
106                // turns $com to valid utf-8.
107                // thus if no change, it's utf-8, otherwise it's something else.
108                if ( $com !== $oldCom ) {
109                    AtEase::suppressWarnings();
110                    $com = $oldCom = iconv( 'windows-1252', 'UTF-8//IGNORE', $oldCom );
111                    AtEase::restoreWarnings();
112                }
113                // Try it again, if it's still not a valid string, then probably
114                // binary junk or some really weird encoding, so don't extract.
115                UtfNormal\Validator::quickIsNFCVerify( $com );
116                if ( $com === $oldCom ) {
117                    $segments["COM"][] = $oldCom;
118                } else {
119                    wfDebug( __METHOD__ . " Ignoring JPEG comment as is garbage." );
120                }
121            } elseif ( $buffer === "\xE1" ) {
122                // APP1 section (Exif, XMP, and XMP extended)
123                // only extract if XMP is enabled.
124                $temp = self::jpegExtractMarker( $fh );
125                // check what type of app segment this is.
126                if ( substr( $temp, 0, 29 ) === "http://ns.adobe.com/xap/1.0/\x00" && $showXMP ) {
127                    // use trim to remove trailing \0 chars
128                    $segments["XMP"] = trim( substr( $temp, 29 ) );
129                } elseif ( substr( $temp, 0, 35 ) === "http://ns.adobe.com/xmp/extension/\x00" && $showXMP ) {
130                    // use trim to remove trailing \0 chars
131                    $segments["XMP_ext"][] = trim( substr( $temp, 35 ) );
132                } elseif ( substr( $temp, 0, 29 ) === "XMP\x00://ns.adobe.com/xap/1.0/\x00" && $showXMP ) {
133                    // Some images (especially flickr images) seem to have this.
134                    // I really have no idea what the deal is with them, but
135                    // whatever...
136                    // use trim to remove trailing \0 chars
137                    $segments["XMP"] = trim( substr( $temp, 29 ) );
138                    wfDebug( __METHOD__ . ' Found XMP section with wrong app identifier '
139                        . "Using anyways." );
140                } elseif ( substr( $temp, 0, 6 ) === "Exif\0\0" ) {
141                    // Just need to find out what the byte order is.
142                    // because php's exif plugin sucks...
143                    // This is a II for little Endian, MM for big. Not a unicode BOM.
144                    $byteOrderMarker = substr( $temp, 6, 2 );
145                    if ( $byteOrderMarker === 'MM' ) {
146                        $segments['byteOrder'] = 'BE';
147                    } elseif ( $byteOrderMarker === 'II' ) {
148                        $segments['byteOrder'] = 'LE';
149                    } else {
150                        wfDebug( __METHOD__ . " Invalid byte ordering?!" );
151                    }
152                }
153            } elseif ( $buffer === "\xED" ) {
154                // APP13 - PSIR. IPTC and some photoshop stuff
155                $temp = self::jpegExtractMarker( $fh );
156                if ( substr( $temp, 0, 14 ) === "Photoshop 3.0\x00" ) {
157                    $segments["PSIR"][] = $temp;
158                }
159            } elseif ( $buffer === "\xD9" || $buffer === "\xDA" ) {
160                // EOI - end of image or SOS - start of scan. either way we're past any interesting segments
161                return $segments;
162            } elseif ( in_array( $buffer, [
163                "\xC0", "\xC1", "\xC2", "\xC3", "\xC5", "\xC6", "\xC7",
164                "\xC9", "\xCA", "\xCB", "\xCD", "\xCE", "\xCF" ] )
165            ) {
166                // SOF0, SOF1, SOF2, ... (same list as getimagesize)
167                $temp = self::jpegExtractMarker( $fh );
168                try {
169                    $segments["SOF"] = StringUtils::unpack( 'Cbits/nheight/nwidth/Ccomponents', $temp );
170                } catch ( UnpackFailedException $e ) {
171                    throw new InvalidJpegException( $e->getMessage() );
172                }
173            } else {
174                // segment we don't care about, so skip
175                try {
176                    $size = StringUtils::unpack( "nint", fread( $fh, 2 ), 2 );
177                } catch ( UnpackFailedException $e ) {
178                    throw new InvalidJpegException( $e->getMessage() );
179                }
180                if ( $size['int'] < 2 ) {
181                    throw new InvalidJpegException( "invalid marker size in jpeg" );
182                }
183                // Note it's possible to seek beyond end of file if truncated.
184                // fseek doesn't report a failure in this case.
185                fseek( $fh, $size['int'] - 2, SEEK_CUR );
186            }
187        }
188        // shouldn't get here.
189        throw new InvalidJpegException( "Reached end of jpeg file unexpectedly" );
190    }
191
192    /**
193     * Helper function for jpegSegmentSplitter
194     * @param resource &$fh File handle for JPEG file
195     * @throws InvalidJpegException
196     * @return string Data content of segment.
197     */
198    private static function jpegExtractMarker( &$fh ) {
199        try {
200            $size = StringUtils::unpack( "nint", fread( $fh, 2 ), 2 );
201        } catch ( UnpackFailedException $e ) {
202            throw new InvalidJpegException( $e->getMessage() );
203        }
204        if ( $size['int'] < 2 ) {
205            throw new InvalidJpegException( "invalid marker size in jpeg" );
206        }
207        if ( $size['int'] === 2 ) {
208            // fread( ..., 0 ) generates a warning
209            return '';
210        }
211        $segment = fread( $fh, $size['int'] - 2 );
212        if ( strlen( $segment ) !== $size['int'] - 2 ) {
213            throw new InvalidJpegException( "Segment shorter than expected" );
214        }
215
216        return $segment;
217    }
218
219    /**
220     * This reads the photoshop image resource.
221     * Currently it only compares the iptc/iim hash
222     * with the stored hash, which is used to determine the precedence
223     * of the iptc data. In future it may extract some other info, like
224     * url of copyright license.
225     *
226     * This should generally be called by BitmapMetadataHandler::doApp13()
227     *
228     * @param string $app13 Photoshop psir app13 block from jpg.
229     * @throws InvalidPSIRException
230     * @return string If the iptc hash is good or not. One of 'iptc-no-hash',
231     *   'iptc-good-hash', 'iptc-bad-hash'.
232     */
233    public static function doPSIR( $app13 ) {
234        if ( !$app13 ) {
235            throw new InvalidPSIRException( "No App13 segment given" );
236        }
237        // First compare hash with real thing
238        // 0x404 contains IPTC, 0x425 has hash
239        // This is used to determine if the iptc is newer than
240        // the xmp data, as xmp programs update the hash,
241        // where non-xmp programs don't.
242
243        $offset = 14; // skip past PHOTOSHOP 3.0 identifier. should already be checked.
244        $appLen = strlen( $app13 );
245        $realHash = "";
246        $recordedHash = "";
247
248        // the +12 is the length of an empty item.
249        while ( $offset + 12 <= $appLen ) {
250            $valid = true;
251            if ( substr( $app13, $offset, 4 ) !== '8BIM' ) {
252                // it's supposed to be 8BIM
253                // but apparently sometimes isn't esp. in
254                // really old jpg's
255                $valid = false;
256            }
257            $offset += 4;
258            $id = substr( $app13, $offset, 2 );
259            // id is a 2 byte id number which identifies
260            // the piece of info this record contains.
261
262            $offset += 2;
263
264            // some record types can contain a name, which
265            // is a pascal string 0-padded to be an even
266            // number of bytes. Most times (and any time
267            // we care) this is empty, making it two null bytes.
268
269            $lenName = ord( substr( $app13, $offset, 1 ) ) + 1;
270            // we never use the name so skip it. +1 for length byte
271            if ( $lenName % 2 === 1 ) {
272                $lenName++;
273            } // pad to even.
274            $offset += $lenName;
275
276            // now length of data (unsigned long big endian)
277            try {
278                $lenData = StringUtils::unpack( 'Nlen', substr( $app13, $offset, 4 ), 4 );
279            } catch ( UnpackFailedException $e ) {
280                throw new InvalidPSIRException( $e->getMessage() );
281            }
282            // PHP can take issue with very large unsigned ints and make them negative.
283            // Which should never ever happen, as this has to be inside a segment
284            // which is limited to a 16 bit number.
285            if ( $lenData['len'] < 0 ) {
286                throw new InvalidPSIRException( "Too big PSIR (" . $lenData['len'] . ')' );
287            }
288
289            $offset += 4; // 4bytes length field;
290
291            // this should not happen, but check.
292            if ( $lenData['len'] + $offset > $appLen ) {
293                throw new InvalidPSIRException( "PSIR data too long. (item length=" . $lenData['len']
294                    . "; offset=$offset; total length=$appLen)" );
295            }
296
297            if ( $valid ) {
298                switch ( $id ) {
299                    case "\x04\x04":
300                        // IPTC block
301                        $realHash = md5( substr( $app13, $offset, $lenData['len'] ), true );
302                        break;
303                    case "\x04\x25":
304                        $recordedHash = substr( $app13, $offset, $lenData['len'] );
305                        break;
306                }
307            }
308
309            // if odd, add 1 to length to account for
310            // null pad byte.
311            if ( $lenData['len'] % 2 === 1 ) {
312                $lenData['len']++;
313            }
314            $offset += $lenData['len'];
315        }
316
317        if ( !$realHash || !$recordedHash ) {
318            return 'iptc-no-hash';
319        }
320        if ( $realHash === $recordedHash ) {
321            return 'iptc-good-hash';
322        }
323        /* if $realHash !== $recordedHash */
324        return 'iptc-bad-hash';
325    }
326}