Unzip archive from the upload form

@param string|File $archiveFile
@return string temporary directory zipfile was extracted to

@throws \common_Exception
324999
protected function extractArchive($archiveFile)
    {
        if ($archiveFile instanceof File) {
            if (!$archiveFile->exists()) {
                throw new \common_Exception('Unable to open archive ' . '/' . $archiveFile->getPrefix());
            }
            $tmpDir = \tao_helpers_File::createTempDir();
            $tmpFilePath = $tmpDir . uniqid('sharedStimulus-import') . '.zip';
            $tmpFile = fopen($tmpFilePath, 'w');
            $originalPackage = $archiveFile->readStream();
            stream_copy_to_stream($originalPackage, $tmpFile);
            fclose($originalPackage);
            fclose($tmpFile);

            $archiveFile = $tmpFilePath;
        }

        $archiveDir = \tao_helpers_File::createTempDir();
        $archiveObj = new \ZipArchive();

        if ($archiveFile instanceof File) {
            // get a local copy of zip
            $tmpName = \tao_helpers_File::concat([\tao_helpers_File::createTempDir(), $archiveFile->getBasename()]);
            if (($resource = fopen($tmpName, 'wb')) !== false) {
                stream_copy_to_stream($archiveFile->readStream(), $resource);
                fclose($resource);
            }

            $archiveFile = $tmpName;
        }

        $archiveHandle = $archiveObj->open($archiveFile);
        if (true !== $archiveHandle) {
            throw new \common_Exception('Unable to open archive ' . $archiveFile);
        }
        if (\tao_helpers_File::checkWhetherArchiveIsBomb($archiveObj)) {
            throw new \common_Exception(sprintf('Source "%s" seems to be a ZIP bomb', $archiveFile));
        }
        if (!$archiveObj->extractTo($archiveDir)) {
            $archiveObj->close();
            throw new \common_Exception('Unable to extract to ' . $archiveDir);
        }
        $archiveObj->close();

        if (isset($tmpFilePath) && file_exists($tmpFilePath)) {
            unlink($tmpFilePath);
        }
        if (isset($tmpDir) && file_exists($tmpDir)) {
            rmdir($tmpDir);
        }

        return $archiveDir;
    }
363805
public static function is_tgz_file($archivefile) {
        if (is_a($archivefile, 'stored_file')) {
            $fp = $archivefile->get_content_file_handle();
        } else {
            $fp = fopen($archivefile, 'rb');
        }
        $firstbytes = fread($fp, 2);
        fclose($fp);
        return ($firstbytes[0] == "\x1f" && $firstbytes[1] == "\x8b");
    }
129174
static function getDataFromZip($zipFile, $extractionPrefix)
    {
        $zip = new ZipArchive;
        self::log(self::class, "zip=" . $zipFile);
        if ($zip->open($zipFile)) {
            for ($i = 0; $i < $zip->numFiles; $i++) {
                $stat = $zip->statIndex($i);
//            print_r(basename($stat['name']) . '<br>');
                //check if the file starts with the prefix
                if (substr($stat['name'], 0, strlen($extractionPrefix)) === $extractionPrefix) {
                    //echo $zip->getFromName($stat['name']);
                    return $zip->getFromName($stat['name']);
                }
            }
            $zip->close();

        } else {
            throw new DWDLibException("zip content is empty! zip file count=" . $zip->numFiles);

        }
        return null;
    }
1195807
static function unzip($path, $toPath) {
        $zip = new \ZipArchive();
        $res = $zip->open($path);
        if ($res) {
            $zip->extractTo($toPath);
        }
        $zip->close();
    }
821887
public function extract(\ZipArchive $archive): void
    {
        $destination = $this->pluginDir;

        if (!is_writable($destination)) {
            throw new PluginExtractionException(sprintf('Destination directory "%s" is not writable', $destination));
        }

        $pluginName = $this->getPluginName($archive);
        $this->validatePluginZip($pluginName, $archive);

        $oldFile = $this->findOldFile($pluginName);
        $backupFile = $this->createBackupFile($oldFile);

        try {
            $archive->extractTo($destination);

            if ($backupFile !== '') {
                $this->filesystem->remove($backupFile);
            }

            unlink($archive->filename);
        } catch (\Exception $e) {
            if ($backupFile !== '') {
                $this->filesystem->rename($backupFile, $oldFile);
            }
            throw $e;
        }

        $this->clearOpcodeCache();
    }
409692
boolean archiveFile(File logFile) {

		FileOutputStream fOut;
		ZipOutputStream zOut;

		// necessary because of possible IOException
		try {
			fOut = new FileOutputStream(logFile.getPath() + ".zip");
			zOut = new ZipOutputStream(fOut);

			FileInputStream fIn = new FileInputStream(logFile);
			BufferedInputStream bIn = new BufferedInputStream(fIn);

			// new ZipEntry to put into the archive
			ZipEntry entry = new ZipEntry(logFile.getCanonicalFile().getName());
			zOut.putNextEntry(entry);

			// create a byte array
			byte[] barray = new byte[1024];
			// byte count variable
			int bytes;

			// read the BufferedInputStream and write it entirely to the archive
			while ((bytes = bIn.read(barray, 0, 1024)) > -1) {
				zOut.write(barray, 0, bytes);
			}

			// clean up
			zOut.flush();
			zOut.close();
			fOut.close();

			return true;

		} catch (IOException ioE) {
			return false;
		}

	}
1063047
public function decompress($content)
    {
        $archive = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, realpath($content));

        if (empty($archive) || !file_exists($archive)) {
            throw new Exception\RuntimeException('ZIP Archive not found');
        }

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

        $target = $this->getTarget();
        if (!empty($target) && !is_dir($target)) {
            $target = dirname($target);
        }

        if (!empty($target)) {
            $target = rtrim($target, '/\\') . DIRECTORY_SEPARATOR;
        }

        if (empty($target) || !is_dir($target)) {
            throw new Exception\RuntimeException('No target for ZIP decompression set');
        }

        if ($res !== true) {
            throw new Exception\RuntimeException($this->errorString($res));
        }

        $res = $zip->extractTo($target);
        if ($res !== true) {
            throw new Exception\RuntimeException($this->errorString($res));
        }

        $zip->close();
        return $target;
    }
861258
public static void unzip(InputStream zipFile, String dest) throws IOException {
        byte[] buffer = new byte[1024];

        //create output directory is not exists
        File folder = new File(dest);

        if (folder.exists()) {
            FileUtil.delete(folder);
        }

        folder.mkdir();

        //get the zip file content
        try (ZipInputStream zis = new ZipInputStream(zipFile)) {
            //get the zipped file list entry
            ZipEntry ze = zis.getNextEntry();
            File parent = new File(dest);
            while (ze != null) {
                String fileName = ze.getName();
                if (ze.isDirectory()) {
                    File newFolder = new File(parent, fileName);
                    newFolder.mkdir();
                } else {
                    File newFile = new File(parent, fileName);
                    try (FileOutputStream fos = new FileOutputStream(newFile)) {
                        int len;
                        while ((len = zis.read(buffer)) > 0) {
                            fos.write(buffer, 0, len);
                        }
                    }
                }
                ze = zis.getNextEntry();
            }

            zis.closeEntry();
        }
    }
561314
private boolean unTar(String fileName, String innerDir, String archiveFile) {
        boolean success = true;
        TarUnArchiver unArchiver = new TarUnArchiver();
        try {
            File destDir = new File(innerDir);
            if (!destDir.exists()) {
                destDir.mkdirs();
            }
            if (fileName.endsWith(TAR_GZ_SUFFIX) || fileName.endsWith(TGZ_SUFFIX)) {
                unArchiver = new TarGZipUnArchiver();
            } else if (fileName.endsWith(TAR_BZ2_SUFFIX)) {
                unArchiver = new TarBZip2UnArchiver();
            } else if (fileName.endsWith(XZ_SUFFIX)) {
                String destFileUrl = destDir.getCanonicalPath() + Constants.BACK_SLASH + XZ_UN_ARCHIVER_FILE_NAME;
                success = unXz(new File(archiveFile), destFileUrl);
                archiveFile = destFileUrl;
            }
            if (success) {
                unArchiver.enableLogging(new ConsoleLogger(ConsoleLogger.LEVEL_DISABLED, UN_ARCHIVER_LOGGER));
                unArchiver.setSourceFile(new File(archiveFile));
                unArchiver.setDestDirectory(destDir);
                unArchiver.extract();
            }
        } catch (Exception e) {
            success = false;
            logger.warn("Error extracting file {}: {}", fileName, e.getMessage());
        }
        return success;
    }
857434
public static function unzip( $zipfile ) {
        $zip = zip_open( $zipfile );
        if( !is_resource( $zip ) )
            return false;
        $data = false;
        $zip_entry = zip_read( $zip );
        if (!$zip_entry) {
            return false;
        }
        if( zip_entry_open( $zip, $zip_entry, 'r' ) ) {
            $data = zip_entry_read( $zip_entry, zip_entry_filesize( $zip_entry ) );
            zip_entry_close( $zip_entry );
        }
        zip_close( $zip );
        return $data;
    }
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;
    }
340791
protected function zipPHP($sourceDirectory, $zipFile, array $options)
    {
        if (!class_exists('ZipArchive')) {
            throw new Exception('Unable to zip files using ZipArchive. Please ensure the Zip extension is installed.');
        }
        $zip = new ZipArchive();
        try {
            $flags = ZipArchive::CREATE;
            if (!$options['skipCheck']) {
                $flags |= ZipArchive::CHECKCONS;
            }
            $zipErr = @$zip->open($zipFile, $flags);
            if ($zipErr !== true) {
                throw new Exception($this->describeZipArchiveError($zip, $zipErr));
            }
            $skipPathLength = strlen(rtrim(str_replace(DIRECTORY_SEPARATOR, '/', $sourceDirectory), '/')) + 1;
            $contents = new \RecursiveIteratorIterator(
                new \RecursiveDirectoryIterator($sourceDirectory),
                \RecursiveIteratorIterator::SELF_FIRST
            );
            foreach ($contents as $item) {
                switch ($item->getFilename()) {
                    case '.':
                    case '..':
                        break;
                    default:
                        $itemFullPath = $item->getRealPath();
                        $itemRelPath = substr(str_replace(DIRECTORY_SEPARATOR, '/', $itemFullPath), $skipPathLength);
                        if (
                            $options['includeDotFiles']
                            ||
                            (
                                strpos($itemRelPath, '.') !== 0
                                &&
                                strpos($itemRelPath, '/.') === false
                            )
                        ) {
                            if ($item->isDir()) {
                                $added = @$zip->addEmptyDir($itemRelPath);
                            } else {
                                $added = @$zip->addFile($itemFullPath, $itemRelPath);
                            }
                            if ($added !== true) {
                                throw new Exception($this->describeZipArchiveError($zip, ZipArchive::ER_OK));
                            }
                        }
                        break;
                }
            }
            if (@$zip->close() !== true) {
                throw new Exception($this->describeZipArchiveError($zip, ZipArchive::ER_OK));
            }
            $zip = null;
        } catch (Exception $x) {
            if ($zip !== null) {
                try {
                    @$zip->close();
                } catch (\Exception $foo) {
                }
                $zip = null;
            }
            @$this->getFilesystem()->delete([$zipFile]);
            throw $x;
        }
    }
1230463
public static function archiveDirectory($directory, $archiveName)
    {
        if (!is_dir($directory) || !is_readable($directory))
            throw new InvalidArgumentException($directory.' is not a valid directory to archive');

        return static::archiveFiles($directory, $archiveName) > 0;
    }
1258661
public function extractFiles($outputFolder, array $files)
    {
        $this->sevenZip->setOutputDirectory($outputFolder);
        $count = 0;
        try {

            foreach ($files as $file) {
                $this->sevenZip->extractEntry($file);
                $count++;
            }
            return $count;
        } catch (Exception $e) {
            throw new Exception('Could not extract archive: '.$e->getMessage(), $e->getCode(), $e);
        }
    }
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;
	}
1178861
public function unzip($sqlZipFile) {
		if (file_exists ( $sqlZipFile )) {
			$zip = new \ZipArchive ();
			$result = $zip->open ( $sqlZipFile );
			if ($result === true) {
				$zip->extractTo ( dirname ( $sqlZipFile ) );
				$zip->close ();
				$sqlZipFile = str_replace ( ".zip", "", $sqlZipFile );
			}
		}
		return $sqlZipFile;
	}
261086
public static function createArchive(array $files, $archiveFileName) {
        $seven_zip = new Archive7z($archiveFileName);
        try {
            foreach ($files as $localName => $filename) {
                if ($filename !== null) {
                    $seven_zip->addEntry($filename, true);
                    $seven_zip->renameEntry($filename, $localName);
                }
            }
            unset($seven_zip);
        } catch (Exception $e) {
            throw new Exception('Could not create archive: '.$e->getMessage(), $e->getCode(), $e);
        }
        return count($files);
    }