MediaWiki  master
PNGMetadataExtractor.php
Go to the documentation of this file.
1 <?php
35  private static $pngSig;
36 
38  private static $crcSize;
39 
41  private static $textChunks;
42 
43  public const VERSION = 1;
44  private const MAX_CHUNK_SIZE = 3145728; // 3 mebibytes
45 
46  public static function getMetadata( $filename ) {
47  self::$pngSig = pack( "C8", 137, 80, 78, 71, 13, 10, 26, 10 );
48  self::$crcSize = 4;
49  /* based on list at http://owl.phy.queensu.ca/~phil/exiftool/TagNames/PNG.html#TextualData
50  * and https://www.w3.org/TR/PNG/#11keywords
51  */
52  self::$textChunks = [
53  'xml:com.adobe.xmp' => 'xmp',
54  # Artist is unofficial. Author is the recommended
55  # keyword in the PNG spec. However some people output
56  # Artist so support both.
57  'artist' => 'Artist',
58  'model' => 'Model',
59  'make' => 'Make',
60  'author' => 'Artist',
61  'comment' => 'PNGFileComment',
62  'description' => 'ImageDescription',
63  'title' => 'ObjectName',
64  'copyright' => 'Copyright',
65  # Source as in original device used to make image
66  # not as in who gave you the image
67  'source' => 'Model',
68  'software' => 'Software',
69  'disclaimer' => 'Disclaimer',
70  'warning' => 'ContentWarning',
71  'url' => 'Identifier', # Not sure if this is best mapping. Maybe WebStatement.
72  'label' => 'Label',
73  'creation time' => 'DateTimeDigitized',
74  /* Other potentially useful things - Document */
75  ];
76 
77  $frameCount = 0;
78  $loopCount = 1;
79  $text = [];
80  $duration = 0.0;
81  $width = 0;
82  $height = 0;
83  $bitDepth = 0;
84  $colorType = 'unknown';
85 
86  if ( !$filename ) {
87  throw new Exception( __METHOD__ . ": No file name specified" );
88  } elseif ( !file_exists( $filename ) || is_dir( $filename ) ) {
89  throw new Exception( __METHOD__ . ": File $filename does not exist" );
90  }
91 
92  $fh = fopen( $filename, 'rb' );
93 
94  if ( !$fh ) {
95  throw new Exception( __METHOD__ . ": Unable to open file $filename" );
96  }
97 
98  // Check for the PNG header
99  $buf = self::read( $fh, 8 );
100  if ( $buf != self::$pngSig ) {
101  throw new Exception( __METHOD__ . ": Not a valid PNG file; header: $buf" );
102  }
103 
104  // Read chunks
105  while ( !feof( $fh ) ) {
106  $buf = self::read( $fh, 4 );
107  $chunk_size = unpack( "N", $buf )[1];
108 
109  if ( $chunk_size < 0 ) {
110  throw new Exception( __METHOD__ . ": Chunk size too big for unpack" );
111  }
112 
113  $chunk_type = self::read( $fh, 4 );
114  $buf = self::read( $fh, $chunk_size );
115  $crc = self::read( $fh, self::$crcSize );
116  $computed = crc32( $chunk_type . $buf );
117  if ( pack( 'N', $computed ) !== $crc ) {
118  wfDebug( __METHOD__ . ': chunk has invalid CRC, skipping' );
119  continue;
120  }
121 
122  if ( $chunk_type == "IHDR" ) {
123  $width = unpack( 'N', substr( $buf, 0, 4 ) )[1];
124  $height = unpack( 'N', substr( $buf, 4, 4 ) )[1];
125  $bitDepth = ord( substr( $buf, 8, 1 ) );
126  // Detect the color type in British English as per the spec
127  // https://www.w3.org/TR/PNG/#11IHDR
128  switch ( ord( substr( $buf, 9, 1 ) ) ) {
129  case 0:
130  $colorType = 'greyscale';
131  break;
132  case 2:
133  $colorType = 'truecolour';
134  break;
135  case 3:
136  $colorType = 'index-coloured';
137  break;
138  case 4:
139  $colorType = 'greyscale-alpha';
140  break;
141  case 6:
142  $colorType = 'truecolour-alpha';
143  break;
144  default:
145  $colorType = 'unknown';
146  break;
147  }
148  } elseif ( $chunk_type == "acTL" ) {
149  if ( $chunk_size < 4 ) {
150  wfDebug( __METHOD__ . ": acTL chunk too small" );
151  continue;
152  }
153 
154  $actl = unpack( "Nframes/Nplays", $buf );
155  $frameCount = $actl['frames'];
156  $loopCount = $actl['plays'];
157  } elseif ( $chunk_type == "fcTL" ) {
158  $buf = substr( $buf, 20 );
159  if ( strlen( $buf ) < 4 ) {
160  wfDebug( __METHOD__ . ": fcTL chunk too small" );
161  continue;
162  }
163 
164  $fctldur = unpack( "ndelay_num/ndelay_den", $buf );
165  if ( $fctldur['delay_den'] == 0 ) {
166  $fctldur['delay_den'] = 100;
167  }
168  if ( $fctldur['delay_num'] ) {
169  $duration += $fctldur['delay_num'] / $fctldur['delay_den'];
170  }
171  } elseif ( $chunk_type == "iTXt" ) {
172  // Extracts iTXt chunks, uncompressing if necessary.
173  $items = [];
174  if ( preg_match(
175  '/^([^\x00]{1,79})\x00(\x00|\x01)\x00([^\x00]*)(.)[^\x00]*\x00(.*)$/Ds',
176  $buf, $items )
177  ) {
178  /* $items[1] = text chunk name, $items[2] = compressed flag,
179  * $items[3] = lang code (or ""), $items[4]= compression type.
180  * $items[5] = content
181  */
182 
183  // Theoretically should be case-sensitive, but in practise...
184  $items[1] = strtolower( $items[1] );
185  if ( !isset( self::$textChunks[$items[1]] ) ) {
186  // Only extract textual chunks on our list.
187  continue;
188  }
189 
190  $items[3] = strtolower( $items[3] );
191  if ( $items[3] == '' ) {
192  // if no lang specified use x-default like in xmp.
193  $items[3] = 'x-default';
194  }
195 
196  // if compressed
197  if ( $items[2] == "\x01" ) {
198  if ( function_exists( 'gzuncompress' ) && $items[4] === "\x00" ) {
199  Wikimedia\suppressWarnings();
200  $items[5] = gzuncompress( $items[5] );
201  Wikimedia\restoreWarnings();
202 
203  if ( $items[5] === false ) {
204  // decompression failed
205  wfDebug( __METHOD__ . ' Error decompressing iTxt chunk - ' . $items[1] );
206  continue;
207  }
208  } else {
209  wfDebug( __METHOD__ . ' Skipping compressed png iTXt chunk due to lack of zlib,'
210  . " or potentially invalid compression method" );
211  continue;
212  }
213  }
214  $finalKeyword = self::$textChunks[$items[1]];
215  $text[$finalKeyword][$items[3]] = $items[5];
216  $text[$finalKeyword]['_type'] = 'lang';
217  } else {
218  // Error reading iTXt chunk
219  wfDebug( __METHOD__ . ": Invalid iTXt chunk" );
220  }
221  } elseif ( $chunk_type == 'tEXt' ) {
222  // In case there is no \x00 which will make explode fail.
223  if ( strpos( $buf, "\x00" ) === false ) {
224  wfDebug( __METHOD__ . ": Invalid tEXt chunk: no null byte" );
225  continue;
226  }
227 
228  list( $keyword, $content ) = explode( "\x00", $buf, 2 );
229  if ( $keyword === '' ) {
230  wfDebug( __METHOD__ . ": Empty tEXt keyword" );
231  continue;
232  }
233 
234  // Theoretically should be case-sensitive, but in practise...
235  $keyword = strtolower( $keyword );
236  if ( !isset( self::$textChunks[$keyword] ) ) {
237  // Don't recognize chunk, so skip.
238  continue;
239  }
240  Wikimedia\suppressWarnings();
241  $content = iconv( 'ISO-8859-1', 'UTF-8', $content );
242  Wikimedia\restoreWarnings();
243 
244  if ( $content === false ) {
245  wfDebug( __METHOD__ . ": Read error (error with iconv)" );
246  continue;
247  }
248 
249  $finalKeyword = self::$textChunks[$keyword];
250  $text[$finalKeyword]['x-default'] = $content;
251  $text[$finalKeyword]['_type'] = 'lang';
252  } elseif ( $chunk_type == 'zTXt' ) {
253  if ( function_exists( 'gzuncompress' ) ) {
254  // In case there is no \x00 which will make explode fail.
255  if ( strpos( $buf, "\x00" ) === false ) {
256  wfDebug( __METHOD__ . ": No null byte in zTXt chunk" );
257  continue;
258  }
259 
260  list( $keyword, $postKeyword ) = explode( "\x00", $buf, 2 );
261  if ( $keyword === '' || $postKeyword === '' ) {
262  wfDebug( __METHOD__ . ": Empty zTXt chunk" );
263  continue;
264  }
265  // Theoretically should be case-sensitive, but in practise...
266  $keyword = strtolower( $keyword );
267 
268  if ( !isset( self::$textChunks[$keyword] ) ) {
269  // Don't recognize chunk, so skip.
270  continue;
271  }
272  $compression = substr( $postKeyword, 0, 1 );
273  $content = substr( $postKeyword, 1 );
274  if ( $compression !== "\x00" ) {
275  wfDebug( __METHOD__ . " Unrecognized compression method in zTXt ($keyword). Skipping." );
276  continue;
277  }
278 
279  Wikimedia\suppressWarnings();
280  $content = gzuncompress( $content );
281  Wikimedia\restoreWarnings();
282 
283  if ( $content === false ) {
284  // decompression failed
285  wfDebug( __METHOD__ . ' Error decompressing zTXt chunk - ' . $keyword );
286  continue;
287  }
288 
289  Wikimedia\suppressWarnings();
290  $content = iconv( 'ISO-8859-1', 'UTF-8', $content );
291  Wikimedia\restoreWarnings();
292 
293  if ( $content === false ) {
294  wfDebug( __METHOD__ . ": iconv error in zTXt chunk" );
295  continue;
296  }
297 
298  $finalKeyword = self::$textChunks[$keyword];
299  $text[$finalKeyword]['x-default'] = $content;
300  $text[$finalKeyword]['_type'] = 'lang';
301  } else {
302  wfDebug( __METHOD__ . " Cannot decompress zTXt chunk due to lack of zlib. Skipping." );
303  }
304  } elseif ( $chunk_type == 'tIME' ) {
305  // last mod timestamp.
306  if ( $chunk_size !== 7 ) {
307  wfDebug( __METHOD__ . ": tIME wrong size" );
308  continue;
309  }
310 
311  // Note: spec says this should be UTC.
312  $t = unpack( "ny/Cm/Cd/Ch/Cmin/Cs", $buf );
313  $strTime = sprintf( "%04d%02d%02d%02d%02d%02d",
314  $t['y'], $t['m'], $t['d'], $t['h'],
315  $t['min'], $t['s'] );
316 
317  $exifTime = wfTimestamp( TS_EXIF, $strTime );
318 
319  if ( $exifTime ) {
320  $text['DateTime'] = $exifTime;
321  }
322  } elseif ( $chunk_type == 'pHYs' ) {
323  // how big pixels are (dots per meter).
324  if ( $chunk_size !== 9 ) {
325  wfDebug( __METHOD__ . ": pHYs wrong size" );
326  continue;
327  }
328 
329  $dim = unpack( "Nwidth/Nheight/Cunit", $buf );
330  if ( $dim['unit'] == 1 ) {
331  // Need to check for negative because php
332  // doesn't deal with super-large unsigned 32-bit ints well
333  if ( $dim['width'] > 0 && $dim['height'] > 0 ) {
334  // unit is meters
335  // (as opposed to 0 = undefined )
336  $text['XResolution'] = $dim['width']
337  . '/100';
338  $text['YResolution'] = $dim['height']
339  . '/100';
340  $text['ResolutionUnit'] = 3;
341  // 3 = dots per cm (from Exif).
342  }
343  }
344  } elseif ( $chunk_type == "IEND" ) {
345  break;
346  }
347  }
348  fclose( $fh );
349 
350  if ( $loopCount > 1 ) {
351  $duration *= $loopCount;
352  }
353 
354  if ( isset( $text['DateTimeDigitized'] ) ) {
355  // Convert date format from rfc2822 to exif.
356  foreach ( $text['DateTimeDigitized'] as $name => &$value ) {
357  if ( $name === '_type' ) {
358  continue;
359  }
360 
361  // @todo FIXME: Currently timezones are ignored.
362  // possibly should be wfTimestamp's
363  // responsibility. (at least for numeric TZ)
364  $formatted = wfTimestamp( TS_EXIF, $value );
365  if ( $formatted ) {
366  // Only change if we could convert the
367  // date.
368  // The png standard says it should be
369  // in rfc2822 format, but not required.
370  // In general for the exif stuff we
371  // prettify the date if we can, but we
372  // display as-is if we cannot or if
373  // it is invalid.
374  // So do the same here.
375 
376  $value = $formatted;
377  }
378  }
379  }
380 
381  return [
382  'width' => $width,
383  'height' => $height,
384  'frameCount' => $frameCount,
385  'loopCount' => $loopCount,
386  'duration' => $duration,
387  'text' => $text,
388  'bitDepth' => $bitDepth,
389  'colorType' => $colorType,
390  ];
391  }
392 
401  private static function read( $fh, $size ) {
402  if ( $size > self::MAX_CHUNK_SIZE ) {
403  throw new Exception( __METHOD__ . ': Chunk size of ' . $size .
404  ' too big. Max size is: ' . self::MAX_CHUNK_SIZE );
405  }
406  if ( $size === 0 ) {
407  return '';
408  }
409 
410  $result = fread( $fh, $size );
411  if ( $result === false ) {
412  throw new Exception( __METHOD__ . ': read error' );
413  }
414  if ( strlen( $result ) < $size ) {
415  throw new Exception( __METHOD__ . ': unexpected end of file' );
416  }
417  return $result;
418  }
419 }
PNGMetadataExtractor\VERSION
const VERSION
Definition: PNGMetadataExtractor.php:43
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1692
PNGMetadataExtractor
PNG frame counter.
Definition: PNGMetadataExtractor.php:33
PNGMetadataExtractor\$crcSize
static int $crcSize
Definition: PNGMetadataExtractor.php:38
PNGMetadataExtractor\$pngSig
static string $pngSig
Definition: PNGMetadataExtractor.php:35
PNGMetadataExtractor\$textChunks
static array $textChunks
Definition: PNGMetadataExtractor.php:41
PNGMetadataExtractor\getMetadata
static getMetadata( $filename)
Definition: PNGMetadataExtractor.php:46
wfDebug
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Definition: GlobalFunctions.php:894
PNGMetadataExtractor\read
static read( $fh, $size)
Read a chunk, checking to make sure its not too big.
Definition: PNGMetadataExtractor.php:401
$content
$content
Definition: router.php:76
PNGMetadataExtractor\MAX_CHUNK_SIZE
const MAX_CHUNK_SIZE
Definition: PNGMetadataExtractor.php:44
$t
$t
Definition: testCompression.php:74