1<?php
2
3/////////////////////////////////////////////////////////////////
4/// getID3() by James Heinrich <info@getid3.org>               //
5//  available at https://github.com/JamesHeinrich/getID3       //
6//            or https://www.getid3.org                        //
7//            or http://getid3.sourceforge.net                 //
8//  see readme.txt for more details                            //
9/////////////////////////////////////////////////////////////////
10//                                                             //
11// module.archive.zip.php                                      //
12// module for analyzing pkZip files                            //
13// dependencies: NONE                                          //
14//                                                            ///
15/////////////////////////////////////////////////////////////////
16
17if (!defined('GETID3_INCLUDEPATH')) { // prevent path-exposing attacks that access modules directly on public webservers
18	exit;
19}
20
21class getid3_zip extends getid3_handler
22{
23	/**
24	 * @return bool
25	 */
26	public function Analyze() {
27		$info = &$this->getid3->info;
28
29		$info['fileformat']      = 'zip';
30		$info['zip']['encoding'] = 'ISO-8859-1';
31		$info['zip']['files']    = array();
32
33		$info['zip']['compressed_size']   = 0;
34		$info['zip']['uncompressed_size'] = 0;
35		$info['zip']['entries_count']     = 0;
36
37		if (!getid3_lib::intValueSupported($info['filesize'])) {
38			$this->error('File is larger than '.round(PHP_INT_MAX / 1073741824).'GB, not supported by PHP');
39			return false;
40		} else {
41			$EOCDsearchData    = '';
42			$EOCDsearchCounter = 0;
43			while ($EOCDsearchCounter++ < 512) {
44
45				$this->fseek(-128 * $EOCDsearchCounter, SEEK_END);
46				$EOCDsearchData = $this->fread(128).$EOCDsearchData;
47
48				if (strstr($EOCDsearchData, 'PK'."\x05\x06")) {
49
50					$EOCDposition = strpos($EOCDsearchData, 'PK'."\x05\x06");
51					$this->fseek((-128 * $EOCDsearchCounter) + $EOCDposition, SEEK_END);
52					$info['zip']['end_central_directory'] = $this->ZIPparseEndOfCentralDirectory();
53
54					$this->fseek($info['zip']['end_central_directory']['directory_offset']);
55					$info['zip']['entries_count'] = 0;
56					while ($centraldirectoryentry = $this->ZIPparseCentralDirectory()) {
57						$info['zip']['central_directory'][] = $centraldirectoryentry;
58						$info['zip']['entries_count']++;
59						$info['zip']['compressed_size']   += $centraldirectoryentry['compressed_size'];
60						$info['zip']['uncompressed_size'] += $centraldirectoryentry['uncompressed_size'];
61
62						//if ($centraldirectoryentry['uncompressed_size'] > 0) { zero-byte files are valid
63						if (!empty($centraldirectoryentry['filename'])) {
64							$info['zip']['files'] = getid3_lib::array_merge_clobber($info['zip']['files'], getid3_lib::CreateDeepArray($centraldirectoryentry['filename'], '/', $centraldirectoryentry['uncompressed_size']));
65						}
66					}
67
68					if ($info['zip']['entries_count'] == 0) {
69						$this->error('No Central Directory entries found (truncated file?)');
70						return false;
71					}
72
73					if (!empty($info['zip']['end_central_directory']['comment'])) {
74						$info['zip']['comments']['comment'][] = $info['zip']['end_central_directory']['comment'];
75					}
76
77					if (isset($info['zip']['central_directory'][0]['compression_method'])) {
78						$info['zip']['compression_method'] = $info['zip']['central_directory'][0]['compression_method'];
79					}
80					if (isset($info['zip']['central_directory'][0]['flags']['compression_speed'])) {
81						$info['zip']['compression_speed']  = $info['zip']['central_directory'][0]['flags']['compression_speed'];
82					}
83					if (isset($info['zip']['compression_method']) && ($info['zip']['compression_method'] == 'store') && !isset($info['zip']['compression_speed'])) {
84						$info['zip']['compression_speed']  = 'store';
85					}
86
87					// secondary check - we (should) already have all the info we NEED from the Central Directory above, but scanning each
88					// Local File Header entry will
89					foreach ($info['zip']['central_directory'] as $central_directory_entry) {
90						$this->fseek($central_directory_entry['entry_offset']);
91						if ($fileentry = $this->ZIPparseLocalFileHeader()) {
92							$info['zip']['entries'][] = $fileentry;
93						} else {
94							$this->warning('Error parsing Local File Header at offset '.$central_directory_entry['entry_offset']);
95						}
96					}
97
98					// check for EPUB files
99					if (!empty($info['zip']['entries'][0]['filename']) &&
100						($info['zip']['entries'][0]['filename'] == 'mimetype') &&
101						($info['zip']['entries'][0]['compression_method'] == 'store') &&
102						($info['zip']['entries'][0]['uncompressed_size'] == 20) &&
103						isset($info['zip']['entries'][0]['data_offset'])) {
104							// http://idpf.org/epub/30/spec/epub30-ocf.html
105							// "3.3 OCF ZIP Container Media Type Identification
106							//  OCF ZIP Containers must include a mimetype file as the first file in the Container, and the contents of this file must be the MIME type string application/epub+zip.
107							//  The contents of the mimetype file must not contain any leading padding or whitespace, must not begin with the Unicode signature (or Byte Order Mark),
108							//  and the case of the MIME type string must be exactly as presented above. The mimetype file additionally must be neither compressed nor encrypted,
109							//  and there must not be an extra field in its ZIP header."
110							$this->fseek($info['zip']['entries'][0]['data_offset']);
111							if ($this->fread(20) == 'application/epub+zip') {
112								$info['fileformat'] = 'zip.epub';
113								$info['mime_type'] = 'application/epub+zip';
114							}
115					}
116
117					// check for Office Open XML files (e.g. .docx, .xlsx)
118					if (!empty($info['zip']['files']['[Content_Types].xml']) &&
119					    !empty($info['zip']['files']['_rels']['.rels'])      &&
120					    !empty($info['zip']['files']['docProps']['app.xml']) &&
121					    !empty($info['zip']['files']['docProps']['core.xml'])) {
122							// http://technet.microsoft.com/en-us/library/cc179224.aspx
123							$info['fileformat'] = 'zip.msoffice';
124							if (!empty($ThisFileInfo['zip']['files']['ppt'])) {
125								$info['mime_type'] = 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
126							} elseif (!empty($ThisFileInfo['zip']['files']['xl'])) {
127								$info['mime_type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
128							} elseif (!empty($ThisFileInfo['zip']['files']['word'])) {
129								$info['mime_type'] = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
130							}
131					}
132
133					return true;
134				}
135			}
136		}
137
138		if (!$this->getZIPentriesFilepointer()) {
139			unset($info['zip']);
140			$info['fileformat'] = '';
141			$this->error('Cannot find End Of Central Directory (truncated file?)');
142			return false;
143		}
144
145		// central directory couldn't be found and/or parsed
146		// scan through actual file data entries, recover as much as possible from probable trucated file
147		if ($info['zip']['compressed_size'] > ($info['filesize'] - 46 - 22)) {
148			$this->error('Warning: Truncated file! - Total compressed file sizes ('.$info['zip']['compressed_size'].' bytes) is greater than filesize minus Central Directory and End Of Central Directory structures ('.($info['filesize'] - 46 - 22).' bytes)');
149		}
150		$this->error('Cannot find End Of Central Directory - returned list of files in [zip][entries] array may not be complete');
151		foreach ($info['zip']['entries'] as $key => $valuearray) {
152			$info['zip']['files'][$valuearray['filename']] = $valuearray['uncompressed_size'];
153		}
154		return true;
155	}
156
157	/**
158	 * @return bool
159	 */
160	public function getZIPHeaderFilepointerTopDown() {
161		$info = &$this->getid3->info;
162
163		$info['fileformat'] = 'zip';
164
165		$info['zip']['compressed_size']   = 0;
166		$info['zip']['uncompressed_size'] = 0;
167		$info['zip']['entries_count']     = 0;
168
169		rewind($this->getid3->fp);
170		while ($fileentry = $this->ZIPparseLocalFileHeader()) {
171			$info['zip']['entries'][] = $fileentry;
172			$info['zip']['entries_count']++;
173		}
174		if ($info['zip']['entries_count'] == 0) {
175			$this->error('No Local File Header entries found');
176			return false;
177		}
178
179		$info['zip']['entries_count']     = 0;
180		while ($centraldirectoryentry = $this->ZIPparseCentralDirectory()) {
181			$info['zip']['central_directory'][] = $centraldirectoryentry;
182			$info['zip']['entries_count']++;
183			$info['zip']['compressed_size']   += $centraldirectoryentry['compressed_size'];
184			$info['zip']['uncompressed_size'] += $centraldirectoryentry['uncompressed_size'];
185		}
186		if ($info['zip']['entries_count'] == 0) {
187			$this->error('No Central Directory entries found (truncated file?)');
188			return false;
189		}
190
191		if ($EOCD = $this->ZIPparseEndOfCentralDirectory()) {
192			$info['zip']['end_central_directory'] = $EOCD;
193		} else {
194			$this->error('No End Of Central Directory entry found (truncated file?)');
195			return false;
196		}
197
198		if (!empty($info['zip']['end_central_directory']['comment'])) {
199			$info['zip']['comments']['comment'][] = $info['zip']['end_central_directory']['comment'];
200		}
201
202		return true;
203	}
204
205	/**
206	 * @return bool
207	 */
208	public function getZIPentriesFilepointer() {
209		$info = &$this->getid3->info;
210
211		$info['zip']['compressed_size']   = 0;
212		$info['zip']['uncompressed_size'] = 0;
213		$info['zip']['entries_count']     = 0;
214
215		rewind($this->getid3->fp);
216		while ($fileentry = $this->ZIPparseLocalFileHeader()) {
217			$info['zip']['entries'][] = $fileentry;
218			$info['zip']['entries_count']++;
219			$info['zip']['compressed_size']   += $fileentry['compressed_size'];
220			$info['zip']['uncompressed_size'] += $fileentry['uncompressed_size'];
221		}
222		if ($info['zip']['entries_count'] == 0) {
223			$this->error('No Local File Header entries found');
224			return false;
225		}
226
227		return true;
228	}
229
230	/**
231	 * @return array|false
232	 */
233	public function ZIPparseLocalFileHeader() {
234		$LocalFileHeader['offset'] = $this->ftell();
235
236		$ZIPlocalFileHeader = $this->fread(30);
237
238		$LocalFileHeader['raw']['signature']          = getid3_lib::LittleEndian2Int(substr($ZIPlocalFileHeader,  0, 4));
239		if ($LocalFileHeader['raw']['signature'] != 0x04034B50) { // "PK\x03\x04"
240			// invalid Local File Header Signature
241			$this->fseek($LocalFileHeader['offset']); // seek back to where filepointer originally was so it can be handled properly
242			return false;
243		}
244		$LocalFileHeader['raw']['extract_version']    = getid3_lib::LittleEndian2Int(substr($ZIPlocalFileHeader,  4, 2));
245		$LocalFileHeader['raw']['general_flags']      = getid3_lib::LittleEndian2Int(substr($ZIPlocalFileHeader,  6, 2));
246		$LocalFileHeader['raw']['compression_method'] = getid3_lib::LittleEndian2Int(substr($ZIPlocalFileHeader,  8, 2));
247		$LocalFileHeader['raw']['last_mod_file_time'] = getid3_lib::LittleEndian2Int(substr($ZIPlocalFileHeader, 10, 2));
248		$LocalFileHeader['raw']['last_mod_file_date'] = getid3_lib::LittleEndian2Int(substr($ZIPlocalFileHeader, 12, 2));
249		$LocalFileHeader['raw']['crc_32']             = getid3_lib::LittleEndian2Int(substr($ZIPlocalFileHeader, 14, 4));
250		$LocalFileHeader['raw']['compressed_size']    = getid3_lib::LittleEndian2Int(substr($ZIPlocalFileHeader, 18, 4));
251		$LocalFileHeader['raw']['uncompressed_size']  = getid3_lib::LittleEndian2Int(substr($ZIPlocalFileHeader, 22, 4));
252		$LocalFileHeader['raw']['filename_length']    = getid3_lib::LittleEndian2Int(substr($ZIPlocalFileHeader, 26, 2));
253		$LocalFileHeader['raw']['extra_field_length'] = getid3_lib::LittleEndian2Int(substr($ZIPlocalFileHeader, 28, 2));
254
255		$LocalFileHeader['extract_version']           = sprintf('%1.1f', $LocalFileHeader['raw']['extract_version'] / 10);
256		$LocalFileHeader['host_os']                   = $this->ZIPversionOSLookup(($LocalFileHeader['raw']['extract_version'] & 0xFF00) >> 8);
257		$LocalFileHeader['compression_method']        = $this->ZIPcompressionMethodLookup($LocalFileHeader['raw']['compression_method']);
258		$LocalFileHeader['compressed_size']           = $LocalFileHeader['raw']['compressed_size'];
259		$LocalFileHeader['uncompressed_size']         = $LocalFileHeader['raw']['uncompressed_size'];
260		$LocalFileHeader['flags']                     = $this->ZIPparseGeneralPurposeFlags($LocalFileHeader['raw']['general_flags'], $LocalFileHeader['raw']['compression_method']);
261		$LocalFileHeader['last_modified_timestamp']   = $this->DOStime2UNIXtime($LocalFileHeader['raw']['last_mod_file_date'], $LocalFileHeader['raw']['last_mod_file_time']);
262
263		$FilenameExtrafieldLength = $LocalFileHeader['raw']['filename_length'] + $LocalFileHeader['raw']['extra_field_length'];
264		if ($FilenameExtrafieldLength > 0) {
265			$ZIPlocalFileHeader .= $this->fread($FilenameExtrafieldLength);
266
267			if ($LocalFileHeader['raw']['filename_length'] > 0) {
268				$LocalFileHeader['filename']                = substr($ZIPlocalFileHeader, 30, $LocalFileHeader['raw']['filename_length']);
269			}
270			if ($LocalFileHeader['raw']['extra_field_length'] > 0) {
271				$LocalFileHeader['raw']['extra_field_data'] = substr($ZIPlocalFileHeader, 30 + $LocalFileHeader['raw']['filename_length'], $LocalFileHeader['raw']['extra_field_length']);
272			}
273		}
274
275		if ($LocalFileHeader['compressed_size'] == 0) {
276			// *Could* be a zero-byte file
277			// But could also be a file written on the fly that didn't know compressed filesize beforehand.
278			// Correct compressed filesize should be in the data_descriptor located after this file data, and also in Central Directory (at end of zip file)
279			if (!empty($this->getid3->info['zip']['central_directory'])) {
280				foreach ($this->getid3->info['zip']['central_directory'] as $central_directory_entry) {
281					if ($central_directory_entry['entry_offset'] == $LocalFileHeader['offset']) {
282						if ($central_directory_entry['compressed_size'] > 0) {
283							// overwrite local zero value (but not ['raw']'compressed_size']) so that seeking for data_descriptor (and next file entry) works correctly
284							$LocalFileHeader['compressed_size'] = $central_directory_entry['compressed_size'];
285						}
286						break;
287					}
288				}
289			}
290
291		}
292		$LocalFileHeader['data_offset'] = $this->ftell();
293		$this->fseek($LocalFileHeader['compressed_size'], SEEK_CUR); // this should (but may not) match value in $LocalFileHeader['raw']['compressed_size'] -- $LocalFileHeader['compressed_size'] could have been overwritten above with value from Central Directory
294
295		if ($LocalFileHeader['flags']['data_descriptor_used']) {
296			$DataDescriptor = $this->fread(16);
297			$LocalFileHeader['data_descriptor']['signature']         = getid3_lib::LittleEndian2Int(substr($DataDescriptor,  0, 4));
298			if ($LocalFileHeader['data_descriptor']['signature'] != 0x08074B50) { // "PK\x07\x08"
299				$this->getid3->warning('invalid Local File Header Data Descriptor Signature at offset '.($this->ftell() - 16).' - expecting 08 07 4B 50, found '.getid3_lib::PrintHexBytes($LocalFileHeader['data_descriptor']['signature']));
300				$this->fseek($LocalFileHeader['offset']); // seek back to where filepointer originally was so it can be handled properly
301				return false;
302			}
303			$LocalFileHeader['data_descriptor']['crc_32']            = getid3_lib::LittleEndian2Int(substr($DataDescriptor,  4, 4));
304			$LocalFileHeader['data_descriptor']['compressed_size']   = getid3_lib::LittleEndian2Int(substr($DataDescriptor,  8, 4));
305			$LocalFileHeader['data_descriptor']['uncompressed_size'] = getid3_lib::LittleEndian2Int(substr($DataDescriptor, 12, 4));
306			if (!$LocalFileHeader['raw']['compressed_size'] && $LocalFileHeader['data_descriptor']['compressed_size']) {
307				foreach ($this->getid3->info['zip']['central_directory'] as $central_directory_entry) {
308					if ($central_directory_entry['entry_offset'] == $LocalFileHeader['offset']) {
309						if ($LocalFileHeader['data_descriptor']['compressed_size'] == $central_directory_entry['compressed_size']) {
310							// $LocalFileHeader['compressed_size'] already set from Central Directory
311						} else {
312							$this->warning('conflicting compressed_size from data_descriptor ('.$LocalFileHeader['data_descriptor']['compressed_size'].') vs Central Directory ('.$central_directory_entry['compressed_size'].') for file at offset '.$LocalFileHeader['offset']);
313						}
314
315						if ($LocalFileHeader['data_descriptor']['uncompressed_size'] == $central_directory_entry['uncompressed_size']) {
316							$LocalFileHeader['uncompressed_size'] = $LocalFileHeader['data_descriptor']['uncompressed_size'];
317						} else {
318							$this->warning('conflicting uncompressed_size from data_descriptor ('.$LocalFileHeader['data_descriptor']['uncompressed_size'].') vs Central Directory ('.$central_directory_entry['uncompressed_size'].') for file at offset '.$LocalFileHeader['offset']);
319						}
320						break;
321					}
322				}
323			}
324		}
325		return $LocalFileHeader;
326	}
327
328	/**
329	 * @return array|false
330	 */
331	public function ZIPparseCentralDirectory() {
332		$CentralDirectory['offset'] = $this->ftell();
333
334		$ZIPcentralDirectory = $this->fread(46);
335
336		$CentralDirectory['raw']['signature']            = getid3_lib::LittleEndian2Int(substr($ZIPcentralDirectory,  0, 4));
337		if ($CentralDirectory['raw']['signature'] != 0x02014B50) {
338			// invalid Central Directory Signature
339			$this->fseek($CentralDirectory['offset']); // seek back to where filepointer originally was so it can be handled properly
340			return false;
341		}
342		$CentralDirectory['raw']['create_version']       = getid3_lib::LittleEndian2Int(substr($ZIPcentralDirectory,  4, 2));
343		$CentralDirectory['raw']['extract_version']      = getid3_lib::LittleEndian2Int(substr($ZIPcentralDirectory,  6, 2));
344		$CentralDirectory['raw']['general_flags']        = getid3_lib::LittleEndian2Int(substr($ZIPcentralDirectory,  8, 2));
345		$CentralDirectory['raw']['compression_method']   = getid3_lib::LittleEndian2Int(substr($ZIPcentralDirectory, 10, 2));
346		$CentralDirectory['raw']['last_mod_file_time']   = getid3_lib::LittleEndian2Int(substr($ZIPcentralDirectory, 12, 2));
347		$CentralDirectory['raw']['last_mod_file_date']   = getid3_lib::LittleEndian2Int(substr($ZIPcentralDirectory, 14, 2));
348		$CentralDirectory['raw']['crc_32']               = getid3_lib::LittleEndian2Int(substr($ZIPcentralDirectory, 16, 4));
349		$CentralDirectory['raw']['compressed_size']      = getid3_lib::LittleEndian2Int(substr($ZIPcentralDirectory, 20, 4));
350		$CentralDirectory['raw']['uncompressed_size']    = getid3_lib::LittleEndian2Int(substr($ZIPcentralDirectory, 24, 4));
351		$CentralDirectory['raw']['filename_length']      = getid3_lib::LittleEndian2Int(substr($ZIPcentralDirectory, 28, 2));
352		$CentralDirectory['raw']['extra_field_length']   = getid3_lib::LittleEndian2Int(substr($ZIPcentralDirectory, 30, 2));
353		$CentralDirectory['raw']['file_comment_length']  = getid3_lib::LittleEndian2Int(substr($ZIPcentralDirectory, 32, 2));
354		$CentralDirectory['raw']['disk_number_start']    = getid3_lib::LittleEndian2Int(substr($ZIPcentralDirectory, 34, 2));
355		$CentralDirectory['raw']['internal_file_attrib'] = getid3_lib::LittleEndian2Int(substr($ZIPcentralDirectory, 36, 2));
356		$CentralDirectory['raw']['external_file_attrib'] = getid3_lib::LittleEndian2Int(substr($ZIPcentralDirectory, 38, 4));
357		$CentralDirectory['raw']['local_header_offset']  = getid3_lib::LittleEndian2Int(substr($ZIPcentralDirectory, 42, 4));
358
359		$CentralDirectory['entry_offset']              = $CentralDirectory['raw']['local_header_offset'];
360		$CentralDirectory['create_version']            = sprintf('%1.1f', $CentralDirectory['raw']['create_version'] / 10);
361		$CentralDirectory['extract_version']           = sprintf('%1.1f', $CentralDirectory['raw']['extract_version'] / 10);
362		$CentralDirectory['host_os']                   = $this->ZIPversionOSLookup(($CentralDirectory['raw']['extract_version'] & 0xFF00) >> 8);
363		$CentralDirectory['compression_method']        = $this->ZIPcompressionMethodLookup($CentralDirectory['raw']['compression_method']);
364		$CentralDirectory['compressed_size']           = $CentralDirectory['raw']['compressed_size'];
365		$CentralDirectory['uncompressed_size']         = $CentralDirectory['raw']['uncompressed_size'];
366		$CentralDirectory['flags']                     = $this->ZIPparseGeneralPurposeFlags($CentralDirectory['raw']['general_flags'], $CentralDirectory['raw']['compression_method']);
367		$CentralDirectory['last_modified_timestamp']   = $this->DOStime2UNIXtime($CentralDirectory['raw']['last_mod_file_date'], $CentralDirectory['raw']['last_mod_file_time']);
368
369		$FilenameExtrafieldCommentLength = $CentralDirectory['raw']['filename_length'] + $CentralDirectory['raw']['extra_field_length'] + $CentralDirectory['raw']['file_comment_length'];
370		if ($FilenameExtrafieldCommentLength > 0) {
371			$FilenameExtrafieldComment = $this->fread($FilenameExtrafieldCommentLength);
372
373			if ($CentralDirectory['raw']['filename_length'] > 0) {
374				$CentralDirectory['filename']                  = substr($FilenameExtrafieldComment, 0, $CentralDirectory['raw']['filename_length']);
375			}
376			if ($CentralDirectory['raw']['extra_field_length'] > 0) {
377				$CentralDirectory['raw']['extra_field_data']   = substr($FilenameExtrafieldComment, $CentralDirectory['raw']['filename_length'], $CentralDirectory['raw']['extra_field_length']);
378			}
379			if ($CentralDirectory['raw']['file_comment_length'] > 0) {
380				$CentralDirectory['file_comment']              = substr($FilenameExtrafieldComment, $CentralDirectory['raw']['filename_length'] + $CentralDirectory['raw']['extra_field_length'], $CentralDirectory['raw']['file_comment_length']);
381			}
382		}
383
384		return $CentralDirectory;
385	}
386
387	/**
388	 * @return array|false
389	 */
390	public function ZIPparseEndOfCentralDirectory() {
391		$EndOfCentralDirectory['offset'] = $this->ftell();
392
393		$ZIPendOfCentralDirectory = $this->fread(22);
394
395		$EndOfCentralDirectory['signature']                   = getid3_lib::LittleEndian2Int(substr($ZIPendOfCentralDirectory,  0, 4));
396		if ($EndOfCentralDirectory['signature'] != 0x06054B50) {
397			// invalid End Of Central Directory Signature
398			$this->fseek($EndOfCentralDirectory['offset']); // seek back to where filepointer originally was so it can be handled properly
399			return false;
400		}
401		$EndOfCentralDirectory['disk_number_current']         = getid3_lib::LittleEndian2Int(substr($ZIPendOfCentralDirectory,  4, 2));
402		$EndOfCentralDirectory['disk_number_start_directory'] = getid3_lib::LittleEndian2Int(substr($ZIPendOfCentralDirectory,  6, 2));
403		$EndOfCentralDirectory['directory_entries_this_disk'] = getid3_lib::LittleEndian2Int(substr($ZIPendOfCentralDirectory,  8, 2));
404		$EndOfCentralDirectory['directory_entries_total']     = getid3_lib::LittleEndian2Int(substr($ZIPendOfCentralDirectory, 10, 2));
405		$EndOfCentralDirectory['directory_size']              = getid3_lib::LittleEndian2Int(substr($ZIPendOfCentralDirectory, 12, 4));
406		$EndOfCentralDirectory['directory_offset']            = getid3_lib::LittleEndian2Int(substr($ZIPendOfCentralDirectory, 16, 4));
407		$EndOfCentralDirectory['comment_length']              = getid3_lib::LittleEndian2Int(substr($ZIPendOfCentralDirectory, 20, 2));
408
409		if ($EndOfCentralDirectory['comment_length'] > 0) {
410			$EndOfCentralDirectory['comment']                 = $this->fread($EndOfCentralDirectory['comment_length']);
411		}
412
413		return $EndOfCentralDirectory;
414	}
415
416	/**
417	 * @param int $flagbytes
418	 * @param int $compressionmethod
419	 *
420	 * @return array
421	 */
422	public static function ZIPparseGeneralPurposeFlags($flagbytes, $compressionmethod) {
423		// https://users.cs.jmu.edu/buchhofp/forensics/formats/pkzip-printable.html
424		$ParsedFlags = array();
425		$ParsedFlags['encrypted']               = (bool) ($flagbytes & 0x0001);
426		//                                                             0x0002 -- see below
427		//                                                             0x0004 -- see below
428		$ParsedFlags['data_descriptor_used']    = (bool) ($flagbytes & 0x0008);
429		$ParsedFlags['enhanced_deflation']      = (bool) ($flagbytes & 0x0010);
430		$ParsedFlags['compressed_patched_data'] = (bool) ($flagbytes & 0x0020);
431		$ParsedFlags['strong_encryption']       = (bool) ($flagbytes & 0x0040);
432		//                                                             0x0080 - unused
433		//                                                             0x0100 - unused
434		//                                                             0x0200 - unused
435		//                                                             0x0400 - unused
436		$ParsedFlags['language_encoding']       = (bool) ($flagbytes & 0x0800);
437		//                                                             0x1000 - reserved
438		$ParsedFlags['mask_header_values']      = (bool) ($flagbytes & 0x2000);
439		//                                                             0x4000 - reserved
440		//                                                             0x8000 - reserved
441
442		switch ($compressionmethod) {
443			case 6:
444				$ParsedFlags['dictionary_size']    = (($flagbytes & 0x0002) ? 8192 : 4096);
445				$ParsedFlags['shannon_fano_trees'] = (($flagbytes & 0x0004) ? 3    : 2);
446				break;
447
448			case 8:
449			case 9:
450				switch (($flagbytes & 0x0006) >> 1) {
451					case 0:
452						$ParsedFlags['compression_speed'] = 'normal';
453						break;
454					case 1:
455						$ParsedFlags['compression_speed'] = 'maximum';
456						break;
457					case 2:
458						$ParsedFlags['compression_speed'] = 'fast';
459						break;
460					case 3:
461						$ParsedFlags['compression_speed'] = 'superfast';
462						break;
463				}
464				break;
465		}
466
467		return $ParsedFlags;
468	}
469
470	/**
471	 * @param int $index
472	 *
473	 * @return string
474	 */
475	public static function ZIPversionOSLookup($index) {
476		static $ZIPversionOSLookup = array(
477			0  => 'MS-DOS and OS/2 (FAT / VFAT / FAT32 file systems)',
478			1  => 'Amiga',
479			2  => 'OpenVMS',
480			3  => 'Unix',
481			4  => 'VM/CMS',
482			5  => 'Atari ST',
483			6  => 'OS/2 H.P.F.S.',
484			7  => 'Macintosh',
485			8  => 'Z-System',
486			9  => 'CP/M',
487			10 => 'Windows NTFS',
488			11 => 'MVS',
489			12 => 'VSE',
490			13 => 'Acorn Risc',
491			14 => 'VFAT',
492			15 => 'Alternate MVS',
493			16 => 'BeOS',
494			17 => 'Tandem',
495			18 => 'OS/400',
496			19 => 'OS/X (Darwin)',
497		);
498
499		return (isset($ZIPversionOSLookup[$index]) ? $ZIPversionOSLookup[$index] : '[unknown]');
500	}
501
502	/**
503	 * @param int $index
504	 *
505	 * @return string
506	 */
507	public static function ZIPcompressionMethodLookup($index) {
508		// http://www.sno.phy.queensu.ca/~phil/exiftool/TagNames/ZIP.html
509		static $ZIPcompressionMethodLookup = array(
510			0  => 'store',
511			1  => 'shrink',
512			2  => 'reduce-1',
513			3  => 'reduce-2',
514			4  => 'reduce-3',
515			5  => 'reduce-4',
516			6  => 'implode',
517			7  => 'tokenize',
518			8  => 'deflate',
519			9  => 'deflate64',
520			10 => 'Imploded (old IBM TERSE)',
521			11 => 'RESERVED[11]',
522			12 => 'BZIP2',
523			13 => 'RESERVED[13]',
524			14 => 'LZMA (EFS)',
525			15 => 'RESERVED[15]',
526			16 => 'RESERVED[16]',
527			17 => 'RESERVED[17]',
528			18 => 'IBM TERSE (new)',
529			19 => 'IBM LZ77 z Architecture (PFS)',
530			96 => 'JPEG recompressed',
531			97 => 'WavPack compressed',
532			98 => 'PPMd version I, Rev 1',
533		);
534
535		return (isset($ZIPcompressionMethodLookup[$index]) ? $ZIPcompressionMethodLookup[$index] : '[unknown]');
536	}
537
538	/**
539	 * @param int $DOSdate
540	 * @param int $DOStime
541	 *
542	 * @return int
543	 */
544	public static function DOStime2UNIXtime($DOSdate, $DOStime) {
545		// wFatDate
546		// Specifies the MS-DOS date. The date is a packed 16-bit value with the following format:
547		// Bits      Contents
548		// 0-4    Day of the month (1-31)
549		// 5-8    Month (1 = January, 2 = February, and so on)
550		// 9-15   Year offset from 1980 (add 1980 to get actual year)
551
552		$UNIXday    =  ($DOSdate & 0x001F);
553		$UNIXmonth  = (($DOSdate & 0x01E0) >> 5);
554		$UNIXyear   = (($DOSdate & 0xFE00) >> 9) + 1980;
555
556		// wFatTime
557		// Specifies the MS-DOS time. The time is a packed 16-bit value with the following format:
558		// Bits   Contents
559		// 0-4    Second divided by 2
560		// 5-10   Minute (0-59)
561		// 11-15  Hour (0-23 on a 24-hour clock)
562
563		$UNIXsecond =  ($DOStime & 0x001F) * 2;
564		$UNIXminute = (($DOStime & 0x07E0) >> 5);
565		$UNIXhour   = (($DOStime & 0xF800) >> 11);
566
567		return gmmktime($UNIXhour, $UNIXminute, $UNIXsecond, $UNIXmonth, $UNIXday, $UNIXyear);
568	}
569
570}
571