本文整理汇总了PHP中ZipArchive::setArchiveComment方法的典型用法代码示例。如果您正苦于以下问题:PHP ZipArchive::setArchiveComment方法的具体用法?PHP ZipArchive::setArchiveComment怎么用?PHP ZipArchive::setArchiveComment使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ZipArchive
的用法示例。
在下文中一共展示了ZipArchive::setArchiveComment方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: CreateFromFilesystem
/**
* 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();
}
示例2: createZipArchive
/**
* @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')));
}
示例3: setComment
/**
* 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;
}
示例4: csv_zip_dir
/**
* 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;
}
示例5: date
}
$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.
*/
示例6: ZipArchive
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;
}
示例7: cards_download
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();
}
示例8: testIfStateFileHasIncorrectCommentItShouldThrowInvalidArgumentExceptionOnLoadFromFileMethod
/**
* @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);
}
示例9: buildMotif
/**
* 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
}
示例10: _exportLoteZip
/**
* 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());
}
}
示例11: createBuildZip
/**
* @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;
}
示例12: ZipArchive
<?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 . '"');
示例13: sprintf
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);
示例14: edih_archive_create_zip
/**
* 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}");
//.........这里部分代码省略.........
示例15: _ExportData
/**
* 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;
}
}