Unzip a given ZIP file into the web resources directory.

@param Workspace $workspace
@param File      $file
@param string    $hashName  name of the destination directory
775590
public function unzipScormArchive(Workspace $workspace, File $file, $hashName)
    {
        $zip = new \ZipArchive();
        $zip->open($file);
        $ds = DIRECTORY_SEPARATOR;
        $destinationDir = $this->uploadDir.$ds.'scorm'.$ds.$workspace->getUuid().$ds.$hashName;

        if (!file_exists($destinationDir)) {
            mkdir($destinationDir, 0777, true);
        }

        $zip->extractTo($destinationDir);
        $zip->close();
    }
270056
public function removeNodesWithInvalidDimensions($workspaceName)
    {
        $this->dispatch(self::EVENT_NOTICE, 'Checking for nodes with invalid dimensions ...');

        $allowedDimensionCombinations = $this->contentDimensionCombinator->getAllAllowedCombinations();
        $nodesArray = $this->collectNodesWithInvalidDimensions($workspaceName, $allowedDimensionCombinations);
        if ($nodesArray === []) {
            return;
        }
        $numberOfNodes = count($nodesArray);
        $taskDescription = sprintf('Remove <i>%d</i> node%s with invalid dimension values', $numberOfNodes, $numberOfNodes > 1 ? 's' : '');
        $taskClosure = function () use ($nodesArray) {
            foreach ($nodesArray as $nodeArray) {
                $this->removeNode($nodeArray['identifier'], $nodeArray['dimensionsHash']);
            }
        };
        $taskRequiresConfirmation = true;
        $this->dispatch(self::EVENT_TASK, $taskDescription, $taskClosure, $taskRequiresConfirmation);
    }
166429
private void zipFiles(final File file, ZipOutputStream zos) throws IOException
	{
		if (file.isDirectory())
		{
			File[] fList;
			List<File> foundedFiles;
			if (null != this.fileFilter)
			{
				final File[] tmpfList = file.listFiles(this.fileFilter);
				final List<File> foundedDirs = FileSearchExtensions.listDirs(file);
				if (0 < foundedDirs.size())
				{
					final List<File> tmp = Arrays.asList(tmpfList);
					foundedDirs.addAll(tmp);
					foundedFiles = foundedDirs;
				}
				else
				{
					final List<File> tmp = Arrays.asList(tmpfList);
					foundedFiles = tmp;
				}
			}
			else
			{
				fList = file.listFiles();
				final List<File> tmp = Arrays.asList(fList);
				foundedFiles = tmp;
			}
			for (final File foundedFile : foundedFiles)
			{
				this.zipFiles(foundedFile, zos);
			}
		}
		else
		{
			this.fileLength += file.length();
			this.fileCounter++;
			final String absolutePath = file.getAbsolutePath();
			if (this.dirToStart == null)
			{
				this.dirToStart = this.directoryToZip.getName();
			}
			final int index = absolutePath.indexOf(this.dirToStart);
			final String zipEntryName = absolutePath.substring(index, absolutePath.length());
			final byte[] b = new byte[(int)file.length()];
			final ZipEntry cpZipEntry = new ZipEntry(zipEntryName);
			zos.putNextEntry(cpZipEntry);
			zos.write(b, 0, (int)file.length());
			zos.closeEntry();
		}
	}
701163
function removeFileNameHash( fileName ) {
  return fileName
    .replace( appBuild, '' )
    .replace( /\/?(.*)(\.\w+)(\.js|\.css)/, ( match_, p1, p2_, p3 ) => p1 + p3 );
}
247842
public function delete(string $namespace, string $hash): void
    {
        $fileName = $this->getFileName($namespace, $hash);
        if (file_exists($fileName)) {
            unlink($fileName);
        }
    }
361735
@Override
    public void delete(final String fileName) throws FileMissingException, IOException {

        // This prevents other read/write/delete/merge/purge operations to occur
        this.lock.writeLock().lock();

        try {
            // Check active flag
            Preconditions.checkState(this.active.get());

            // Lookup the zip file / deleted status for the supplied file
            final String zipName = indexGet(fileName);

            // Proceed only if file is not marked as deleted
            if (!DELETED.equals(zipName)) {
                if (zipName != null) {

                    // Explode the ZIP file (except for the deleted file)
                    final Map<String, String> entries = new HashMap<>();
                    final Path zipPath = pathForZipFile(zipName);
                    LOGGER.debug("Exploding zip file {}", zipPath);
                    try (final ZipInputStream zipStream = new ZipInputStream(openForRead(zipPath))) {
                        ZipEntry entry;
                        while ((entry = zipStream.getNextEntry()) != null) {
                            final String smallName = entry.getName();
                            if (!smallName.equals(fileName)) {
                                entries.put(smallName, null);
                                final Path smallPath = pathForSmallFile(smallName);
                                // note: small file may already exist (as previously packed in ZIP
                                // file but not yet purged): in this case it is silently
                                // overwritten
                                try (OutputStream stream = openForWrite(smallPath)) {
                                    ByteStreams.copy(zipStream, stream);
                                }
                            }
                        }
                    } catch (final IOException ex) {
                        // Perform clean up and propagate exception
                        for (final String smallName : entries.keySet()) {
                            final Path smallPath = pathForSmallFile(smallName);
                            try {
                                this.fileSystem.delete(smallPath, false);
                            } catch (final Throwable ex2) {
                                LOGGER.warn("Could not delete extracted file " + smallPath
                                        + " after failed to explod ZIP file " + zipPath, ex2);
                            }
                        }
                        throw new IOException("Cannot explode ZIP file " + zipPath, ex);
                    }

                    // Update index, marking small file and ZIP as deleted and de-associating
                    // other small files previously in the ZIP from the ZIP file
                    entries.put(fileName, DELETED); // because the file may still exist
                    entries.put(zipName, DELETED);
                    indexPut(entries);
                    return;

                } else {
                    // Mark a small file with the name supplied as deleted
                    final Path smallPath = pathForSmallFile(fileName);
                    if (this.fileSystem.exists(smallPath)) {
                        LOGGER.debug("Marking small file {} as deleted", smallPath);
                        indexPut(ImmutableMap.of(fileName, DELETED));
                        return;
                    }
                }
            }

            // Report file does not exist
            throw new FileMissingException(fileName, "The file does not exist");

        } finally {
            // Always release the lock
            this.lock.writeLock().unlock();
        }
    }
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);
                    });
                }
            });
        }
    });
}
469907
public function checkEnoughStorageSpaceLeft(Workspace $workspace, \SplFileInfo $file)
    {
        $workspaceManager = $this->container->get('claroline.manager.workspace_manager');
        $workspaceDir = $workspaceManager->getStorageDirectory($workspace);
        $fileSize = filesize($file);
        $allowedMaxSize = $this->ut->getRealFileSize($workspace->getMaxStorageSize());
        $currentStorage = $this->ut->getRealFileSize($workspaceManager->getUsedStorage($workspace));

        return ($currentStorage + $fileSize > $allowedMaxSize) ? false: true;
    }
652578
public function deleteWorkspace(Workspace $workspace)
    {
        $this->om->startFlushSuite();
        $root = $this->resourceManager->getWorkspaceRoot($workspace);
        $this->log('Removing root directory ' . $root->getName() . '[id:' . $root->getId() . ']');

        if ($root) {
            $children = $root->getChildren();
            $this->log('Looping through ' . count($children) . ' children...');

            if ($children) {
                foreach ($children as $node) {
                    $this->resourceManager->delete($node);
                }
            }
        }
        $this->dispatcher->dispatch(
            'claroline_workspaces_delete',
            'GenericDatas',
            array(array($workspace))
        );
        $this->om->remove($workspace);
        $this->om->endFlushSuite();
    }
200068
private FileSystem newZipFileSystem(final File file) throws IOException {

        final Map<String, String> env = new HashMap<>();
        env.put("create", "true");
        return newFileSystem(URI.create("jar:" + file.toURI()), env);
    }
271493
def unzip(filename):
        
        with zipfile.ZipFile(filename, "r") as zip_ref:
            zip_ref.extractall(Spark.svm_path())
        return True
661646
function unzipWorker(unzipTask, workerCb) {
  var zipfile = unzipTask.zipfile;
  var entry = unzipTask.entry;
  var workingDir = unzipTask.workingDir;
  if (/\/$/.test(entry.fileName)) {
    // directory file names end with '/'
    makeExportDirectory({
      entry: entry,
      zipfile: zipfile,
      workingDir: workingDir
    }, workerCb);
  } else {
    // file entry
    streamFileEntry({
      zipfile: zipfile,
      entry: entry,
      workingDir: workingDir
    }, workerCb);
  }
}
736750
def _hash_the_file(hasher, filename):
    
    BUF_SIZE = 65536
    with open(filename, 'rb') as f:
        buf = f.read(BUF_SIZE)
        while len(buf) > 0:
            hasher.update(buf)
            buf = f.read(BUF_SIZE)
    return hasher
508540
public function newFileFromName($path, $name, $hashName = false){
        $info = pathinfo($name);
        $ext = isset($info['extension'])? ".{$info['extension']}":"";
        $name = $info['filename'];
        $n = $hashName?md5($name):$name;
        $file = new FileImpl("$path/$n$ext");
        $i = 0;
        while($file->exists()){
            $i++;
            $n = $hashName?md5($name.$i):"$name ($i)";
            $file = new FileImpl("$path/$n$ext");
        }
        return $file;

    }
735611
def _unzip_file(self, zip_file, out_folder):
        
        try:
            zf = zipfile.ZipFile(zip_file, 'r')
            zf.extractall(path=out_folder)
            zf.close()
            del zf
            return True
        except:
            return False
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);
					}
				}
			}
		}
	}
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);
          }
        }
      }
    }
  }