Extract a ZIP compressed file to a given path

@param   string  $archive      Path to ZIP archive to extract
@param   string  $destination  Path to extract archive into

@return  boolean True if successful

@since   1.0
@throws  \RuntimeException
554446
public function extract($archive, $destination)
	{
		$this->data = null;
		$this->metadata = null;

		$this->data = file_get_contents($archive);

		if (!$this->data)
		{
			throw new \RuntimeException('Unable to read archive');
		}

		$this->getTarInfo($this->data);

		for ($i = 0, $n = count($this->metadata); $i < $n; $i++)
		{
			$type = strtolower($this->metadata[$i]['type']);

			if ($type == 'file' || $type == 'unix file')
			{
				$buffer = $this->metadata[$i]['data'];
				$path = Path::clean($destination . '/' . $this->metadata[$i]['name']);

				// Make sure the destination folder exists
				if (!Folder::create(dirname($path)))
				{
					throw new \RuntimeException('Unable to create destination');
				}

				if (File::write($path, $buffer) === false)
				{
					throw new \RuntimeException('Unable to write entry');
				}
			}
		}

		return true;
	}
110281
public function copy( $source, $destination ) {

		$source = $this->get_file( $source );

		if ( false === $source ) {
			return false;
		}

		$destination_parent = $this->get_file( dirname( $destination ) );
		$filename = basename( $destination );

		if ( false === $destination_parent ) {
			return false;
		}

		$destination_parent->contents->$filename = clone $source;

		return true;
	}
1291508
public static void unzip(String compressedFileName, String destinationDir) {
        //strip everything except the applications name
        String dirName = null;
        // checks to see if there is a dash "-" in the filename of the war. 
        String applicationName = compressedFileName.substring(compressedFileName.lastIndexOf("/"));
        int dashIndex = applicationName.indexOf('-');
        if (dashIndex != -1) {
            //strip everything except the applications name
            dirName = compressedFileName.substring(0, dashIndex);
        } else {
            //grab every char up to the last '.'
            dirName = compressedFileName.substring(0, compressedFileName.lastIndexOf('.'));
        }
        log.debug("Directory: {}", dirName);
        //String tmpDir = System.getProperty("java.io.tmpdir");
        File zipDir = new File(compressedFileName);
        File parent = zipDir.getParentFile();
        log.debug("Parent: {}", (parent != null ? parent.getName() : null));
        //File tmpDir = new File(System.getProperty("java.io.tmpdir"), dirName);
        File tmpDir = new File(destinationDir);
        // make the war directory
        log.debug("Making directory: {}", tmpDir.mkdirs());
        ZipFile zf = null;
        try {
            zf = new ZipFile(compressedFileName);
            Enumeration<?> e = zf.entries();
            while (e.hasMoreElements()) {
                ZipEntry ze = (ZipEntry) e.nextElement();
                log.debug("Unzipping {}", ze.getName());
                if (ze.isDirectory()) {
                    log.debug("is a directory");
                    File dir = new File(tmpDir + "/" + ze.getName());
                    Boolean tmp = dir.mkdir();
                    log.debug("{}", tmp);
                    continue;
                }

                // checks to see if a zipEntry contains a path
                // i.e. ze.getName() == "META-INF/MANIFEST.MF"
                // if this case is true, then we create the path first
                if (ze.getName().lastIndexOf("/") != -1) {
                    String zipName = ze.getName();
                    String zipDirStructure = zipName.substring(0, zipName.lastIndexOf("/"));
                    File completeDirectory = new File(tmpDir + "/" + zipDirStructure);
                    if (!completeDirectory.exists()) {
                        if (!completeDirectory.mkdirs()) {
                            log.error("could not create complete directory structure");
                        }
                    }
                }

                // creates the file
                FileOutputStream fout = new FileOutputStream(tmpDir + "/" + ze.getName());
                InputStream in = zf.getInputStream(ze);
                copy(in, fout);
                in.close();
                fout.close();
            }
            e = null;
        } catch (IOException e) {
            log.error("Errored unzipping", e);
            //log.warn("Exception {}", e);
        } finally {
            if (zf != null) {
                try {
                    zf.close();
                } catch (IOException e) {
                }
            }
        }
    }
1174813
public function removeZip(Zip $zip): bool {

        $archive_key = array_search($zip, $this->zip_archives, true);
        if ( $archive_key === false ) {
            throw new ZipException("Archive not found");
        }

        unset($this->zip_archives[$archive_key]);
        return true;

    }
1220071
protected function unzipNative($zipFile, $destinationDirectory, array $options)
    {
        $cmd = 'unzip';
        $cmd .= ' -o'; // overwrite files WITHOUT prompting
        $cmd .= ' -q'; // quiet mode, to avoid overflow of stdout
        $cmd .= ' ' . escapeshellarg(str_replace('/', DIRECTORY_SEPARATOR, $zipFile)); // file to extract
        $cmd .= ' -d ' . escapeshellarg(str_replace('/', DIRECTORY_SEPARATOR, $destinationDirectory)); // destination directory
        $rc = 1;
        $output = [];
        @exec($cmd . ' 2>&1', $output, $rc);
        if ($rc !== 0) {
            $error = trim(implode("\n", $output)) ?: t('Unknown error decompressing a ZIP archive');
            throw new Exception($error);
        }
    }
707864
protected function extract($zipFile, $directory, OutputInterface $output = null)
    {
        if ($output) {
            $output->writeln('<info>Extracting file...</info>');
        }

        $archive = new ZipArchive;
        $archive->open($zipFile);
        $archive->extractTo($directory);
        $archive->close();

        return $this;
    }
899557
public function extract($archivename, $extractdir)
	{
		$ext      = pathinfo($archivename, PATHINFO_EXTENSION);
		$path     = pathinfo($archivename, PATHINFO_DIRNAME);
		$filename = pathinfo($archivename, PATHINFO_FILENAME);

		switch (strtolower($ext))
		{
			case 'zip':
				$result = $this->getAdapter('zip')->extract($archivename, $extractdir);

				break;

			case 'tar':
				$result = $this->getAdapter('tar')->extract($archivename, $extractdir);

				break;

			case 'tgz':
			case 'gz':
			case 'gzip':
				// This may just be an individual file (e.g. sql script)
				$tmpfname = $this->options['tmp_path'] . '/' . uniqid('gzip');

				try
				{
					$this->getAdapter('gzip')->extract($archivename, $tmpfname);
				}
				catch (\RuntimeException $exception)
				{
					@unlink($tmpfname);

					return false;
				}

				if ($ext === 'tgz' || stripos($filename, '.tar') !== false)
				{
					$result = $this->getAdapter('tar')->extract($tmpfname, $extractdir);
				}
				else
				{
					Folder::create($extractdir);
					$result = File::copy($tmpfname, $extractdir . '/' . $filename, null, 0);
				}

				@unlink($tmpfname);

				break;

			case 'tbz2':
			case 'bz2':
			case 'bzip2':
				// This may just be an individual file (e.g. sql script)
				$tmpfname = $this->options['tmp_path'] . '/' . uniqid('bzip2');

				try
				{
					$this->getAdapter('bzip2')->extract($archivename, $tmpfname);
				}
				catch (\RuntimeException $exception)
				{
					@unlink($tmpfname);

					return false;
				}

				if ($ext === 'tbz2' || stripos($filename, '.tar') !== false)
				{
					$result = $this->getAdapter('tar')->extract($tmpfname, $extractdir);
				}
				else
				{
					Folder::create($extractdir);
					$result = File::copy($tmpfname, $extractdir . '/' . $filename, null, 0);
				}

				@unlink($tmpfname);

				break;

			default:
				throw new \InvalidArgumentException(sprintf('Unknown archive type: %s', $ext));
		}

		return $result;
	}
1219990
private function extractZip()
    {
        $this->info("Extracting");
        $this->tmpDirectory = tmpPath($this->tmpRandomName);

        // extract
        Zipper::make($this->tmpZipFile)->extractTo($this->tmpDirectory);

        // delete zip file
        File::delete($this->tmpZipFile);

        // zip creates a parent directory on extract, pass it
        $directories = File::directories($this->tmpDirectory);
        if(isset($directories[0])) {
            $this->tmpDirectory = $directories[0];
        }

        return $this;
    }
1260935
public function extractTo($destination, $entities = null)
    {
        if ($entities) {
            return $this->zipArchive->extractTo($destination, $entities);
        } else {
            return $this->zipArchive->extractTo($destination);
        }
    }
1301280
protected function _unpackCurrentTar($destination)
    {
        $archiveReader = $this->_getReader();
        $list = array();

        while (!$archiveReader->eof()) {
            $header = $this->_extractFileHeader();

            if (!$header) {
                continue;
            }

            $currentFile = $destination . $header['name'];
            $dirname = dirname($currentFile);

            if (in_array($header['type'], array("0",chr(0), ''))) {

                if(!file_exists($dirname)) {
                    $mkdirResult = @mkdir($dirname, 0777, true);

                    if (false === $mkdirResult) {
                        throw new Mage_Exception('Failed to create directory ' . $dirname);
                    }
                }

                $this->_extractAndWriteFile($header, $currentFile);
                $list[] = $currentFile;

            } elseif ($header['type'] == '5') {

                if(!file_exists($dirname)) {
                    $mkdirResult = @mkdir($currentFile, $header['mode'], true);

                    if (false === $mkdirResult) {
                        throw new Mage_Exception('Failed to create directory ' . $currentFile);
                    }
                }
                $list[] = $currentFile . DS;
            } elseif ($header['type'] == '2') {

                //we do not interrupt unpack process if symlink creation failed as symlinks are not so important
                @symlink($header['symlink'], $currentFile);
            }
        }

        return $list;
    }
600500
public static void extract(final ZipFile zipFile4j, final File destination,
		final String password) throws ZipException
	{
		if (zipFile4j.isEncrypted())
		{
			zipFile4j.setPassword(password);
		}
		zipFile4j.extractAll(destination.getAbsolutePath());
	}
182103
public function create($archive, $files)
	{
		$contents = array();
		$ctrldir  = array();

		foreach ($files as $file)
		{
			$this->addToZipFile($file, $contents, $ctrldir);
		}

		return $this->createZipFile($contents, $ctrldir, $archive);
	}
267021
protected function _extractAndWriteFile($fileHeader, $destination)
    {
        $fileWriter = new Mage_Archive_Helper_File($destination);
        $fileWriter->open('w', $fileHeader['mode']);

        $archiveReader = $this->_getReader();

        $filesize = $fileHeader['size'];
        $bytesExtracted = 0;

        while ($filesize > $bytesExtracted && !$archiveReader->eof()) {
            $block = $archiveReader->read(self::TAR_BLOCK_SIZE);
            $nonExtractedBytesCount = $filesize - $bytesExtracted;

            $data = substr($block, 0, $nonExtractedBytesCount);
            $fileWriter->write($data);

            $bytesExtracted += strlen($block);
        }
    }
351564
public function unzip($source, $destination)
    {
        @mkdir($destination, 0777, true);

        foreach ((array) glob($source.'/*.zip') as $key => $value) {
            if ($this->zip->open(str_replace('//', '/', $value)) === true) {
                $this->zip->extractTo($destination);
                echo $this->ZipStatusString($this->zip);
                $this->zip->close();
            }
        }
    }
595635
protected function unzipArchive($file = '', $targetDir = '', $deleteZipArchive = true) : bool
    {
        if (empty($file) || ! File::exists($file)) {
            throw new \InvalidArgumentException("Archive [{$file}] cannot be found or is empty.");
        }

        $zip = new \ZipArchive();
        $res = $zip->open($file);

        if (! $res) {
            throw new \Exception("Cannot open zip archive [{$file}].");
        }

        if (empty($targetDir)) {
            $extracted = $zip->extractTo(File::dirname($file));
        } else {
            $extracted = $zip->extractTo($targetDir);
        }

        $zip->close();

        if ($extracted && $deleteZipArchive === true) {
            File::delete($file);
        }

        return true;
    }
668545
private function copyToPackage(\ZipArchive $archive, $pathInArchive, $path)
    {
        if (file_exists($path)) {
            if (is_dir($path)) {
                /** @var \SplFileInfo[] $files */
                $files = new \RecursiveIteratorIterator(
                    new \RecursiveDirectoryIterator($path), \RecursiveIteratorIterator::LEAVES_ONLY
                );

                foreach ($files as $file) {
                    // Skip directories
                    if (!$file->isDir()) {
                        // Get real and relative path for current file
                        // Add current file to archive
                        $archive->addFile(
                            $path.DIRECTORY_SEPARATOR.$file->getFilename(),
                            $pathInArchive.DIRECTORY_SEPARATOR.$file->getFilename());
                    }
                }
            } else {
                $archive->addFile($path, $pathInArchive);
            }
        } else {
            throw new FileNotFoundException(sprintf('File "%s" could not be found.', $path));
        }
    }
913572
public function extractTo($destination, $entries = array())
    {
        $result = false;
        if (!empty($entries)) {
            $result = $this->tar->extractList($entries, $destination);
        } else {
            $result = $this->tar->extract($destination, true);
        }
        if ($result === false) {
            throw new ArchiveException('Error extracting archive.');
        }

        return $this;
    }