本文整理汇总了PHP中PclZip::errorCode方法的典型用法代码示例。如果您正苦于以下问题:PHP PclZip::errorCode方法的具体用法?PHP PclZip::errorCode怎么用?PHP PclZip::errorCode使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PclZip
的用法示例。
在下文中一共展示了PclZip::errorCode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: privExtractFile
protected function privExtractFile(&$p_entry, $p_path, $p_remove_path, $p_remove_all_path, &$p_options)
{
$v_result = 1;
// Read the file header
if (($v_result = $this->privReadFileHeader($v_header)) != 1) {
return $v_result;
}
// Check that the file header is coherent with $p_entry info
if ($this->privCheckFileHeaders($v_header, $p_entry) != 1) {
// TBC
}
// Look for all path to remove
if ($p_remove_all_path == true) {
// Look for folder entry that not need to be extracted
if (($p_entry['external'] & 0x10) == 0x10) {
$p_entry['status'] = "filtered";
return $v_result;
}
// Get the basename of the path
$p_entry['filename'] = basename($p_entry['filename']);
} else {
if ($p_remove_path != '') {
// Look for path to remove
if (self::UtilPathInclusion($p_remove_path, $p_entry['filename']) == 2) {
// Change the file status
$p_entry['status'] = 'filtered';
// Return
return $v_result;
}
$p_remove_path_size = strlen($p_remove_path);
if (substr($p_entry['filename'], 0, $p_remove_path_size) == $p_remove_path) {
// Remove the path
$p_entry['filename'] = substr($p_entry['filename'], $p_remove_path_size);
}
}
}
// Add the path
if ($p_path != '') {
$p_entry['filename'] = $p_path . "/" . $p_entry['filename'];
}
// Check a base_dir_restriction
if (isset($p_options[self::OPT_EXTRACT_DIR_RESTRICTION])) {
$v_inclusion = self::UtilPathInclusion($p_options[self::OPT_EXTRACT_DIR_RESTRICTION], $p_entry['filename']);
if ($v_inclusion == 0) {
$this->privErrorLog(self::ERR_DIRECTORY_RESTRICTION, 'Filename \'' . $p_entry['filename'] . '\' is outside ' . self::OPT_EXTRACT_DIR_RESTRICTION);
return self::errorCode();
}
}
// Look for pre-extract callback
if (isset($p_options[self::CB_PRE_EXTRACT])) {
// Generate a local information
$v_local_header = array();
$this->privConvertHeader2FileInfo($p_entry, $v_local_header);
// Call the callback
// Here I do not use call_user_func() because I need to send a reference to the header.
// eval('$v_result = '.$p_options[self::CB_PRE_EXTRACT].'(self::CB_PRE_EXTRACT, $v_local_header);');
$v_result = $p_options[self::CB_PRE_EXTRACT](self::CB_PRE_EXTRACT, $v_local_header);
if ($v_result == 0) {
// Change the file status
$p_entry['status'] = 'skipped';
$v_result = 1;
}
// Look for abort result
if ($v_result == 2) {
// This status is internal and will be changed in 'skipped'
$p_entry['status'] = 'aborted';
$v_result = self::ERR_USER_ABORTED;
}
// Update the informations
// Only some fields can be modified
$p_entry['filename'] = $v_local_header['filename'];
}
// Look if extraction should be done
if ($p_entry['status'] == 'ok') {
// Look for specific actions while the file exist
if (file_exists($p_entry['filename'])) {
// Look if file is a directory
if (is_dir($p_entry['filename'])) {
// Change the file status
$p_entry['status'] = 'already_a_directory';
// Look for self::OPT_STOP_ON_ERROR
// For historical reason first PclZip implementation does not stop
// when this kind of error occurs.
if (isset($p_options[self::OPT_STOP_ON_ERROR]) && $p_options[self::OPT_STOP_ON_ERROR] === true) {
$this->privErrorLog(self::ERR_ALREADY_A_DIRECTORY, 'Filename \'' . $p_entry['filename'] . '\' is already used by an existing directory');
return PclZip::errorCode();
}
} else {
if (!is_writeable($p_entry['filename'])) {
// Look if file is write protected
// Change the file status
$p_entry['status'] = "write_protected";
// Look for self::OPT_STOP_ON_ERROR
// For historical reason first PclZip implementation does not stop
// when this kind of error occurs.
if (isset($p_options[self::OPT_STOP_ON_ERROR]) && $p_options[self::OPT_STOP_ON_ERROR] === true) {
$this->privErrorLog(self::ERR_WRITE_OPEN_FAIL, 'Filename \'' . $p_entry['filename'] . '\' exists and is write protected');
return PclZip::errorCode();
}
} else {
//.........这里部分代码省略.........
示例2: privDuplicate
function privDuplicate($p_archive_filename)
{
$v_result = 1;
if (!is_file($p_archive_filename)) {
$v_result = 1;
return $v_result;
}
if (($v_result = $this->privOpenFd('wb')) != 1) {
return $v_result;
}
if (($v_zip_temp_fd = @fopen($p_archive_filename, 'rb')) == 0) {
$this->privCloseFd();
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive file \'' . $p_archive_filename . '\' in binary write mode');
return PclZip::errorCode();
}
$v_size = filesize($p_archive_filename);
while ($v_size != 0) {
$v_read_size = $v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE;
$v_buffer = fread($v_zip_temp_fd, $v_read_size);
@fwrite($this->zip_fd, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
$this->privCloseFd();
@fclose($v_zip_temp_fd);
return $v_result;
}
示例3: array
//.........这里部分代码省略.........
if ($compression !== true) {
pb_backupbuddy::status('details', __('PCLZip compression disabled based on settings.', 'it-l10n-backupbuddy'));
$arguments = array($add_directory, PCLZIP_OPT_NO_COMPRESSION, PCLZIP_OPT_REMOVE_PATH, $add_directory);
} else {
pb_backupbuddy::status('details', __('PCLZip compression enabled based on settings.', 'it-l10n-backupbuddy'));
$arguments = array($add_directory, PCLZIP_OPT_REMOVE_PATH, $add_directory);
}
$mode = 'create';
if (file_exists($zip_file) && $append === true) {
pb_backupbuddy::status('details', __('ZIP file exists. Appending based on options.', 'it-l10n-backupbuddy'));
$mode = 'append';
}
if ($mode == 'append') {
pb_backupbuddy::status('details', __('Appending to ZIP file via PCLZip.', 'it-l10n-backupbuddy'));
$retval = call_user_func_array(array(&$pclzip, 'add'), $arguments);
} else {
// create
pb_backupbuddy::status('details', __('Creating ZIP file via PCLZip', 'it-l10n-backupbuddy') . ':' . implode(';', $arguments));
//error_log( 'pclzip args: ' . print_r( $arguments, true ) . "\n" );
$retval = call_user_func_array(array(&$pclzip, 'create'), $arguments);
}
// Move the zip file if we were creating it in a temporary directory
if (!empty($temporary_zip_directory)) {
if (file_exists($temporary_zip_directory . basename($zip_file))) {
pb_backupbuddy::status('details', __('Renaming PCLZip File...', 'it-l10n-backupbuddy'));
rename($temporary_zip_directory . basename($zip_file), $zip_file);
if (file_exists($zip_file)) {
pb_backupbuddy::status('details', __('Renaming PCLZip success.', 'it-l10n-backupbuddy'));
} else {
pb_backupbuddy::status('details', __('Renaming PCLZip failure.', 'it-l10n-backupbuddy'));
}
} else {
pb_backupbuddy::status('details', __('Temporary PCLZip archive file expected but not found. Please verify permissions on the ZIP archive directory.', 'it-l10n-backupbuddy'));
}
}
// Work out whether we have a problem or not
if (is_array($retval)) {
// It's an array so a good result
$exitcode = 0;
} else {
// Not an array so a bad error code
$exitcode = $pclzip->errorCode();
}
// Convenience for handling different scanarios
$result = false;
// See if we can figure out what happened - note that $exitcode could be non-zero for a warning or error
// There may be no zip file at all if there was a problem creating it or it may be left in the temp
// directory if it couldn't be moved
if (!file_exists($zip_file) || $exitcode != 0) {
// If we had a non-zero exit code then should report it (file may or may not be created)
if ($exitcode != 0) {
pb_backupbuddy::status('details', __('Zip process exit code: ', 'it-l10n-backupbuddy') . $exitcode);
}
// Report whether or not the zip file was created
if (!file_exists($zip_file)) {
pb_backupbuddy::status('details', __('Zip Archive file not created - check process exit code.', 'it-l10n-backupbuddy'));
} else {
pb_backupbuddy::status('details', __('Zip Archive file created but will be removed - check process exit code.', 'it-l10n-backupbuddy'));
@unlink($zip_file);
}
// Put the error information into an array for consistency
$zip_output[] = $pclzip->errorInfo(true);
// Now we don't move it (because either it doesn't exist or may be incomplete) but we'll show any error/wartning output
if (!empty($zip_output)) {
// Assume we don't have a lot of lines for now - could be risky assumption!
foreach ($zip_output as $line) {
pb_backupbuddy::status('details', __('Zip process reported: ', 'it-l10n-backupbuddy') . $line);
}
// Extra details for particular error
if (false !== strpos($pclzip->errorInfo(true), 'PCLZIP_ERR_READ_OPEN_FAIL')) {
pb_backupbuddy::status('details', __('PCLZIP_ERR_READ_OPEN_FAIL details: This error indicates that fopen failed (returned false) when trying to open the file in the mode specified. This is almost always due to permissions.', 'it-l10n-backupbuddy'));
}
}
// One way or another we failed
$result = false;
} else {
// Got file with no error or warnings at all so it should be good to go
if (file_exists($zip_file)) {
pb_backupbuddy::status('details', __('Zip Archive file moved to local archive directory.', 'it-l10n-backupbuddy'));
pb_backupbuddy::status('message', __('Zip Archive file successfully created with no errors or warnings.', 'it-l10n-backupbuddy'));
$result = true;
} else {
pb_backupbuddy::status('details', __('Zip Archive file could not be moved to local archive directory.', 'it-l10n-backupbuddy'));
$result = false;
}
}
if (!empty($temporary_zip_directory)) {
// Cleanup the temporary directory that will have all detritus and maybe incomplete zip file
pb_backupbuddy::status('details', __('Removing temporary directory.', 'it-l10n-backupbuddy'));
if (!$this->delete_directory_recursive($temporary_zip_directory)) {
pb_backupbuddy::status('details', __('Temporary directory could not be deleted: ', 'it-l10n-backupbuddy') . $temporary_zip_directory);
}
}
if ($result) {
return $result;
}
}
// If we made it this far then something didnt result in a success.
return false;
}
示例4: main
/**
* do the work
* @throws BuildException
*/
public function main()
{
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());
}
// shouldn't need to clone, since the entries in filesets
// themselves won't be modified -- only elements will be added
$savedFileSets = $this->filesets;
try {
if (empty($this->filesets)) {
throw new BuildException("You must supply some nested filesets.", $this->getLocation());
}
$this->log("Building ZIP: " . $this->zipFile->__toString(), Project::MSG_INFO);
$zip = new PclZip($this->zipFile->getAbsolutePath());
if ($zip->errorCode() != 1) {
throw new Exception("PclZip::open() failed: " . $zip->errorInfo());
}
foreach ($this->filesets as $fs) {
$files = $fs->getFiles($this->project, $this->includeEmpty);
$fsBasedir = null != $this->baseDir ? $this->baseDir : $fs->getDir($this->project);
$filesToZip = array();
for ($i = 0, $fcount = count($files); $i < $fcount; $i++) {
$f = new PhingFile($fsBasedir, $files[$i]);
//$filesToZip[] = realpath($f->getPath());
$fileAbsolutePath = $f->getPath();
$fileDir = rtrim(dirname($fileAbsolutePath), '/\\');
$fileBase = basename($fileAbsolutePath);
if (substr($fileDir, -4) == '.svn') {
continue;
}
if ($fileBase == '.svn') {
continue;
}
if (substr(rtrim($fileAbsolutePath, '/\\'), -4) == '.svn') {
continue;
}
if ($fileBase == '.gitignore') {
continue;
}
if (strtolower($fileBase) == '.ds_store') {
continue;
}
if ($fileBase == 'Thumbs.db') {
continue;
}
//echo "\t\t$fileAbsolutePath\n";
$filesToZip[] = $f->getPath();
}
/*
$zip->add($filesToZip,
PCLZIP_OPT_ADD_PATH, is_null($this->prefix) ? '' : $this->prefix ,
PCLZIP_OPT_REMOVE_PATH, realpath($fsBasedir->getPath()) );
*/
$zip->add($filesToZip, PCLZIP_OPT_ADD_PATH, is_null($this->prefix) ? '' : $this->prefix, PCLZIP_OPT_REMOVE_PATH, $fsBasedir->getPath());
}
} catch (IOException $ioe) {
$msg = "Problem creating ZIP: " . $ioe->getMessage();
$this->filesets = $savedFileSets;
throw new BuildException($msg, $ioe, $this->getLocation());
}
$this->filesets = $savedFileSets;
}
示例5: define
function _compressFiles($name)
{
require_once MAX_PATH . '/lib/pclzip/pclzip.lib.php';
define('OS_WINDOWS', substr(PHP_OS, 0, 3) == 'WIN' ? 1 : 0);
$target = $this->outputDir . $name . '.zip';
$oZip = new PclZip($target);
$result = $oZip->create($this->aFileList, PCLZIP_OPT_REMOVE_PATH, $this->basePath);
if ($oZip->errorCode()) {
$this->aErrors[] = 'compression error: ' . $oZip->errorName(true);
return false;
}
if (!$result || !count($result)) {
$this->aErrors[] = 'no files were compressed';
return false;
}
//$aContents = $oZip->listContent();
$error = !file_exists($target);
if (!$error) {
foreach ($result as $i => $aInfo) {
if ($aInfo['status'] != 'ok') {
switch ($aInfo['status']) {
case 'filename_too_long':
case 'write_error':
case 'read_error':
case 'invalid_header':
$this->aErrors[] = 'Error: ' . $aInfo['status'] . ' : ' . $aInfo['filename'];
$error = true;
break;
case 'filtered':
case 'skipped':
default:
break;
}
}
}
}
return $error ? false : $target;
}
示例6: create
/**
* create()
*
* A function that creates an archive file
*
* The $excludes will be a list or relative path excludes if the $listmaker object is NULL otehrwise
* will be absolute path excludes and relative path excludes can be had from the $listmaker object
*
* @param string $zip Full path & filename of ZIP Archive file to create
* @param string $dir Full path of directory to add to ZIP Archive file
* @param bool $compression True to enable compression of files added to ZIP Archive file
* @parame array $excludes List of either absolute path exclusions or relative exclusions
* @param string $tempdir Full path of directory for temporary usage
* @param object $listmaker The object from which we can get an inclusions list
* @return bool True if the creation was successful, false otherwise
*
*/
public function create($zip, $dir, $compression, $excludes, $tempdir, $listmaker = NULL)
{
$exitcode = 0;
$zip_output = array();
$temp_zip = '';
$excluding_additional = false;
$exclude_count = 0;
$exclusions = array();
// The basedir must have a trailing directory separator
$basedir = rtrim(trim($dir), DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
$this->status('message', __('Using Compatibility Mode.', 'it-l10n-backupbuddy'));
$this->status('message', __('If your backup times out in Compatibility Mode try disabling zip compression in Settings.', 'it-l10n-backupbuddy'));
require_once ABSPATH . 'wp-admin/includes/class-pclzip.php';
if (empty($tempdir) || !file_exists($tempdir)) {
$this->status('details', __('Temporary working directory must be available.', 'it-l10n-backupbuddy'));
return false;
}
// Decide whether we are offering exclusions or not
// Note that unlike proc and zip we always use inclusion if available to offer exclusion capability for pclzip
if (is_object($listmaker)) {
// Need to get the relative exclusions so we can log what is being excluded...
$exclusions = $listmaker->get_relative_excludes($basedir);
// Build the exclusion list - first the relative directories
if (count($exclusions) > 0) {
$this->status('details', __('Calculating directories to exclude from backup.', 'it-l10n-backupbuddy'));
foreach ($exclusions as $exclude) {
if (!strstr($exclude, 'backupbuddy_backups')) {
// Set variable to show we are excluding additional directories besides backup dir.
$excluding_additional = true;
}
$this->status('details', __('Excluding', 'it-l10n-backupbuddy') . ': ' . $exclude);
$exclude_count++;
}
}
if ($excluding_additional === true) {
$this->status('message', __('Excluding archives directory and additional directories defined in settings.', 'it-l10n-backupbuddy') . ' ' . $exclude_count . ' ' . __('total', 'it-l10n-backupbuddy') . '.');
} else {
$this->status('message', __('Only excluding archives directory based on settings.', 'it-l10n-backupbuddy') . ' ' . $exclude_count . ' ' . __('total', 'it-l10n-backupbuddy') . '.');
}
// Now get the list from the top node
$the_list = $listmaker->get_terminals();
// Retain this for reference for now
file_put_contents(dirname($tempdir) . DIRECTORY_SEPARATOR . self::ZIP_CONTENT_FILE_NAME, print_r($the_list, true));
} else {
// We don't have the inclusion list so we are not offering exclusions
$this->status('message', __('WARNING: Directory/file exclusion unavailable in Compatibility Mode. Even existing old backups will be backed up.', 'it-l10n-backupbuddy'));
$the_list = array($dir);
}
// Get started with out zip object
// Put our final zip file in the temporary directory - it will be moved later
$temp_zip = $tempdir . basename($zip);
$pclzip = new PclZip($temp_zip);
if ($compression !== true) {
$this->status('details', __('Compression disabled based on settings.', 'it-l10n-backupbuddy'));
$arguments = array($the_list, PCLZIP_OPT_NO_COMPRESSION, PCLZIP_OPT_REMOVE_PATH, $dir);
} else {
$arguments = array($the_list, PCLZIP_OPT_REMOVE_PATH, $dir);
}
if (file_exists($zip)) {
$this->status('details', __('Existing ZIP Archive file will be replaced.', 'it-l10n-backupbuddy'));
unlink($zip);
}
// Now actually create the zip archive file
$this->status('details', $this->get_method_tag() . __(' commmand arguments', 'it-l10n-backupbuddy') . ': ' . implode(';', $arguments));
$retval = call_user_func_array(array(&$pclzip, 'create'), $arguments);
// Work out whether we have a problem or not
if (is_array($retval)) {
// It's an array so a good result
$exitcode = 0;
} else {
// Not an array so a bad error code
$exitcode = $pclzip->errorCode();
}
// Convenience for handling different scanarios
$result = false;
// See if we can figure out what happened - note that $exitcode could be non-zero for a warning or error
if (!file_exists($temp_zip) || $exitcode != 0) {
// If we had a non-zero exit code then should report it (file may or may not be created)
if ($exitcode != 0) {
$this->status('details', __('Zip process exit code: ', 'it-l10n-backupbuddy') . $exitcode);
}
// Report whether or not the zip file was created
if (!file_exists($temp_zip)) {
//.........这里部分代码省略.........
示例7: makezip_addfiles
private function makezip_addfiles()
{
global $updraftplus;
# Used to detect requests to bump the size
$bump_index = false;
$zipfile = $this->zip_basename . ($this->index == 0 ? '' : $this->index + 1) . '.zip.tmp';
$maxzipbatch = $updraftplus->jobdata_get('maxzipbatch', 26214400);
if ((int) $maxzipbatch < 1) {
$maxzipbatch = 26214400;
}
// Short-circuit the null case, because we want to detect later if something useful happenned
if (count($this->zipfiles_dirbatched) == 0 && count($this->zipfiles_batched) == 0) {
return true;
}
# If on PclZip, then if possible short-circuit to a quicker method (makes a huge time difference - on a folder of 1500 small files, 2.6s instead of 76.6)
# This assumes that makezip_addfiles() is only called once so that we know about all needed files (the new style)
# This is rather conservative - because it assumes zero compression. But we can't know that in advance.
if (0 == $this->index && 'UpdraftPlus_PclZip' == $this->use_zip_object && $this->makezip_recursive_batchedbytes < $this->zip_split_every && ($this->makezip_recursive_batchedbytes < 512 * 1024 * 1024 || defined('UPDRAFTPLUS_PCLZIP_FORCEALLINONE') && UPDRAFTPLUS_PCLZIP_FORCEALLINONE == true)) {
$updraftplus->log("PclZip, and only one archive required - will attempt to do in single operation (data: " . round($this->makezip_recursive_batchedbytes / 1024, 1) . " Kb, split: " . round($this->zip_split_every / 1024, 1) . " Kb)");
if (!class_exists('PclZip')) {
require_once ABSPATH . '/wp-admin/includes/class-pclzip.php';
}
$zip = new PclZip($zipfile);
$remove_path = $this->whichone == 'wpcore' ? untrailingslashit(ABSPATH) : WP_CONTENT_DIR;
$add_path = false;
// Remove prefixes
$backupable_entities = $updraftplus->get_backupable_file_entities(true);
if (isset($backupable_entities[$this->whichone])) {
if ('plugins' == $this->whichone || 'themes' == $this->whichone || 'uploads' == $this->whichone) {
$remove_path = dirname($backupable_entities[$this->whichone]);
# To normalise instead of removing (which binzip doesn't support, so we don't do it), you'd remove the dirname() in the above line, and uncomment the below one.
#$add_path = $this->whichone;
} else {
$remove_path = $backupable_entities[$this->whichone];
}
}
if ($add_path) {
$zipcode = $zip->create($this->source, PCLZIP_OPT_REMOVE_PATH, $remove_path, PCLZIP_OPT_ADD_PATH, $add_path);
} else {
$zipcode = $zip->create($this->source, PCLZIP_OPT_REMOVE_PATH, $remove_path);
}
if ($zipcode == 0) {
$updraftplus->log("PclZip Error: " . $zip->errorInfo(true), 'warning');
return $zip->errorCode();
} else {
return true;
}
}
// 05-Mar-2013 - added a new check on the total data added; it appears that things fall over if too much data is contained in the cumulative total of files that were addFile'd without a close-open cycle; presumably data is being stored in memory. In the case in question, it was a batch of MP3 files of around 100Mb each - 25 of those equals 2.5Gb!
$data_added_since_reopen = 0;
# The following array is used only for error reporting if ZipArchive::close fails (since that method itself reports no error messages - we have to track manually what we were attempting to add)
$files_zipadded_since_open = array();
$zip = new $this->use_zip_object();
if (file_exists($zipfile)) {
$opencode = $zip->open($zipfile);
$original_size = filesize($zipfile);
clearstatcache();
} else {
$create_code = defined('ZIPARCHIVE::CREATE') ? ZIPARCHIVE::CREATE : 1;
$opencode = $zip->open($zipfile, $create_code);
$original_size = 0;
}
if ($opencode !== true) {
return new WP_Error('no_open', sprintf(__('Failed to open the zip file (%s) - %s', 'updraftplus'), $zipfile, $zip->last_error));
}
// Make sure all directories are created before we start creating files
while ($dir = array_pop($this->zipfiles_dirbatched)) {
$zip->addEmptyDir($dir);
}
$zipfiles_added_thisbatch = 0;
// Go through all those batched files
foreach ($this->zipfiles_batched as $file => $add_as) {
$fsize = filesize($file);
if ($fsize > UPDRAFTPLUS_WARN_FILE_SIZE) {
$updraftplus->log(sprintf(__('A very large file was encountered: %s (size: %s Mb)', 'updraftplus'), $add_as, round($fsize / 1048576, 1)), 'warning');
}
// Skips files that are already added
if (!isset($this->existing_files[$add_as]) || $this->existing_files[$add_as] != $fsize) {
@touch($zipfile);
$zip->addFile($file, $add_as);
$zipfiles_added_thisbatch++;
$this->zipfiles_added_thisrun++;
$files_zipadded_since_open[] = array('file' => $file, 'addas' => $add_as);
$data_added_since_reopen += $fsize;
/* Conditions for forcing a write-out and re-open:
- more than $maxzipbatch bytes have been batched
- more than 1.5 seconds have passed since the last time we wrote
- that adding this batch of data is likely already enough to take us over the split limit (and if that happens, then do actually split - to prevent a scenario of progressively tinier writes as we approach but don't actually reach the limit)
- more than 500 files batched (should perhaps intelligently lower this as the zip file gets bigger - not yet needed)
*/
# Add 10% margin. It only really matters when the OS has a file size limit, exceeding which causes failure (e.g. 2Gb on 32-bit)
# Since we don't test before the file has been created (so that zip_last_ratio has meaningful data), we rely on max_zip_batch being less than zip_split_every - which should always be the case
$reaching_split_limit = $this->zip_last_ratio > 0 && $original_size > 0 && $original_size + 1.1 * $data_added_since_reopen * $this->zip_last_ratio > $this->zip_split_every ? true : false;
if ($zipfiles_added_thisbatch > 500 || $reaching_split_limit || $data_added_since_reopen > $maxzipbatch || time() - $this->zipfiles_lastwritetime > 1.5) {
$something_useful_sizetest = false;
if ($data_added_since_reopen > $maxzipbatch) {
$something_useful_sizetest = true;
$updraftplus->log("Adding batch to zip file (" . $this->use_zip_object . "): over " . round($maxzipbatch / 1048576, 1) . " Mb added on this batch (" . round($data_added_since_reopen / 1048576, 1) . " Mb, " . count($this->zipfiles_batched) . " files batched, {$zipfiles_added_thisbatch} (" . $this->zipfiles_added_thisrun . ") added so far); re-opening (prior size: " . round($original_size / 1024, 1) . ' Kb)');
} elseif ($zipfiles_added_thisbatch > 500) {
$updraftplus->log("Adding batch to zip file (" . $this->use_zip_object . "): over 500 files added on this batch (" . round($data_added_since_reopen / 1048576, 1) . " Mb, " . count($this->zipfiles_batched) . " files batched, {$zipfiles_added_thisbatch} (" . $this->zipfiles_added_thisrun . ") added so far); re-opening (prior size: " . round($original_size / 1024, 1) . ' Kb)');
//.........这里部分代码省略.........
示例8: array
/**
* This 'file' process
*
* @since 1.0.6
* @see
*
* @param none
*
* @return none
*/
function snapshot_ajax_backup_file($item, $_post_array)
{
$error_status = array();
$error_status['errorStatus'] = false;
$error_status['errorText'] = "";
$error_status['responseText'] = "";
$home_path = apply_filters('snapshot_home_path', get_home_path());
if (isset($_post_array['snapshot-file-data-key'])) {
$file_data_key = sanitize_text_field($_post_array['snapshot-file-data-key']);
if (isset($this->_session->data['files_data']['included'][$file_data_key])) {
@set_time_limit(0);
$backupZipFile = trailingslashit($this->_session->data['backupItemFolder']) . 'snapshot-backup.zip';
if ($this->config_data['config']['zipLibrary'] == "PclZip") {
$zipArchive = new PclZip($backupZipFile);
try {
$zip_add_ret = $zipArchive->add($this->_session->data['files_data']['included'][$file_data_key], PCLZIP_OPT_REMOVE_PATH, $home_path, PCLZIP_OPT_ADD_PATH, 'www', PCLZIP_OPT_TEMP_FILE_THRESHOLD, 10, PCLZIP_OPT_ADD_TEMP_FILE_ON);
if (!$zip_add_ret) {
$error_status['errorStatus'] = true;
$error_status['errorText'] = "ERROR: PcLZIP file:" . $file_data_key . " add failed " . $zipArchive->errorCode() . ": " . $zipArchive->errorInfo();
return $error_status;
}
} catch (Exception $e) {
$error_status['errorStatus'] = true;
$error_status['errorText'] = "ERROR: PclZIP file:" . $file_data_key . " : add failed : " . $zipArchive->errorCode() . ": " . $zipArchive->errorInfo();
return $error_status;
}
} else {
if ($this->config_data['config']['zipLibrary'] == "ZipArchive") {
$zipArchive = new ZipArchive();
if ($zipArchive) {
if (!file_exists($backupZipFile)) {
$zip_flags = ZIPARCHIVE::CREATE;
} else {
$zip_flags = null;
}
$zip_hdl = $zipArchive->open($backupZipFile, $zip_flags);
if ($zip_hdl !== true) {
$error_status['errorStatus'] = true;
$error_status['errorText'] = "ERROR: ZipArchive file:" . $file_data_key . " : add failed: " . ZipArchiveStatusString($zip_hdl);
return $error_status;
}
$fileCount = 0;
foreach ($this->_session->data['files_data']['included'][$file_data_key] as $file) {
$file = str_replace('\\', '/', $file);
$zipArchive->addFile($file, str_replace($home_path, 'www/', $file));
// Per some PHP documentation.
/*
When a file is set to be added to the archive, PHP will attempt to lock the file and it is
only released once the ZIP operation is done. In short, it means you can first delete an
added file after the archive is closed. Related to this there is a limit to the number of
files that can be added at once. So we are setting a limit of 200 files per add session.
Then we close the archive and re-open.
*/
$fileCount += 1;
if ($fileCount >= 200) {
$zipArchive->close();
$zip_hdl = $zipArchive->open($backupZipFile, $zip_flags);
$fileCount = 0;
}
}
$zipArchive->close();
}
}
}
if (isset($zipArchive)) {
unset($zipArchive);
}
foreach ($this->_session->data['files_data']['included'][$file_data_key] as $idx => $filename) {
$filename = str_replace($home_path, '', $filename);
$this->snapshot_logger->log_message("file: " . $filename);
}
}
}
return $error_status;
}
示例9: basename
function make_zipfile($source, $destination, $whichone = '')
{
global $updraftplus;
$destination_base = basename($destination);
// Legacy/redundant
if (empty($whichone) && is_string($whichone)) {
$whichone = basename($source);
}
// When to prefer PCL:
// - We were asked to
// - No zip extension present and no relevant method present
// The zip extension check is not redundant, because method_exists segfaults some PHP installs, leading to support requests
// We need meta-info about $whichone
$backupable_entities = $updraftplus->get_backupable_file_entities(true, false);
// Fallback to PclZip - which my tests show is 25% slower (and we can't resume)
if ($this->zip_preferpcl || !extension_loaded('zip') && !method_exists('ZipArchive', 'AddFile')) {
if (!class_exists('PclZip')) {
require_once ABSPATH . '/wp-admin/includes/class-pclzip.php';
}
$zip_object = new PclZip($destination);
$remove_path = WP_CONTENT_DIR;
$add_path = false;
// Remove prefixes
if (isset($backupable_entities[$whichone])) {
if ('plugins' == $whichone || 'themes' == $whichone || 'uploads' == $whichone) {
$remove_path = dirname($backupable_entities[$whichone]);
# To normalise instead of removing (which binzip doesn't support, so we don't do it), you'd remove the dirname() in the above line, and uncomment the below one.
#$add_path = $whichone;
} else {
$remove_path = $backupable_entities[$whichone];
}
}
if ($add_path) {
$zipcode = $zip_object->create($source, PCLZIP_OPT_REMOVE_PATH, $remove_path, PCLZIP_OPT_ADD_PATH, $add_path);
} else {
$zipcode = $zip_object->create($source, PCLZIP_OPT_REMOVE_PATH, $remove_path);
}
if ($zipcode == 0) {
$updraftplus->log("PclZip Error: " . $zip_object->errorInfo(true), 'warning');
return $zip_object->errorCode();
} else {
return true;
}
}
if ($this->binzip === false && (!defined('UPDRAFTPLUS_NO_BINZIP') || !UPDRAFTPLUS_NO_BINZIP)) {
$updraftplus->log('Checking if we have a zip executable available');
$binzip = $updraftplus->find_working_bin_zip();
if (is_string($binzip)) {
$updraftplus->log("Found one: {$binzip}");
$this->binzip = $binzip;
}
}
// TODO: Handle stderr?
// We only use binzip up to resumption 8, in case there is some undetected problem. We can make this more sophisticated if a need arises.
if (is_string($this->binzip) && $updraftplus->current_resumption < 9) {
if (is_string($source)) {
$source = array($source);
}
$all_ok = true;
$debug = UpdraftPlus_Options::get_updraft_option('updraft_debug_mode');
# Don't use -q and do use -v, as we rely on output to process to detect useful activity
$zip_params = '-v';
$orig_size = file_exists($destination) ? filesize($destination) : 0;
$last_size = $orig_size;
clearstatcache();
foreach ($source as $s) {
$exec = "cd " . escapeshellarg(dirname($s)) . "; " . $this->binzip . " {$zip_params} -u -r " . escapeshellarg($destination) . " " . escapeshellarg(basename($s)) . " ";
$updraftplus->log("Attempting binary zip ({$exec})");
$handle = popen($exec, "r");
$something_useful_happened = $updraftplus->something_useful_happened;
if ($handle) {
while (!feof($handle)) {
$w = fgets($handle, 1024);
// Logging all this really slows things down
if ($w && $debug) {
$updraftplus->log("Output from zip: " . trim($w), 'debug');
}
if (file_exists($destination)) {
$new_size = filesize($destination);
if (!$something_useful_happened && $new_size > $orig_size + 20) {
$updraftplus->something_useful_happened();
$something_useful_happened = true;
}
clearstatcache();
# Log when 20% bigger or at least every 50Mb
if ($new_size > $last_size * 1.2 || $new_size > $last_size + 52428800) {
$updraftplus->log(sprintf("{$destination_base}: size is now: %.2f Mb", round($new_size / 1048576, 1)));
$last_size = $new_size;
}
}
}
$ret = pclose($handle);
// Code 12 = nothing to do
if ($ret != 0 && $ret != 12) {
$updraftplus->log("Binary zip: error (code: {$ret})");
if ($w && !$debug) {
$updraftplus->log("Last output from zip: " . trim($w), 'debug');
}
$all_ok = false;
}
//.........这里部分代码省略.........
示例10: insitem
function insitem()
{
//checkPerm( 'view', FALSE, 'storage' );
require_once _base_ . '/lib/lib.upload.php';
require_once _base_ . '/addons/pclzip/pclzip.lib.php';
require_once dirname(__FILE__) . '/RendererDb.php';
require_once dirname(__FILE__) . '/CPManager.php';
$back_url = urldecode($_POST['back_url']);
// there is a file?
if ($_FILES['attach']['name'] == '') {
$_SESSION['last_error'] = _FILEUNSPECIFIED;
Util::jump_to('' . $back_url . '&create_result=0');
}
$path = str_replace('\\', '/', '/appLms/' . Get::sett('pathscorm'));
$savefile = getLogUserId() . '_' . rand(0, 100) . '_' . time() . '_' . $_FILES['attach']['name'];
if (!file_exists($GLOBALS['where_files_relative'] . $path . $savefile)) {
sl_open_fileoperations();
if (!sl_upload($_FILES['attach']['tmp_name'], $path . $savefile)) {
//if( !move_uploaded_file($_FILES['attach']['tmp_name'], $GLOBALS['where_files_relative'].$path.$savefile ) ) {
sl_close_fileoperations();
$_SESSION['last_error'] = _ERROR_UPLOAD;
Util::jump_to('' . $back_url . '&create_result=0');
}
} else {
sl_close_fileoperations();
$_SESSION['last_error'] = _ERROR_UPLOAD;
Util::jump_to('' . $back_url . '&create_result=0');
}
// compute filepath
$filepath = $path . $savefile . STRPOSTCONTENT;
// extract zip file
$zip = new PclZip($path . $savefile);
// check disk quota --------------------------------------------------
if (isset($_SESSION['idCourse']) && defined("LMS")) {
$zip_content = $zip->listContent();
$zip_extracted_size = 0;
while (list(, $file_info) = each($zip_content)) {
$zip_extracted_size += $file_info['size'];
}
$quota = $GLOBALS['course_descriptor']->getQuotaLimit();
$used = $GLOBALS['course_descriptor']->getUsedSpace();
if (Util::exceed_quota(false, $quota, $used, $zip_extracted_size)) {
sl_unlink($path . $savefile);
$_SESSION['last_error'] = Lang::t('_QUOTA_EXCEDED');
Util::jump_to('' . $back_url . '&create_result=0');
}
$GLOBALS['course_descriptor']->addFileToUsedSpace(false, $zip_extracted_size);
}
// extract zip ------------------------------------------------------
$zip->extract(PCLZIP_OPT_PATH, $filepath);
if ($zip->errorCode() != PCLZIP_ERR_NO_ERROR && $zip->errorCode() != 1) {
sl_unlink($path . $savefile);
$_SESSION['last_error'] = _ERROR_UPLOAD;
sl_close_fileoperations();
Util::jump_to('' . $back_url . '&create_result=0');
}
/* remove zip file */
sl_unlink($path . $savefile);
sl_close_fileoperations();
$cpm = new CPManager();
// try to open content package
if (!$cpm->Open($GLOBALS['where_files_relative'] . $filepath)) {
$_SESSION['last_error'] = 'Error: ' . $cpm->errText . ' [' . $cpm->errCode . ']';
Util::jump_to('' . $back_url . '&create_result=0');
}
// and parse the manifest
if (!$cpm->ParseManifest()) {
$_SESSION['last_error'] = 'Error: ' . $cpm->errText . ' [' . $cpm->errCode . ']';
Util::jump_to('' . $back_url . '&create_result=0');
}
// create entry in content package table
$query = "INSERT INTO " . $GLOBALS['prefix_lms'] . "_scorm_package" . " (idpackage,idProg,path,defaultOrg,idUser,scormVersion) VALUES" . " ('" . addslashes($cpm->identifier) . "','0','" . $savefile . STRPOSTCONTENT . "','" . addslashes($cpm->defaultOrg) . "','" . (int) getLogUserId() . "','" . $cpm->scorm_version . "')";
if (!($result = sql_query($query))) {
$_SESSION['last_error'] = _OPERATION_FAILURE;
Util::jump_to('' . $back_url . '&create_result=0');
}
$idscorm_package = mysql_insert_id();
// create the n entries in resources table
for ($i = 0; $i < $cpm->GetResourceNumber(); $i++) {
$info = $cpm->GetResourceInfo($cpm->GetResourceIdentifier($i));
$query = "INSERT INTO " . $GLOBALS['prefix_lms'] . "_scorm_resources (idsco,idscorm_package,scormtype,href)" . " VALUES ('" . addslashes($info['identifier']) . "','" . (int) $idscorm_package . "','" . $info['scormtype'] . "','" . addslashes($info['href']) . "')";
$result = sql_query($query);
if (!$result) {
$_SESSION['last_error'] = _OPERATION_FAILURE;
Util::jump_to('' . $back_url . '&create_result=0');
} else {
if (mysql_affected_rows() == 0) {
$_SESSION['last_error'] = _OPERATION_FAILURE;
Util::jump_to('' . $back_url . '&create_result=0');
}
}
}
$rdb = new RendererDb($GLOBALS['dbConn'], $GLOBALS['prefix_lms'], $idscorm_package);
$orgElems = $cpm->orgElems;
// save all organizations
for ($iOrg = 0; $iOrg < $orgElems->getLength(); $iOrg++) {
$org = $orgElems->item($iOrg);
$cpm->RenderOrganization($org->getAttribute('identifier'), $rdb);
}
if ($_POST['lesson_resources'] == 'import' || $cpm->defaultOrg == '-resource-') {
//.........这里部分代码省略.........
示例11: foreach
}
// unzip to buffer and store in DB / fetch ach entry as single process, to surpress buffer overflow
foreach ($aRequestVars['restore_id'] as $index => $iArchiveIndex) {
$oArchive = new PclZip($aRequestVars['ArchiveFile']);
$sDroplet = $oArchive->extract(PCLZIP_OPT_BY_INDEX, $iArchiveIndex, PCLZIP_OPT_EXTRACT_AS_STRING);
if ($sDroplet == 0) {
msgQueue::add('UNABLE TO UNZIP FILE' . '::' . $oArchive->errorInfo(true));
} else {
// $sSearchFor = 'php';
// $file_types = preg_replace( '/\s*[,;\|#]\s*/','|',$sSearchFor );
// if (!preg_match('/^(to|cc|bcc|Reply-To)$/', $kind)) {
$aDroplet['name'] = $sDroplet[0]['filename'];
$aDroplet['content'] = explode("\n", $sDroplet[0]['content']);
// if ( !preg_match('/'.$file_types.'/si', $aDroplet['name'], $aMatch) ) {
// continue; }
if ($sTmp = insertDroplet($aDroplet, false)) {
$aUnzipDroplets[] = $sTmp;
}
}
}
//
if (($error = $oArchive->errorCode()) != 0) {
msgQueue::add(sizeof($aUnzipDroplets) . ' ' . $Droplet_Import['ARCHIV_IMPORTED']);
} else {
if (sizeof($aUnzipDroplets) > 0) {
msgQueue::add(implode(', ', $aUnzipDroplets) . '<br />' . sizeof($aUnzipDroplets) . ' ' . $Droplet_Import['ARCHIV_IMPORTED'], true);
} else {
msgQueue::add(sizeof($aUnzipDroplets) . ' ' . $Droplet_Import['ARCHIV_IMPORTED'], true);
}
}
}
示例12: privDirCheck
function privDirCheck($p_dir, $p_is_dir = false)
{
$v_result = 1;
if ($p_is_dir && substr($p_dir, -1) == '/') {
$p_dir = substr($p_dir, 0, strlen($p_dir) - 1);
}
if (is_dir($p_dir) || $p_dir == "") {
return 1;
}
$p_parent_dir = dirname($p_dir);
if ($p_parent_dir != $p_dir) {
if ($p_parent_dir != "") {
if (($v_result = $this->privDirCheck($p_parent_dir)) != 1) {
return $v_result;
}
}
}
if (!@mkdir($p_dir, 0777)) {
PclZip::privErrorLog(PCLZIP_ERR_DIR_CREATE_FAIL, "Unable to create directory '{$p_dir}'");
return PclZip::errorCode();
}
return $v_result;
}
示例13: zip_to
/**
* Recursively ZIPs a directory via PHP.
*
* @param string $dir A full directory path to ZIP.
*
* @param string $to A new ZIP file path — to ZIP `$dir` into.
* The directory this lives in MUST already exist and be writable.
* If this file already exists, an exception will be thrown.
*
* @return string New ZIP file location; else an exception is thrown.
*
* @throws exception If invalid types are passed through arguments list.
* @throws exception If the `$dir` is NOT a readable directory, or CANNOT be zipped for any reason.
* @throws exception If the `$to` ZIP already exists, or CANNOT be created by this routine for any reason.
* @throws exception If the `$to` ZIP does NOT end with the proper `.zip` extension.
* @throws exception If the `$to` ZIP parent directory does NOT exist or is not writable.
* @throws \exception The PclZip class may throw exceptions of it's own here.
*/
public function zip_to($dir, $to)
{
$this->check_arg_types('string:!empty', 'string:!empty', func_get_args());
$dir = $this->n_seps($dir);
$to = $this->n_seps($to);
$to_dir = $this->n_seps_up($to);
if (!class_exists('\\PclZip')) {
require_once ABSPATH . 'wp-admin/includes/class-pclzip.php';
}
if (!is_dir($dir)) {
throw $this->©exception($this->method(__FUNCTION__) . '#source_dir_missing', get_defined_vars(), $this->__('Unable to ZIP a directory (source `dir` missing).') . ' ' . sprintf($this->__('Non-existent source directory: `%1$s`.'), $dir));
}
if (!is_readable($dir)) {
throw $this->©exception($this->method(__FUNCTION__) . '#read_write_issues', get_defined_vars(), $this->__('Unable to ZIP a directory; not readable; due to permission issues.') . ' ' . sprintf($this->__('Need this directory to be readable please: `%1$s`.'), $dir));
}
if (file_exists($to)) {
throw $this->©exception($this->method(__FUNCTION__) . '#existing_zip', get_defined_vars(), $this->__('Destination ZIP exists; it MUST first be deleted please.') . ' ' . sprintf($this->__('Please check this ZIP archive: `%1$s`.'), $to));
}
if ($this->extension($to) !== 'zip') {
throw $this->©exception($this->method(__FUNCTION__) . '#invalid_zip', get_defined_vars(), $this->__('Invalid ZIP extension. The destination must end with `.zip`.') . ' ' . sprintf($this->__('Instead got: `%1$s`.'), $to));
}
if (!is_dir($to_dir)) {
throw $this->©exception($this->method(__FUNCTION__) . '#zip_to_dir_missing', get_defined_vars(), $this->__('Destination ZIP directory does NOT exist yet.') . ' ' . sprintf($this->__('Please check this directory: `%1$s`.'), $to_dir));
}
if (!is_writable($to_dir)) {
throw $this->©exception($this->method(__FUNCTION__) . '#zip_to_dir_permissions', get_defined_vars(), $this->__('Destination ZIP directory is not writable.') . ' ' . sprintf($this->__('Please check permissions on this directory: `%1$s`.'), $to_dir));
}
$archive = new \PclZip($to);
if (!$archive->create($dir, PCLZIP_OPT_REMOVE_PATH, $this->n_seps_up($dir))) {
throw $this->©exception($this->method(__FUNCTION__) . '#pclzip_archive_failure#' . $archive->errorCode(), get_defined_vars(), sprintf($this->__('PclZip archive failure: `%1$s`.'), $archive->errorInfo(TRUE)));
}
return $to;
// It's a good day in Eureka!
}
示例14: privMerge
function privMerge(&$p_archive_to_add)
{
$v_result = 1;
// ----- Look if the archive_to_add exists
if (!is_file($p_archive_to_add->zipname)) {
// ----- Nothing to merge, so merge is a success
$v_result = 1;
// ----- Return
return $v_result;
}
// ----- Look if the archive exists
if (!is_file($this->zipname)) {
// ----- Do a duplicate
$v_result = $this->privDuplicate($p_archive_to_add->zipname);
// ----- Return
return $v_result;
}
// ----- Open the zip file
if (($v_result = $this->privOpenFd('rb')) != 1) {
// ----- Return
return $v_result;
}
// ----- Read the central directory informations
$v_central_dir = array();
if (($v_result = $this->privReadEndCentralDir($v_central_dir)) != 1) {
$this->privCloseFd();
return $v_result;
}
// ----- Go to beginning of File
@rewind($this->zip_fd);
// ----- Open the archive_to_add file
if (($v_result = $p_archive_to_add->privOpenFd('rb')) != 1) {
$this->privCloseFd();
// ----- Return
return $v_result;
}
// ----- Read the central directory informations
$v_central_dir_to_add = array();
if (($v_result = $p_archive_to_add->privReadEndCentralDir($v_central_dir_to_add)) != 1) {
$this->privCloseFd();
$p_archive_to_add->privCloseFd();
return $v_result;
}
// ----- Go to beginning of File
@rewind($p_archive_to_add->zip_fd);
// ----- Creates a temporay file
$v_zip_temp_name = PCLZIP_TEMPORARY_DIR . uniqid('pclzip-') . '.tmp';
// ----- Open the temporary file in write mode
if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0) {
$this->privCloseFd();
$p_archive_to_add->privCloseFd();
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \'' . $v_zip_temp_name . '\' in binary write mode');
// ----- Return
return PclZip::errorCode();
}
// ----- Copy the files from the archive to the temporary file
// TBC : Here I should better append the file and go back to erase the central dir
$v_size = $v_central_dir['offset'];
while ($v_size != 0) {
$v_read_size = $v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE;
$v_buffer = fread($this->zip_fd, $v_read_size);
@fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Copy the files from the archive_to_add into the temporary file
$v_size = $v_central_dir_to_add['offset'];
while ($v_size != 0) {
$v_read_size = $v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE;
$v_buffer = fread($p_archive_to_add->zip_fd, $v_read_size);
@fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Store the offset of the central dir
$v_offset = @ftell($v_zip_temp_fd);
// ----- Copy the block of file headers from the old archive
$v_size = $v_central_dir['size'];
while ($v_size != 0) {
$v_read_size = $v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE;
$v_buffer = @fread($this->zip_fd, $v_read_size);
@fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Copy the block of file headers from the archive_to_add
$v_size = $v_central_dir_to_add['size'];
while ($v_size != 0) {
$v_read_size = $v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE;
$v_buffer = @fread($p_archive_to_add->zip_fd, $v_read_size);
@fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Merge the file comments
$v_comment = $v_central_dir['comment'] . ' ' . $v_central_dir_to_add['comment'];
// ----- Calculate the size of the (new) central header
$v_size = @ftell($v_zip_temp_fd) - $v_offset;
// ----- Swap the file descriptor
// Here is a trick : I swap the temporary fd with the zip fd, in order to use
// the following methods on the temporary fil and not the real archive fd
$v_swap = $this->zip_fd;
$this->zip_fd = $v_zip_temp_fd;
$v_zip_temp_fd = $v_swap;
//.........这里部分代码省略.........
示例15: privGrow
function privGrow($p_filedescr_list, &$p_result_list, &$p_options)
{
$v_result = 1;
$v_list_detail = array();
// ----- Look if the archive exists or is empty
if (!is_file($this->_za->zipname) || filesize($this->_za->zipname) == 0) {
// ----- Do a create
$v_result = $this->_za->privCreate($p_filedescr_list, $p_result_list, $p_options);
// ----- Return
return $v_result;
}
// ----- Magic quotes trick
$this->_za->privDisableMagicQuotes();
// ----- Open the zip file
// ----- Open the zip file in r/w binary mode with no truncation and file pointer at start
if (($v_result = $this->_za->privOpenFd('c+b')) != 1) {
// ----- Magic quotes trick
$this->_za->privSwapBackMagicQuotes();
// ----- Return
return $v_result;
}
// ----- Read the central directory informations
$v_central_dir = array();
if (($v_result = $this->_za->privReadEndCentralDir($v_central_dir)) != 1) {
$this->_za->privCloseFd();
$this->_za->privSwapBackMagicQuotes();
return $v_result;
}
// ----- Go to beginning of File
//@rewind($this->_za->zip_fd);
// ----- Go to the start of the central dir
@fseek($this->_za->zip_fd, $v_central_dir['offset']);
// ----- Creates a temporay file
//$v_zip_temp_name = PCLZIP_TEMPORARY_DIR.uniqid('pclzip-').'.tmp';
$v_zip_temp_name = 'php://temp/maxmemory:10485760';
// ----- Open the temporary file in write mode
//if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0)
// ----- Open the temporary file in read/write mode
if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'w+b')) == 0) {
$this->_za->privCloseFd();
$this->_za->privSwapBackMagicQuotes();
//PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \''.$v_zip_temp_name.'\' in binary write mode');
PclZip::privErrorLog(PCLZIP_ERR_READ_OPEN_FAIL, 'Unable to open temporary file \'' . $v_zip_temp_name . '\' in binary read/write mode');
// ----- Return
return PclZip::errorCode();
}
// ----- Copy the files from the archive to the temporary file
// TBC : Here I should better append the file and go back to erase the central dir
//$v_size = $v_central_dir['offset'];
// ----- Copy the existing central dir to a temporary file
$v_size = $v_central_dir['size'];
while ($v_size != 0) {
$v_read_size = $v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE;
$v_buffer = fread($this->_za->zip_fd, $v_read_size);
@fwrite($v_zip_temp_fd, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Swap the file descriptor
// Here is a trick : I swap the temporary fd with the zip fd, in order to use
// the following methods on the temporary fil and not the real archive
//$v_swap = $this->_za->zip_fd;
//$this->_za->zip_fd = $v_zip_temp_fd;
//$v_zip_temp_fd = $v_swap;
// ----- Modify existing zip file so keep file descriptors as they are
// ----- Now truncate after existing files and seek to end to add new files
@rewind($this->_za->zip_fd);
@ftruncate($this->_za->zip_fd, $v_central_dir['offset']);
@fseek($this->_za->zip_fd, 0, SEEK_END);
// ----- Add the files
$v_header_list = array();
if (($v_result = $this->_za->privAddFileList($p_filedescr_list, $v_header_list, $p_options)) != 1) {
fclose($v_zip_temp_fd);
$this->_za->privCloseFd();
//@unlink($v_zip_temp_name);
$this->_za->privSwapBackMagicQuotes();
// ----- Return
return $v_result;
}
// ----- Store the offset of the central dir
$v_offset = @ftell($this->_za->zip_fd);
// ----- Rewind temp file ready to copy original central dir entries
@rewind($v_zip_temp_fd);
// ----- Copy the block of file headers from the old archive
$v_size = $v_central_dir['size'];
while ($v_size != 0) {
$v_read_size = $v_size < PCLZIP_READ_BLOCK_SIZE ? $v_size : PCLZIP_READ_BLOCK_SIZE;
$v_buffer = @fread($v_zip_temp_fd, $v_read_size);
@fwrite($this->_za->zip_fd, $v_buffer, $v_read_size);
$v_size -= $v_read_size;
}
// ----- Create the Central Dir files header
for ($i = 0, $v_count = 0; $i < sizeof($v_header_list); $i++) {
// ----- Create the file header
if ($v_header_list[$i]['status'] == 'ok') {
if (($v_result = $this->_za->privWriteCentralFileHeader($v_header_list[$i])) != 1) {
fclose($v_zip_temp_fd);
$this->_za->privCloseFd();
//@unlink($v_zip_temp_name);
$this->_za->privSwapBackMagicQuotes();
// ----- Return
//.........这里部分代码省略.........