Sends generated zip file to the user
425494
protected function sendZipFile()
  {
    if (!function_exists('ob_list_handlers') || ob_list_handlers()) {
      @ob_end_clean();
    }
    header("Content-Encoding: none");

    $this->checkConnector();
    $this->checkRequest();

    // empty wystarczy
    if ( empty($_GET['FileName']) ){
      $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_FILE_NOT_FOUND);
    }

    $resourceTypeInfo = $this->_currentFolder->getResourceTypeConfig();
    $hash = $resourceTypeInfo->getHash();
    if ( $hash !== $_GET['hash'] || $hash !== substr($_GET['FileName'],16,16) ){
      $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_REQUEST);
    }

    if (!$this->_currentFolder->checkAcl(CKFINDER_CONNECTOR_ACL_FILE_VIEW)) {
      $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_UNAUTHORIZED);
    }

    $fileName = CKFinder_Connector_Utils_FileSystem::convertToFilesystemEncoding(trim($_GET['FileName']));

    if (!CKFinder_Connector_Utils_FileSystem::checkFileName($fileName)) {
      $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_REQUEST);
    }

    if ( strtolower(pathinfo($fileName, PATHINFO_EXTENSION)) !== 'zip'){
      $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_EXTENSION);
    }

    $dest_dir = CKFinder_Connector_Utils_FileSystem::getTmpDir();
    $filePath = CKFinder_Connector_Utils_FileSystem::combinePaths($dest_dir,$fileName);
    if ( !file_exists($filePath) || !is_file($filePath)) {
      $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_FILE_NOT_FOUND);
    }
    if (!is_readable($filePath)) {
      $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED);
    }

    $zipFileName = CKFinder_Connector_Utils_FileSystem::convertToFilesystemEncoding(trim($_GET['ZipName']));
    if (!CKFinder_Connector_Utils_FileSystem::checkFileName($zipFileName)) {
      $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_REQUEST);
    }
    $fileFilename = pathinfo($zipFileName,PATHINFO_BASENAME );

    header("Content-Encoding: none");
    header("Cache-Control: cache, must-revalidate");
    header("Pragma: public");
    header("Expires: 0");
    $user_agent = !empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : "";
    $encodedName = str_replace("\"", "\\\"", $fileFilename);
    if (strpos($user_agent, "MSIE") !== false) {
      $encodedName = str_replace(array("+", "%2E"), array(" ", "."), urlencode($encodedName));
    }
    header("Content-type: application/octet-stream; name=\"" . $fileFilename . "\"");
    header("Content-Disposition: attachment; filename=\"" . $encodedName. "\"");
    header("Content-Length: " . filesize($filePath));
    CKFinder_Connector_Utils_FileSystem::sendFile($filePath);
    exit;
  }
340378
def open(self):
        
        self.zf = zipfile.ZipFile(self.write_to_path, self.mode)
1030151
function createZip (targetZipPath, currentFolder, filesToInclude, done) {
  const args = ['-FS', targetZipPath].concat(filesToInclude)
  const startTime = Date.now()
  trace(`Calling: zip ${args.join(' ')}`)
  const child = childProcess.spawn('zip', args, {
    cwd: currentFolder,
    stdio: [ 'ignore', 'ignore', 'ignore' ]
  })
  child.on('error', (err) => {
    error(`Error: please verify that <zip> is installed on your system`)
    error(err.toString())
  })
  child.on('close', (code, signal) => {
    const elapsed = Math.floor(Date.now() - startTime)
    debug(`Zip exited with code ${code} in ${elapsed}ms`)
    done(code === 0 ? null : new Error(`Error creating ZIP file ${targetZipPath}`))
  })
}
450581
private static void processZipStream(File dir, InputStream inputStream) throws IOException
   {
      ZipInputStream zip = new ZipInputStream(inputStream);
      while (true)
      {
         ZipEntry entry = zip.getNextEntry();
         if (entry == null)
         {
            break;
         }

         File file = new File(dir, entry.getName());
         if (entry.isDirectory())
         {
            FileHelper.mkdirsQuietly(file);
            continue;
         }

         File parent = file.getParentFile();
         if (parent != null)
         {
            FileHelper.mkdirsQuietly(parent);
         }

         FileOutputStream fos = new FileOutputStream(file);
         byte[] bytes = new byte[1024];
         int length;
         while ((length = zip.read(bytes)) >= 0)
         {
            fos.write(bytes, 0, length);
         }
         fos.close();
      }
   }
287352
def __zip_file(self):
        """"""
        if self.zip_path:
            # If using a local file, just open it:
            self.__print('Opening local zipfile: %s' % self.zip_path)
            return open(self.zip_path, 'rb')

        # Otherwise, download it and make a file object in-memory:
        url = self.__release_url
        self.__print('Downloading from URL: %s' % url)
        response = urlopen(url)
        return io.BytesIO(response.read())
569545
def create_zip(archive, compression, cmd, verbosity, interactive, filenames):
    """"""
    try:
        with zipfile.ZipFile(archive, 'w') as zfile:
            for filename in filenames:
                if os.path.isdir(filename):
                    write_directory(zfile, filename)
                else:
                    zfile.write(filename)
    except Exception as err:
        msg = "error creating %s: %s" % (archive, err)
        raise util.PatoolError(msg)
    return None
1207118
def _to_zipfile(self, file_generator):
        
        with zipfile.ZipFile(file_generator.to_path, mode="w", compression=zipfile.ZIP_DEFLATED) as outfile:
            for f in file_generator:
                outpath = self._output_path(f.source, file_generator.to_format, archive=True)
                outfile.writestr(outpath, f.writestr(file_generator.to_format))
902825
def create_zip_from_folder(zip_file, fldr, mode="r"):
    
    #print('zip from folder - adding folder : ', fldr)
    zipf = zipfile.ZipFile(zip_file, 'w')
    for root, dirs, files in os.walk(fldr):
        for file in files:
            fullname = os.path.join(root, file)
            #print('zip - adding file : ', fullname)
            zipf.write(fullname)
    
    
    zipf.close()
1080942
function downloadZip($fileName, $contentType = "application/zip")
    {
        if (!$this->isFinalized) {
            $this->finalize();
        }

        $headerFile = null;
        $headerLine = null;
        if (!headers_sent($headerFile, $headerLine)) {
            if ((ob_get_contents() === FALSE || ob_get_contents() == '') or die("\n<p><strong>Error:</strong> Unable to send file <strong>$fileName.epub</strong>. Output buffer contains the following text (typically warnings or errors):<br>" . ob_get_contents() . "</p>")) {
                if (ini_get('zlib.output_compression')) {
                    ini_set('zlib.output_compression', 'Off');
                }

                header("Pragma: public");
                header("Last-Modified: " . gmdate("D, d M Y H:i:s T"));
                header("Expires: 0");
                header("Accept-Ranges: bytes");
                header("Connection: close");
                header("Content-Type: " . $contentType);
                header('Content-Disposition: attachment; filename="' . $fileName . '";');
                header("Content-Transfer-Encoding: binary");
                header("Content-Length: " . $this->getArchiveSize());

                if (!is_resource($this->zipFile)) {
                    echo $this->zipData;
                } else {
                    rewind($this->zipFile);

                    while (!feof($this->zipFile)) {
                        echo fread($this->zipFile, $this->streamChunkSize);
                    }
                }
            }
            return TRUE;
        }
        return FALSE;
    }
1213815
def save(output_path)
      output_path = File.expand_path(output_path)

      create_epub do
        mimetype = Zip::ZipOutputStream::open(output_path) do |os|
          os.put_next_entry("mimetype", nil, nil, Zip::ZipEntry::STORED, Zlib::NO_COMPRESSION)
          os << "application/epub+zip"
        end
        zipfile = Zip::ZipFile.open(output_path)
        Dir.glob('**/*').each do |path|
          zipfile.add(path, path)
        end
        zipfile.commit
      end
      FileUtils.remove_entry_secure dir
    end
1283612
def _comic_archive_write_zipfile(new_filename, tmp_dir):
    """"""
    if Settings.verbose:
        print('Rezipping archive', end='')
    with zipfile.ZipFile(new_filename, 'w',
                         compression=zipfile.ZIP_DEFLATED) as new_zf:
        root_len = len(os.path.abspath(tmp_dir))
        for r_d_f in os.walk(tmp_dir):
            root = r_d_f[0]
            filenames = r_d_f[2]
            archive_root = os.path.abspath(root)[root_len:]
            for fname in filenames:
                fullpath = os.path.join(root, fname)
                archive_name = os.path.join(archive_root, fname)
                if Settings.verbose:
                    print('.', end='')
                new_zf.write(fullpath, archive_name, zipfile.ZIP_DEFLATED)
1237455
def zip_file(self, app_path, app_name, tmp_path):
        
        # zip build directory
        zip_file = os.path.join(app_path, self.args.outdir, app_name)
        zip_file_zip = '{}.zip'.format(zip_file)
        zip_file_tcx = '{}.tcx'.format(zip_file)
        shutil.make_archive(zip_file, 'zip', tmp_path, app_name)
        shutil.move(zip_file_zip, zip_file_tcx)
        self._app_packages.append(zip_file_tcx)
        # update package data
        self.package_data['package'].append({'action': 'App Package:', 'output': zip_file_tcx})
641253
function zip(contentsZip, publicKey, signature) {
  debug(`zip(): start`);
  return new Promise((res, rej) => {
    const output = new streamBuffers.WritableStreamBuffer();
    const zipFile = new ZipFile();
    output.on("finish", () => {
      debug(`zip(): output finish event`);
      res(output.getContents());
    });
    zipFile.outputStream.pipe(output);
    zipFile.addBuffer(contentsZip, "contents.zip");
    zipFile.addBuffer(publicKey, "PUBKEY");
    zipFile.addBuffer(signature, "SIGNATURE");
    zipFile.end(finalSize => {
      debug(`zip(): ZipFile end event: finalSize ${finalSize} bytes`);
    });
  });
}
1003925
def send_file(resource, env)
      file     = ::Rack::File.new nil
      path     = resource.file_descriptor[:full_path]
      if !file.respond_to?(:path=)
        request  = ::Rack::Request.new(env)
        response = file.serving(request, path)
      else
        file.path = path
        response = file.serving(env)
      end
      status = response[0]
      response[1]['Content-Encoding'] = 'gzip' if %w[.svgz .gz].include?(resource.ext)
      # Do not set Content-Type if status is 1xx, 204, 205 or 304, otherwise
      # Rack will throw an error (500)
      if !(100..199).cover?(status) && ![204, 205, 304].include?(status)
        response[1]['Content-Type'] = resource.content_type || (resource.binary? ? 'application/octet-stream' : 'text/plain')
      end

      halt response
    end
626979
function zip_put_byte(c) {
  zip_outbuf[zip_outoff + zip_outcnt++] = c;
  if (zip_outoff + zip_outcnt == zip_OUTBUFSIZ) { zip_qoutbuf(); }
}
1359888
public function zip()
    {

        if (empty($this->filepath)) {
            throw(new \Exception("Must set \sb\Email\Attachment::file_path before zipping attachment"));
        }

        if (empty($this->name)) {
            $this->name = basename($this->filepath);
        }

        $zip = new \ZipArchive();
        $zipfile_path = \ROOT . "/private/cache/compression/" . md5(microtime(true)) . '_' . $this->name . ".zip";
        $zip_dir = dirname($zipfile_path);
        if (!is_dir($zip_dir) && !@mkdir($zip_dir, 0755, true)) {
            throw(new \Exception("Cannot create /private/cache/compression directory\n"));
        }

        if ($zip->open($zipfile_path, \ZIPARCHIVE::CREATE) !== true) {
            throw(new \Exception("Cannot open <$zipfile_path>\n"));
        }

        $zip->addFromString($this->name, \file_get_contents($this->filepath));

        $zip->close();

        $this->name .= '.zip';

        //this is the content, in this case I am ready the blob data from a saved image file but you could easily replace this with blob data from a database.  The mime type will be added based on the extension using \sb\Files::extensionToMime.  For bizarre mime-types that are not in \sb\Files::extensionToMime you can override this by setting the mime-type manually $myAttachment->mime_type ='bizarre/weird';
        $this->contents = \file_get_contents($zipfile_path);

        //remove the tmp zip file
        \unlink($zipfile_path);

        //add mime type for zip files, \sb\Files should handle this after 1.41
        $this->mime_type = 'application/x-zip-compressed';
    }
373744
public static void zipDir(File zipFile, File dirObj) throws Exception {
        // File dirObj = new File(dir);
        if (!dirObj.isDirectory()) {
            System.err.println(dirObj.getName() + " is not a directory");
            System.exit(1);
        }

        try {

            ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
                    zipFile));

            System.out.println("Creating : " + zipFile);

            addDir(dirObj, out);
            // Complete the ZIP file
            out.close();

        } catch (IOException e) {
            throw new Exception(e.getMessage());
        }

    }