/** * Zip a file, or entire directory recursively. * * @param string $source directory or file name * @param string $destinationPathAndFilename full path to output * @throws App_File_Zip_Exception * @return boolean whether zip was a success */ public static function CreateFromFilesystem($source, $destinationPathAndFilename) { $base = realpath(dirname($destinationPathAndFilename)); if (!is_writable($base)) { throw new App_File_Zip_Exception('Destination must be writable directory.'); } if (!is_dir($base)) { throw new App_File_Zip_Exception('Destination must be a writable directory.'); } if (!file_exists($source)) { throw new App_File_Zip_Exception('Source doesnt exist in location: ' . $source); } $source = realpath($source); if (!extension_loaded('zip') || !file_exists($source)) { return false; } $zip = new ZipArchive(); $zip->open($destinationPathAndFilename, ZipArchive::CREATE); if (is_dir($source) === true) { $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST); $baseName = realpath($source); foreach ($files as $file) { if (in_array(substr($file, strrpos($file, DIRECTORY_SEPARATOR) + 1), array('.', '..'))) { continue; } $relative = substr($file, strlen($baseName)); if (is_dir($file) === true) { // Add directory $added = $zip->addEmptyDir(trim($relative, "\\/")); if (!$added) { throw new App_File_Zip_Exception('Unable to add directory named: ' . trim($relative, "\\/")); } } else { if (is_file($file) === true) { // Add file $added = $zip->addFromString(trim($relative, "\\/"), file_get_contents($file)); if (!$added) { throw new App_File_Zip_Exception('Unable to add file named: ' . trim($relative, "\\/")); } } } } } else { if (is_file($source) === true) { // Add file $added = $zip->addFromString(trim(basename($source), "\\/"), file_get_contents($source)); if (!$added) { throw new App_File_Zip_Exception('Unable to add file named: ' . trim($relative, "\\/")); } } else { throw new App_File_Zip_Exception('Source must be a directory or a file.'); } } $zip->setArchiveComment('Created with App_Framework'); return $zip->close(); }
/** * @test */ public function createZipArchive() { $zip = new ZipArchive(); $this->assertTrue($zip->open(vfsStream::url('root/test.zip'), ZIPARCHIVE::CREATE)); $this->assertTrue($zip->addFromString("testfile1.txt", "#1 This is a test string added as testfile1.txt.\n")); $this->assertTrue($zip->addFromString("testfile2.txt", "#2 This is a test string added as testfile2.txt.\n")); $zip->setArchiveComment('a test'); var_dump($zip); $this->assertTrue($zip->close()); var_dump($zip->getStatusString()); var_dump($zip->close()); var_dump($zip->getStatusString()); var_dump($zip); var_dump(file_exists(vfsStream::url('root/test.zip'))); }
/** * Add a comment to archive or file. * @param string $mixed * @param $comment * @return bool @params mixed, string $mixed : comment by index(int), name(string), entire archive ('archive') */ function setComment($mixed = 'archive', $comment = null) { if (is_array($mixed)) { foreach ($mixed as $key => $value) { $constant = is_string($value) ? 'Name' : 'Index'; if (!$this->zip->{'setComment' . $constant}($key, $value)) { return false; } } } else { if (strtolower($mixed) === 'archive') { return $this->zip->setArchiveComment($comment); } else { $constant = is_string($mixed) ? 'Name' : 'Index'; return $this->zip->{'setComment' . $constant}($mixed, $comment); } } return true; }
/** * Creates a zip archive of the files in the $filename_ar array and * returns the path/name of the archive or FALSE on error * * @param array $parameters array for file type from csv_parameters * @param array $filename_ar filenames to be archived * @param string $archive_date date of archive to be incorporated in archive file name * @return mixed either the name of the zip archive or FALSE in case or error */ function csv_zip_dir($parameters, $filename_ar, $archive_date) { // we deal with possible maximum files issues by chunking the $fn_ar array //$ulim = array(); //exec("ulimit -a | grep 'open files'", $ulim); open files (-n) 1024 // $f_max = 200; $fn_ar2 = array(); if (count($filename_ar) > $f_max) { $fn_ar2 = array_chunk($filename_ar, $f_max); } else { $fn_ar2[] = $filename_ar; } // $zpath = csv_edih_basedir(); $ztemp = csv_edih_tmpdir(); $zip_name = $zpath . DIRECTORY_SEPARATOR . "archive" . DIRECTORY_SEPARATOR . $type . "_{$archive_date}.zip"; $ftmpn = $ztemp . DIRECTORY_SEPARATOR; $fdir = $parameters['directory'] . DIRECTORY_SEPARATOR; $type = $parameters['type']; // $zip_obj = new ZipArchive(); // foreach ($fn_ar2 as $fnz) { // reopen the zip archive on each loop so the open file count is controlled if (is_file($zip_name)) { $isOK = $zip_obj->open($zip_name, ZIPARCHIVE::CHECKCONS); $isNew = FALSE; } else { $isOK = $zip_obj->open($zip_name, ZIPARCHIVE::CREATE); $isNew = $isOK; } // if ($isOK && $isNew) { $zip_obj->addEmptyDir($type); $zip_obj->setArchiveComment("archive " . $fdir . "prior to {$archive_date}"); } // if ($isOK) { // we are working with the open archive // now add the files to the archive foreach ($fnz as $fz) { if (is_file($fdir . $fz)) { $iscp = copy($fdir . $fz, $ftmpn . $fz); $isOK = $zip_obj->addFile($ftmpn . $fz, $type . DIRECTORY_SEPARATOR . $fz); } else { csv_edihist_log("csv_zip_dir: in record, but not in directory {$fz} "); // possible that file is in csv table, but not in directory? } // if ($isOK && $iscp) { // if we have added the file to the archive, remove it from the storage directory // but keep the /tmp file copy for now unlink($fdir . $fz); } else { $msg = $zip_obj->getStatusString(); csv_edihist_log("csv_zip_dir: {$type} ZipArchive failed for {$fz} {$msg}"); } } // end foreach } else { // ZipArchive open() failed -- try to get the error message and return false $msg = $zip_obj->getStatusString(); csv_edihist_log("csv_zip_dir: {$type} ZipArchive open() failed {$msg}"); return $isOK; } // // errors on close would be non-existing file added or something else $isOK = $zip_obj->close($zip_name); if (!$isOK) { $msg = $zip_obj->getStatusString(); csv_edihist_log("csv_zip_dir: {$type} ZipArchive close() error for {$fz} {$msg}"); // return $isOK; } } // end foreach($fn_ar2 as $fnz) // return $isOK ? $zip_name : $isOK; }
} $zipinfo = '{ "appID":"cbzget/001", "lastModified":"' . date("Y-m-d h:i:s O") . '", "ComicBookInfo/1.0":{ "title":"' . $page_title . '", "series":"' . $original_url->host . '", "publisher":"' . $original_url . '", "url":"' . $original_url . '", "publicationYear":' . date('Y') . ', "publicationMonth":' . date('n') . ', "tags":["Downloads"] }}'; $zip->addFromString("ZipInfo.txt", $zipinfo); $zip->addFromString("manifest.txt", $manifest); $zip->setArchiveComment($zipinfo); $zip->close(); print_log("Created zip file '{$zipfilename}'"); print_log("numfiles: {$zip->numFiles}, size: " . format_bytes(filesize($zipfilename))); } else { print_log("No valid files retrieved. With no contents to bundle, I'm going to skip creating that zip file for you."); } // Clean up rrmdir($dirname); /////////////////////////////////////////////////////////////////////// /** * A list of domains to ignore. * These are domains that often look like image thumbnails - * An img icon with a link around it is indistinguishable from a thumbnail * linking to a gallery page - until you visit it. */
function set_comment($zip_file, $comment) { //Use ZipArchive if available if (in_array('ziparchive', $this->_zip_methods)) { // Make doubly sure it is available if (class_exists('ZipArchive', false)) { $za = new ZipArchive(); $result = $za->open($zip_file); // Make sure at least the zip file opened ok if ($result === true) { // Set the comment - true on success, false on failure $result = $za->setArchiveComment($comment); $za->close(); // If we got back true then all is well with the world if ($result === true) { pb_backupbuddy::status('details', sprintf(__('ZipArchive set comment in file %1$s', 'it-l10n-backupbuddy'), $zip_file)); return true; } else { // If we failed to set the commnent then log it (?) and drop through pb_backupbuddy::status('details', sprintf(__('ZipArchive failed to set comment in file %1$s', 'it-l10n-backupbuddy'), $zip_file)); } } else { // If we couldn't open the zip file then log it (?) and drop through $error_string = $this->ziparchive_error_info($result); pb_backupbuddy::status('details', sprintf(__('ZipArchive failed to open file to set comment in file %1$s - Error Info: %2$s', 'it-l10n-backupbuddy'), $zip_file, $error_string)); } } else { // Something fishy - the methods indicated ziparchive but we couldn't find the class pb_backupbuddy::status('details', __('ziparchive indicated as available method but ZipArchive class non-existent', 'it-l10n-backupbuddy')); } } // Dropped through because ZipArchive not available or failed for some reason if (in_array('pclzip', $this->_zip_methods)) { // Make sure we have it if (!class_exists('PclZip', false)) { // It's not already loaded so try and find/load it from possible locations if (file_exists(ABSPATH . 'wp-admin/includes/class-pclzip.php')) { // Running under WordPress @(include_once ABSPATH . 'wp-admin/includes/class-pclzip.php'); } elseif (file_exists(pb_backupbuddy::plugin_path() . '/lib/pclzip/pclzip.php')) { // Running Standalone (importbuddy) @(include_once pb_backupbuddy::plugin_path() . '/lib/pclzip/pclzip.php'); } } // Make sure we did load it if (class_exists('PclZip', false)) { $za = new PclZip($zip_file); // Make sure we opened the zip ok and we added the comment ok // Note: using empty array as we don't actually want to add any files if (($list = $za->add(array(), PCLZIP_OPT_COMMENT, $comment)) !== 0) { // We got a list back so adding comment should have been successful pb_backupbuddy::status('details', sprintf(__('PclZip set comment in file %1$s', 'it-l10n-backupbuddy'), $zip_file)); return true; } else { // If we failed to set the commnent then log it (?) and drop through $error_string = $za->errorInfo(true); pb_backupbuddy::status('details', sprintf(__('PclZip failed to set comment in file %1$s - Error Info: %2$s', 'it-l10n-backupbuddy'), $zip_file, $error_string)); } } else { // Something fishy - the methods indicated pclzip but we couldn't find the class pb_backupbuddy::status('details', __('pclzip indicated as available method but class PclZip non-existent', 'it-l10n-backupbuddy')); } } // We couldn't set a comment at all - either no available method or all methods failed pb_backupbuddy::status('details', sprintf(__('Unable to set comment in file %1$s: No compatible zip method found or all methods failed - note stored internally only.', 'it-l10n-backupbuddy'), $zip_file)); // Return message for display - maybe should return false and have caller display it's own message? $message = "\n\nUnable to set note in file.\nThe note will only be stored internally in your settings and not in the zip file itself."; return $message; }
function cards_download() { global $tmpdir; $bdl = new Modele('cardbundle'); $bdl->fetch($_GET['bundle']); $bdl->cbundle_status = 'WAIT'; $crd = new Modele('card'); $crd->find(array('card_bundle' => $bdl->cbundle_id)); $zipfile = tempnam($tmpdir, 'zip'); $zip = new ZipArchive(); $zip->open($zipfile, ZipArchive::CREATE); $zip->setArchiveComment("Automade zip archive from EPITANIME intra software. Bundle " . $bdl->cbundle_date); while ($crd->next()) { $zip->addFile($crd->card_picture, "card{$crd->card_id}.png"); $crd->card_status = 'PRINT'; } $zip->close(); header('Content-Type: application/zip'); header('Content-Disposition: attachment; filename="bundle_' . $bdl->cbundle_date . '.zip"'); readfile($zipfile); unlink($zipfile); quit(); }
/** * @expectedException InvalidArgumentException */ public function testIfStateFileHasIncorrectCommentItShouldThrowInvalidArgumentExceptionOnLoadFromFileMethod() { $stateFileName = $this->_source('magento.state-'); $stateFile = new \ZipArchive(); $stateFile->open($stateFileName, GenericState::MODE_CREATE); $stateFile->setArchiveComment('Blah-blah'); $stateFile->addEmptyDir('test'); $stateFile->close(); $state = new GenericState($stateFileName); }
/** * Build a Motif * * @param string $path * @param array $manifest */ protected function buildMotif(string $path, array $manifest = []) { // Step One -- Let's build our .zip file $zipName = $manifest['supplier'] . '.' . $manifest['name'] . '.zip'; if (\file_exists($path . '/dist/' . $zipName)) { \unlink($path . '/dist/' . $zipName); \clearstatcache(); } if (\file_exists($path . '/dist/' . $zipName . '.ed25519.sig')) { \unlink($path . '/dist/' . $zipName . '.ed25519.sig'); \clearstatcache(); } $zip = new \ZipArchive(); $flags = \ZipArchive::CREATE | \ZipArchive::OVERWRITE; // Open the zip for writing if ($zip->open($path . '/dist/' . $zipName, $flags) !== true) { echo 'Could not open .zip', "\n"; exit(255); // Return an error flag } $zipOpts = ['remove_all_path' => true]; $currentDir = \getcwd(); \chdir($path . '/src/'); $zip->addGlob('*.json', 0, $zipOpts); $zip->addGlob('*/*', 0, $zipOpts); \chdir($currentDir); $zip->setArchiveComment(\json_encode($manifest)); if (!$zip->close()) { echo 'Zip archive unsuccessful', "\n"; exit(255); } echo 'Motif built.', "\n", $path . '/dist/' . $zipName, "\n", 'Don\'t forget to sign it!', "\n"; exit(0); // Return a success flag }
/** * Força o download de um arquivo zip contendo o(s) arquivo(s) gerado(s). * @throws Exception */ private function _exportLoteZip($dados_array) { $timenow = time(); $str_date_filename = date("Y-m-d_His", $timenow); $str_date_comment = date("d/m/Y H:i:s", $timenow); $filepath = tempnam("tmp", "zip"); $dir = dirname($filepath); if (!is_writable($dir)) { throw new Exception("Não foi possível escrever em " . $dir); } try { $zip = new ZipArchive(); $res = $zip->open($filepath, ZipArchive::CREATE); if ($res !== TRUE) { throw new Exception("Erro ao criar arquivo zip. Código " . $res); } $zip->setArchiveComment("Gerado pelo SiGE <https://github.com/comsolid/sige> em " . $str_date_comment); foreach ($dados_array as $dados) { $zipfilename = "artigo_" . preg_replace("/ /", "_", strtolower($this->_utf8_remove_acentos($dados["nome"]))) . "_" . $dados["id_artigo"] . ".pdf"; $zip->addFromString($zipfilename, base64_decode($dados["dados"])); } if (!$zip->close()) { throw new Exception("Não foi possível fechar o arquivo " . $filepath); } if (!is_readable($filepath)) { throw new Exception("Não foi possível ler o arquivo " . $filepath); } $filesize = filesize($filepath); if (!$filesize) { throw new Exception("Não foi possível calcular o tamanho do arquivo " . $filepath); } $zipfilename = "artigos_sige_" . preg_replace("/ /", "_", strtolower($this->_utf8_remove_acentos($dados["apelido_encontro"]))) . "_{$str_date_filename}.zip"; header("Content-Type: application/zip"); header("Content-Length: " . $filesize); header("Content-Disposition: attachment; filename=\"{$zipfilename}\""); readfile($filepath); unlink($filepath); clearstatcache(); } catch (Exception $exc) { // código repetido devido ao php 5.4 ou < não suportar finally unlink($filepath); clearstatcache(); throw new Exception("Ocorreu o seguinte erro ao gerar o zip: " . $exc->getMessage()); } }
/** * @param string $websiteId * @param string $name Zip name * @param \Cms\Data\Build $build * * @return string Name of the export zip file */ private function createBuildZip($websiteId, $name, BuildData $build) { $zipFile = FS::joinPath($this->getWebsiteBuildsDirectory($websiteId), $name . self::BUILD_FILE_EXTENSION); $websiteCreatorDirectory = $this->getLastCreatorDirectory(); $zip = new \ZipArchive(); $zip->open($zipFile, \ZipArchive::CREATE); $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($websiteCreatorDirectory), \RecursiveIteratorIterator::SELF_FIRST); while ($iterator->valid()) { if (!$iterator->isDot()) { if ($iterator->isDir()) { $zip->addEmptyDir(str_replace('\\', '/', $iterator->getSubPathName())); } else { $zip->addEmptyDir(str_replace('\\', '/', $iterator->getSubPath())); $zip->addFile($iterator->key(), str_replace('\\', '/', $iterator->getSubPathName())); } } $iterator->next(); } $zip->setArchiveComment($this->getBuiltArchiveComment($build)); $zip->close(); return $zipFile; }
<?php // create ZIP file $zip = new ZipArchive(); $res = $zip->open($zipname, ZipArchive::OVERWRITE); if ($res !== true) { die('Error creating ZIP file for downloading.'); } // create "readme" file $readme = "Each column's value is delimited by a new line. These are their names:" . PHP_EOL; $readme .= implode(PHP_EOL, $headers); $zip->addFromString("README.txt", $readme); // add meta comments $zip->setArchiveComment("Downloaded on " . date('l jS \\of F Y h:i:s A')); // get log values foreach ($records as $i => $r) { // create single TXT file foreach ($headers as $h) { $row[] = $r[$h]; } // append file to ZIP $zip->addFromString($i . "." . $format, implode(PHP_EOL, $row)); } // end if (!$zip->close()) { die('Cannot create ZIP file.'); } // now force download header('Content-type: application/zip'); header("Content-Length: " . filesize($zipname)); header('Content-Disposition: attachment; filename="' . $zipname . '"');
if ($outputMode == EXPORT_OPTION_IMAGE && count($cacheImages) == 1) { $CacheImage = $cacheImages[0]; Image::OutputImage($CacheImage->getFilenameOnDisk(), $CacheImage->getImageWidth(), $CacheImage->getImageHeight(), TRUE, NULL, $PromptDownload ? sprintf('%1$s.jpg', $Model->GetFullName()) : NULL); } if ($outputMode == EXPORT_OPTION_ZIP && count($cacheImages) > 0) { $tmpFile = sprintf('%1$s/%2$s.zip', sys_get_temp_dir(), Utils::UUID()); $finalFile = sprintf('Index %1$s.zip', $Model->GetFullName()); $zip = new ZipArchive(); if (file_exists($tmpFile)) { $resource = $zip->open($tmpFile, ZipArchive::OVERWRITE); } else { $resource = $zip->open($tmpFile, ZipArchive::CREATE); } if ($resource === TRUE) { ini_set('max_execution_time', '3600'); $zip->setArchiveComment('Downloaded from CandyDoll DB' . "\nhttps://code.google.com/p/candydolldb/"); foreach ($cacheImages as $CacheImage) { if (!file_exists($CacheImage->getFilenameOnDisk())) { continue; } $zip->addFile($CacheImage->getFilenameOnDisk(), str_replace($CacheImage->getID(), $Model->GetFullName(), basename($CacheImage->getFilenameOnDisk()))); } $zip->close(); } Utils::DownloadZip($tmpFile, $finalFile, TRUE); } if ($outputMode == EXPORT_OPTION_SERIALIZE) { // TODO Figure out a way of returning multiple CacheImages // Perhaps a JSON array with serialized images? // Or a string-array of on-disk filenames? var_dump($cacheImages);
/** * Creates a zip archive of the files in the $filename_ar array and * returns the path/name of the archive or FALSE on error * * @param array $parameters array for file type from csv_parameters * @param array $filename_ar array of filenames to be archived * @param string $archive_date date of archive to be incorporated in archive file name * * @return bool result of zipArchive functions */ function edih_archive_create_zip($parameters, $filename_ar, $archive_date, $archive_filename) { // we deal with possible maximum files issues by chunking the $fn_ar array // $ft = $parameters['type']; $fdir = $parameters['directory']; $tmp_dir = csv_edih_tmpdir(); // archive csv rows -- same name as from edih_archive_main // $fn_files_arch = $tmp_dir.DS.'arch_'.basename($files_csv); $files_csv_arch = 'arch_' . basename($parameters['files_csv']); // $fn_claims_arch = $tmp_dir.DS.'arch_'.basename($claim_csv); $claims_csv_arch = 'arch_' . basename($parameters['claims_csv']); // $f_max = 200; $fn_ar2 = array(); // to handle possibility of more than 200 files in the archive // use the 'chunk' method if (count($filename_ar) > $f_max) { $fn_ar2 = array_chunk($filename_ar, $f_max); } else { $fn_ar2[] = $filename_ar; } // $zip_name = $tmp_dir . DS . $archive_filename; csv_edihist_log("edih_archive_create_zip: using {$zip_name}"); // $zip_obj = new ZipArchive(); csv_edihist_log("edih_archive_create_zip: now opening archive {$archive_filename}"); if (is_file($zip_name)) { $isOK = $zip_obj->open($zip_name, ZIPARCHIVE::CHECKCONS); if ($isOK) { if ($zip_obj->locateName($ft) === false) { $isOK = $zip_obj->addEmptyDir($ft); if (!$isOK) { csv_edihist_log("edih_archive_create_zip: adding {$ft} ZipArchive error {$msg}"); return $isOK; } } } else { $msg = $zip_obj->getStatusString(); csv_edihist_log("edih_archive_create_zip: {$ft} ZipArchive error {$msg}"); return $isOK; } } else { $isOK = $zip_obj->open($zip_name, ZIPARCHIVE::CREATE); $isOK = $zip_obj->addEmptyDir('csv'); $isOK = $zip_obj->addEmptyDir($ft); $zip_obj->setArchiveComment("edi_history archive prior to {$archive_date}"); } // we are working with the open archive // now add the old csv files to the archive if (is_file($tmp_dir . DS . $files_csv_arch)) { csv_edihist_log("edih_archive_create_zip: now adding {$files_csv_arch} to archive"); $isOK = $zip_obj->addFile($tmp_dir . DS . $files_csv_arch, 'csv' . DS . $files_csv_arch); } if (is_file($tmp_dir . DS . $claims_csv_arch)) { csv_edihist_log("edih_archive_create_zip: now adding {$claims_csv_arch} to archive"); $isOK = $zip_obj->addFile($tmp_dir . DS . $claims_csv_arch, 'csv' . DS . $claims_csv_arch); } // close zip archive csv_edihist_log("edih_archive_create_zip: now closing archive"); $isOK = $zip_obj->close(); if ($isOK !== true) { $msg = $zip_obj->getStatusString(); csv_edihist_log("edih_archive_create_zip: {$ft} ZipArchive error {$msg}"); return $isOK; } // $fn_ar2[i][j] csv_edihist_log("edih_archive_create_zip: with file name groups " . count($fn_ar2)); foreach ($fn_ar2 as $fnz) { // reopen the zip archive on each loop so the open file count is controlled if (is_file($zip_name)) { csv_edihist_log("edih_archive_create_zip: now opening archive"); $isOK = $zip_obj->open($zip_name, ZIPARCHIVE::CHECKCONS); } // if ($isOK === true) { // we are working with the open archive // now add the old x12 files to the archive csv_edihist_log("edih_archive_create_zip: now adding {$ft} files to archive"); foreach ($fnz as $fz) { if ($fz == '.' || $fz == '..') { continue; } if (is_file($fdir . DS . $fz) && is_readable($fdir . DS . $fz)) { $isOK = $zip_obj->addFile($fdir . DS . $fz, $ft . DS . $fz); } else { // possible that file is in csv table, but not in directory? $msg = $zip_obj->getStatusString(); csv_edihist_log("edih_archive_create_zip: error adding file {$fz} zipArchive: {$msg}"); } } // end foreach($fnz as $fz) // close zip object for next iteration of chunked array csv_edihist_log("edih_archive_create_zip: now closing archive"); $isOK = $zip_obj->close(); // errors on close would be non-existing file added or something else if ($isOK !== true) { $msg = $zip_obj->getStatusString(); csv_edihist_log("edih_archive_create_zip: {$ft} ZipArchive error {$msg}"); // return $isOK; } } else { // ZipArchive open() failed -- try to get the error message and return false $msg = $zip_obj->getStatusString(); csv_edihist_log("edih_archive_create_zip: {$ft} ZipArchive failed {$msg}"); return $isOK; } // end if ($isOK) // } // end foreach($fn_ar2 as $fnz) // return $isOK; }
/** * Creates a transport file for easily transferring Yaga configurations across * installs * * @param array An array containing the config areas to transfer * @param string Where to save the transport file * @return mixed False on failure, the path to the transport file on success */ protected function _ExportData($Include = array(), $Path = NULL) { $StartTime = microtime(TRUE); $Info = new stdClass(); $Info->Version = C('Yaga.Version', '?.?'); $Info->StartDate = date('Y-m-d H:i:s'); if (is_null($Path)) { $Path = PATH_UPLOADS . DS . 'export' . date('Y-m-d-His') . '.yaga.zip'; } $FH = new ZipArchive(); $Images = array(); $Hashes = array(); if ($FH->open($Path, ZipArchive::CREATE) !== TRUE) { $this->Form->AddError(sprintf(T('Yaga.Error.ArchiveCreate'), $FH->getStatusString())); return FALSE; } // Add configuration items $Info->Config = 'configs.yaga'; $Configs = Gdn::Config('Yaga', array()); unset($Configs['Version']); $ConfigData = serialize($Configs); $FH->addFromString('configs.yaga', $ConfigData); $Hashes[] = md5($ConfigData); // Add actions if ($Include['Action']) { $Info->Action = 'actions.yaga'; $Actions = Yaga::ActionModel()->Get('Sort', 'asc'); $this->SetData('ActionCount', count($Actions)); $ActionData = serialize($Actions); $FH->addFromString('actions.yaga', $ActionData); $Hashes[] = md5($ActionData); } // Add ranks and associated image if ($Include['Rank']) { $Info->Rank = 'ranks.yaga'; $Ranks = Yaga::RankModel()->Get('Level', 'asc'); $this->SetData('RankCount', count($Ranks)); $RankData = serialize($Ranks); $FH->addFromString('ranks.yaga', $RankData); array_push($Images, C('Yaga.Ranks.Photo'), NULL); $Hashes[] = md5($RankData); } // Add badges and associated images if ($Include['Badge']) { $Info->Badge = 'badges.yaga'; $Badges = Yaga::BadgeModel()->Get(); $this->SetData('BadgeCount', count($Badges)); $BadgeData = serialize($Badges); $FH->addFromString('badges.yaga', $BadgeData); $Hashes[] = md5($BadgeData); foreach ($Badges as $Badge) { array_push($Images, $Badge->Photo); } } // Add in any images $FilteredImages = array_filter($Images); $ImageCount = count($FilteredImages); $this->SetData('ImageCount', $ImageCount); if ($ImageCount > 0) { $FH->addEmptyDir('images'); } foreach ($FilteredImages as $Image) { if ($FH->addFile('.' . $Image, 'images/' . $Image) === FALSE) { $this->Form->AddError(sprintf(T('Yaga.Error.AddFile'), $FH->getStatusString())); //return FALSE; } $Hashes[] = md5_file('.' . $Image); } // Save all the hashes sort($Hashes); $Info->MD5 = md5(implode(',', $Hashes)); $Info->EndDate = date('Y-m-d H:i:s'); $EndTime = microtime(TRUE); $TotalTime = $EndTime - $StartTime; $m = floor($TotalTime / 60); $s = $TotalTime - $m * 60; $Info->ElapsedTime = sprintf('%02d:%02.2f', $m, $s); $FH->setArchiveComment(serialize($Info)); if ($FH->close()) { return $Path; } else { $this->Form->AddError(sprintf(T('Yaga.Error.ArchiveSave'), $FH->getStatusString())); return FALSE; } }
/** * @return array * * @throws \MailSo\Base\Exceptions\Exception */ public function DoAttachmentsActions() { if (!$this->GetCapa(false, \RainLoop\Enumerations\Capa::ATTACHMENTS_ACTIONS)) { return $this->FalseResponse(__FUNCTION__); } $oAccount = $this->initMailClientConnection(); $sAction = $this->GetActionParam('Do', ''); $aHashes = $this->GetActionParam('Hashes', null); $mResult = false; $bError = false; $aData = false; if (\is_array($aHashes) && 0 < \count($aHashes)) { $aData = array(); foreach ($aHashes as $sZipHash) { $aResult = $this->getMimeFileByHash($oAccount, $sZipHash); if (\is_array($aResult) && !empty($aResult['FileHash'])) { $aData[] = $aResult; } else { $bError = true; break; } } } $oFilesProvider = $this->FilesProvider(); if (!empty($sAction) && !$bError && \is_array($aData) && 0 < \count($aData) && $oFilesProvider && $oFilesProvider->IsActive()) { $bError = false; switch (\strtolower($sAction)) { case 'zip': if (\class_exists('ZipArchive')) { $sZipHash = \MailSo\Base\Utils::Md5Rand(); $sZipFileName = $oFilesProvider->GenerateLocalFullFileName($oAccount, $sZipHash); if (!empty($sZipFileName)) { $oZip = new \ZipArchive(); $oZip->open($sZipFileName, \ZIPARCHIVE::CREATE | \ZIPARCHIVE::OVERWRITE); $oZip->setArchiveComment('RainLoop/' . APP_VERSION); foreach ($aData as $aItem) { $sFileName = (string) (isset($aItem['FileName']) ? $aItem['FileName'] : 'file.dat'); $sFileHash = (string) (isset($aItem['FileHash']) ? $aItem['FileHash'] : ''); if (!empty($sFileHash)) { $sFullFileNameHash = $oFilesProvider->GetFileName($oAccount, $sFileHash); if (!$oZip->addFile($sFullFileNameHash, $sFileName)) { $bError = true; } } } if (!$bError) { $bError = !$oZip->close(); } else { $oZip->close(); } } foreach ($aData as $aItem) { $sFileHash = (string) (isset($aItem['FileHash']) ? $aItem['FileHash'] : ''); if (!empty($sFileHash)) { $oFilesProvider->Clear($oAccount, $sFileHash); } } if (!$bError) { $mResult = array('Files' => array(array('FileName' => 'attachments.zip', 'Hash' => \RainLoop\Utils::EncodeKeyValuesQ(array('V' => APP_VERSION, 'Account' => $oAccount ? \md5($oAccount->Hash()) : '', 'FileName' => 'attachments.zip', 'MimeType' => 'application/zip', 'FileHash' => $sZipHash))))); } } break; case 'owncloud': $mResult = false; if (\RainLoop\Utils::IsOwnCloudLoggedIn() && \class_exists('OCP\\Files')) { $sSaveFolder = $this->Config()->Get('labs', 'owncloud_save_folder', ''); if (empty($sSaveFolder)) { $sSaveFolder = 'Attachments'; } $oFiles = \OCP\Files::getStorage('files'); if ($oFilesProvider && $oFiles && $oFilesProvider->IsActive() && \method_exists($oFiles, 'file_put_contents')) { if (!$oFiles->is_dir($sSaveFolder)) { $oFiles->mkdir($sSaveFolder); } $mResult = true; foreach ($aData as $aItem) { $sSavedFileName = isset($aItem['FileName']) ? $aItem['FileName'] : 'file.dat'; $sSavedFileHash = !empty($aItem['FileHash']) ? $aItem['FileHash'] : ''; if (!empty($sSavedFileHash)) { $fFile = $oFilesProvider->GetFile($oAccount, $sSavedFileHash, 'rb'); if (\is_resource($fFile)) { $sSavedFileNameFull = \MailSo\Base\Utils::SmartFileExists($sSaveFolder . '/' . $sSavedFileName, function ($sPath) use($oFiles) { return $oFiles->file_exists($sPath); }); if (!$oFiles->file_put_contents($sSavedFileNameFull, $fFile)) { $mResult = false; } if (\is_resource($fFile)) { @\fclose($fFile); } } } } } } foreach ($aData as $aItem) { $sFileHash = (string) (isset($aItem['FileHash']) ? $aItem['FileHash'] : ''); if (!empty($sFileHash)) { $oFilesProvider->Clear($oAccount, $sFileHash); } } break; case 'dropbox': $mResult = array('ShortLife' => '_' . $this->GetShortLifeSpecAuthToken(), 'Url' => \preg_replace('/\\?(.*)$/', '', $this->Http()->GetFullUrl()), 'Files' => array()); foreach ($aData as $aItem) { $mResult['Files'][] = array('FileName' => isset($aItem['FileName']) ? $aItem['FileName'] : 'file.dat', 'Hash' => \RainLoop\Utils::EncodeKeyValuesQ($aItem)); } break; } } else { $bError = true; } $this->requestSleep(); return $this->DefaultResponse(__FUNCTION__, $bError ? false : $mResult); }
/** * Create an zip file. Requires ZipArchive class to exist. * Usage: $result = create_zip($files_to_zip, 'my-archive.zip', true, $prefix_to_strip, 'Slavi created this archive at ' . date('r') ); * * @param array $files * @param str $destination zip file * @param str $overwrite * @param str $prefix_to_strip * @param str $comment * @return boolean */ function create_zip($files = array(), $destination = '', $overwrite = false, $prefix_to_strip = '', $comment = '') { if (file_exists($destination) && !$overwrite || !class_exists('ZipArchive')) { return false; } $zip = new ZipArchive(); if ($zip->open($destination, $overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) !== true) { return false; } foreach ($files as $file) { // if we specify abs path to the dir we'll add a relative folder in the archive. $file_in_archive = str_ireplace($prefix_to_strip, '', $file); $zip->addFile($file, $file_in_archive); } if (!empty($comment)) { $zip->setArchiveComment($comment); } $zip->close(); return file_exists($destination); }
/** * do the work * @throws BuildException */ public function main() { if (!extension_loaded('zip')) { throw new BuildException("Zip extension is required"); } if ($this->zipFile === null) { throw new BuildException("zipfile attribute must be set!", $this->getLocation()); } if ($this->zipFile->exists() && $this->zipFile->isDirectory()) { throw new BuildException("zipfile is a directory!", $this->getLocation()); } if ($this->zipFile->exists() && !$this->zipFile->canWrite()) { throw new BuildException("Can not write to the specified zipfile!", $this->getLocation()); } try { if ($this->baseDir !== null) { if (!$this->baseDir->exists()) { throw new BuildException("basedir '" . (string) $this->baseDir . "' does not exist!", $this->getLocation()); } if (empty($this->filesets)) { // add the main fileset to the list of filesets to process. $mainFileSet = new ZipFileSet($this->fileset); $mainFileSet->setDir($this->baseDir); $this->filesets[] = $mainFileSet; } } if (empty($this->filesets)) { throw new BuildException("You must supply either a basedir " . "attribute or some nested filesets.", $this->getLocation()); } // check if zip is out of date with respect to each // fileset if ($this->areFilesetsUpToDate()) { $this->log("Nothing to do: " . $this->zipFile->__toString() . " is up to date.", Project::MSG_INFO); return; } $this->log("Building zip: " . $this->zipFile->__toString(), Project::MSG_INFO); $zip = new ZipArchive(); $res = $zip->open($this->zipFile->getAbsolutePath(), ZIPARCHIVE::CREATE); if ($res !== true) { throw new Exception("ZipArchive::open() failed with code " . $res); } if ($this->comment !== '') { $isCommented = $zip->setArchiveComment($this->comment); if ($isCommented === false) { $this->log("Could not add a comment for the Archive.", Project::MSG_INFO); } } $this->addFilesetsToArchive($zip); $zip->close(); } catch (IOException $ioe) { $msg = "Problem creating ZIP: " . $ioe->getMessage(); throw new BuildException($msg, $ioe, $this->getLocation()); } }
include $dirname . 'utils.inc'; $file = $dirname . '__tmp_oo_set_comment.zip'; @unlink($file); $zip = new ZipArchive(); if (!$zip->open($file, ZIPARCHIVE::CREATE)) { exit('failed'); } $zip->addFromString('entry1.txt', 'entry #1'); $zip->addFromString('entry2.txt', 'entry #2'); $zip->addFromString('dir/entry2d.txt', 'entry #2'); $zip->addFromString('entry4.txt', 'entry #1'); $zip->addFromString('entry5.txt', 'entry #2'); var_dump($zip->setCommentName('entry1.txt', 'entry1.txt')); var_dump($zip->setCommentName('entry2.txt', 'entry2.txt')); var_dump($zip->setCommentName('dir/entry2d.txt', 'dir/entry2d.txt')); var_dump($zip->setArchiveComment('archive')); var_dump($zip->setCommentIndex(3, 'entry4.txt')); var_dump($zip->setCommentIndex(4, 'entry5.txt')); var_dump($zip->setArchiveComment('archive')); if (!$zip->status == ZIPARCHIVE::ER_OK) { echo "failed to write zip\n"; } $zip->close(); if (!$zip->open($file)) { @unlink($file); exit('failed'); } var_dump($zip->getCommentIndex(0)); var_dump($zip->getCommentIndex(1)); var_dump($zip->getCommentIndex(2)); var_dump($zip->getCommentIndex(3));
function writeArchive($files_contents) { $zip = new ZipArchive(); $fileName = TEMP_FILE_PATH . "/tmp_export_zip_" . date('j_m_Y_h_m_s_u') . ".zip"; if ($zip->open($fileName, ZIPARCHIVE::CREATE) !== true) { echo "Error while creating archive file"; die; } foreach ($files_contents as $fname => $fcontent) { $zip->addFromString($fname, $fcontent); } $zip->setArchiveComment('Exported surveys...'); $zip->close(); header("Content-Type: application/zip"); header('Content-Transfer-Encoding: binary'); header('Content-Disposition: attachment; filename="export.zip"'); header('Expires: 0'); header('Cache-Control: must-revalidate'); header("Content-Length: " . filesize($fileName)); readfile($fileName); unlink($fileName); exit; }
function unphar_toZip($tmpName, &$result, $name = "") { $result = ["tmpDir" => null, "zipPath" => null, "zipRelativePath" => null, "basename" => null, "error" => false]; rename($tmpName, "{$tmpName}.phar"); $tmpName .= ".phar"; try { $phar = new Phar($tmpName); $result["tmpDir"] = $tmpDir = getTmpDir(); $pharPath = "phar://{$phar->getPath()}/"; foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($pharPath)) as $f) { $subpath = substr($f, strlen($pharPath)); @mkdir(dirname($realSubpath = $tmpDir . $subpath), 0777, true); copy($f, $realSubpath); } $zip = new ZipArchive(); $dir = "/data/phars/"; while (is_file($file = htdocs . ($rel = $dir . randomClass(16, "zip_" . $name . "_") . ".zip"))) { } $result["zipPath"] = $file; $result["zipRelativePath"] = $rel; $result["basename"] = substr($rel, 12); $err = $zip->open($file, ZipArchive::CREATE); if ($err !== true) { $msg = "Error creating zip file: "; switch ($err) { case ZipArchive::ER_EXISTS: $msg .= "ER_EXISTS ({$err}) File already exists ({$file})"; break; case ZipArchive::ER_INCONS: $msg .= "ER_INCONS ({$err}) Zip archive inconsistent."; break; case ZipArchive::ER_INVAL: $msg .= "ER_INVAL ({$err}) Invalid argument."; break; case ZipArchive::ER_MEMORY: $msg .= "ER_MEMORY ({$err}) Malloc failure."; break; case ZipArchive::ER_NOENT: $msg .= "ER_NOENT ({$err}) No such file."; break; case ZipArchive::ER_NOZIP: $msg .= "ER_NOZIP ({$err}) Not a zip archive."; break; case ZipArchive::ER_OPEN: $msg .= "ER_OPEN ({$err}) Can't open file."; break; case ZipArchive::ER_READ: $msg .= "ER_READ ({$err}) Read error."; break; case ZipArchive::ER_SEEK: $msg .= "ER_SEEK ({$err}) Seek error."; } throw new RuntimeException($msg . " Dump: " . var_export($result, true)); } $tmpDir = realpath($tmpDir); foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($tmpDir)) as $file) { if (!is_file($file)) { continue; } $file = realpath($file); $rel = substr($file, strlen($tmpDir) + 1); $zip->addFile($file, str_replace("\\", "/", $rel)); } $zip->setArchiveComment(json_encode($phar->getMetadata(), JSON_PRETTY_PRINT)); $zip->close(); } catch (Exception $e) { echo "<pre>"; echo get_class($e) . ": {$e->getMessage()}"; echo "\r\n\tat {$e->getFile()}:{$e->getLine()}</pre>"; $result["error"] = true; } }
/** * Creates the backup with given name and description * * @param string $name filename * @param string $description * @return bool true on success, false on error */ private function createBackup($name, $description = '') { $zip = new ZipArchive(); // create empty array if ($zip->open(__DIR__ . '/data/' . $name, ZipArchive::CREATE) !== true) { return false; } // add all files if (!isset($this->CONFIG['backup_list']) || !is_array($this->CONFIG['backup_list'])) { return false; } foreach ($this->CONFIG['backup_list'] as $item) { $zip->addGlob($item); } // rename files as zip thinks there are CP866 filenames but they are in 1251 // so all cyrillic names are unreadable for ($i = 0; $i < $zip->numFiles; $i++) { if ($zip->getNameIndex($i) > '') { $zip->renameIndex($i, iconv(filesystem_encoding(), 'CP866', $zip->getNameIndex($i))); } } // ok, finished $zip->setArchiveComment($description); $zip->close(); return true; }
} } $dsv .= PHP_EOL . implode($delimiter, $row); } // set ZIP name (in a writeable dir) $zipname = 'smt2logs-' . date("Ymd") . '.zip'; $zippath = CACHE_DIR . '/' . $zipname; // create ZIP file $zip = new ZipArchive(); $res = $zip->open($zippath, ZipArchive::OVERWRITE); if (!$res) { die('Cannot open ZIP file.'); } // add meta comments $comm = "Downloaded on " . date('l jS \\of F Y h:i:s A'); $zip->setArchiveComment($comm); $readme = $comm . PHP_EOL; $readme .= "Each column's value is delimited either by a colon (CSV) or a tab (TSV)." . PHP_EOL; //$readme .= "These are their names:".PHP_EOL; //$readme .= implode(PHP_EOL, $headers); $zip->addFromString("README", $readme); $zip->addFromString("logs." . $format, $dsv); if (!$zip->close()) { die('Cannot close ZIP file.'); } // now force download header('Content-type: application/zip'); header("Content-Length: " . filesize($zippath)); header('Content-Disposition: attachment; filename="' . $zipname . '"'); readfile($zippath); unlink($zippath);
/** * Creates ZIP archive. * * @return \ApiGen\Generator * @throws \RuntimeException If something went wrong. */ private function generateArchive() { if (!extension_loaded('zip')) { throw new RuntimeException('Extension zip is not loaded'); } $archive = new \ZipArchive(); if (true !== $archive->open($this->getArchivePath(), \ZipArchive::CREATE)) { throw new RuntimeException('Could not open ZIP archive'); } $archive->setArchiveComment(trim(sprintf('%s API documentation generated by %s %s on %s', $this->config->title, Environment::getApplicationName(), Environment::getApplicationVersion(), date('Y-m-d H:i:s')))); $directory = Nette\Utils\Strings::webalize(trim(sprintf('%s API documentation', $this->config->title)), null, false); $destinationLength = strlen($this->config->destination); foreach ($this->getGeneratedFiles() as $file) { if (is_file($file)) { $archive->addFile($file, $directory . DIRECTORY_SEPARATOR . substr($file, $destinationLength + 1)); } } if (false === $archive->close()) { throw new RuntimeException('Could not save ZIP archive'); } $this->fireEvent('generateProgress', 1); return $this; }
foreach ($iterator as $path) { if ($path->isDir() and $path->isReadable() and !in_array($path->getFilename(), array('.', '..'))) { $make_zip->addEmptyDir(str_ireplace($extract_dir . '/', '', $path->__toString() . '/')); } if ($path->isFile() and $path->isReadable() and in_array($path->getExtension(), $supported_extensions)) { $files[] = $path->__toString(); } } $replaced = array(); $total = count($files); foreach ($files as $file) { $save_path = str_ireplace($extract_dir, $gen_dir, dirname($file)); $replace = new \Dummy_Image_Replacement($watermark_path, $file); $replaced[] = $replace->Generate("{$save_path}/"); $progress = round(count($replaced) / $total * 100); echo "<script> btn.button('loading'); can_close = false; progress = {$progress}; \$('.progress-bar').css('width', '{$progress}%').text('{$progress}%').attr('aria-valuenow', '{$progress}'); </script>"; ob_flush(); flush(); } chdir($gen_dir); foreach ($replaced as $file) { $make_zip->addFile(str_ireplace($gen_dir . '/', '', $file)); } chdir("../../../"); $make_zip->setArchiveComment('Image Replace Github: https://github.com/EmranAhmed/envato-watermark-image-replacement'); $make_zip->close(); removeDir($user_dir); echo "<script>if( progress==100 ){ btn.button('reset'); can_close=true; window.location.replace('makendownload.php?name={$image_zip_base_name}&id={$id}');}</script>"; ob_flush(); flush(); }