MediaWiki  master
JpegMetadataExtractor.php
Go to the documentation of this file.
1 <?php
24 use Wikimedia\XMPReader\Reader as XMPReader;
25 
35  const MAX_JPEG_SEGMENTS = 200;
36 
37  // the max segment is a sanity check.
38  // A jpeg file should never even remotely have
39  // that many segments. Your average file has about 10.
40 
52  static function segmentSplitter( $filename ) {
53  $showXMP = XMPReader::isSupported();
54 
55  $segmentCount = 0;
56 
57  $segments = [
58  'XMP_ext' => [],
59  'COM' => [],
60  'PSIR' => [],
61  ];
62 
63  if ( !$filename ) {
64  throw new MWException( "No filename specified for " . __METHOD__ );
65  }
66  if ( !file_exists( $filename ) || is_dir( $filename ) ) {
67  throw new MWException( "Invalid file $filename passed to " . __METHOD__ );
68  }
69 
70  $fh = fopen( $filename, "rb" );
71 
72  if ( !$fh ) {
73  throw new MWException( "Could not open file $filename" );
74  }
75 
76  $buffer = fread( $fh, 2 );
77  if ( $buffer !== "\xFF\xD8" ) {
78  throw new MWException( "Not a jpeg, no SOI" );
79  }
80  while ( !feof( $fh ) ) {
81  $buffer = fread( $fh, 1 );
82  $segmentCount++;
83  if ( $segmentCount > self::MAX_JPEG_SEGMENTS ) {
84  // this is just a sanity check
85  throw new MWException( 'Too many jpeg segments. Aborting' );
86  }
87  while ( $buffer !== "\xFF" && !feof( $fh ) ) {
88  // In theory JPEG files are not allowed to contain anything between the sections,
89  // but in practice they sometimes do. It's customary to ignore the garbage data.
90  $buffer = fread( $fh, 1 );
91  }
92 
93  $buffer = fread( $fh, 1 );
94  while ( $buffer === "\xFF" && !feof( $fh ) ) {
95  // Skip through any 0xFF padding bytes.
96  $buffer = fread( $fh, 1 );
97  }
98  if ( $buffer === "\xFE" ) {
99  // COM section -- file comment
100  // First see if valid utf-8,
101  // if not try to convert it to windows-1252.
102  $com = $oldCom = trim( self::jpegExtractMarker( $fh ) );
103  UtfNormal\Validator::quickIsNFCVerify( $com );
104  // turns $com to valid utf-8.
105  // thus if no change, its utf-8, otherwise its something else.
106  if ( $com !== $oldCom ) {
107  Wikimedia\suppressWarnings();
108  $com = $oldCom = iconv( 'windows-1252', 'UTF-8//IGNORE', $oldCom );
109  Wikimedia\restoreWarnings();
110  }
111  // Try it again, if its still not a valid string, then probably
112  // binary junk or some really weird encoding, so don't extract.
113  UtfNormal\Validator::quickIsNFCVerify( $com );
114  if ( $com === $oldCom ) {
115  $segments["COM"][] = $oldCom;
116  } else {
117  wfDebug( __METHOD__ . " Ignoring JPEG comment as is garbage.\n" );
118  }
119  } elseif ( $buffer === "\xE1" ) {
120  // APP1 section (Exif, XMP, and XMP extended)
121  // only extract if XMP is enabled.
122  $temp = self::jpegExtractMarker( $fh );
123  // check what type of app segment this is.
124  if ( substr( $temp, 0, 29 ) === "http://ns.adobe.com/xap/1.0/\x00" && $showXMP ) {
125  $segments["XMP"] = substr( $temp, 29 );
126  } elseif ( substr( $temp, 0, 35 ) === "http://ns.adobe.com/xmp/extension/\x00" && $showXMP ) {
127  $segments["XMP_ext"][] = substr( $temp, 35 );
128  } elseif ( substr( $temp, 0, 29 ) === "XMP\x00://ns.adobe.com/xap/1.0/\x00" && $showXMP ) {
129  // Some images (especially flickr images) seem to have this.
130  // I really have no idea what the deal is with them, but
131  // whatever...
132  $segments["XMP"] = substr( $temp, 29 );
133  wfDebug( __METHOD__ . ' Found XMP section with wrong app identifier '
134  . "Using anyways.\n" );
135  } elseif ( substr( $temp, 0, 6 ) === "Exif\0\0" ) {
136  // Just need to find out what the byte order is.
137  // because php's exif plugin sucks...
138  // This is a II for little Endian, MM for big. Not a unicode BOM.
139  $byteOrderMarker = substr( $temp, 6, 2 );
140  if ( $byteOrderMarker === 'MM' ) {
141  $segments['byteOrder'] = 'BE';
142  } elseif ( $byteOrderMarker === 'II' ) {
143  $segments['byteOrder'] = 'LE';
144  } else {
145  wfDebug( __METHOD__ . " Invalid byte ordering?!\n" );
146  }
147  }
148  } elseif ( $buffer === "\xED" ) {
149  // APP13 - PSIR. IPTC and some photoshop stuff
150  $temp = self::jpegExtractMarker( $fh );
151  if ( substr( $temp, 0, 14 ) === "Photoshop 3.0\x00" ) {
152  $segments["PSIR"][] = $temp;
153  }
154  } elseif ( $buffer === "\xD9" || $buffer === "\xDA" ) {
155  // EOI - end of image or SOS - start of scan. either way we're past any interesting segments
156  return $segments;
157  } else {
158  // segment we don't care about, so skip
159  $size = wfUnpack( "nint", fread( $fh, 2 ), 2 );
160  if ( $size['int'] < 2 ) {
161  throw new MWException( "invalid marker size in jpeg" );
162  }
163  // Note it's possible to seek beyond end of file if truncated.
164  // fseek doesn't report a failure in this case.
165  fseek( $fh, $size['int'] - 2, SEEK_CUR );
166  }
167  }
168  // shouldn't get here.
169  throw new MWException( "Reached end of jpeg file unexpectedly" );
170  }
171 
178  private static function jpegExtractMarker( &$fh ) {
179  $size = wfUnpack( "nint", fread( $fh, 2 ), 2 );
180  if ( $size['int'] < 2 ) {
181  throw new MWException( "invalid marker size in jpeg" );
182  }
183  if ( $size['int'] === 2 ) {
184  // fread( ..., 0 ) generates a warning
185  return '';
186  }
187  $segment = fread( $fh, $size['int'] - 2 );
188  if ( strlen( $segment ) !== $size['int'] - 2 ) {
189  throw new MWException( "Segment shorter than expected" );
190  }
191 
192  return $segment;
193  }
194 
209  public static function doPSIR( $app13 ) {
210  if ( !$app13 ) {
211  throw new MWException( "No App13 segment given" );
212  }
213  // First compare hash with real thing
214  // 0x404 contains IPTC, 0x425 has hash
215  // This is used to determine if the iptc is newer than
216  // the xmp data, as xmp programs update the hash,
217  // where non-xmp programs don't.
218 
219  $offset = 14; // skip past PHOTOSHOP 3.0 identifier. should already be checked.
220  $appLen = strlen( $app13 );
221  $realHash = "";
222  $recordedHash = "";
223 
224  // the +12 is the length of an empty item.
225  while ( $offset + 12 <= $appLen ) {
226  $valid = true;
227  if ( substr( $app13, $offset, 4 ) !== '8BIM' ) {
228  // its supposed to be 8BIM
229  // but apparently sometimes isn't esp. in
230  // really old jpg's
231  $valid = false;
232  }
233  $offset += 4;
234  $id = substr( $app13, $offset, 2 );
235  // id is a 2 byte id number which identifies
236  // the piece of info this record contains.
237 
238  $offset += 2;
239 
240  // some record types can contain a name, which
241  // is a pascal string 0-padded to be an even
242  // number of bytes. Most times (and any time
243  // we care) this is empty, making it two null bytes.
244 
245  $lenName = ord( substr( $app13, $offset, 1 ) ) + 1;
246  // we never use the name so skip it. +1 for length byte
247  if ( $lenName % 2 == 1 ) {
248  $lenName++;
249  } // pad to even.
250  $offset += $lenName;
251 
252  // now length of data (unsigned long big endian)
253  $lenData = wfUnpack( 'Nlen', substr( $app13, $offset, 4 ), 4 );
254  // PHP can take issue with very large unsigned ints and make them negative.
255  // Which should never ever happen, as this has to be inside a segment
256  // which is limited to a 16 bit number.
257  if ( $lenData['len'] < 0 ) {
258  throw new MWException( "Too big PSIR (" . $lenData['len'] . ')' );
259  }
260 
261  $offset += 4; // 4bytes length field;
262 
263  // this should not happen, but check.
264  if ( $lenData['len'] + $offset > $appLen ) {
265  throw new MWException( "PSIR data too long. (item length=" . $lenData['len']
266  . "; offset=$offset; total length=$appLen)" );
267  }
268 
269  if ( $valid ) {
270  switch ( $id ) {
271  case "\x04\x04":
272  // IPTC block
273  $realHash = md5( substr( $app13, $offset, $lenData['len'] ), true );
274  break;
275  case "\x04\x25":
276  $recordedHash = substr( $app13, $offset, $lenData['len'] );
277  break;
278  }
279  }
280 
281  // if odd, add 1 to length to account for
282  // null pad byte.
283  if ( $lenData['len'] % 2 == 1 ) {
284  $lenData['len']++;
285  }
286  $offset += $lenData['len'];
287  }
288 
289  if ( !$realHash || !$recordedHash ) {
290  return 'iptc-no-hash';
291  } elseif ( $realHash === $recordedHash ) {
292  return 'iptc-good-hash';
293  } else { /*$realHash !== $recordedHash */
294  return 'iptc-bad-hash';
295  }
296  }
297 }
static jpegExtractMarker(&$fh)
Helper function for jpegSegmentSplitter.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
static segmentSplitter( $filename)
Function to extract metadata segments of interest from jpeg files based on GIFMetadataExtractor.
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
$buffer
static doPSIR( $app13)
This reads the photoshop image resource.
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
Class for reading jpegs and extracting metadata.
wfUnpack( $format, $data, $length=false)
Wrapper around php&#39;s unpack.