Merge branch 'MDL-43332_m26' of https://github.com/markn86/moodle into MOODLE_26_STABLE
[moodle.git] / lib / filestorage / zip_archive.php
blob8a995a1cd05ac68867e45b51cad27f8d20ad124b
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Implementation of zip file archive.
20 * @package core_files
21 * @copyright 2008 Petr Skoda (http://skodak.org)
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 defined('MOODLE_INTERNAL') || die();
27 require_once("$CFG->libdir/filestorage/file_archive.php");
29 /**
30 * Zip file archive class.
32 * @package core_files
33 * @category files
34 * @copyright 2008 Petr Skoda (http://skodak.org)
35 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
37 class zip_archive extends file_archive {
39 /** @var string Pathname of archive */
40 protected $archivepathname = null;
42 /** @var int archive open mode */
43 protected $mode = null;
45 /** @var int Used memory tracking */
46 protected $usedmem = 0;
48 /** @var int Iteration position */
49 protected $pos = 0;
51 /** @var ZipArchive instance */
52 protected $za;
54 /** @var bool was this archive modified? */
55 protected $modified = false;
57 /** @var array unicode decoding array, created by decoding zip file */
58 protected $namelookup = null;
60 /** @var string base64 encoded contents of empty zip file */
61 protected static $emptyzipcontent = 'UEsFBgAAAAAAAAAAAAAAAAAAAAAAAA==';
63 /** @var bool ugly hack for broken empty zip handling in < PHP 5.3.10 */
64 protected $emptyziphack = false;
66 /**
67 * Create new zip_archive instance.
69 public function __construct() {
70 $this->encoding = null; // Autodetects encoding by default.
73 /**
74 * Open or create archive (depending on $mode).
76 * @todo MDL-31048 return error message
77 * @param string $archivepathname
78 * @param int $mode OPEN, CREATE or OVERWRITE constant
79 * @param string $encoding archive local paths encoding, empty means autodetect
80 * @return bool success
82 public function open($archivepathname, $mode=file_archive::CREATE, $encoding=null) {
83 $this->close();
85 $this->usedmem = 0;
86 $this->pos = 0;
87 $this->encoding = $encoding;
88 $this->mode = $mode;
90 $this->za = new ZipArchive();
92 switch($mode) {
93 case file_archive::OPEN: $flags = 0; break;
94 case file_archive::OVERWRITE: $flags = ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE; break; //changed in PHP 5.2.8
95 case file_archive::CREATE:
96 default : $flags = ZIPARCHIVE::CREATE; break;
99 $result = $this->za->open($archivepathname, $flags);
101 if ($flags == 0 and $result === ZIPARCHIVE::ER_NOZIP and filesize($archivepathname) === 22) {
102 // Legacy PHP versions < 5.3.10 can not deal with empty zip archives.
103 if (file_get_contents($archivepathname) === base64_decode(self::$emptyzipcontent)) {
104 if ($temp = make_temp_directory('zip')) {
105 $this->emptyziphack = tempnam($temp, 'zip');
106 $this->za = new ZipArchive();
107 $result = $this->za->open($this->emptyziphack, ZIPARCHIVE::CREATE);
112 if ($result === true) {
113 if (file_exists($archivepathname)) {
114 $this->archivepathname = realpath($archivepathname);
115 } else {
116 $this->archivepathname = $archivepathname;
118 return true;
120 } else {
121 $message = 'Unknown error.';
122 switch ($result) {
123 case ZIPARCHIVE::ER_EXISTS: $message = 'File already exists.'; break;
124 case ZIPARCHIVE::ER_INCONS: $message = 'Zip archive inconsistent.'; break;
125 case ZIPARCHIVE::ER_INVAL: $message = 'Invalid argument.'; break;
126 case ZIPARCHIVE::ER_MEMORY: $message = 'Malloc failure.'; break;
127 case ZIPARCHIVE::ER_NOENT: $message = 'No such file.'; break;
128 case ZIPARCHIVE::ER_NOZIP: $message = 'Not a zip archive.'; break;
129 case ZIPARCHIVE::ER_OPEN: $message = 'Can\'t open file.'; break;
130 case ZIPARCHIVE::ER_READ: $message = 'Read error.'; break;
131 case ZIPARCHIVE::ER_SEEK: $message = 'Seek error.'; break;
133 debugging($message.': '.$archivepathname, DEBUG_DEVELOPER);
134 $this->za = null;
135 $this->archivepathname = null;
136 return false;
141 * Normalize $localname, always keep in utf-8 encoding.
143 * @param string $localname name of file in utf-8 encoding
144 * @return string normalised compressed file or directory name
146 protected function mangle_pathname($localname) {
147 $result = str_replace('\\', '/', $localname); // no MS \ separators
148 $result = preg_replace('/\.\.+/', '', $result); // prevent /.../
149 $result = ltrim($result, '/'); // no leading slash
151 if ($result === '.') {
152 $result = '';
155 return $result;
159 * Tries to convert $localname into utf-8
160 * please note that it may fail really badly.
161 * The resulting file name is cleaned.
163 * @param string $localname name (encoding is read from zip file or guessed)
164 * @return string in utf-8
166 protected function unmangle_pathname($localname) {
167 $this->init_namelookup();
169 if (!isset($this->namelookup[$localname])) {
170 $name = $localname;
171 // This should not happen.
172 if (!empty($this->encoding) and $this->encoding !== 'utf-8') {
173 $name = @core_text::convert($name, $this->encoding, 'utf-8');
175 $name = str_replace('\\', '/', $name); // no MS \ separators
176 $name = clean_param($name, PARAM_PATH); // only safe chars
177 return ltrim($name, '/'); // no leading slash
180 return $this->namelookup[$localname];
184 * Close archive, write changes to disk.
186 * @return bool success
188 public function close() {
189 if (!isset($this->za)) {
190 return false;
193 if ($this->emptyziphack) {
194 $this->za->close();
195 $this->za = null;
196 $this->mode = null;
197 $this->namelookup = null;
198 $this->modified = false;
199 @unlink($this->emptyziphack);
200 $this->emptyziphack = false;
201 return true;
203 } else if ($this->za->numFiles == 0) {
204 // PHP can not create empty archives, so let's fake it.
205 $this->za->close();
206 $this->za = null;
207 $this->mode = null;
208 $this->namelookup = null;
209 $this->modified = false;
210 @unlink($this->archivepathname);
211 $data = base64_decode(self::$emptyzipcontent);
212 if (!file_put_contents($this->archivepathname, $data)) {
213 return false;
215 return true;
218 $res = $this->za->close();
219 $this->za = null;
220 $this->mode = null;
221 $this->namelookup = null;
223 if ($this->modified) {
224 $this->fix_utf8_flags();
225 $this->modified = false;
228 return $res;
232 * Returns file stream for reading of content.
234 * @param int $index index of file
235 * @return resource|bool file handle or false if error
237 public function get_stream($index) {
238 if (!isset($this->za)) {
239 return false;
242 $name = $this->za->getNameIndex($index);
243 if ($name === false) {
244 return false;
247 return $this->za->getStream($name);
251 * Returns file information.
253 * @param int $index index of file
254 * @return stdClass|bool info object or false if error
256 public function get_info($index) {
257 if (!isset($this->za)) {
258 return false;
261 // Need to use the ZipArchive's numfiles, as $this->count() relies on this function to count actual files (skipping OSX junk).
262 if ($index < 0 or $index >=$this->za->numFiles) {
263 return false;
266 $result = $this->za->statIndex($index);
268 if ($result === false) {
269 return false;
272 $info = new stdClass();
273 $info->index = $index;
274 $info->original_pathname = $result['name'];
275 $info->pathname = $this->unmangle_pathname($result['name']);
276 $info->mtime = (int)$result['mtime'];
278 if ($info->pathname[strlen($info->pathname)-1] === '/') {
279 $info->is_directory = true;
280 $info->size = 0;
281 } else {
282 $info->is_directory = false;
283 $info->size = (int)$result['size'];
286 if ($this->is_system_file($info)) {
287 // Don't return system files.
288 return false;
291 return $info;
295 * Returns array of info about all files in archive.
297 * @return array of file infos
299 public function list_files() {
300 if (!isset($this->za)) {
301 return false;
304 $infos = array();
306 foreach ($this as $info) {
307 // Simply iterating over $this will give us info only for files we're interested in.
308 array_push($infos, $info);
311 return $infos;
314 public function is_system_file($fileinfo) {
315 if (substr($fileinfo->pathname, 0, 8) === '__MACOSX' or substr($fileinfo->pathname, -9) === '.DS_Store') {
316 // Mac OSX system files.
317 return true;
319 if (substr($fileinfo->pathname, -9) === 'Thumbs.db') {
320 $stream = $this->za->getStream($fileinfo->pathname);
321 $info = base64_encode(fread($stream, 8));
322 fclose($stream);
323 if ($info === '0M8R4KGxGuE=') {
324 // It's an OLE Compound File - so it's almost certainly a Windows thumbnail cache.
325 return true;
328 return false;
332 * Returns number of files in archive.
334 * @return int number of files
336 public function count() {
337 if (!isset($this->za)) {
338 return false;
341 return count($this->list_files());
345 * Returns approximate number of files in archive. This may be a slight
346 * overestimate.
348 * @return int|bool Estimated number of files, or false if not opened
350 public function estimated_count() {
351 if (!isset($this->za)) {
352 return false;
355 return $this->za->numFiles;
359 * Add file into archive.
361 * @param string $localname name of file in archive
362 * @param string $pathname location of file
363 * @return bool success
365 public function add_file_from_pathname($localname, $pathname) {
366 if ($this->emptyziphack) {
367 $this->close();
368 $this->open($this->archivepathname, file_archive::OVERWRITE, $this->encoding);
371 if (!isset($this->za)) {
372 return false;
375 if ($this->archivepathname === realpath($pathname)) {
376 // Do not add self into archive.
377 return false;
380 if (!is_readable($pathname) or is_dir($pathname)) {
381 return false;
384 if (is_null($localname)) {
385 $localname = clean_param($pathname, PARAM_PATH);
387 $localname = trim($localname, '/'); // No leading slashes in archives!
388 $localname = $this->mangle_pathname($localname);
390 if ($localname === '') {
391 // Sorry - conversion failed badly.
392 return false;
395 if (!$this->za->addFile($pathname, $localname)) {
396 return false;
398 $this->modified = true;
399 return true;
403 * Add content of string into archive.
405 * @param string $localname name of file in archive
406 * @param string $contents contents
407 * @return bool success
409 public function add_file_from_string($localname, $contents) {
410 if ($this->emptyziphack) {
411 $this->close();
412 $this->open($this->archivepathname, file_archive::OVERWRITE, $this->encoding);
415 if (!isset($this->za)) {
416 return false;
419 $localname = trim($localname, '/'); // No leading slashes in archives!
420 $localname = $this->mangle_pathname($localname);
422 if ($localname === '') {
423 // Sorry - conversion failed badly.
424 return false;
427 if ($this->usedmem > 2097151) {
428 // This prevents running out of memory when adding many large files using strings.
429 $this->close();
430 $res = $this->open($this->archivepathname, file_archive::OPEN, $this->encoding);
431 if ($res !== true) {
432 print_error('cannotopenzip');
435 $this->usedmem += strlen($contents);
437 if (!$this->za->addFromString($localname, $contents)) {
438 return false;
440 $this->modified = true;
441 return true;
445 * Add empty directory into archive.
447 * @param string $localname name of file in archive
448 * @return bool success
450 public function add_directory($localname) {
451 if ($this->emptyziphack) {
452 $this->close();
453 $this->open($this->archivepathname, file_archive::OVERWRITE, $this->encoding);
456 if (!isset($this->za)) {
457 return false;
459 $localname = trim($localname, '/'). '/';
460 $localname = $this->mangle_pathname($localname);
462 if ($localname === '/') {
463 // Sorry - conversion failed badly.
464 return false;
467 if ($localname !== '') {
468 if (!$this->za->addEmptyDir($localname)) {
469 return false;
471 $this->modified = true;
473 return true;
477 * Returns current file info.
479 * @return stdClass
481 public function current() {
482 if (!isset($this->za)) {
483 return false;
486 return $this->get_info($this->pos);
490 * Returns the index of current file.
492 * @return int current file index
494 public function key() {
495 return $this->pos;
499 * Moves forward to next file.
501 public function next() {
502 $this->pos++;
506 * Rewinds back to the first file.
508 public function rewind() {
509 $this->pos = 0;
513 * Did we reach the end?
515 * @return bool
517 public function valid() {
518 if (!isset($this->za)) {
519 return false;
522 // Skip over unwanted system files (get_info will return false).
523 while (!$this->get_info($this->pos) && $this->pos < $this->za->numFiles) {
524 $this->next();
527 // No files left - we're at the end.
528 if ($this->pos >= $this->za->numFiles) {
529 return false;
532 return true;
536 * Create a map of file names used in zip archive.
537 * @return void
539 protected function init_namelookup() {
540 if ($this->emptyziphack) {
541 $this->namelookup = array();
542 return;
545 if (!isset($this->za)) {
546 return;
548 if (isset($this->namelookup)) {
549 return;
552 $this->namelookup = array();
554 if ($this->mode != file_archive::OPEN) {
555 // No need to tweak existing names when creating zip file because there are none yet!
556 return;
559 if (!file_exists($this->archivepathname)) {
560 return;
563 if (!$fp = fopen($this->archivepathname, 'rb')) {
564 return;
566 if (!$filesize = filesize($this->archivepathname)) {
567 return;
570 $centralend = self::zip_get_central_end($fp, $filesize);
572 if ($centralend === false or $centralend['disk'] !== 0 or $centralend['disk_start'] !== 0 or $centralend['offset'] === 0xFFFFFFFF) {
573 // Single disk archives only and o support for ZIP64, sorry.
574 fclose($fp);
575 return;
578 fseek($fp, $centralend['offset']);
579 $data = fread($fp, $centralend['size']);
580 $pos = 0;
581 $files = array();
582 for($i=0; $i<$centralend['entries']; $i++) {
583 $file = self::zip_parse_file_header($data, $centralend, $pos);
584 if ($file === false) {
585 // Wrong header, sorry.
586 fclose($fp);
587 return;
589 $files[] = $file;
591 fclose($fp);
593 foreach ($files as $file) {
594 $name = $file['name'];
595 if (preg_match('/^[a-zA-Z0-9_\-\.]*$/', $file['name'])) {
596 // No need to fix ASCII.
597 $name = fix_utf8($name);
599 } else if (!($file['general'] & pow(2, 11))) {
600 // First look for unicode name alternatives.
601 $found = false;
602 foreach($file['extra'] as $extra) {
603 if ($extra['id'] === 0x7075) {
604 $data = unpack('cversion/Vcrc', substr($extra['data'], 0, 5));
605 if ($data['crc'] === crc32($name)) {
606 $found = true;
607 $name = substr($extra['data'], 5);
611 if (!$found and !empty($this->encoding) and $this->encoding !== 'utf-8') {
612 // Try the encoding from open().
613 $newname = @core_text::convert($name, $this->encoding, 'utf-8');
614 $original = core_text::convert($newname, 'utf-8', $this->encoding);
615 if ($original === $name) {
616 $found = true;
617 $name = $newname;
620 if (!$found and $file['version'] === 0x315) {
621 // This looks like OS X build in zipper.
622 $newname = fix_utf8($name);
623 if ($newname === $name) {
624 $found = true;
625 $name = $newname;
628 if (!$found and $file['version'] === 0) {
629 // This looks like our old borked Moodle 2.2 file.
630 $newname = fix_utf8($name);
631 if ($newname === $name) {
632 $found = true;
633 $name = $newname;
636 if (!$found and $encoding = get_string('oldcharset', 'langconfig')) {
637 // Last attempt - try the dos/unix encoding from current language.
638 $windows = true;
639 foreach($file['extra'] as $extra) {
640 // In Windows archivers do not usually set any extras with the exception of NTFS flag in WinZip/WinRar.
641 $windows = false;
642 if ($extra['id'] === 0x000a) {
643 $windows = true;
644 break;
648 if ($windows === true) {
649 switch(strtoupper($encoding)) {
650 case 'ISO-8859-1': $encoding = 'CP850'; break;
651 case 'ISO-8859-2': $encoding = 'CP852'; break;
652 case 'ISO-8859-4': $encoding = 'CP775'; break;
653 case 'ISO-8859-5': $encoding = 'CP866'; break;
654 case 'ISO-8859-6': $encoding = 'CP720'; break;
655 case 'ISO-8859-7': $encoding = 'CP737'; break;
656 case 'ISO-8859-8': $encoding = 'CP862'; break;
657 case 'UTF-8':
658 if ($winchar = get_string('localewincharset', 'langconfig')) {
659 // Most probably works only for zh_cn,
660 // if there are more problems we could add zipcharset to langconfig files.
661 $encoding = $winchar;
663 break;
666 $newname = @core_text::convert($name, $encoding, 'utf-8');
667 $original = core_text::convert($newname, 'utf-8', $encoding);
669 if ($original === $name) {
670 $name = $newname;
674 $name = str_replace('\\', '/', $name); // no MS \ separators
675 $name = clean_param($name, PARAM_PATH); // only safe chars
676 $name = ltrim($name, '/'); // no leading slash
678 if (function_exists('normalizer_normalize')) {
679 $name = normalizer_normalize($name, Normalizer::FORM_C);
682 $this->namelookup[$file['name']] = $name;
687 * Add unicode flag to all files in archive.
689 * NOTE: single disk archives only, no ZIP64 support.
691 * @return bool success, modifies the file contents
693 protected function fix_utf8_flags() {
694 if ($this->emptyziphack) {
695 return true;
698 if (!file_exists($this->archivepathname)) {
699 return true;
702 // Note: the ZIP structure is described at http://www.pkware.com/documents/casestudies/APPNOTE.TXT
703 if (!$fp = fopen($this->archivepathname, 'rb+')) {
704 return false;
706 if (!$filesize = filesize($this->archivepathname)) {
707 return false;
710 $centralend = self::zip_get_central_end($fp, $filesize);
712 if ($centralend === false or $centralend['disk'] !== 0 or $centralend['disk_start'] !== 0 or $centralend['offset'] === 0xFFFFFFFF) {
713 // Single disk archives only and o support for ZIP64, sorry.
714 fclose($fp);
715 return false;
718 fseek($fp, $centralend['offset']);
719 $data = fread($fp, $centralend['size']);
720 $pos = 0;
721 $files = array();
722 for($i=0; $i<$centralend['entries']; $i++) {
723 $file = self::zip_parse_file_header($data, $centralend, $pos);
724 if ($file === false) {
725 // Wrong header, sorry.
726 fclose($fp);
727 return false;
730 $newgeneral = $file['general'] | pow(2, 11);
731 if ($newgeneral === $file['general']) {
732 // Nothing to do with this file.
733 continue;
736 if (preg_match('/^[a-zA-Z0-9_\-\.]*$/', $file['name'])) {
737 // ASCII file names are always ok.
738 continue;
740 if ($file['extra']) {
741 // Most probably not created by php zip ext, better to skip it.
742 continue;
744 if (fix_utf8($file['name']) !== $file['name']) {
745 // Does not look like a valid utf-8 encoded file name, skip it.
746 continue;
749 // Read local file header.
750 fseek($fp, $file['local_offset']);
751 $localfile = unpack('Vsig/vversion_req/vgeneral/vmethod/vmtime/vmdate/Vcrc/Vsize_compressed/Vsize/vname_length/vextra_length', fread($fp, 30));
752 if ($localfile['sig'] !== 0x04034b50) {
753 // Borked file!
754 fclose($fp);
755 return false;
758 $file['local'] = $localfile;
759 $files[] = $file;
762 foreach ($files as $file) {
763 $localfile = $file['local'];
764 // Add the unicode flag in central file header.
765 fseek($fp, $file['central_offset'] + 8);
766 if (ftell($fp) === $file['central_offset'] + 8) {
767 $newgeneral = $file['general'] | pow(2, 11);
768 fwrite($fp, pack('v', $newgeneral));
770 // Modify local file header too.
771 fseek($fp, $file['local_offset'] + 6);
772 if (ftell($fp) === $file['local_offset'] + 6) {
773 $newgeneral = $localfile['general'] | pow(2, 11);
774 fwrite($fp, pack('v', $newgeneral));
778 fclose($fp);
779 return true;
783 * Read end of central signature of ZIP file.
784 * @internal
785 * @static
786 * @param resource $fp
787 * @param int $filesize
788 * @return array|bool
790 public static function zip_get_central_end($fp, $filesize) {
791 // Find end of central directory record.
792 fseek($fp, $filesize - 22);
793 $info = unpack('Vsig', fread($fp, 4));
794 if ($info['sig'] === 0x06054b50) {
795 // There is no comment.
796 fseek($fp, $filesize - 22);
797 $data = fread($fp, 22);
798 } else {
799 // There is some comment with 0xFF max size - that is 65557.
800 fseek($fp, $filesize - 65557);
801 $data = fread($fp, 65557);
804 $pos = strpos($data, pack('V', 0x06054b50));
805 if ($pos === false) {
806 // Borked ZIP structure!
807 return false;
809 $centralend = unpack('Vsig/vdisk/vdisk_start/vdisk_entries/ventries/Vsize/Voffset/vcomment_length', substr($data, $pos, 22));
810 if ($centralend['comment_length']) {
811 $centralend['comment'] = substr($data, 22, $centralend['comment_length']);
812 } else {
813 $centralend['comment'] = '';
816 return $centralend;
820 * Parse file header.
821 * @internal
822 * @param string $data
823 * @param array $centralend
824 * @param int $pos (modified)
825 * @return array|bool file info
827 public static function zip_parse_file_header($data, $centralend, &$pos) {
828 $file = unpack('Vsig/vversion/vversion_req/vgeneral/vmethod/Vmodified/Vcrc/Vsize_compressed/Vsize/vname_length/vextra_length/vcomment_length/vdisk/vattr/Vattrext/Vlocal_offset', substr($data, $pos, 46));
829 $file['central_offset'] = $centralend['offset'] + $pos;
830 $pos = $pos + 46;
831 if ($file['sig'] !== 0x02014b50) {
832 // Borked ZIP structure!
833 return false;
835 $file['name'] = substr($data, $pos, $file['name_length']);
836 $pos = $pos + $file['name_length'];
837 $file['extra'] = array();
838 $file['extra_data'] = '';
839 if ($file['extra_length']) {
840 $extradata = substr($data, $pos, $file['extra_length']);
841 $file['extra_data'] = $extradata;
842 while (strlen($extradata) > 4) {
843 $extra = unpack('vid/vsize', substr($extradata, 0, 4));
844 $extra['data'] = substr($extradata, 4, $extra['size']);
845 $extradata = substr($extradata, 4+$extra['size']);
846 $file['extra'][] = $extra;
848 $pos = $pos + $file['extra_length'];
850 if ($file['comment_length']) {
851 $pos = $pos + $file['comment_length'];
852 $file['comment'] = substr($data, $pos, $file['comment_length']);
853 } else {
854 $file['comment'] = '';
856 return $file;