Unzip a file.

@param string      $file
@param string|null $pathToExtractTo

@throws IOException
481835
public static function unzip($file, $pathToExtractTo = null)
    {
        $call = "ionice -c 3 unzip -q -j -o -DD {$file} 2>&1";
        if ($pathToExtractTo) {
            $call .= " -d {$pathToExtractTo}";
        }

        exec($call, $output, $returnCode);

        if ($returnCode != 0) {
            throw new IOException(sprintf("Cannot unzip %s: %s", $file, join("\n", $output)));
        }
    }
1118085
public function fileExists($filename, $pathToFile = null)
    {
        if ($pathToFile==null) {
            $pathToFile=$this->_filePath;
        }
        return file_exists($pathToFile."/".$filename);
    }
962884
protected function unlink($file)
    {
        ErrorHandler::start();
        $res = unlink($file);
        $err = ErrorHandler::stop();

        // only throw exception if file still exists after deleting
        if (!$res && file_exists($file)) {
            throw new Exception\RuntimeException(
                "Error unlinking file '{$file}'; file still exists", 0, $err
            );
        }
    }
564063
function unzip(file, callback) {
    var metafile = metapath(file);
    // return cached result of unzipped file
    // intentionally sync here to avoid race condition unzipping
    // same file for multiple layers
    try {
        var meta_data = fs.readFileSync(metafile);
        if (meta_data) {
            var meta = JSON.parse(meta_data);
            var dest_file = meta['unzipped_file'];
            if (dest_file && existsSync(dest_file)) {
                if (env == 'development') console.error('[millstone] found previously unzipped file: ' + dest_file);
                return callback(null,dest_file);
            }
        } else {
            if (env == 'development') console.error('[millstone] empty meta file for zipfile: ' + metafile);
        }
    }
    catch (err) {
        if (env == 'development') console.error('[millstone] error opening meta file for zipfile: ' + err.message);
    }
    var zf;
    try {
        zf = new zipfile.ZipFile(file);
    } catch (err) {
        return callback(err);
    }

    if (zf.names.length < 1) {
        return callback(new Error("could not find any valid data in zip archive: '" + file + "'"));
    }

    var remain = zf.names.length;
    var ds_files = _(zf.names).chain()
        .reject(function(name) {
            return (name && (name[0] === '.' || path.basename(name)[0] === '.'));
        })
        .map(function(name) {
            if (!valid_ds_extensions[path.extname(name).toLowerCase()]) return;
            var new_name = path.join(
                path.dirname(file),
                path.basename(file, path.extname(file)) +
                path.extname(name).toLowerCase());
            return {new_name:new_name,original_name:name};
        })
        .uniq()
        .compact()
        .value();

    if (!ds_files || ds_files.length < 1) return callback(new Error("Valid datasource not detected (by extension) in zip: '" + file + "'"));

    var original_name = ds_files[0].original_name;
    var new_name = ds_files[0].new_name;

    var len = Object.keys(ds_files).length;
    if (len > 1) {
        // prefer first .shp
        for (var i=0;i<len;++i) {
            var fname = ds_files[i].original_name;
            if (path.extname(fname) == '.shp') {
                original_name = fname;
                new_name = ds_files[i].new_name;
                break;
            }
        }
        if (env == 'development') {
            console.warn('[millstone] warning: detected more than one file in zip (by ext) that may be valid: ');
            for (var i=0;i<len;++i) {
                console.warn('[millstone]   ' + ds_files[i].original_name);
            }
            console.warn('[millstone] picked: ' + original_name);
        }
    }

    if (!new_name) return callback(new Error("Valid datasource not detected (by extension) in zip: '" + file + "'"));

    if (env == 'development') {
        console.warn('[millstone] renaming ' + original_name + ' to ' + new_name);
    }

    // only unzip files that match our target name
    // naive '(name.indexOf(search_basename) < 0)' does the trick
    // yes this is simplistic, but its better than corrupt data: https://github.com/mapbox/millstone/issues/99
    var search_basename = path.basename(original_name,path.extname(original_name));
    zf.names.forEach(function(name) {
        // Skip directories, hiddens.
        var basename = path.basename(name);
        if (!path.extname(name) || (name.indexOf(search_basename) < 0) || name[0] === '.' || basename[0] === '.') {
            remain--;
            if (!remain) callback(null, new_name);
        } else {
            // We're brutal in our expectations -- don't support nested
            // directories, and rename any file from `arbitraryName.SHP`
            // to `[hash].shp`.
            var dest = path.join(
                path.dirname(file),
                path.basename(file, path.extname(file)) +
                path.extname(name).toLowerCase()
            );
            zf.copyFile(name, dest, function(err) {
                if (err) return callback(err);
                remain--;
                if (!remain) {
                    add_item_to_metafile(metafile,'unzipped_file',new_name,function(err) {
                        // ignore error from add_item_to_metafile
                        //if (err && env == 'development') console.error('[millstone] ' + err.message);
                        if (err) throw err;
                        callback(null, new_name);
                    });
                }
            });
        }
    });
}
1209484
private void unzip(final File file, final String outputDir) throws IOException {

		try (final ZipFile zipFile = new ZipFile(file)) {

			final Enumeration<? extends ZipEntry> entries = zipFile.entries();

			while (entries.hasMoreElements()) {

				final ZipEntry entry = entries.nextElement();
				final File targetFile = new File(outputDir, entry.getName());

				if (entry.isDirectory()) {

					targetFile.mkdirs();

				} else {

					targetFile.getParentFile().mkdirs();
					InputStream in = zipFile.getInputStream(entry);

					try (OutputStream out = new FileOutputStream(targetFile)) {

						IOUtils.copy(in, out);
						IOUtils.closeQuietly(in);
					}
				}
			}
		}
	}
394971
protected static function getPathFromFile(File $file)
    {
        $path = tempnam(TEMP_PATH, 'pdftextextractor_');
        if (false === $path) {
            throw new Exception(static::class . '->getPathFromFile() could not allocate temporary file name');
        }

        // Append extension to temp file if one is set
        if ($file->getExtension()) {
            $path .= '.' . $file->getExtension();
        }

        // Remove any existing temp files with this name
        if (file_exists($path)) {
            unlink($path);
        }

        $bytesWritten = file_put_contents($path, $file->getStream());
        if (false === $bytesWritten) {
            throw new Exception(static::class . '->getPathFromFile() failed to write temporary file');
        }

        return $path;
    }
667334
protected function _recursivelyExtractObject(string $path, EntityInterface $object): ?EntityInterface
    {
        if (stripos($path, '.') !== false) {
            $split = explode('.', $path);
            $path = array_shift($split);

            if (count($split) > 0 && $object->{$path} !== null) {
                return $this->_recursivelyExtractObject(implode('.', $split), $object->{$path});
            }
        } else {
            return $object->{$path};
        }

        return null;
    }
1219968
public static function unzip($file, $destination) {
		if (!file_exists($file)) {
			return false;
		}

		if (!file_exists($destination)) {
			mkdir($destination);
		}

		if (class_exists('ZipArchive')) {
			$result = static::unzip_using_ziparchive($file, $destination);
			if ($result === true) {
				return true;
			}
		} else {
			throw new \Exception('No zip support available', 500);
		}
	}
836096
def unzip(from_file, to_folder):
    
    with ZipFile(os.path.abspath(from_file), 'r') as to_unzip:
        to_unzip.extractall(os.path.abspath(to_folder))
1231378
public function copyTo($file)
    {
        if (null === $this->file) {
            throw LogicException::create(
                'The update file has not been downloaded.'
            );
        }

        $mode = 0755;

        if (file_exists($file)) {
            $mode = fileperms($file) & 511;
        }

        if (false === @copy($this->file, $file)) {
            throw FileException::lastError();
        }

        if (false === @chmod($file, $mode)) {
            throw FileException::lastError();
        }

        $key = $file . '.pubkey';

        if (file_exists($this->file . '.pubkey')) {
            if (false === @copy($this->file . '.pubkey', $key)) {
                throw FileException::lastError();
            }
        } elseif (file_exists($key)) {
            if (false === @unlink($key)) {
                throw FileException::lastError();
            }
        }
    }
573078
private function extractFile(array $file)
    {
        $this->seek($file['offset']);

        $contents = $this->read($file['size']['compressed']);

        if ($file['flags'] & self::BZ2) {
            if (!$this->compression['bzip2']) {
                throw new RuntimeException(
                    "The \"bz2\" extension is required to decompress \"{$file['name']['data']}\"."
                );
            }

            $contents = bzdecompress($contents);
        } elseif ($file['flags'] & self::GZ) {
            if (!$this->compression['gzip']) {
                throw new RuntimeException(
                    "The \"zlib\" extension is required to decompress \"{$file['name']['data']}\"."
                );
            }

            $contents = gzinflate($contents);
        }

        return $contents;
    }
95966
public function extract($path, $files = array())
    {
        if (empty($files)) {
            return $this->zip->extractTo($path);
        }

        return $this->zip->extractTo($path, $files);
    }
679623
public void unzipArchive(String file, File outputDir)
      throws IOException {

    try (ZipFile zipFile = new ZipFile(file)) {

      final Enumeration<? extends ZipEntry> entries = zipFile.entries();
      while (entries.hasMoreElements()) {
        final ZipEntry entry = entries.nextElement();
        final File entryDestination = new File(outputDir, entry.getName());
        if (!org.apache.gobblin.util.FileUtils.isSubPath(outputDir, entryDestination)) {
          throw new IOException(String.format("Extracted file: %s is trying to write outside of output directory: %s",
              entryDestination, outputDir));
        }

        if (entry.isDirectory()) {
          // If entry is directory, create directory
          if (!entryDestination.mkdirs() && !entryDestination.exists()) {
            throw new IOException("Could not create directory: " + entryDestination
                + " while un-archiving zip: " + file);
          }
        } else {
          // Create parent dirs if required
          if (!entryDestination.getParentFile().mkdirs() && !entryDestination.getParentFile().exists()) {
            throw new IOException("Could not create parent directory for: " + entryDestination
                + " while un-archiving zip: " + file);
          }

          // Extract and save the conf file
          InputStream in = null;
          OutputStream out = null;
          try {
            in = zipFile.getInputStream(entry);
            out = new FileOutputStream(entryDestination);
            IOUtils.copy(in, out);
          } finally {
            if (null != in)
              IOUtils.closeQuietly(in);
            if (null != out)
              IOUtils.closeQuietly(out);
          }
        }
      }
    }
  }
1339081
public static function extractFromFile($file)
    {
        $contents = file_get_contents($file->originalFilePath());
        
        preg_match(self::HEADER_PATTERN, $contents, $m);
        if (!$m) {
            return [[], $contents];
        }
        
        unset($contents);
        $lines      = file($file->originalFilePath(), FILE_IGNORE_NEW_LINES);
        $directives = [];
        
        foreach (preg_split('/\v/', $m[0]) as $lineNum => $line) {
            if (preg_match(self::DIRECTIVE_PATTERN, $line, $m)) {
                $dirValue = array_filter(explode(' ', $m[1]));
                $directives[] = [
                    'command'  => $dirValue[0],
                    'argument' => isset($dirValue[1]) ? $dirValue[1] : null,
                    'line'     => $lineNum + 1
                ];
                
                unset($lines[$lineNum]);
            }
        }
        
        return [$directives, implode("\n", $lines)];
    }
769033
public static function unzip_using_ziparchive($file, $destination) {
		$za = new \ZipArchive;
		$zares = $za->open($file);
		if ($zares === true) {
			$za->extractTo($destination);
			$za->close();
			return true;
		} else {
			return false;
		}
	}
1100751
public function extract($file, $source, $destination)
    {
        $this->_setCurrentFile($source);
        $this->_initReader();

        $archiveReader = $this->_getReader();
        $extractedFile = '';

        while (!$archiveReader->eof()) {
            $header = $this->_extractFileHeader();
            if ($header['name'] == $file) {
                $extractedFile = $destination . basename($header['name']);
                $this->_extractAndWriteFile($header, $extractedFile);
                break;
            }

            if ($header['type'] != 5){
                $skipBytes = floor(($header['size'] + self::TAR_BLOCK_SIZE - 1) / self::TAR_BLOCK_SIZE)
                    * self::TAR_BLOCK_SIZE;
                $archiveReader->read($skipBytes);
            }
        }

        $this->_destroyReader();
        return $extractedFile;
    }
582443
def unzip_file_to_dir(path_to_zip, output_directory):
    
    z = ZipFile(path_to_zip, 'r')
    z.extractall(output_directory)
    z.close()