public function browse() { // Check permissions $this->_checkPermissions(); // Set the profile $this->_setProfile(); // Start the backup JLoader::import('joomla.utilities.date'); AECoreKettenrad::reset(array('maxrun' => 0)); AEUtilTempfiles::deleteTempFiles(); AEUtilTempvars::reset(AKEEBA_BACKUP_ORIGIN); $kettenrad = AECoreKettenrad::load(AKEEBA_BACKUP_ORIGIN); $dateNow = new JDate(); $description = JText::_('BACKUP_DEFAULT_DESCRIPTION') . ' ' . $dateNow->format(JText::_('DATE_FORMAT_LC2'), true); $options = array('description' => $description, 'comment' => ''); $kettenrad->setup($options); $kettenrad->tick(); $kettenrad->tick(); $array = $kettenrad->getStatusArray(); AECoreKettenrad::save(AKEEBA_BACKUP_ORIGIN); if ($array['Error'] != '') { // An error occured die('500 ERROR -- ' . $array['Error']); } else { $noredirect = $this->input->get('noredirect', 0, 'int'); if ($noredirect != 0) { @ob_end_clean(); echo "301 More work required"; flush(); JFactory::getApplication()->close(); } else { $this->_customRedirect(JURI::base() . 'index.php?option=com_akeeba&view=backup&task=step&key=' . $this->input->get('key', '', 'none', 2) . '&profile=' . $this->input->get('profile', 1, 'int')); } } }
/** * Creates a randomly-named temporary file, registers it with the temporary * files management and returns its absolute path * @return string The temporary file name */ static function createRegisterTempFile() { // Create a randomly named file in the temp directory $registry = AEFactory::getConfiguration(); $tempFile = tempnam($registry->get('akeeba.basic.output_directory'), 'ak'); // Register it and return its absolute path $tempName = basename($tempFile); return AEUtilTempfiles::registerTempFile($tempName); }
/** * Find where to store the backup files * @param $partNumber int The SQL part number, default is 0 (.sql) */ protected function getBackupFilePaths( $partNumber = 0 ) { AEUtilLogger::WriteLog(_AE_LOG_DEBUG, 'XXX '.__CLASS__." :: Getting temporary file"); $this->tempFile = AEUtilTempfiles::registerTempFile( dechex(crc32(microtime())).'.sql' ); AEUtilLogger::WriteLog(_AE_LOG_DEBUG, 'XXX '.__CLASS__." :: Temporary file is {$this->tempFile}"); // Get the base name of the dump file $partNumber = intval($partNumber); $baseName = $this->dumpFile; if($partNumber > 0) { // The file names are in the format dbname.sql, dbname.s01, dbname.s02, etc if( strtolower(substr($baseName, -4)) == '.sql' ) { $baseName = substr($baseName, 0, -4).'.s'.sprintf('%02u', $partNumber); } else { $baseName = $baseName.'.s'.sprintf('%02u', $partNumber); } } switch(AEUtilScripting::getScriptingParameter('db.saveasname','normal')) { case 'output': // The SQL file will be stored uncompressed in the output directory $statistics =& AEFactory::getStatistics(); $statRecord = $statistics->getRecord(); $this->saveAsName = $statRecord['absolute_path']; break; case 'normal': // The SQL file will be stored in the SQL root of the archive, as // specified by the particular embedded installer's settings $this->saveAsName = $this->installerSettings->sqlroot.'/'.$baseName; break; case 'short': // The SQL file will be stored on archive's root $this->saveAsName = $baseName; break; } if($partNumber > 0) { AEUtilLogger::WriteLog(_AE_LOG_DEBUG, "AkeebaDomainDBBackup :: Creating new SQL dump part #$partNumber"); } AEUtilLogger::WriteLog(_AE_LOG_DEBUG, "AkeebaDomainDBBackup :: SQL temp file is " . $this->tempFile); AEUtilLogger::WriteLog(_AE_LOG_DEBUG, "AkeebaDomainDBBackup :: SQL file location in archive is " . $this->saveAsName); }
public function display() { // Check permissions $this->_checkPermissions(); // Set the profile $this->_setProfile(); // Start the backup jimport('joomla.utilities.date'); AECoreKettenrad::reset(array('maxrun' => 0)); AEUtilTempfiles::deleteTempFiles(); AEUtilTempvars::reset(AKEEBA_BACKUP_ORIGIN); $kettenrad = AECoreKettenrad::load(AKEEBA_BACKUP_ORIGIN); $user = JFactory::getUser(); $userTZ = $user->getParam('timezone', 0); $dateNow = new JDate(); $dateNow->setOffset($userTZ); if (AKEEBA_JVERSION == '16') { $description = JText::_('BACKUP_DEFAULT_DESCRIPTION') . ' ' . $dateNow->format(JText::_('DATE_FORMAT_LC2'), true); } else { $description = JText::_('BACKUP_DEFAULT_DESCRIPTION') . ' ' . $dateNow->toFormat(JText::_('DATE_FORMAT_LC2')); } $options = array('description' => $description, 'comment' => ''); $kettenrad->setup($options); $array = $kettenrad->tick(); $array = $kettenrad->tick(); AECoreKettenrad::save(AKEEBA_BACKUP_ORIGIN); if ($array['Error'] != '') { // An error occured die('500 ERROR -- ' . $array['Error']); } else { $noredirect = JRequest::getInt('noredirect', 0); if ($noredirect != 0) { @ob_end_clean(); echo "301 More work required"; flush(); JFactory::getApplication()->close(); } else { $this->setRedirect(JURI::base() . 'index.php?option=com_akeeba&view=backup&task=step&key=' . JRequest::getVar('key') . '&profile=' . JRequest::getInt('profile', 1)); } } }
public function browse() { // Check permissions $this->_checkPermissions(); // Set the profile $this->_setProfile(); // Get the backup ID $backupId = $this->input->get('backupid', null, 'raw', 2); if (strtoupper($backupId) == '[DEFAULT]') { $db = JFactory::getDbo(); $query = $db->getQuery(true)->select('MAX(' . $db->qn('id') . ')')->from($db->qn('#__ak_stats')); try { $maxId = $db->setQuery($query)->loadResult(); } catch (Exception $e) { $maxId = 0; } $backupId = 'id' . ($maxId + 1); } elseif (empty($backupId)) { $backupId = null; } // Start the backup JLoader::import('joomla.utilities.date'); AECoreKettenrad::reset(array('maxrun' => 0)); AEUtilTempfiles::deleteTempFiles(); $tempVarsTag = AKEEBA_BACKUP_ORIGIN; $tempVarsTag .= empty($backupId) ? '' : '.' . $backupId; AEUtilTempvars::reset($tempVarsTag); $kettenrad = AECoreKettenrad::load(AKEEBA_BACKUP_ORIGIN, $backupId); $kettenrad->setBackupId($backupId); $dateNow = new JDate(); $description = JText::_('BACKUP_DEFAULT_DESCRIPTION') . ' ' . $dateNow->format(JText::_('DATE_FORMAT_LC2'), true); $options = array('description' => $description, 'comment' => ''); $kettenrad->setup($options); $kettenrad->tick(); $kettenrad->tick(); $array = $kettenrad->getStatusArray(); AECoreKettenrad::save(AKEEBA_BACKUP_ORIGIN, $backupId); if ($array['Error'] != '') { // An error occured die('500 ERROR -- ' . $array['Error']); } else { $noredirect = $this->input->get('noredirect', 0, 'int'); if ($noredirect != 0) { @ob_end_clean(); echo "301 More work required"; flush(); JFactory::getApplication()->close(); } else { $curUri = JUri::getInstance(); $ssl = $curUri->isSSL() ? 1 : 0; $tempURL = JRoute::_('index.php?option=com_akeeba', false, $ssl); $uri = new JUri($tempURL); $uri->setVar('view', 'backup'); $uri->setVar('task', 'step'); $uri->setVar('key', $this->input->get('key', '', 'none', 2)); $uri->setVar('profile', $this->input->get('profile', 1, 'int')); if (!empty($backupId)) { $uri->setVar('backupid', $backupId); } // Maybe we have a multilingual site? $lg = F0FPlatform::getInstance()->getLanguage(); $languageTag = $lg->getTag(); $uri->setVar('lang', $languageTag); $redirectionUrl = $uri->toString(); $this->_customRedirect($redirectionUrl); } } }
/** * Resets the Kettenrad state, wipping out any pending backups and/or stale * temporary data. * * @param array $config Configuration parameters for the reset operation */ public static function reset($config = array()) { $default_config = array('global' => true, 'log' => false, 'maxrun' => 0); $config = (object) array_merge($default_config, $config); // Pause logging if so desired if (!$config->log) { AEUtilLogger::WriteLog(false, ''); } $tag = null; if (!$config->global) { // If we're not resetting globally, get a list of running backups per tag $tag = AEPlatform::getInstance()->get_backup_origin(); } // Cache the factory before proceeding $factory = AEFactory::serialize(); $runningList = AEPlatform::getInstance()->get_running_backups($tag); // Origins we have to clean $origins = array(AEPlatform::getInstance()->get_backup_origin()); // 1. Detect failed backups if (is_array($runningList) && !empty($runningList)) { // The current timestamp $now = time(); // Mark running backups as failed foreach ($runningList as $running) { if (empty($tag)) { // Check the timestamp of the log file to decide if it's stuck, // but only if a tag is not set $tstamp = @filemtime(AEUtilLogger::logName($running['origin'])); if ($tstamp !== false) { // We can only check the timestamp if it's returned. If not, we assume the backup is stale $difference = abs($now - $tstamp); // Backups less than 3 minutes old are not considered stale if ($difference < $config->maxrun) { continue; } } } $filenames = AEUtilStatistics::get_all_filenames($running, false); // Process if there are files to delete... if (!is_null($filenames)) { // Delete the failed backup's archive, if exists foreach ($filenames as $failedArchive) { AEPlatform::getInstance()->unlink($failedArchive); } } // Mark the backup failed $running['status'] = 'fail'; $running['multipart'] = 0; $dummy = null; AEPlatform::getInstance()->set_or_update_statistics($running['id'], $running, $dummy); $origins[] = $running['origin']; } } if (!empty($origins)) { $origins = array_unique($origins); foreach ($origins as $tag) { AECoreKettenrad::load($tag); // Remove temporary files AEUtilTempfiles::deleteTempFiles(); // Delete any stale temporary data AEUtilTempvars::reset($tag); } } // Reload the factory AEFactory::unserialize($factory); unset($factory); // Unpause logging if it was previously paused if (!$config->log) { AEUtilLogger::WriteLog(true, ''); } }
/** * Creates the ZIP file out of its pieces. * Official ZIP file format: http://www.pkware.com/appnote.txt * * @return boolean TRUE on success, FALSE on failure */ public function finalize() { // 1. Get size of central directory clearstatcache(); $cdOffset = @filesize($this->_dataFileName); $this->_totalDataSize += $cdOffset; $cdSize = @filesize($this->_ctrlDirFileName); // 2. Append Central Directory to data file and remove the CD temp file afterwards $dataFP = fopen($this->_dataFileName, "ab"); $cdFP = fopen($this->_ctrlDirFileName, "rb"); if ($dataFP === false) { $this->setError('Could not open ZIP data file ' . $this->_dataFileName . ' for reading'); return false; } if ($cdFP === false) { // Already glued, return fclose($dataFP); return false; } if (!$this->_useSplitZIP) { while (!feof($cdFP)) { $chunk = fread($cdFP, _AKEEBA_DIRECTORY_READ_CHUNK); $this->_fwrite($dataFP, $chunk); if ($this->getError()) { return; } } unset($chunk); fclose($cdFP); } else { // Calcuate size of Central Directory + EOCD records $comment_length = function_exists('mb_strlen') ? mb_strlen($this->_comment, '8bit') : strlen($this->_comment); $total_cd_eocd_size = $cdSize + 22 + $comment_length; // Free space on the part clearstatcache(); $current_part_size = @filesize($this->_dataFileName); $free_space = $this->_fragmentSize - ($current_part_size === false ? 0 : $current_part_size); if ($free_space < $total_cd_eocd_size && $total_cd_eocd_size > 65536) { // Not enough space on archive for CD + EOCD, will go on separate part // Create new final part if (!$this->_createNewPart(true)) { // 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($dataFP); // Open data file for output $dataFP = @fopen($this->_dataFileName, "ab"); if ($dataFP === false) { $this->setError("Could not open archive file {$this->_dataFileName} for append!"); return false; } // Write the CD record while (!feof($cdFP)) { $chunk = fread($cdFP, _AKEEBA_DIRECTORY_READ_CHUNK); $this->_fwrite($dataFP, $chunk); if ($this->getError()) { return; } } unset($chunk); fclose($cdFP); } } else { // Glue the CD + EOCD on the same part if they fit, or anyway if they are less than 64Kb. // NOTE: WE *MUST NOT* CREATE FRAGMENTS SMALLER THAN 64Kb!!!! while (!feof($cdFP)) { $chunk = fread($cdFP, _AKEEBA_DIRECTORY_READ_CHUNK); $this->_fwrite($dataFP, $chunk); if ($this->getError()) { return; } } unset($chunk); fclose($cdFP); } } AEUtilTempfiles::unregisterAndDeleteTempFile($this->_ctrlDirFileName); // 3. Write the rest of headers to the end of the ZIP file fclose($dataFP); clearstatcache(); $dataFP = fopen($this->_dataFileName, "ab"); if ($dataFP === false) { $this->setError('Could not open ' . $this->_dataFileName . ' for append'); return false; } $this->_fwrite($dataFP, $this->_ctrlDirEnd); if ($this->getError()) { return; } if ($this->_useSplitZIP) { // Split ZIP files, enter relevant disk number information $this->_fwrite($dataFP, pack('v', $this->_totalFragments - 1)); /* Number of this disk. */ $this->_fwrite($dataFP, pack('v', $this->_totalFragments - 1)); /* Disk with central directory start. */ } else { // Non-split ZIP files, the disk numbers MUST be 0 $this->_fwrite($dataFP, pack('V', 0)); } $this->_fwrite($dataFP, pack('v', $this->_totalFileEntries)); /* Total # of entries "on this disk". */ $this->_fwrite($dataFP, pack('v', $this->_totalFileEntries)); /* Total # of entries overall. */ $this->_fwrite($dataFP, pack('V', $cdSize)); /* Size of central directory. */ $this->_fwrite($dataFP, pack('V', $cdOffset)); /* Offset to start of central dir. */ $sizeOfComment = $comment_length = function_exists('mb_strlen') ? mb_strlen($this->_comment, '8bit') : strlen($this->_comment); // 2.0.b2 -- Write a ZIP file comment $this->_fwrite($dataFP, pack('v', $sizeOfComment)); /* ZIP file comment length. */ $this->_fwrite($dataFP, $this->_comment); fclose($dataFP); //sleep(2); // If Split ZIP and there is no .zip file, rename the last fragment to .ZIP if ($this->_useSplitZIP) { $extension = substr($this->_dataFileName, -3); if ($extension != '.zip') { AEUtilLogger::WriteLog(_AE_LOG_DEBUG, 'Renaming last ZIP part to .ZIP extension'); $newName = $this->_dataFileNameBase . '.zip'; if (!@rename($this->_dataFileName, $newName)) { $this->setError('Could not rename last ZIP part to .ZIP extension.'); return false; } $this->_dataFileName = $newName; } } // If Split ZIP and only one fragment, change the signature if ($this->_useSplitZIP && $this->_totalFragments == 1) { $fp = fopen($this->_dataFileName, 'r+b'); $this->_fwrite($fp, "PK00"); } if (function_exists('chmod')) { @chmod($this->_dataFileName, 0755); } return true; }
/** * Creates a new dump part */ protected function getNextDumpPart() { // On database dump only mode we mustn't create part files! if (AEUtilScripting::getScriptingParameter('db.saveasname', 'normal') == 'output') { return false; } // If the archiver is still processing, quit $finished = true; $configuration = AEFactory::getConfiguration(); $archiver = AEFactory::getArchiverEngine(); if ($configuration->get('volatile.engine.archiver.processingfile', false)) { return false; } // We have to add the dump file to the archive $this->closeFile(); AEUtilLogger::WriteLog(_AE_LOG_DEBUG, "Adding the SQL dump part to the archive"); $archiver->addFileRenamed($this->tempFile, $this->saveAsName); if ($this->getError()) { return false; } $finished = !$configuration->get('volatile.engine.archiver.processingfile', false); if (!$finished) { return false; } // Return if the file didn't finish getting added to the archive // Remove the old file AEUtilLogger::WriteLog(_AE_LOG_DEBUG, "Removing dump part's temporary file"); AEUtilTempfiles::unregisterAndDeleteTempFile($this->tempFile, true); // Create the new dump part $this->partNumber++; $this->getBackupFilePaths($this->partNumber); $null = null; $this->writeline($null); return true; }
/** * Removes temporary files * * @return bool */ private function remove_temp_files() { $this->setStep('Removing temporary files'); $this->setSubstep(''); AEUtilLogger::WriteLog(_AE_LOG_DEBUG, "Removing temporary files"); AEUtilTempfiles::deleteTempFiles(); return true; }
/** * 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 */ protected function _addFile($isVirtual, &$sourceNameOrData, $targetName) { // Are we connected to a server? if (!is_resource($this->_sftphandle)) { if (!$this->_connectSFTP()) { return false; } } // See if it's a directory $isDir = $isVirtual ? false : is_dir($sourceNameOrData); if ($isDir) { // Just try to create the remote directory return $this->_makeDirectory($targetName); } else { // We have a file we need to upload if ($isVirtual) { // Create a temporary file, upload, rename it $tempFileName = AEUtilTempfiles::createRegisterTempFile(); if (function_exists('file_put_contents')) { // Easy writing using file_put_contents if (@file_put_contents($tempFileName, $sourceNameOrData) === false) { $this->setError('Could not store virtual file ' . $targetName . ' to ' . $tempFileName . ' using file_put_contents() before uploading.'); return false; } } else { // The long way, using fopen() and fwrite() $fp = @fopen($tempFileName, 'wb'); if ($fp === false) { $this->setError('Could not store virtual file ' . $targetName . ' to ' . $tempFileName . ' using fopen() before uploading.'); return false; } else { $result = @fwrite($fp, $sourceNameOrData); if ($result === false) { $this->setError('Could not store virtual file ' . $targetName . ' to ' . $tempFileName . ' using fwrite() before uploading.'); return false; } @fclose($fp); } } // Upload the temporary file under the final name $res = $this->_upload($tempFileName, $targetName); // Remove the temporary file AEUtilTempfiles::unregisterAndDeleteTempFile($tempFileName, true); return $res; } else { // Upload a file return $this->_upload($sourceNameOrData, $targetName); } } }
private function _apiStartBackup($config) { // Get the passed configuration values $defConfig = array('profile' => 1, 'description' => '', 'comment' => '', 'backupid' => null); $config = array_merge($defConfig, $config); foreach ($config as $key => $value) { if (!array_key_exists($key, $defConfig)) { unset($config[$key]); } } extract($config); // Nuke the factory AEFactory::nuke(); // Set the profile $profile = (int) $profile; if (!is_numeric($profile)) { $profile = 1; } if (strtoupper($backupid) == '[DEFAULT]') { $db = JFactory::getDbo(); $query = $db->getQuery(true)->select('MAX(' . $db->qn('id') . ')')->from($db->qn('#__ak_stats')); try { $maxId = $db->setQuery($query)->loadResult(); } catch (Exception $e) { $maxId = 0; } $backupid = 'id' . ($maxId + 1); } elseif (empty($backupid)) { $backupid = null; } $session = JFactory::getSession(); $session->set('profile', $profile, 'akeeba'); AEPlatform::getInstance()->load_configuration($profile); // Use the default description if none specified if (empty($description)) { JLoader::import('joomla.utilities.date'); $dateNow = new JDate(); /* $user = JFactory::getUser(); $userTZ = $user->getParam('timezone',0); $dateNow->setOffset($userTZ); */ $description = JText::_('BACKUP_DEFAULT_DESCRIPTION') . ' ' . $dateNow->format(JText::_('DATE_FORMAT_LC2'), true); } // Start the backup AECoreKettenrad::reset(array('maxrun' => 0)); AEUtilTempfiles::deleteTempFiles(); $tempVarsTag = AKEEBA_BACKUP_ORIGIN; $tempVarsTag .= empty(${$backupid}) ? '' : '.' . ${$backupid}; AEUtilTempvars::reset($tempVarsTag); $kettenrad = AECoreKettenrad::load(AKEEBA_BACKUP_ORIGIN, $backupid); $kettenrad->setBackupId($backupid); $options = array('description' => $description, 'comment' => $comment, 'tag' => AKEEBA_BACKUP_ORIGIN); $kettenrad->setup($options); // Setting up the engine $array = $kettenrad->tick(); // Initializes the init domain AECoreKettenrad::save(AKEEBA_BACKUP_ORIGIN, $backupid); $array = $kettenrad->getStatusArray(); if ($array['Error'] != '') { // A backup error had occurred. Why are we here?! $this->status = self::STATUS_ERROR; $this->encapsulation = self::ENCAPSULATION_RAW; return 'A backup error had occurred: ' . $array['Error']; } else { $statistics = AEFactory::getStatistics(); $array['BackupID'] = $statistics->getId(); $array['HasRun'] = 1; // Force the backup to go on. return $array; } }