本文整理汇总了PHP中AEFactory::getTimer方法的典型用法代码示例。如果您正苦于以下问题:PHP AEFactory::getTimer方法的具体用法?PHP AEFactory::getTimer怎么用?PHP AEFactory::getTimer使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类AEFactory
的用法示例。
在下文中一共展示了AEFactory::getTimer方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: _addFile
protected function _addFile($isVirtual, &$sourceNameOrData, $targetName)
{
if ($isVirtual) {
AEUtilLogger::WriteLog(_AE_LOG_DEBUG, "-- Adding {$targetName} to archive (virtual data)");
} else {
AEUtilLogger::WriteLog(_AE_LOG_DEBUG, "-- Adding {$targetName} to archive (source: {$sourceNameOrData})");
}
$configuration = AEFactory::getConfiguration();
$timer = AEFactory::getTimer();
// Initialize archive file pointer
$fp = null;
// Initialize inode change timestamp
$filectime = 0;
$processingFile = $configuration->get('volatile.engine.archiver.processingfile', false);
if (!$processingFile) {
// Uncache data
$configuration->set('volatile.engine.archiver.sourceNameOrData', null);
$configuration->set('volatile.engine.archiver.unc_len', null);
$configuration->set('volatile.engine.archiver.resume', null);
$configuration->set('volatile.engine.archiver.processingfile', false);
// See if it's a directory
$isDir = $isVirtual ? false : is_dir($sourceNameOrData);
// See if it's a symlink (w/out dereference)
$isSymlink = false;
if ($this->_symlink_store_target && !$isVirtual) {
$isSymlink = is_link($sourceNameOrData);
}
// Get real size before compression
if ($isVirtual) {
$fileSize = akstringlen($sourceNameOrData);
$filectime = time();
} else {
if ($isSymlink) {
$fileSize = akstringlen(@readlink($sourceNameOrData));
} else {
// Is the file readable?
if (!is_readable($sourceNameOrData)) {
// Unreadable files won't be recorded in the archive file
$this->setWarning('Unreadable file ' . $sourceNameOrData . '. Check permissions');
return false;
} else {
// Really, REALLY check if it is readable (PHP sometimes lies, dammit!)
$myfp = @fopen($sourceNameOrData, 'rb');
if ($myfp === false) {
// Unreadable file, skip it.
$this->setWarning('Unreadable file ' . $sourceNameOrData . '. Check permissions');
return false;
}
@fclose($myfp);
}
// Get the filesize and modification time
$fileSize = $isDir ? 0 : @filesize($sourceNameOrData);
$filectime = $isDir ? 0 : @filemtime($sourceNameOrData);
}
}
// Decide if we will compress
if ($isDir || $isSymlink) {
// don't compress directories and symlinks...
$compressionMethod = 0;
} else {
// always compress files using gzip
$compressionMethod = 1;
}
// Fix stored name for directories
$storedName = $targetName;
$storedName .= $isDir ? "/" : "";
// Get file permissions
$perms = $isVirtual ? 0755 : @fileperms($sourceNameOrData);
// Get file type
if (!$isDir && !$isSymlink) {
$fileType = 1;
} elseif ($isSymlink) {
$fileType = 2;
} elseif ($isDir) {
$fileType = 0;
}
// Create the Entity Description Block Data
$headerData = pack('v', akstringlen($storedName)) . $storedName . pack('c', $fileType) . pack('c', $compressionMethod) . pack('V', $fileSize) . pack('V', $perms) . pack('V', $filectime);
// Create and write the Entity Description Block Header
$decryptedSize = akstringlen($headerData);
$headerData = AEUtilEncrypt::AESEncryptCBC($headerData, $this->password, 128);
$encryptedSize = akstringlen($headerData);
$headerData = $this->_fileHeader . pack('v', $encryptedSize) . pack('v', $decryptedSize) . $headerData;
// Do we have enough space to store the header?
if ($this->_useSplitZIP) {
// Compare to free part space
clearstatcache();
$current_part_size = @filesize($this->_dataFileName);
$free_space = $this->_fragmentSize - ($current_part_size === false ? 0 : $current_part_size);
if ($free_space <= akstringlen($headerData)) {
// Not enough space on current part, create new part
if (!$this->_createNewPart()) {
$this->setError('Could not create new JPS part file ' . basename($this->_dataFileName));
return false;
}
}
}
// Open data file for output
$fp = @fopen($this->_dataFileName, "ab");
if ($fp === false) {
//.........这里部分代码省略.........
示例2: partsize
/**
* Creates a dummy file of a given size. Remember to give the filesize
* query parameter in bytes!
*/
public function partsize()
{
$timer = AEFactory::getTimer();
$blocks = $this->input->get('blocks', 1, 'int');
$result = $this->createTempFile($blocks);
if ($result) {
// Save the setting
if ($blocks > 200) {
$blocks = 16383;
// Over 25Mb = 2Gb minus 128Kb limit (safe setting for PHP not running on 64-bit Linux)
}
$profile_id = AEPlatform::getInstance()->get_active_profile();
$config = AEFactory::getConfiguration();
$config->set('engine.archiver.common.part_size', $blocks * 128 * 1024);
AEPlatform::getInstance()->save_configuration($profile_id);
}
// Enforce the min exec time
$timer->enforce_min_exec_time(false);
return $result;
}
示例3: stepDatabaseDump
//.........这里部分代码省略.........
// Write the CREATE command after any DROP command which might be necessary.
if (!$this->writeDump($outCreate)) {
return;
}
if ($dump_records) {
// We are dumping data from a table, get the row count
$this->getRowCount($tableAbstract);
} else {
// We should not dump any data
AEUtilLogger::WriteLog(_AE_LOG_INFO, "Skipping dumping data of " . $tableAbstract);
$this->maxRange = 0;
$this->nextRange = 1;
$outData = '';
$numRows = 0;
}
// Output any data preamble commands, e.g. SET IDENTITY_INSERT for SQL Server
if ($dump_records && AEUtilScripting::getScriptingParameter('db.dropstatements', 0)) {
AEUtilLogger::WriteLog(_AE_LOG_DEBUG, "Writing data dump preamble for " . $tableAbstract);
$preamble = $this->getDataDumpPreamble($tableAbstract, $tableName, $this->maxRange);
if (!empty($preamble)) {
if (!$this->writeDump($preamble)) {
return;
}
}
}
}
// Check if we have more work to do on this table
$configuration = AEFactory::getConfiguration();
$batchsize = intval($configuration->get('engine.dump.common.batchsize', 1000));
if ($batchsize <= 0) {
$batchsize = 1000;
}
if ($this->nextRange < $this->maxRange) {
$timer = AEFactory::getTimer();
// Get the number of rows left to dump from the current table
$sql = $db->getQuery(true)->select('*')->from($db->nameQuote($tableAbstract));
if ($this->nextRange == 0) {
// First run, get a cursor to all records
$db->setQuery($sql, 0, $batchsize);
AEUtilLogger::WriteLog(_AE_LOG_INFO, "Beginning dump of " . $tableAbstract);
} else {
// Subsequent runs, get a cursor to the rest of the records
$db->setQuery($sql, $this->nextRange, $batchsize);
$this->setSubstep($this->nextRange . ' / ' . $this->maxRange);
AEUtilLogger::WriteLog(_AE_LOG_INFO, "Continuing dump of " . $tableAbstract . " from record #{$this->nextRange}");
}
$this->query = '';
$numRows = 0;
$use_abstract = AEUtilScripting::getScriptingParameter('db.abstractnames', 1);
$filters = AEFactory::getFilters();
$mustFilter = $filters->hasFilterType('dbobject', 'children');
try {
$cursor = $db->query();
} catch (Exception $exc) {
$db->resetErrors();
$cursor = null;
}
while (is_array($myRow = $db->fetchAssoc()) && $numRows < $this->maxRange - $this->nextRange) {
$this->createNewPartIfRequired();
$numRows++;
$numOfFields = count($myRow);
// On MS SQL Server there's always a RowNumber pseudocolumn added at the end, screwing up the backup (GRRRR!)
if ($db->getDriverType() == 'mssql') {
$numOfFields--;
}
// If row-level filtering is enabled, please run the filtering
示例4: deleteRemoteFiles
public function deleteRemoteFiles()
{
$id = $this->getState('id', -1);
$part = $this->getState('part', -1);
$ret = array('error' => false, 'finished' => false, 'id' => $id, 'part' => $part);
// Gather the necessary information to perform the delete
$stat = AEPlatform::getInstance()->get_statistics($id);
$remoteFilename = $stat['remote_filename'];
$rfparts = explode('://', $remoteFilename);
$engine = AEFactory::getPostprocEngine($rfparts[0]);
$remote_filename = $rfparts[1];
// Load the correct backup profile
AEPlatform::getInstance()->load_configuration($stat['profile_id']);
$config = AEFactory::getConfiguration();
// Start timing ourselves
$timer = AEFactory::getTimer();
// The core timer object
$start = $timer->getRunningTime();
// Mark the start of this download
$break = false;
// Don't break the step
while ($timer->getTimeLeft() && !$break && $part < $stat['multipart']) {
// Get the remote filename
$basename = basename($remote_filename);
$extension = strtolower(str_replace(".", "", strrchr($basename, ".")));
if ($part > 0) {
$new_extension = substr($extension, 0, 1) . sprintf('%02u', $part);
} else {
$new_extension = $extension;
}
$filename = $basename . '.' . $new_extension;
$remote_filename = substr($remote_filename, 0, -strlen($extension)) . $new_extension;
// Do we have to initialize the process?
if ($part == -1) {
// Init
$part = 0;
}
// Try to delete the part
$required_time = 1.0;
$result = $engine->delete($remote_filename);
if (!$result) {
$ret['error'] = JText::_('REMOTEFILES_ERR_CANTDELETE') . $engine->getWarning();
return $ret;
return;
} else {
// Successful delete
$end = $timer->getRunningTime();
$part++;
}
// Do we predict that we have enough time?
$required_time = max(1.1 * ($end - $start), $required_time);
if ($timer->getTimeLeft() < $required_time) {
$break = true;
}
$start = $end;
}
if ($part >= $stat['multipart']) {
// Just finished!
$stat['remote_filename'] = '';
AEPlatform::getInstance()->set_or_update_statistics($id, $stat, $engine);
$ret['finished'] = true;
return $ret;
} else {
// More work to do...
$ret['id'] = $id;
$ret['part'] = $part;
return $ret;
}
}
示例5: _run
protected function _run()
{
AEUtilLogger::openLog($this->tag);
set_error_handler('akeebaBackupErrorHandler');
// Maybe we're already done or in an error state?
if ($this->getError() || $this->getState() == 'postrun') {
return;
}
// Set running state
$this->setState('running');
// Initialize operation counter
$registry = AEFactory::getConfiguration();
$registry->set('volatile.operation_counter', 0);
// Advance step counter
$stepCounter = $registry->get('volatile.step_counter', 0);
$registry->set('volatile.step_counter', ++$stepCounter);
// Log step start number
AEUtilLogger::WriteLog(_AE_LOG_DEBUG, '====== Starting Step number ' . $stepCounter . ' ======');
if (defined('AKEEBADEBUG')) {
$root = AEPlatform::getInstance()->get_site_root();
AEUtilLogger::WriteLog(_AE_LOG_DEBUG, 'Site root: ' . $root);
}
$timer = AEFactory::getTimer();
$finished = false;
$error = false;
$breakFlag = false;
// BREAKFLAG is optionally passed by domains to force-break current operation
// Apply an infinite time limit if required
if ($registry->get('akeeba.tuning.settimelimit', 0)) {
if (function_exists('set_time_limit')) {
set_time_limit(0);
}
}
// Loop until time's up, we're done or an error occurred, or BREAKFLAG is set
$this->array_cache = null;
while ($timer->getTimeLeft() > 0 && !$finished && !$error && !$breakFlag) {
// Reset the break flag
$registry->set('volatile.breakflag', false);
// Do we have to switch domains? This only happens if there is no active
// domain, or the current domain has finished
$have_to_switch = false;
if ($this->class == '') {
$have_to_switch = true;
} else {
$object = AEFactory::getDomainObject($this->class);
if (!is_object($object)) {
$have_to_switch = true;
} else {
if (!in_array('getState', get_class_methods($object))) {
$have_to_switch = true;
} else {
if ($object->getState() == 'finished') {
$have_to_switch = true;
}
}
}
}
// Switch domain if necessary
if ($have_to_switch) {
if (!AEFactory::getConfiguration()->get('akeeba.tuning.nobreak.domains', 0)) {
AEUtilLogger::WriteLog(_AE_LOG_DEBUG, "Kettenrad :: BREAKING STEP BEFORE SWITCHING DOMAIN");
$registry->set('volatile.breakflag', true);
}
$object = null;
// Free last domain
if (empty($this->domain_chain)) {
// Aw, we're done! No more domains to run.
$this->setState('postrun');
AEUtilLogger::WriteLog(_AE_LOG_DEBUG, "Kettenrad :: No more domains to process");
$this->array_cache = null;
//restore_error_handler();
return;
}
// Shift the next definition off the stack
$this->array_cache = null;
$new_definition = array_shift($this->domain_chain);
if (array_key_exists('class', $new_definition)) {
$this->domain = $new_definition['domain'];
$this->class = $new_definition['class'];
// Get a working object
$object = AEFactory::getDomainObject($this->class);
$object->setup($this->_parametersArray);
} else {
AEUtilLogger::WriteLog(_AE_LOG_WARNING, "Kettenrad :: No class defined trying to switch domains. The backup will crash.");
$this->domain = null;
$this->class = null;
}
} else {
if (!is_object($object)) {
$object = AEFactory::getDomainObject($this->class);
}
}
// Tick the object
$result = $object->tick();
// Propagate errors
$this->propagateFromObject($object);
// Advance operation counter
$currentOperationNumber = $registry->get('volatile.operation_counter', 0);
$currentOperationNumber++;
$registry->set('volatile.operation_counter', $currentOperationNumber);
//.........这里部分代码省略.........
示例6: pack_files
/**
* Try to pack some files in the $file_list, restraining ourselves not to reach the max
* number of files or max fragment size while doing so. If this process is over and we are
* left without any more files, reset $done_scanning to false in order to instruct the class
* to scan for more files.
*
* @return bool True if there were files packed, false otherwise (empty filelist)
*/
private function pack_files()
{
// Get a reference to the archiver and the timer classes
$archiver = AEFactory::getArchiverEngine();
$timer = AEFactory::getTimer();
$configuration = AEFactory::getConfiguration();
// If post-processing after part creation is enabled, make sure we do post-process each part before moving on
if ($configuration->get('engine.postproc.common.after_part', 0)) {
if (!empty($archiver->finishedPart)) {
$filename = array_shift($archiver->finishedPart);
AEUtilLogger::WriteLog(_AE_LOG_INFO, 'Preparing to post process ' . basename($filename));
$post_proc = AEFactory::getPostprocEngine();
$result = $post_proc->processPart($filename);
$this->propagateFromObject($post_proc);
if ($result === false) {
$this->setWarning('Failed to process file ' . basename($filename));
} else {
AEUtilLogger::WriteLog(_AE_LOG_INFO, 'Successfully processed file ' . basename($filename));
}
// Should we delete the file afterwards?
if ($configuration->get('engine.postproc.common.delete_after', false) && $post_proc->allow_deletes && $result !== false) {
AEUtilLogger::WriteLog(_AE_LOG_DEBUG, 'Deleting already processed file ' . basename($filename));
AEPlatform::getInstance()->unlink($filename);
}
if ($post_proc->break_after && $result !== false) {
$configuration->set('volatile.breakflag', true);
return true;
}
// This is required to let the backup continue even after a post-proc failure
$this->resetErrors();
$this->setState('running');
}
}
// If the archiver has work to do, make sure it finished up before continuing
if ($configuration->get('volatile.engine.archiver.processingfile', false)) {
AEUtilLogger::WriteLog(_AE_LOG_DEBUG, "Continuing file packing from previous step");
$result = $archiver->addFile('', '', '');
$this->propagateFromObject($archiver);
if ($this->getError()) {
return false;
}
// If that was the last step, mark a file done
if (!$configuration->get('volatile.engine.archiver.processingfile', false)) {
$this->progressMarkFileDone();
}
}
// Did it finish, or does it have more work to do?
if ($configuration->get('volatile.engine.archiver.processingfile', false)) {
// More work to do. Let's just tell our parent that we finished up successfully.
return true;
}
// Normal file backup loop; we keep on processing the file list, packing files as we go.
if (count($this->file_list) == 0) {
// No files left to pack -- This should never happen! We catch this condition at the end of this method!
$this->done_scanning = false;
$this->progressMarkFolderDone();
return false;
} else {
AEUtilLogger::WriteLog(_AE_LOG_DEBUG, "Packing files");
$packedSize = 0;
$numberOfFiles = 0;
list($usec, $sec) = explode(" ", microtime());
$opStartTime = (double) $usec + (double) $sec;
while (count($this->file_list) > 0) {
$file = @array_shift($this->file_list);
$size = 0;
if (file_exists($file)) {
$size = @filesize($file);
}
// Anticipatory file size algorithm
if ($numberOfFiles > 0 && $size > AELargeFileThreshold) {
if (!AEFactory::getConfiguration()->get('akeeba.tuning.nobreak.beforelargefile', 0)) {
// If the file is bigger than the big file threshold, break the step
// to avoid potential timeouts
$this->setBreakFlag();
AEUtilLogger::WriteLog(_AE_LOG_INFO, "Breaking step _before_ large file: " . $file . " - size: " . $size);
// Push the file back to the list.
array_unshift($this->file_list, $file);
// Mark that we are not done packing files
$this->done_scanning = true;
return true;
}
}
// Proactive potential timeout detection
// Rough estimation of packing speed in bytes per second
list($usec, $sec) = explode(" ", microtime());
$opEndTime = (double) $usec + (double) $sec;
if ($opEndTime - $opStartTime == 0) {
$_packSpeed = 0;
} else {
$_packSpeed = $packedSize / ($opEndTime - $opStartTime);
}
//.........这里部分代码省略.........
示例7: tick
/**
* The public interface to an engine part. This method takes care for
* calling the correct method in order to perform the initialisation -
* run - finalisation cycle of operation and return a proper reponse array.
* @return array A Reponse Array
*/
public final function tick($nesting = 0)
{
$configuration = AEFactory::getConfiguration();
$timer = AEFactory::getTimer();
// Call the right action method, depending on engine part state
switch ($this->getState()) {
case "init":
$this->_prepare();
$breakFlag = $configuration->set('volatile.breakflag', false);
break;
case "prepared":
$this->_run();
break;
case "running":
$this->_run();
break;
case "postrun":
$this->_finalize();
$breakFlag = $configuration->set('volatile.breakflag', false);
break;
}
// If there is still time, we are not finished and there is no break flag set, re-run the tick()
// method.
$breakFlag = $configuration->get('volatile.breakflag', false);
if (!in_array($this->getState(), array('finished', 'error')) && $timer->getTimeLeft() > 0 && !$breakFlag && $nesting < 20 && $this->nest_logging) {
// Nesting is only applied if $this->nest_logging == true (currently only Kettenrad has this)
$nesting++;
if ($this->nest_logging) {
AEUtilLogger::WriteLog(_AE_LOG_DEBUG, "*** Batching successive steps (nesting level {$nesting})");
}
$out = $this->tick($nesting);
} else {
// Return the output array
$out = $this->_makeReturnTable();
// Things to do for nest-logged parts (currently, only Kettenrad is)
if ($this->nest_logging) {
if ($breakFlag) {
AEUtilLogger::WriteLog(_AE_LOG_DEBUG, "*** Engine steps batching: Break flag detected.");
}
// Reset the break flag
$configuration->set('volatile.breakflag', false);
// Log that we're breaking the step
AEUtilLogger::WriteLog(_AE_LOG_DEBUG, "*** Batching of engine steps finished. I will now return control to the caller.");
// Enforce minimum execution time
$timer = AEFactory::getTimer();
$timer->enforce_min_exec_time(true);
}
}
// Send a Return Table back to the caller
return $out;
}
示例8: downloadToServer
public function downloadToServer()
{
if (!$this->_hasAdequateInformation()) {
$this->setError(JText::_('S3IMPORT_ERR_NOTENOUGHINFO'));
return false;
}
// Gather the necessary information to perform the download
$part = JFactory::getApplication()->getUserState('com_akeeba.s3import.part', -1);
$frag = JFactory::getApplication()->getUserState('com_akeeba.s3import.frag', -1);
$remoteFilename = $this->getState('file', '');
$s3 = $this->_getS3Object();
// Get the number of parts and total size from the session, or –if not there– fetch it
$totalparts = JFactory::getApplication()->getUserState('com_akeeba.s3import.totalparts', -1);
$totalsize = JFactory::getApplication()->getUserState('com_akeeba.s3import.totalsize', -1);
if ($totalparts < 0 || $part < 0 && $frag < 0) {
$filePrefix = substr($remoteFilename, 0, -3);
$allFiles = $s3->getBucket($this->getState('s3bucket'), $filePrefix);
$totalsize = 0;
if (count($allFiles)) {
foreach ($allFiles as $name => $file) {
$totalsize += $file['size'];
}
}
JFactory::getApplication()->setUserState('com_akeeba.s3import.totalparts', count($allFiles));
JFactory::getApplication()->setUserState('com_akeeba.s3import.totalsize', $totalsize);
JFactory::getApplication()->setUserState('com_akeeba.s3import.donesize', 0);
$totalparts = JFactory::getApplication()->getUserState('com_akeeba.s3import.totalparts', -1);
}
// Start timing ourselves
$timer = AEFactory::getTimer();
// The core timer object
$start = $timer->getRunningTime();
// Mark the start of this download
$break = false;
// Don't break the step
while ($timer->getRunningTime() < 10 && !$break && $part < $totalparts) {
// Get the remote and local filenames
$basename = basename($remoteFilename);
$extension = strtolower(str_replace(".", "", strrchr($basename, ".")));
if ($part > 0) {
$new_extension = substr($extension, 0, 1) . sprintf('%02u', $part);
} else {
$new_extension = $extension;
}
$filename = $basename . '.' . $new_extension;
$remote_filename = substr($remoteFilename, 0, -strlen($extension)) . $new_extension;
// Figure out where on Earth to put that file
$local_file = AEFactory::getConfiguration()->get('akeeba.basic.output_directory') . '/' . basename($remote_filename);
// Do we have to initialize the process?
if ($part == -1) {
// Currently downloaded size
JFactory::getApplication()->setUserState('com_akeeba.s3import.donesize', 0);
// Init
$part = 0;
}
// Do we have to initialize the file?
if ($frag == -1) {
// Delete and touch the output file
AEPlatform::getInstance()->unlink($local_file);
$fp = @fopen($local_file, 'wb');
if ($fp !== false) {
@fclose($fp);
}
// Init
$frag = 0;
}
// Calculate from and length
$length = 1048576;
// That's wrong: the first byte is byte 0, not byte 1!!!
//$from = $frag * $length + 1;
$from = $frag * $length;
$to = $length + $from;
if ($from == 0) {
$from = 1;
}
// Try to download the first frag
$temp_file = $local_file . '.tmp';
@unlink($temp_file);
$required_time = 1.0;
$result = $s3->getObject($this->getState('s3bucket', ''), $remote_filename, $temp_file, $from, $to);
if (!$result) {
// Failed download
@unlink($temp_file);
if (($part < $totalparts || $totalparts == 1 && $part == 0) && $frag == 0) {
// Failure to download the part's beginning = failure to download. Period.
$this->setError(JText::_('S3IMPORT_ERR_NOTFOUND'));
return false;
} elseif ($part >= $totalparts) {
// Just finished! Create a stats record.
$multipart = $totalparts;
$multipart--;
$filetime = time();
// Create a new backup record
$record = array('description' => JText::_('DISCOVER_LABEL_IMPORTEDDESCRIPTION'), 'comment' => '', 'backupstart' => date('Y-m-d H:i:s', $filetime), 'backupend' => date('Y-m-d H:i:s', $filetime + 1), 'status' => 'complete', 'origin' => 'backend', 'type' => 'full', 'profile_id' => 1, 'archivename' => basename($remoteFilename), 'absolute_path' => dirname($local_file) . '/' . basename($remoteFilename), 'multipart' => $multipart, 'tag' => 'backend', 'filesexist' => 1, 'remote_filename' => '', 'total_size' => $totalsize);
$id = null;
$id = AEPlatform::getInstance()->set_or_update_statistics($id, $record, $this);
return null;
} else {
// Since this is a staggered download, consider this normal and go to the next part.
$part++;
//.........这里部分代码省略.........
示例9: _addFile
/**
* The most basic file transaction: add a single entry (file or directory) to
* the archive.
*
* @param bool $isVirtual If true, the next parameter contains file data instead of a file name
* @param string $sourceNameOrData Absolute file name to read data from or the file data itself is $isVirtual is true
* @param string $targetName The (relative) file name under which to store the file in the archive
* @return True on success, false otherwise
* @since 1.2.1
* @access protected
* @abstract
*/
protected function _addFile($isVirtual, &$sourceNameOrData, $targetName)
{
static $configuration;
$isDir = false;
$isSymlink = false;
if (is_null($isVirtual)) {
$isVirtual = false;
}
$compressionMethod = 0;
if ($isVirtual) {
AEUtilLogger::WriteLog(_AE_LOG_DEBUG, "-- Adding {$targetName} to archive (virtual data)");
} else {
AEUtilLogger::WriteLog(_AE_LOG_DEBUG, "-- Adding {$targetName} to archive (source: {$sourceNameOrData})");
}
if (!$configuration) {
$configuration =& AEFactory::getConfiguration();
}
$timer =& AEFactory::getTimer();
// Initialize archive file pointer
$fp = null;
// Initialize inode change timestamp
$filectime = 0;
if (!$configuration->get('volatile.engine.archiver.processingfile', false)) {
// Uncache data -- WHY DO THAT?!
/**
$configuration->set('volatile.engine.archiver.sourceNameOrData', null);
$configuration->set('volatile.engine.archiver.unc_len', null);
$configuration->set('volatile.engine.archiver.resume', null);
$configuration->set('volatile.engine.archiver.processingfile',false);
/**/
// See if it's a directory
$isDir = $isVirtual ? false : is_dir($sourceNameOrData);
// See if it's a symlink (w/out dereference)
$isSymlink = false;
if ($this->_symlink_store_target && !$isVirtual) {
$isSymlink = is_link($sourceNameOrData);
}
// Get real size before compression
if ($isVirtual) {
$fileSize = akstringlen($sourceNameOrData);
$filectime = time();
} else {
if ($isSymlink) {
$fileSize = akstringlen(@readlink($sourceNameOrData));
} else {
// Is the file readable?
if (!is_readable($sourceNameOrData) && !$isDir) {
// Unreadable files won't be recorded in the archive file
$this->setWarning('Unreadable file ' . $sourceNameOrData . '. Check permissions');
return false;
}
// Get the filesize
$fileSize = $isDir ? 0 : @filesize($sourceNameOrData);
$filectime = $isDir ? 0 : @filemtime($sourceNameOrData);
}
}
// Decide if we will compress
if ($isDir || $isSymlink) {
$compressionMethod = 0;
// don't compress directories...
} else {
// Do we have plenty of memory left?
$memLimit = ini_get("memory_limit");
if (strstr($memLimit, 'M')) {
$memLimit = (int) $memLimit * 1048576;
} elseif (strstr($totalRAM, 'K')) {
$memLimit = (int) $memLimit * 1024;
} elseif (strstr($memLimit, 'G')) {
$memLimit = (int) $memLimit * 1073741824;
} else {
$memLimit = (int) $memLimit;
}
if (is_numeric($memLimit) && $memLimit < 0) {
$memLimit = "";
}
// 1.2a3 -- Rare case with memory_limit < 0, e.g. -1Mb!
if ($memLimit == "" || $fileSize >= _AKEEBA_COMPRESSION_THRESHOLD) {
// No memory limit, or over 1Mb files => always compress up to 1Mb files (otherwise it times out)
$compressionMethod = $fileSize <= _AKEEBA_COMPRESSION_THRESHOLD ? 1 : 0;
} elseif (function_exists("memory_get_usage")) {
// PHP can report memory usage, see if there's enough available memory; Joomla! alone eats about 5-6Mb! This code is called on files <= 1Mb
$memLimit = $this->_return_bytes($memLimit);
$availableRAM = $memLimit - memory_get_usage();
$compressionMethod = $availableRAM / 2.5 >= $fileSize ? 1 : 0;
} else {
// PHP can't report memory usage, compress only files up to 512Kb (conservative approach) and hope it doesn't break
$compressionMethod = $fileSize <= 524288 ? 1 : 0;
}
//.........这里部分代码省略.........
示例10: _addFile
//.........这里部分代码省略.........
// Die if we couldn't create the new part
$this->setError('Could not create new ZIP part file ' . basename($this->_dataFileName));
return false;
} else {
// Close the old data file
fclose($fp);
// Open data file for output
$fp = @fopen($this->_dataFileName, "ab");
if ($fp === false) {
$this->setError("Could not open archive file {$this->_dataFileName} for append!");
return false;
}
}
// Get the rest of the compressed data
$zdata = substr($sourceNameOrData, -$rest_size);
}
$bytes_left = $rest_size;
}
}
}
} else {
// IMPORTANT! Only this case can be spanned across steps: uncompressed, non-virtual data
if ($configuration->get('volatile.engine.archiver.processingfile', false)) {
$sourceNameOrData = $configuration->get('volatile.engine.archiver.sourceNameOrData', '');
$unc_len = $configuration->get('volatile.engine.archiver.unc_len', 0);
$resume = $configuration->get('volatile.engine.archiver.resume', 0);
}
// Copy the file contents, ignore directories
$zdatafp = @fopen($sourceNameOrData, "rb");
if ($zdatafp === false) {
$this->setWarning('Unreadable file ' . $sourceNameOrData . '. Check permissions');
return false;
} else {
$timer = AEFactory::getTimer();
// Seek to the resume point if required
if ($configuration->get('volatile.engine.archiver.processingfile', false)) {
// Seek to new offset
$seek_result = @fseek($zdatafp, $resume);
if ($seek_result === -1) {
// What?! We can't resume!
$this->setError(sprintf('Could not resume packing of file %s. Your archive is damaged!', $sourceNameOrData));
return false;
}
// Doctor the uncompressed size to match the remainder of the data
$unc_len = $unc_len - $resume;
}
if (!$this->_useSplitZIP) {
// For non Split ZIP, just dump the file very fast
while (!feof($zdatafp) && $timer->getTimeLeft() > 0 && $unc_len > 0) {
$zdata = fread($zdatafp, AKEEBA_CHUNK);
$this->_fwrite($fp, $zdata, min(function_exists('mb_strlen') ? mb_strlen($zdata, '8bit') : strlen($zdata), AKEEBA_CHUNK));
$unc_len -= AKEEBA_CHUNK;
if ($this->getError()) {
return;
}
}
if (!feof($zdatafp) && $unc_len != 0) {
// We have to break, or we'll time out!
$resume = @ftell($zdatafp);
$configuration->set('volatile.engine.archiver.resume', $resume);
$configuration->set('volatile.engine.archiver.processingfile', true);
return true;
}
} else {
// Split ZIP - Do we have enough space to host the whole file?
clearstatcache();
示例11: apply_remote_quotas
private function apply_remote_quotas()
{
$this->setStep('Applying remote storage quotas');
$this->setSubstep('');
// Make sure we are enabled
$config = AEFactory::getConfiguration();
$enableRemote = $config->get('akeeba.quota.remote', 0);
if (!$enableRemote) {
return true;
}
// Get the list of files to kill
if (empty($this->remote_files_killlist)) {
AEUtilLogger::WriteLog(_AE_LOG_DEBUG, 'Applying remote file quotas');
$this->remote_files_killlist = $this->get_remote_quotas();
if (empty($this->remote_files_killlist)) {
AEUtilLogger::WriteLog(_AE_LOG_DEBUG, 'No remote files to apply quotas to were found');
return true;
}
}
// Remove the files
$timer = AEFactory::getTimer();
while ($timer->getRunningTime() && count($this->remote_files_killlist)) {
$filename = array_shift($this->remote_files_killlist);
list($engineName, $path) = explode('://', $filename);
$engine = AEFactory::getPostprocEngine($engineName);
if (!$engine->can_delete) {
continue;
}
AEUtilLogger::WriteLog(_AE_LOG_DEBUG, "Removing {$filename}");
$result = $engine->delete($path);
if (!$result) {
AEUtilLogger::WriteLog(_AE_LOG_DEBUG, "Removal failed: " . $engine->getWarning());
}
}
// Return false if we have more work to do or true if we're done
if (count($this->remote_files_killlist)) {
AEUtilLogger::WriteLog(_AE_LOG_DEBUG, "Remote file removal will continue in the next step");
return false;
} else {
AEUtilLogger::WriteLog(_AE_LOG_DEBUG, "Remote file quotas applied successfully");
return true;
}
}
示例12: _run
//.........这里部分代码省略.........
} else {
$type = 'table';
$createStatement = $this->get_create($tableAbstract, $tableName, $type, $dependencies);
$dropStatement = $this->createDrop($createStatement);
}
if(!empty($dropStatement))
{
if(!$this->writeDump($outCreate)) return;
}
}
if( $dump_records )
{
// We are dumping data from a table, get the row count
$this->getRowCount( $tableAbstract );
}
else
{
// We should not dump any data
AEUtilLogger::WriteLog(_AE_LOG_INFO, "Skipping dumping data of " . $tableAbstract);
$this->maxRange = 0;
$this->nextRange = 1;
$outData = '';
$numRows = 0;
}
}
// Check if we have more work to do on this table
$configuration =& AEFactory::getConfiguration();
$batchsize = intval($configuration->get('engine.dump.common.batchsize', 1000));
if($batchsize <= 0) $batchsize = 1000;
if( ($this->nextRange < $this->maxRange) )
{
$timer =& AEFactory::getTimer();
// Get the number of rows left to dump from the current table
$sql = "SELECT * FROM `$tableAbstract`";
if( $this->nextRange == 0 )
{
// First run, get a cursor to all records
$db->setQuery( $sql, 0, $batchsize );
AEUtilLogger::WriteLog(_AE_LOG_INFO, "Beginning dump of " . $tableAbstract);
}
else
{
// Subsequent runs, get a cursor to the rest of the records
$db->setQuery( $sql, $this->nextRange, $batchsize );
AEUtilLogger::WriteLog(_AE_LOG_INFO, "Continuing dump of " . $tableAbstract . " from record #{$this->nextRange}");
}
$this->query = '';
$numRows = 0;
$use_abstract = AEUtilScripting::getScriptingParameter('db.abstractnames', 1);
while( is_array($myRow = $db->loadAssoc(false)) && ( $numRows < ($this->maxRange - $this->nextRange) ) ) {
$this->createNewPartIfRequired();
$numRows++;
$numOfFields = count( $myRow );
if(
(!$this->extendedInserts) || // Add header on simple INSERTs, or...
( $this->extendedInserts && empty($this->query) ) //...on extended INSERTs if there are no other data, yet
)
{
$newQuery = true;
if( $numOfFields > 0 ) $this->query = "INSERT INTO `" . (!$use_abstract ? $tableName : $tableAbstract) . "` VALUES ";
}
示例13: pack_files
/**
* Try to add some files from the $file_list into the archive
*
* @return boolean True if there were files packed, false otherwise
* (empty filelist or fatal error)
*/
private function pack_files()
{
// Get a reference to the archiver and the timer classes
$archiver = AEFactory::getArchiverEngine();
$timer = AEFactory::getTimer();
$configuration = AEFactory::getConfiguration();
// If post-processing after part creation is enabled, make sure we do post-process each part before moving on
if ($configuration->get('engine.postproc.common.after_part', 0) && !empty($archiver->finishedPart)) {
if ($this->postProcessDonePartFile($archiver, $configuration)) {
return true;
}
}
// If the archiver has work to do, make sure it finished up before continuing
if ($configuration->get('volatile.engine.archiver.processingfile', false)) {
AEUtilLogger::WriteLog(_AE_LOG_DEBUG, "Continuing file packing from previous step");
$result = $archiver->addFile('', '', '');
$this->propagateFromObject($archiver);
if ($this->getError()) {
return false;
}
// If that was the last step for packing this file, mark a file done
if (!$configuration->get('volatile.engine.archiver.processingfile', false)) {
$this->progressMarkFileDone();
}
}
// Did it finish, or does it have more work to do?
if ($configuration->get('volatile.engine.archiver.processingfile', false)) {
// More work to do. Let's just tell our parent that we finished up successfully.
return true;
}
// Normal file backup loop; we keep on processing the file list, packing files as we go.
if (count($this->file_list) == 0) {
// No files left to pack. Return true and let the engine loop
$this->progressMarkFolderDone();
return true;
} else {
AEUtilLogger::WriteLog(_AE_LOG_DEBUG, "Packing files");
$packedSize = 0;
$numberOfFiles = 0;
list($usec, $sec) = explode(" ", microtime());
$opStartTime = (double) $usec + (double) $sec;
$largeFileThreshold = AEFactory::getConfiguration()->get('engine.scan.common.largefile', 10485760);
while (count($this->file_list) > 0) {
$file = @array_shift($this->file_list);
$size = 0;
if (file_exists($file)) {
$size = @filesize($file);
}
// Anticipatory file size algorithm
if ($numberOfFiles > 0 && $size > $largeFileThreshold) {
if (!AEFactory::getConfiguration()->get('akeeba.tuning.nobreak.beforelargefile', 0)) {
// If the file is bigger than the big file threshold, break the step
// to avoid potential timeouts
$this->setBreakFlag();
AEUtilLogger::WriteLog(_AE_LOG_INFO, "Breaking step _before_ large file: " . $file . " - size: " . $size);
// Push the file back to the list.
array_unshift($this->file_list, $file);
// Return true and let the engine loop
return true;
}
}
// Proactive potential timeout detection
// Rough estimation of packing speed in bytes per second
list($usec, $sec) = explode(" ", microtime());
$opEndTime = (double) $usec + (double) $sec;
if ($opEndTime - $opStartTime == 0) {
$_packSpeed = 0;
} else {
$_packSpeed = $packedSize / ($opEndTime - $opStartTime);
}
// Estimate required time to pack next file. If it's the first file of this operation,
// do not impose any limitations.
$_reqTime = $_packSpeed - 0.01 <= 0 ? 0 : $size / $_packSpeed;
// Do we have enough time?
if ($timer->getTimeLeft() < $_reqTime) {
if (!AEFactory::getConfiguration()->get('akeeba.tuning.nobreak.proactive', 0)) {
array_unshift($this->file_list, $file);
AEUtilLogger::WriteLog(_AE_LOG_INFO, "Proactive step break - file: " . $file . " - size: " . $size . " - req. time " . sprintf('%2.2f', $_reqTime));
$this->setBreakFlag();
return true;
}
}
$packedSize += $size;
$numberOfFiles++;
$ret = $archiver->addFile($file, $this->remove_path_prefix, $this->path_prefix);
// If no more processing steps are required, mark a done file
if (!$configuration->get('volatile.engine.archiver.processingfile', false)) {
$this->progressMarkFileDone();
}
// Error propagation
$this->propagateFromObject($archiver);
if ($this->getError()) {
return false;
}
//.........这里部分代码省略.........
示例14: execute
//.........这里部分代码省略.........
define('AKEEBA_PROFILE', $profile);
define('AKEEBA_BACKUP_ORIGIN', 'cli');
// Force loading CLI-mode translation class
$dummy = new AEUtilTranslate();
// Load the profile
AEPlatform::getInstance()->load_configuration($profile);
// Reset Kettenrad and its storage
AECoreKettenrad::reset(array('maxrun' => 0));
AEUtilTempvars::reset(AKEEBA_BACKUP_ORIGIN);
// Setup
$kettenrad = AEFactory::getKettenrad();
$options = array('description' => $description, 'comment' => '');
if (!empty($overrides)) {
AEPlatform::getInstance()->configOverrides = $overrides;
}
$kettenrad->setup($options);
// Dummy array so that the loop iterates once
$array = array('HasRun' => 0, 'Error' => '');
$warnings_flag = false;
while ($array['HasRun'] != 1 && empty($array['Error'])) {
// Recycle the database conenction to minimise problems with database timeouts
$db = AEFactory::getDatabase();
$db->close();
$db->open();
AEUtilLogger::openLog(AKEEBA_BACKUP_ORIGIN);
AEUtilLogger::WriteLog(true, '');
// Apply overrides in the command line
if (!empty($overrides)) {
$config = AEFactory::getConfiguration();
foreach ($overrides as $key => $value) {
$config->set($key, $value);
}
}
// Apply engine optimization overrides
$config = AEFactory::getConfiguration();
$config->set('akeeba.tuning.min_exec_time', 0);
$config->set('akeeba.tuning.nobreak.beforelargefile', 1);
$config->set('akeeba.tuning.nobreak.afterlargefile', 1);
$config->set('akeeba.tuning.nobreak.proactive', 1);
$config->set('akeeba.tuning.nobreak.finalization', 1);
$config->set('akeeba.tuning.settimelimit', 0);
$config->set('akeeba.tuning.nobreak.domains', 0);
$kettenrad->tick();
AEFactory::getTimer()->resetTime();
$array = $kettenrad->getStatusArray();
AEUtilLogger::closeLog();
$time = date('Y-m-d H:i:s \\G\\M\\TO (T)');
$memusage = $this->memUsage();
$warnings = "no warnings issued (good)";
$stepWarnings = false;
if (!empty($array['Warnings'])) {
$warnings_flag = true;
$warnings = "POTENTIAL PROBLEMS DETECTED; " . count($array['Warnings']) . " warnings issued (see below).\n";
foreach ($array['Warnings'] as $line) {
$warnings .= "\t{$line}\n";
}
$stepWarnings = true;
$kettenrad->resetWarnings();
}
if ($this->input->get('quiet', -1, 'int') == -1 || $stepWarnings) {
echo <<<ENDSTEPINFO
Last Tick : {$time}
Domain : {$array['Domain']}
Step : {$array['Step']}
Substep : {$array['Substep']}
Memory used : {$memusage}
Warnings : {$warnings}
ENDSTEPINFO;
}
}
// Clean up
AEUtilTempvars::reset(AKEEBA_BACKUP_ORIGIN);
if (!empty($array['Error'])) {
echo "An error has occurred:\n{$array['Error']}\n\n";
$exitCode = 2;
} else {
if ($this->input->get('quiet', -1, 'int') == -1) {
echo "Backup job finished successfully after approximately " . $this->timeago($start_backup, time(), '', false) . "\n";
}
$exitCode = 0;
}
if ($warnings_flag && $this->input->get('quiet', -1, 'int') == -1) {
$exitCode = 1;
echo "\n" . str_repeat('=', 79) . "\n";
echo "!!!!! W A R N I N G !!!!!\n\n";
echo "Akeeba Backup issued warnings during the backup process. You have to review them\n";
echo "and make sure that your backup has completed successfully. Always test a backup with\n";
echo "warnings to make sure that it is working properly, by restoring it to a local server.\n";
echo "DO NOT IGNORE THIS MESSAGE! AN UNTESTED BACKUP IS AS GOOD AS NO BACKUP AT ALL.\n";
echo "\n" . str_repeat('=', 79) . "\n";
} elseif ($warnings_flag) {
$exitCode = 1;
}
if ($this->input->get('quiet', -1, 'int') == -1) {
echo "Peak memory usage: " . $this->peakMemUsage() . "\n\n";
}
$this->close($exitCode);
}
示例15:
/**
* Get the a reference to the Akeeba Engine's timer
* @return AECoreTimer
*/
public static function &getTimer()
{
// TODO I should create another Timer, since I could have problems with backup settings
// ie steps too close => backup error. I can't use the same settings for find that error :)
return AEFactory::getTimer();
}