summaryrefslogtreecommitdiff
path: root/includes/media/PNGMetadataExtractor.php
blob: d3c44d4f18196d5c70c6eb5e9f79befe2eec04e4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
<?php
/**
 * PNG frame counter and metadata extractor.
 * Slightly derived from GIFMetadataExtractor.php
 * Deliberately not using MWExceptions to avoid external dependencies, encouraging
 * redistribution.
 *
 * @file
 * @ingroup Media
 */

/**
 * PNG frame counter.
 *
 * @ingroup Media
 */
class PNGMetadataExtractor {
	static $png_sig;
	static $CRC_size;
	static $text_chunks;

	const VERSION = 1;
	const MAX_CHUNK_SIZE = 3145728; // 3 megabytes

	static function getMetadata( $filename ) {
		self::$png_sig = pack( "C8", 137, 80, 78, 71, 13, 10, 26, 10 );
		self::$CRC_size = 4;
		/* based on list at http://owl.phy.queensu.ca/~phil/exiftool/TagNames/PNG.html#TextualData
		 * and http://www.w3.org/TR/PNG/#11keywords
		 */
		self::$text_chunks = array(
			'xml:com.adobe.xmp' => 'xmp',
			# Artist is unofficial. Author is the recommended
			# keyword in the PNG spec. However some people output
			# Artist so support both.
			'artist'      => 'Artist',
			'model'       => 'Model',
			'make'        => 'Make',
			'author'      => 'Artist',
			'comment'     => 'PNGFileComment',
			'description' => 'ImageDescription',
			'title'       => 'ObjectName',
			'copyright'   => 'Copyright',
			# Source as in original device used to make image
			# not as in who gave you the image
			'source'      => 'Model',
			'software'    => 'Software',
			'disclaimer'  => 'Disclaimer',
			'warning'     => 'ContentWarning',
			'url'         => 'Identifier', # Not sure if this is best mapping. Maybe WebStatement.
			'label'       => 'Label',
			'creation time' => 'DateTimeDigitized',
			/* Other potentially useful things - Document */
		);

		$frameCount = 0;
		$loopCount = 1;
		$text = array();
		$duration = 0.0;
		$bitDepth = 0;
		$colorType = 'unknown';

		if ( !$filename ) {
			throw new Exception( __METHOD__ . ": No file name specified" );
		} elseif ( !file_exists( $filename ) || is_dir( $filename ) ) {
			throw new Exception( __METHOD__ . ": File $filename does not exist" );
		}

		$fh = fopen( $filename, 'rb' );

		if ( !$fh ) {
			throw new Exception( __METHOD__ . ": Unable to open file $filename" );
		}

		// Check for the PNG header
		$buf = fread( $fh, 8 );
		if ( $buf != self::$png_sig ) {
			throw new Exception( __METHOD__ . ": Not a valid PNG file; header: $buf" );
		}

		// Read chunks
		while ( !feof( $fh ) ) {
			$buf = fread( $fh, 4 );
			if ( !$buf || strlen( $buf ) < 4 ) {
				throw new Exception( __METHOD__ . ": Read error" );
			}
			$chunk_size = unpack( "N", $buf );
			$chunk_size = $chunk_size[1];

			if ( $chunk_size < 0 ) {
				throw new Exception( __METHOD__ . ": Chunk size too big for unpack" );
			}

			$chunk_type = fread( $fh, 4 );
			if ( !$chunk_type || strlen( $chunk_type ) < 4 ) {
				throw new Exception( __METHOD__ . ": Read error" );
			}

			if ( $chunk_type == "IHDR" ) {
				$buf = self::read( $fh, $chunk_size );
				if ( !$buf || strlen( $buf ) < $chunk_size ) {
					throw new Exception( __METHOD__ . ": Read error" );
				}
				$bitDepth = ord( substr( $buf, 8, 1 ) );
				// Detect the color type in British English as per the spec
				// http://www.w3.org/TR/PNG/#11IHDR
				switch ( ord( substr( $buf, 9, 1 ) ) ) {
					case 0:
						$colorType = 'greyscale';
						break;
					case 2: 
						$colorType = 'truecolour';
						break;
					case 3:
						$colorType = 'index-coloured';
						break;
					case 4:
						$colorType = 'greyscale-alpha';
						break;
					case 6:
						$colorType = 'truecolour-alpha';
						break;
					default:
						$colorType = 'unknown';
						break;
				}
			} elseif ( $chunk_type == "acTL" ) {
				$buf = fread( $fh, $chunk_size );
				if( !$buf || strlen( $buf ) < $chunk_size || $chunk_size < 4 ) {
					throw new Exception( __METHOD__ . ": Read error" );
				}

				$actl = unpack( "Nframes/Nplays", $buf );
				$frameCount = $actl['frames'];
				$loopCount = $actl['plays'];
			} elseif ( $chunk_type == "fcTL" ) {
				$buf = self::read( $fh, $chunk_size );
				if ( !$buf || strlen( $buf ) < $chunk_size ) {
					throw new Exception( __METHOD__ . ": Read error" );
				}
				$buf = substr( $buf, 20 );
				if ( strlen( $buf ) < 4 ) {
					throw new Exception( __METHOD__ . ": Read error" );
				}

				$fctldur = unpack( "ndelay_num/ndelay_den", $buf );
				if ( $fctldur['delay_den'] == 0 ) {
					$fctldur['delay_den'] = 100;
				}
				if ( $fctldur['delay_num'] ) {
					$duration += $fctldur['delay_num'] / $fctldur['delay_den'];
				}
			} elseif ( $chunk_type == "iTXt" ) {
				// Extracts iTXt chunks, uncompressing if necessary.
				$buf = self::read( $fh, $chunk_size );
				$items = array();
				if ( preg_match(
					'/^([^\x00]{1,79})\x00(\x00|\x01)\x00([^\x00]*)(.)[^\x00]*\x00(.*)$/Ds',
					$buf, $items )
				) {
					/* $items[1] = text chunk name, $items[2] = compressed flag,
					 * $items[3] = lang code (or ""), $items[4]= compression type.
					 * $items[5] = content
					 */

					// Theoretically should be case-sensitive, but in practise...
					$items[1] = strtolower( $items[1] );
					if ( !isset( self::$text_chunks[$items[1]] ) ) {
						// Only extract textual chunks on our list.
						fseek( $fh, self::$CRC_size, SEEK_CUR );
						continue;
					}

					$items[3] = strtolower( $items[3] );
					if ( $items[3] == '' ) {
						// if no lang specified use x-default like in xmp.
						$items[3] = 'x-default';
					}

					// if compressed
					if ( $items[2] == "\x01" ) {
						if ( function_exists( 'gzuncompress' ) && $items[4] === "\x00" ) {
							wfSuppressWarnings();
							$items[5] = gzuncompress( $items[5] );
							wfRestoreWarnings();

							if ( $items[5] === false ) {
								// decompression failed
								wfDebug( __METHOD__ . ' Error decompressing iTxt chunk - ' . $items[1] );
								fseek( $fh, self::$CRC_size, SEEK_CUR );
								continue;
							}

						} else {
							wfDebug( __METHOD__ . ' Skipping compressed png iTXt chunk due to lack of zlib,'
								. ' or potentially invalid compression method' );
							fseek( $fh, self::$CRC_size, SEEK_CUR );
							continue;
						}
					}
					$finalKeyword = self::$text_chunks[ $items[1] ];
					$text[ $finalKeyword ][ $items[3] ] = $items[5];
					$text[ $finalKeyword ]['_type'] = 'lang';

				} else {
					// Error reading iTXt chunk
					throw new Exception( __METHOD__ . ": Read error on iTXt chunk" );
				}

			} elseif ( $chunk_type == 'tEXt' ) {
				$buf = self::read( $fh, $chunk_size );

				// In case there is no \x00 which will make explode fail.
				if ( strpos( $buf, "\x00" ) === false ) {
					throw new Exception( __METHOD__ . ": Read error on tEXt chunk" );
				}

				list( $keyword, $content ) = explode( "\x00", $buf, 2 );
				if ( $keyword === '' || $content === '' ) {
					throw new Exception( __METHOD__ . ": Read error on tEXt chunk" );
				}

				// Theoretically should be case-sensitive, but in practise...
				$keyword = strtolower( $keyword );
				if ( !isset( self::$text_chunks[ $keyword ] ) ) {
					// Don't recognize chunk, so skip.
					fseek( $fh, self::$CRC_size, SEEK_CUR );
					continue;
				}
				wfSuppressWarnings();
				$content = iconv( 'ISO-8859-1', 'UTF-8', $content );
				wfRestoreWarnings();

				if ( $content === false ) {
					throw new Exception( __METHOD__ . ": Read error (error with iconv)" );
				}

				$finalKeyword = self::$text_chunks[ $keyword ];
				$text[ $finalKeyword ][ 'x-default' ] = $content;
				$text[ $finalKeyword ]['_type'] = 'lang';

			} elseif ( $chunk_type == 'zTXt' ) {
				if ( function_exists( 'gzuncompress' ) ) {
					$buf = self::read( $fh, $chunk_size );

					// In case there is no \x00 which will make explode fail.
					if ( strpos( $buf, "\x00" ) === false ) {
						throw new Exception( __METHOD__ . ": Read error on zTXt chunk" );
					}

					list( $keyword, $postKeyword ) = explode( "\x00", $buf, 2 );
					if ( $keyword === '' || $postKeyword === '' ) {
						throw new Exception( __METHOD__ . ": Read error on zTXt chunk" );
					}
					// Theoretically should be case-sensitive, but in practise...
					$keyword = strtolower( $keyword );

					if ( !isset( self::$text_chunks[ $keyword ] ) ) {
						// Don't recognize chunk, so skip.
						fseek( $fh, self::$CRC_size, SEEK_CUR );
						continue;
					}
					$compression = substr( $postKeyword, 0, 1 );
					$content = substr( $postKeyword, 1 );
					if ( $compression !== "\x00" ) {
						wfDebug( __METHOD__ . " Unrecognized compression method in zTXt ($keyword). Skipping." );
						fseek( $fh, self::$CRC_size, SEEK_CUR );
						continue;
					}

					wfSuppressWarnings();
					$content = gzuncompress( $content );
					wfRestoreWarnings();

					if ( $content === false ) {
						// decompression failed
						wfDebug( __METHOD__ . ' Error decompressing zTXt chunk - ' . $keyword );
						fseek( $fh, self::$CRC_size, SEEK_CUR );
						continue;
					}

					wfSuppressWarnings();
					$content = iconv( 'ISO-8859-1', 'UTF-8', $content );
					wfRestoreWarnings();

					if ( $content === false ) {
						throw new Exception( __METHOD__ . ": Read error (error with iconv)" );
					}

					$finalKeyword = self::$text_chunks[ $keyword ];
					$text[ $finalKeyword ][ 'x-default' ] = $content;
					$text[ $finalKeyword ]['_type'] = 'lang';

				} else {
					wfDebug( __METHOD__ . " Cannot decompress zTXt chunk due to lack of zlib. Skipping." );
					fseek( $fh, $chunk_size, SEEK_CUR );
				}
			} elseif ( $chunk_type == 'tIME' ) {
				// last mod timestamp.
				if ( $chunk_size !== 7 ) {
					throw new Exception( __METHOD__ . ": tIME wrong size" );
				}
				$buf = self::read( $fh, $chunk_size );
				if ( !$buf || strlen( $buf ) < $chunk_size ) {
					throw new Exception( __METHOD__ . ": Read error" );
				}

				// Note: spec says this should be UTC.
				$t = unpack( "ny/Cm/Cd/Ch/Cmin/Cs", $buf );
				$strTime = sprintf( "%04d%02d%02d%02d%02d%02d",
					$t['y'], $t['m'], $t['d'], $t['h'],
					$t['min'], $t['s'] );

				$exifTime = wfTimestamp( TS_EXIF, $strTime );

				if ( $exifTime ) {
					$text['DateTime'] = $exifTime;
				}

			} elseif ( $chunk_type == 'pHYs' ) {
				// how big pixels are (dots per meter).
				if ( $chunk_size !== 9 ) {
					throw new Exception( __METHOD__ . ": pHYs wrong size" );
				}

				$buf = self::read( $fh, $chunk_size );
				if ( !$buf || strlen( $buf ) < $chunk_size ) {
					throw new Exception( __METHOD__ . ": Read error" );
				}

				$dim = unpack( "Nwidth/Nheight/Cunit", $buf );
				if ( $dim['unit'] == 1 ) {
					// Need to check for negative because php
					// doesn't deal with super-large unsigned 32-bit ints well
					if ( $dim['width'] > 0 && $dim['height'] > 0 ) {
						// unit is meters
						// (as opposed to 0 = undefined )
						$text['XResolution'] = $dim['width']
							. '/100';
						$text['YResolution'] = $dim['height']
							. '/100';
						$text['ResolutionUnit'] = 3;
						// 3 = dots per cm (from Exif).
					}
				}

			} elseif ( $chunk_type == "IEND" ) {
				break;
			} else {
				fseek( $fh, $chunk_size, SEEK_CUR );
			}
			fseek( $fh, self::$CRC_size, SEEK_CUR );
		}
		fclose( $fh );

		if ( $loopCount > 1 ) {
			$duration *= $loopCount;
		}

		if ( isset( $text['DateTimeDigitized'] ) ) {
			// Convert date format from rfc2822 to exif.
			foreach ( $text['DateTimeDigitized'] as $name => &$value ) {
				if ( $name === '_type' ) {
					continue;
				}

				// @todo FIXME: Currently timezones are ignored.
				// possibly should be wfTimestamp's
				// responsibility. (at least for numeric TZ)
				$formatted = wfTimestamp( TS_EXIF, $value );
				if ( $formatted ) {
					// Only change if we could convert the
					// date.
					// The png standard says it should be
					// in rfc2822 format, but not required.
					// In general for the exif stuff we
					// prettify the date if we can, but we
					// display as-is if we cannot or if
					// it is invalid.
					// So do the same here.

					$value = $formatted;
				}
			}
		}
		return array(
			'frameCount' => $frameCount,
			'loopCount' => $loopCount,
			'duration' => $duration,
			'text' => $text,
			'bitDepth' => $bitDepth,
			'colorType' => $colorType,
		);

	}
	/**
	 * Read a chunk, checking to make sure its not too big.
	 *
	 * @param $fh resource The file handle
	 * @param $size Integer size in bytes.
	 * @throws Exception if too big.
	 * @return String The chunk.
	 */
	static private function read( $fh, $size ) {
		if ( $size > self::MAX_CHUNK_SIZE ) {
			throw new Exception( __METHOD__ . ': Chunk size of ' . $size .
				' too big. Max size is: ' . self::MAX_CHUNK_SIZE );
		}
		return fread( $fh, $size );
	}
}