public function __toString()
 {
     $this->zipCommentLength = ZipUtils::bin_strlen($this->zipComment);
     $eocd = AbstractZipHeader::ZIP_END_OF_CENTRAL_DIRECTORY;
     $eocd .= pack("vvvv", $this->thisDisk, $this->firstCDDisk, $this->cdrCount1, $this->cdrCount2);
     $eocd .= pack("VVv", $this->cdrLength, $this->cdrStart, $this->zipCommentLength);
     if ($this->zipCommentLength > 0) {
         $eocd .= $this->zipComment;
     } else {
         $eocd .= AbstractZipHeader::NULL_WORD;
     }
     return $eocd;
 }
Пример #2
0
 public static function createDirEntry($path, $timestamp)
 {
     $fileEntry = new ZipFileEntry();
     $fileEntry->gzType = 0;
     $fileEntry->gpFlags = 0;
     $fileEntry->fileCRC32 = 0;
     $fileEntry->externalFileAttributes = ZipFileEntry::EXT_FILE_ATTR_DIR;
     $fileEntry->gzLength = 0;
     $fileEntry->dataLength = 0;
     $fileEntry->isDirectory = true;
     $fileEntry->dosTime = ZipUtils::getDosTime($timestamp);
     $fileEntry->path = $path;
     $ef = new ExtendedTimeStampExtraField();
     $ef->setModTime($timestamp);
     $ef->setAccessTime($timestamp);
     $fileEntry->addExtraField($ef);
     $ef = new GenericExtraField();
     $ef->header = AbstractExtraField::HEADER_UNIX_TYPE_3;
     $ef->setFieldData("è", '');
     $fileEntry->addExtraField($ef);
     return $fileEntry;
 }
 /**
  *
  * @author A. Grandt <*****@*****.**>
  * @author Greg Kappatos
  *
  * @return string The full path to a temporary file.
  */
 public static function getTemporaryFile()
 {
     if (is_callable(self::$temp)) {
         $file = @call_user_func(self::$temp);
         if (is_string($file) && ZipUtils::bin_strlen($file) && is_writable($file)) {
             return $file;
         }
     }
     $dir = is_string(self::$temp) && ZipUtils::bin_strlen(self::$temp) ? self::$temp : sys_get_temp_dir();
     if (is_dir($dir) === false) {
         $dir = ini_get('upload_tmp_dir');
     }
     if (is_dir($dir) === false) {
         $dir = ini_get('upload_tmp_dir');
     }
     return tempnam($dir, __NAMESPACE__);
 }
Пример #4
0
		. "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec magna lorem, mattis sit amet porta vitae, consectetur ut eros. Nullam id mattis lacus. In eget neque magna, congue imperdiet nulla. Aenean erat lacus, imperdiet a adipiscing non, dignissim eget felis. Nulla facilisi. Vivamus sit amet lorem eget mauris dictum pharetra. In mauris nulla, placerat a accumsan ac, mollis sit amet ligula. Donec eget facilisis dui. Cras elit quam, imperdiet at malesuada vitae, luctus id orci. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Pellentesque eu libero in leo ultrices tristique. Etiam quis ornare massa. Donec in velit leo. Sed eu ante tortor.\n";

$zip = new \PHPZip\Zip\Stream\ZipStream('ZipStreamExample1.zip'); // $zip = new ZipStream("ZipStreamExample1.zip");

$zip->setComment("Example Zip file for Large file sets.\nCreated on " . date('l jS \of F Y h:i:s A'));
$zip->addFile("Hello World!\r\n", "Hello.txt");

$zip->openStream("big one3.txt");
$zip->addStreamData($chapter1."\n\n\n");
$zip->addStreamData($chapter1."\n\n\n");
$zip->addStreamData($chapter1."\n\n\n");
$zip->closeStream();

// For this test you need to create a large text file called "big one1.txt"
if (file_exists("big one1.txt")) {
	$zip->addLargeFile("big one1.txt", "big one2a.txt", 0, null, \PHPZip\Zip\Core\ZipUtils::getFileExtAttr("big one1.txt"));

	$fhandle = fopen("big one1.txt", "rb");
	$zip->addLargeFile($fhandle, "big one2b.txt");
	fclose($fhandle);
}

$zip->addDirectory("Empty Dir");

//Dir test, using the stream option on $zip->addLargeFile
$fileDir = './';
@$handle = opendir($fileDir);
if ($handle) {
	/* This is the correct way to loop over the directory. */
	while (false !== ($file = readdir($handle))) {
		if (($file != '.') && ($file != '..') && is_file($file)) {
Пример #5
0
    /**
     * Build the Zip file structures
     *
     * @author A. Grandt <*****@*****.**>
     * @author Greg Kappatos
     *
     * @param string $filePath
     * @param string $fileComment
     * @param string $gpFlags
     * @param string $gzType
     * @param int    $timestamp
     * @param string $fileCRC32
     * @param int    $gzLength
     * @param int    $dataLength
     * @param int    $extFileAttr Use self::EXT_FILE_ATTR_FILE for files, self::EXT_FILE_ATTR_DIR for Directories.
     */
    protected function buildZipEntry($filePath, $fileComment, $gpFlags, $gzType, $timestamp, $fileCRC32, $gzLength, $dataLength, $extFileAttr) {
        $filePath = str_replace("\\", "/", $filePath);
        $fileCommentLength = (empty($fileComment) ? 0 : BinStringStatic::_strlen($fileComment));
        $timestamp = (int)$timestamp;
        $timestamp = ($timestamp == 0 ? time() : $timestamp);

        $dosTime = ZipUtils::getDosTime($timestamp);
        $tsPack = pack("V", $timestamp);

        if (!isset($gpFlags) || BinStringStatic::_strlen($gpFlags) != 2) {
            $gpFlags = self::DEFAULT_GP_FLAGS;
        }

        $isFileUTF8 = mb_check_encoding($filePath, "UTF-8") && !mb_check_encoding($filePath, "ASCII");
        $isCommentUTF8 = !empty($fileComment) && mb_check_encoding($fileComment, "UTF-8") && !mb_check_encoding($fileComment, "ASCII");

        $locExField = "";
        $cenExField = "";

        if ($this->addExtraField) {
            $locExField .= self::HEADER_EXTENDED_TIMESTAMP . "\x09\x00\x03"
                . $tsPack . $tsPack
                . self::EXTRA_FIELD_NEW_UNIX_GUID;
            $cenExField .= self::HEADER_EXTENDED_TIMESTAMP . "\x05\x00\x03"
                . $tsPack
                . self::EXTRA_FIELD_NEW_UNIX_GUID_CD;
        }

        if ($isFileUTF8 || $isCommentUTF8) {
            $flag = 0;
            $gpFlagsV = unpack("vflags", $gpFlags);
            if (isset($gpFlagsV['flags'])) {
                $flag = $gpFlagsV['flags'];
            }
            $gpFlags = pack("v", $flag | (1 << 11));

            if ($isFileUTF8) {
                $utfExField = self::HEADER_UNICODE_PATH // utf8 encoded File path extra field
                    . pack ("v", (5 + BinStringStatic::_strlen($filePath)))
                    . "\x01"
                    . pack("V", crc32($filePath))
                    . $filePath;

                $locExField .= $utfExField;
                $cenExField .= $utfExField;
            }
            if ($isCommentUTF8) {
                $cenExField .= self::HEADER_UNICODE_COMMENT // utf8 encoded file comment extra field
                    . pack ("v", (5 + BinStringStatic::_strlen($fileComment)))
                    . "\x01"
                    . pack("V", crc32($fileComment))
                    . $fileComment;
            }
        }

        $header = $gpFlags . $gzType . $dosTime. $fileCRC32
            . pack("VVv", $gzLength, $dataLength, BinStringStatic::_strlen($filePath)); // File name length

        $zipEntry  = self::ZIP_LOCAL_FILE_HEADER
            . self::ATTR_VERSION_TO_EXTRACT
            . $header
            . pack("v", BinStringStatic::_strlen($locExField)) // Extra field length
            . $filePath // FileName
            . $locExField; // Extra fields

        $this->onBuildZipEntry(array(
            'zipEntry' => $zipEntry,
        ));

        $cdEntry  = self::ZIP_CENTRAL_FILE_HEADER
            . self::ATTR_MADE_BY_VERSION
            . ($dataLength === 0 ? "\x0A\x00" : self::ATTR_VERSION_TO_EXTRACT)
            . $header
            . pack("v", BinStringStatic::_strlen($cenExField)) // Extra field length
            . pack("v", $fileCommentLength) // File comment length
            . self::NULL_WORD // Disk number start
            . self::NULL_WORD // internal file attributes
            . pack("V", $extFileAttr) // External file attributes
            . pack("V", $this->offset) // Relative offset of local header
            . $filePath // FileName
            . $cenExField; // Extra fields

        if (!empty($fileComment)) {
            $cdEntry .= $fileComment; // Comment
        }

        $this->cdRec[] = $cdEntry;
        $this->offset += BinStringStatic::_strlen($zipEntry) + $gzLength;

        $this->_notifyListeners(null, array(
            'file' => $zipEntry,
        ));
    }
Пример #6
0
 /**
  * Build the base standard response headers, and ensure the content can be streamed.
  *
  * @author A. Grandt <*****@*****.**>
  *
  * @param String $fileName The name of the Zip archive, in ISO-8859-1 (or ASCII) encoding, ie. "archive.zip". Optional, defaults to null, which means that no ISO-8859-1 encoded file name will be specified.
  * @param String $contentType Content mime type. Optional, defaults to "application/zip".
  * @param String $utf8FileName The name of the Zip archive, in UTF-8 encoding. Optional, defaults to null, which means that no UTF-8 encoded file name will be specified.
  * @param bool   $inline Use Content-Disposition with "inline" instead of "attached". Optional, defaults to false.
  *
  * @return bool Always returns true (for backward compatibility).
  * 
  * @throws \PHPZip\Zip\Exception\BufferNotEmpty, HeadersSent In case of errors
  */
 protected function buildResponseHeader($fileName = null, $contentType = self::CONTENT_TYPE, $utf8FileName = null, $inline = false)
 {
     $ob = null;
     $headerFile = null;
     $headerLine = null;
     $zlibConfig = 'zlib.output_compression';
     $ob = ob_get_contents();
     if ($ob !== false && ZipUtils::bin_strlen($ob)) {
         $this->_throwException(new BufferNotEmpty(array('outputBuffer' => $ob, 'fileName' => $fileName)));
     }
     if (headers_sent($headerFile, $headerLine)) {
         $this->_throwException(new HeadersSent(array('headerFile' => $headerFile, 'headerLine' => $headerLine, 'fileName' => $fileName)));
     }
     if (@ini_get($zlibConfig)) {
         @ini_set($zlibConfig, 'Off');
     }
     $cd = 'Content-Disposition: ' . ($inline ? 'inline' : 'attached');
     if ($fileName) {
         $cd .= '; filename="' . $fileName . '"';
     }
     if ($utf8FileName) {
         $cd .= "; filename*=UTF-8''" . rawurlencode($utf8FileName);
     }
     header('Pragma: public');
     header('Last-Modified: ' . gmdate('D, d M Y H:i:s T'));
     header('Expires: 0');
     header('Accept-Ranges: bytes');
     header('Connection: close');
     header('Content-Type: ' . $contentType);
     header($cd);
     return true;
 }
Пример #7
0
	public function test1(){

		error_reporting(E_ALL | E_STRICT);
		ini_set('error_reporting', E_ALL | E_STRICT);
		ini_set('display_errors', 1);
		//
		//// Example. Zip all .html files in the current directory and save to current directory.
		// Make a copy, also to the current dir, for good measure.
		//$mem = ini_get('memory_limit');
		//$extime = ini_get('max_execution_time');
		//
		////ini_set('memory_limit', '512M');
		ini_set('max_execution_time', 600);

		//include_once("ZipStream.php");
		//print_r(ini_get_all());

		//$fileTime = date("D, d M Y H:i:s T");

		$chapter1 = "Chapter 1\n"
			. "Lorem ipsum\n"
			. "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec magna lorem, mattis sit amet porta vitae, consectetur ut eros. Nullam id mattis lacus. In eget neque magna, congue imperdiet nulla. Aenean erat lacus, imperdiet a adipiscing non, dignissim eget felis. Nulla facilisi. Vivamus sit amet lorem eget mauris dictum pharetra. In mauris nulla, placerat a accumsan ac, mollis sit amet ligula. Donec eget facilisis dui. Cras elit quam, imperdiet at malesuada vitae, luctus id orci. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Pellentesque eu libero in leo ultrices tristique. Etiam quis ornare massa. Donec in velit leo. Sed eu ante tortor.\n";

		//$zip = new ZipStream("ZipStreamExample1.zip");
		$zip = new ZipStream('ZipStreamExample1.zip');

		$zip->setComment("Example Zip file for Large file sets.\nCreated on " . date('l jS \of F Y h:i:s A'));
		$zip->addFile("Hello World!\r\n", "Hello.txt");

		$zip->openStream("big one3.txt");
		$zip->addStreamData($chapter1."\n\n\n");
		$zip->addStreamData($chapter1."\n\n\n");
		$zip->addStreamData($chapter1."\n\n\n");
		$zip->closeStream();

		// For this test you need to create a large text file called "big one1.txt"
		if (file_exists("big one1.txt")) {
			$zip->addLargeFile("big one1.txt", "big one2a.txt", 0, null, ZipUtils::getFileExtAttr("big one1.txt"));

			$fhandle = fopen("big one1.txt", "rb");
			$zip->addLargeFile($fhandle, "big one2b.txt");
			fclose($fhandle);
		}

		$zip->addDirectory("Empty Dir");

		//Dir test, using the stream option on $zip->addLargeFile
		$fileDir = './';
		@$handle = opendir($fileDir);
		if ($handle) {
			while (false !== ($file = readdir($handle))) {
				if (($file != '.') && ($file != '..') && is_file($file)) {
					$zip->addLargeFile(($fileDir . $file), "dirTest/".$file, filectime($fileDir . $file));
				}
			}
		}

		// Add a directory, first recursively, then the same directory, but without recursion.
		// Naturally this requires you to change the path to ../test to point to a directory of your own.
		$zip->addDirectory("recursiveDir/");
		$zip->addDirectoryContent("../../test", "recursiveDir/test");
		$zip->addDirectoryContent("../../test", "recursiveDir/testFlat", FALSE);
		/*
		$addedFiles = array();
		$zip->addDirectoryContent("../test", "recursiveDir/testPermisssions", TRUE, TRUE, $addedFiles,
					TRUE, ZipStream::generateExtAttr(4, 4, 0, FALSE), ZipStream::generateExtAttr(4, 4, 0, TRUE));
		*/
		$zip->finalize(); // Mandatory, needed to send the Zip files central directory structure.
	}
 /**
  * @return string The version of the field for the Central Header.
  */
 public function getCentralField()
 {
     return parent::HEADER_UNICODE_COMMENT . pack('vV', ZipUtils::bin_strlen($this->utf8Data) + 5, $this->CRC32) . $this->version . $this->utf8Data;
 }
Пример #9
0
 /**
  * Return the current size of the archive
  *
  * @author A. Grandt <*****@*****.**>
  *
  * @return int Size of the archive
  */
 public function getArchiveSize()
 {
     if (!is_resource($this->_zipFile)) {
         return ZipUtils::bin_strlen($this->_zipData);
     }
     $stat = fstat($this->_zipFile);
     return $stat['size'];
 }
 public static function encodeField($header, $data)
 {
     if ($header != null) {
         return $header . pack('v', ZipUtils::bin_strlen($data)) . $data;
     }
     return '';
 }
Пример #11
0
	private static function _createAndSendZipArchive(ZipArchiveFile $zip, $fileDir = './'){

		// Archive comments don't really support utf-8. Some tools detect and read it though.
		$zip->setComment("Example Zip file.\nАрхив Комментарий\nCreated on " . date('l jS \of F Y h:i:s A'));

		// A bit of russian (I hope), to test UTF-8 file names.
		$zip->addFile("Привет мир!", "Кириллица имя файла.txt");
		$zip->addFile("Привет мир!", "Привет мир. С комментарий к файлу.txt", 0, "Кириллица файл комментарий");
		$zip->addFile("Hello World!", "hello.txt");

		@$handle = opendir($fileDir);
		if ($handle) {
			while (false !== ($file = readdir($handle))) {
				if (strpos($file, ".php") !== false) {
					$pathData = pathinfo($fileDir . $file);
					$fileName = $pathData['filename'];

					$zip->addFile(file_get_contents($fileDir . $file), $file, filectime($fileDir . $file), null, true, ZipUtils::getFileExtAttr($file));
				}
			}
		}

		// Add a directory, first recursively, then the same directory, but without recursion.
		// Naturally this requires you to change the path to ../test to point to a directory of your own.
		// $zip->addDirectoryContent("testData/test", "recursiveDir/test");
		// $zip->addDirectoryContent("testData/test", "recursiveDir/testFlat", FALSE);

		//$zip->sendZip("ZipExample1.zip");
		//$zip->sendZip("ZipExample1_€2,000.zip");
		$zip->sendZip("ZipExample1_€2,000.zip", "application/zip", "ZipExample1_€2,000_utf8.zip");

	}
 /**
  * @return string The version of the field for the Central Header.
  */
 public function getCentralField()
 {
     $ts = $this->isModTimeSet ? pack('V', $this->modTime) : '';
     $flags = 0;
     ZipUtils::setBit($flags, 0, $this->isModTimeSet);
     ZipUtils::setBit($flags, 1, $this->isAcTimeSet);
     ZipUtils::setBit($flags, 2, $this->isCrTimeSet);
     return parent::HEADER_EXTENDED_TIMESTAMP . pack('vc', 1 + ZipUtils::bin_strlen($ts), $flags) . $ts;
 }