Filter archive files based on an "ignore" list.

@param  ZipArchive $archive
@param  array      $ignore
@param  array      $force
@return array
343065
protected function filterZipFiles(ZipArchive $archive, array $ignore = [], array $force = [])
    {
        $dirName = $archive->getNameIndex(0);
        $return = [];
        $numFiles = $archive->getNumFiles();
        for ($i = 0; $i < $numFiles; ++$i) {
            $stat = $archive->statIndex($i);
            $return[] = $stat['name'];
        }
        $that = $this;
        $filter = array_filter($return, function ($var) use ($ignore, $force, $dirName, $that) {
            return !$that->isIgnored($var, $ignore, $force, $dirName);
        });

        return array_values($filter);
    }
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);
	}
1151902
public function ignore($ignore)
    {
        if (!is_array($ignore)) {
            $ignore = [$ignore];
        }
        $this->ignore = array_unique(array_merge($this->ignore, $ignore));

        return $this;
    }
1064057
def purge(self, ignore_ignores):
        """"""
        command = ['status', '--xml']
        if ignore_ignores:
            command.append('--no-ignore')
        d = self._dovccmd(command, collectStdout=True)

        @d.addCallback
        def parseAndRemove(stdout):
            files = []
            for filename in self.getUnversionedFiles(stdout, self.keep_on_purge):
                filename = self.build.path_module.join(self.workdir, filename)
                files.append(filename)
            if not files:
                d = defer.succeed(0)
            else:
                if self.workerVersionIsOlderThan('rmdir', '2.14'):
                    d = self.removeFiles(files)
                else:
                    d = self.runRmdir(files, abandonOnFailure=False, timeout=self.timeout)
            return d

        @d.addCallback
        def evaluateCommand(rc):
            if rc != 0:
                log.msg("Failed removing files")
                raise buildstep.BuildStepFailed()
            return rc
        return d
98810
private function ignoreItem($type, $name, $ignore)
    {
        if ($type == 'file' && in_array(pathinfo($name, PATHINFO_EXTENSION), $ignore)) {
            return true;
        } elseif ($type == 'dir' && in_array($name, $ignore)) {
            return true;
        }
        return false;
    }
840547
protected function findRepositoryRoot(\ZipArchive $archive)
    {
        // Find root directory in zip file.
        $count    = $archive->numFiles;
        $rootFile = $archive->statIndex(0);
        $root     = $rootFile['name'];
        for ($i = 1; $i < $count; ++$i) {
            $file = $archive->statIndex($i);
            $root = $this->commonStartString($root, $file['name']);
        }

        return $root;
    }
187968
public List<File> getInactiveHistory() throws PatchingException {
        if (validHistory == null) {
            walk();
        }
        final File[] inactiveDirs = installedIdentity.getInstalledImage().getPatchesDir().listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                return pathname.isDirectory() && !validHistory.contains(pathname.getName());
            }
        });
        return inactiveDirs == null ? Collections.<File>emptyList() : Arrays.asList(inactiveDirs);
    }
908917
private void handleArchiveByFile(Predicate<String> filter, File archive, List<String> discoveredFiles)
    {
        try
        {
            try (ZipFile zip = new ZipFile(archive))
            {
                Enumeration<? extends ZipEntry> entries = zip.entries();
                
                while (entries.hasMoreElements())
                {
                    ZipEntry entry = entries.nextElement();
                    String name = entry.getName();
                    if (filter.accept(name))
                        discoveredFiles.add(name);
                }
            }
        }
        catch (IOException e)
        {
            throw new RuntimeException("Error handling file " + archive, e);
        }
    }
1240439
public function copyFiles($extension, Dir $destination, $flat = FALSE, Array $ignores = NULL) {
    foreach ($this->getFiles($extension, $ignores, $flat) as $f) {
      $f->copy(new File($destination, $f->getName()));
    }
    return $this;
  }
61754
def get_archives_to_prune(archives, hook_data):
    """"""
    files_to_skip = []
    for i in ['current_archive_filename', 'old_archive_filename']:
        if hook_data.get(i):
            files_to_skip.append(hook_data[i])
    archives.sort(key=itemgetter('LastModified'),
                  reverse=False)  # sort from oldest to newest
    # Drop all but last 15 files
    return [i['Key'] for i in archives[:-15] if i['Key'] not in files_to_skip]
1291941
public function create($archive, $files)
	{
		$contents = array();
		$ctrldir = array();

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

		return $this->createZIPFile($contents, $ctrldir, $archive);
	}
691754
private void removeOldLogs()
  {
    try {
      Path path = getPath();
      Path parent = path.getParent();

      ArrayList<String> matchList = new ArrayList<String>();

      Pattern archiveRegexp = getArchiveRegexp();
      Files.list(parent).forEach(child->{
        String subPath = child.getFileName().toString();
        
        Matcher matcher = archiveRegexp.matcher(subPath);

        if (matcher.matches())
          matchList.add(subPath);
      });

      Collections.sort(matchList);

      if (_rolloverCount <= 0 || matchList.size() < _rolloverCount)
        return;

      for (int i = 0; i + _rolloverCount < matchList.size(); i++) {
        try {
          Files.delete(parent.resolve(matchList.get(i)));
        } catch (Throwable e) {
        }
      }
    } catch (Throwable e) {
    }
  }
1294819
public function download(array $elements, $forceArchive = false)
    {
        $data = [];

        if (0 === count($elements)) {
            throw new ExportResourceException('No resources were selected.');
        }

        $pathArch = $this->container->get('claroline.manager.temp_file')->generate();

        $archive = new \ZipArchive();
        $archive->open($pathArch, \ZipArchive::CREATE);

        $nodes = $this->expandResources($elements);
        if (!$forceArchive && 1 === count($nodes)) {
            $event = $this->dispatcher->dispatch(
                "download_{$nodes[0]->getResourceType()->getName()}",
                'Resource\DownloadResource',
                [$this->getResourceFromNode($this->getRealTarget($nodes[0]))]
            );
            $extension = $event->getExtension();
            $hasExtension = '' !== pathinfo($nodes[0]->getName(), PATHINFO_EXTENSION);

            $extGuesser = ExtensionGuesser::getInstance();
            $mimeGuesser = MimeTypeGuesser::getInstance();

            if (!$hasExtension) {
                $extension = $extGuesser->guess($nodes[0]->getMimeType());
            }

            $data['name'] = $hasExtension ?
                $nodes[0]->getName() :
                $nodes[0]->getName().'.'.$extension;
            $data['file'] = $event->getItem();
            $data['mimeType'] = $nodes[0]->getMimeType() ? $nodes[0]->getMimeType() : $mimeGuesser->guess($extension);

            return $data;
        }

        if (isset($elements[0])) {
            $currentDir = $elements[0];
        } else {
            $archive->addEmptyDir($elements[0]->getName());
        }

        foreach ($nodes as $node) {
            //we only download is we can...
            if ($this->container->get('security.authorization_checker')->isGranted('EXPORT', $node)) {
                $resource = $this->getResourceFromNode($node);

                if ($resource) {
                    $filename = $this->getRelativePath($currentDir, $node).$node->getName();
                    $resource = $this->getResourceFromNode($node);

                    //if it's a file, we may have to add the extension back in case someone removed it from the name
                    if ('file' === $node->getResourceType()->getName()) {
                        $extension = '.'.pathinfo($resource->getHashName(), PATHINFO_EXTENSION);
                        if (!preg_match("#$extension#", $filename)) {
                            $filename .= $extension;
                        }
                    }

                    if ('directory' !== $node->getResourceType()->getName()) {
                        $event = $this->dispatcher->dispatch(
                            "download_{$node->getResourceType()->getName()}",
                            'Resource\DownloadResource',
                            [$resource]
                        );

                        $obj = $event->getItem();

                        if (null !== $obj) {
                            $archive->addFile($obj, iconv($this->ut->detectEncoding($filename), $this->getEncoding(), $filename));
                        } else {
                            $archive->addFromString(iconv($this->ut->detectEncoding($filename), $this->getEncoding(), $filename), '');
                        }
                    } else {
                        $archive->addEmptyDir(iconv($this->ut->detectEncoding($filename), $this->getEncoding(), $filename));
                    }

                    $this->dispatcher->dispatch('log', 'Log\LogResourceExport', [$node]);
                }
            }
        }

        $archive->close();

        $data['name'] = 'archive.zip';
        $data['file'] = $pathArch;
        $data['mimeType'] = 'application/zip';

        return $data;
    }
351120
public function compareArchive(array $unexpectedArtifacts)
    {
        $foundUnexpectedArtifacts = [];
        $archive = new PharData($this->getFilename());
        $hasLicenseFile = false;

        foreach ($archive as $archiveFile) {
            if ($archiveFile instanceof \SplFileInfo) {
                if ($archiveFile->isDir()) {
                    $file = basename($archiveFile) . '/';
                    if (in_array($file, $unexpectedArtifacts)) {
                        $foundUnexpectedArtifacts[] = $file;
                    }
                    continue;
                }

                $file = basename($archiveFile);
                if ($this->validateLicenseFilePresence()) {
                    if (preg_match('/(License.*)/i', $file)) {
                        $hasLicenseFile = true;
                    }
                }

                if (in_array($file, $unexpectedArtifacts)) {
                    $foundUnexpectedArtifacts[] = $file;
                }
            }
        }

        if ($this->validateLicenseFilePresence() && $hasLicenseFile === false) {
            throw new NoLicenseFilePresent('No license file present in archive.');
        }

        sort($foundUnexpectedArtifacts, SORT_STRING | SORT_FLAG_CASE);

        return $foundUnexpectedArtifacts;
    }
669952
public static function getAllZipNames(ZipArchive $zipArchive)
    {
        $i = 0;
        $entries = [];

        while (($entryName = $zipArchive->getNameIndex($i)) || ($statIndex = $zipArchive->statIndex($i,ZipArchive::FL_UNCHANGED))) {
            if ($entryName) {
                $entries[] = $entryName;
            }

            $i++;
        }

        return $entries;
    }
835362
public function ignoreDotFiles($ignoreDotFiles)
    {
        if ($ignoreDotFiles) {
            $this->ignore |= static::IGNORE_DOT_FILES;
        } else {
            $this->ignore &= ~static::IGNORE_DOT_FILES;
        }

        return $this;
    }
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;
    }