archiveFileName = InstallerBootstrapData::ARCHIVE_FILENAME; $this->archiveFileSize = InstallerBootstrapData::ARCHIVE_SIZE; $this->installerDirName = InstallerBootstrapData::INSTALLER_DIR_NAME; $this->packageHash = InstallerBootstrapData::PACKAGE_HASH; $this->secondaryHash = InstallerBootstrapData::SECONDARY_PACKAGE_HASH; $this->version = InstallerBootstrapData::VERSION; $this->setHTTPHeaders(); $this->targetRoot = BootstrapUtils::setSafePath(__DIR__); $this->overwriteData = BootstrapUtils::readOverwriteData($this->targetRoot, $this->packageHash); $this->log('', true); $archive_filepath = $this->getArchiveFilePath(); $this->origDupInstFolder = $this->installerDirName; $this->targetDupInstFolder = filter_input(INPUT_GET, 'dup_folder', FILTER_SANITIZE_SPECIAL_CHARS, [ "options" => [ "default" => $this->installerDirName, ], 'flags' => FILTER_FLAG_STRIP_HIGH, ]); $this->isCustomDupFolder = $this->origDupInstFolder !== $this->targetDupInstFolder; $this->targetDupInst = $this->targetRoot . '/' . $this->targetDupInstFolder; $this->manualExtractFileName = $this->getManualExtractFileName(); $this->extractionTmpFolder = $this->isCustomDupFolder ? $this->getTempDir($this->targetRoot) : $this->targetRoot; SecureCsrf::init($this->targetDupInst, $this->packageHash); $archiveActualSize = @file_exists($archive_filepath) ? @filesize($archive_filepath) : false; $archiveActualSize = ($archiveActualSize !== false) ? $archiveActualSize : 0; $this->archiveExpectedSize = (is_numeric($this->archiveFileSize) ? (int) $this->archiveFileSize : 0); $this->archiveActualSize = $archiveActualSize; if ($this->archiveExpectedSize > 0) { $this->archiveRatio = (((1.0) * $this->archiveActualSize) / $this->archiveExpectedSize) * 100; } else { $this->archiveRatio = 100; } } public static function getInstance() { if (is_null(self::$instance)) { self::$instance = new self(); } return self::$instance; } public static function initSetValues(): void { define('KB_IN_BYTES', 1024); define('MB_IN_BYTES', 1024 * KB_IN_BYTES); define('GB_IN_BYTES', 1024 * MB_IN_BYTES); define('DUPLICATOR_PHP_MAX_MEMORY', 4096 * MB_IN_BYTES); date_default_timezone_set('UTC'); // Some machines don't have this set so just do it here. @ignore_user_abort(true); @set_time_limit(3600); if (BootstrapUtils::isIniValChangeable('memory_limit')) { @ini_set('memory_limit', (string) DUPLICATOR_PHP_MAX_MEMORY); } if (BootstrapUtils::isIniValChangeable('max_input_time')) { @ini_set('max_input_time', '-1'); } if (BootstrapUtils::isIniValChangeable('pcre.backtrack_limit')) { @ini_set('pcre.backtrack_limit', (string) PHP_INT_MAX); } if (BootstrapUtils::isIniValChangeable('default_socket_timeout')) { @ini_set('default_socket_timeout', '3600'); } } private function setHTTPHeaders(): void { header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); } private function getTempDir(string $path) { $tempfile = tempnam($path, 'dup-installer_tmp_'); if (file_exists($tempfile)) { unlink($tempfile); mkdir($tempfile); if (is_dir($tempfile)) { return $tempfile; } } return false; } public function run(): string { date_default_timezone_set('UTC'); // Some machines don't have this set so just do it here $this->log('==DUPLICATOR INSTALLER BOOTSTRAP v' . $this->version . '=='); $this->log('----------------------------------------------------'); $this->log('Installer bootstrap start'); $archive_filepath = $this->getArchiveFilePath(); $this->log('Target dir dup folder "' . $this->targetDupInst . '"'); $this->errorMessage = ''; $is_installer_file_valid = true; if (preg_match('/_([a-z0-9]{7})[a-z0-9]+_[0-9]{6}([0-9]{8})_archive.(?:zip|daf)$/', $this->archiveFileName, $matches)) { $expected_package_hash = $matches[1] . '-' . $matches[2]; if ($this->packageHash != $expected_package_hash) { $is_installer_file_valid = false; $this->log("[ERROR] Installer and archive mismatch detected."); } } else { $this->log("[ERROR] Invalid archive file name."); $is_installer_file_valid = false; } if (false === $is_installer_file_valid) { $this->errorMessage = "Installer and archive mismatch detected. Ensure uncorrupted installer and matching archive are present."; return BootstrapView::VIEW_ERROR; } if ($this->archiveCheck() == false) { return BootstrapView::VIEW_ERROR; } if (!$this->isManualExtractFound()) { if ($this->engineCheck() == false) { return BootstrapView::VIEW_ERROR; } if (!$this->passwordCheck()) { return BootstrapView::VIEW_PASSWORD; } } if ($this->installerDirExists()) { if (($extract_installer = filter_input(INPUT_GET, 'force-extract-installer', FILTER_VALIDATE_BOOLEAN))) { $this->log("Manual extract found with force extract installer get parametr"); } else { $this->log("Manual extract found so not going to extract " . $this->targetDupInst . " dir"); } } else { $extract_installer = true; } if (file_exists($this->targetDupInst)) { $this->log("EXTRACT " . $this->targetDupInst . " dir"); $hashPattern = '[a-z0-9][a-z0-9][a-z0-9][a-z0-9][a-z0-9][a-z0-9][a-z0-9]-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'; $globs = glob($this->targetDupInst . '/' . self::DESCRIPTORS_FOLDER_PREFIX . $hashPattern, GLOB_ONLYDIR); $hashDir = self::DESCRIPTORS_FOLDER_PREFIX . $this->packageHash; if (!empty($globs)) { foreach ($globs as $glob) { $dir = basename($glob); if ($dir === $hashDir) { continue; } if (BootstrapUtils::rrmdir($glob)) { $this->log('Successfully deleted the dir ' . $glob); } else { $this->errorMessage .= '[ERROR] Error deleting the dir ' . $glob . ' Please manually delete it and try again.'; $this->log($this->errorMessage); } } } } if ($extract_installer) { try { $this->extractInstaller(); } catch (Exception $e) { $this->log("Extraction exception msg: " . $e->getMessage() . "\n" . $e->getTraceAsString()); return BootstrapView::VIEW_ERROR; } } else { $this->log("NOTICE: Didn't need to extract the installer."); } if ($this->isCustomDupFolder && file_exists($this->extractionTmpFolder)) { rmdir($this->extractionTmpFolder); } $this->copyDeployAvailableAddons(); $config_files = glob($this->targetDupInst . '/' . $this->getArchiveConfigFileName('*')); $config_file_absolute_path = array_pop($config_files); if (!file_exists($config_file_absolute_path)) { $this->errorMessage = 'Archive config file not found in ' . $this->targetDupInst . ' folder.

'; return BootstrapView::VIEW_ERROR; } if (!file_exists($this->targetDupInst)) { $this->errorMessage = 'Can\'t extract installer directory. ' . 'See this FAQ item' . ' for details on how to resolve.'; return BootstrapView::VIEW_ERROR; } $bootloader_name = basename(__FILE__); $this->archive = $archive_filepath; $this->bootloader = $bootloader_name; $this->fixInstallerPerms(); $this->setCsrfData(); $this->log("DONE: No detected errors so redirecting to the main installer. Main Installer URI = " . $this->getMainInstallerUrl()); return BootstrapView::VIEW_REDIRECT; } public function getMainInstallerUrl(): string { $uri_start = BootstrapUtils::getCurrentUrl(false, false, 1); if (self::isBridgeInstall()) { return $uri_start; } else { return $uri_start . '/' . $this->targetDupInstFolder . '/main.installer.php'; } } public function getMainInstallerUrlData(): array { $data = [ 'ctrl_action' => 'ctrl-step1', 'ctrl_csrf_token' => SecureCsrf::generate('ctrl-step1'), 'step_action' => 'init', ]; if (self::isBridgeInstall()) { $data['dup_mu_action'] = 'installer'; $data['inst_main_path'] = __DIR__ . '/' . $this->targetDupInstFolder . '/main.installer.php'; $data['brchk'] = BootstrapUtils::sanitizeNSCharsNewline($_REQUEST['brchk']); } return $data; } public function getErrorMessage() { return $this->errorMessage; } private function installerDirExists(): bool { return file_exists($this->targetDupInst) && file_exists($this->targetDupInst . "/main.installer.php") && file_exists($this->targetDupInst . '/' . $this->getArchiveConfigFileName()); } private function isManualExtractFound(): bool { return $this->installerDirExists() && file_exists($this->targetDupInst . "/" . $this->manualExtractFileName); } public function appendErrorMessage($message): void { $this->errorMessage .= (strlen($message) ? " \n" : '') . $message; } public function isZip(): bool { return (strcasecmp(pathinfo($this->archiveFileName, PATHINFO_EXTENSION), 'zip') === 0); } protected function isArchiveEncrypted() { static $isEncrypted = null; if ($isEncrypted === null) { if ($this->isZip()) { if (BootstrapUtils::isZipAvailable()) { $isEncrypted = BootstrapUtils::isZipArchiveEncrypted($this->getArchiveFilePath(), 'main.installer.php'); } else { $isEncrypted = null; throw new Exception("ERROR: Can't check if zip archive is encrypted. " . "ZipArchive " . "and ShellExec unzip" . "are not enabled on this server. Please " . "talk to your host or server admin about enabling at least one of them.
" . "Alternative is to manually extract archive then choose Advanced > Manual Extract in installer."); } } else { $isEncrypted = DupArchive::isEncrypted($this->getArchiveFilePath()); } } return $isEncrypted; } protected function passwordCheck() { if (!$this->isArchiveEncrypted()) { return true; } $this->log('ARCHIVE ENCRYPTED, PASSWORD CHECK'); $result = false; $password = (isset($_REQUEST[self::NAME_PWD]) ? BootstrapUtils::sanitizeNSCharsNewline($_REQUEST[self::NAME_PWD]) : ''); $passwordSend = (strlen($password) > 0 || (isset($_REQUEST[self::NAME_PWD_BUTTON]) && $_REQUEST[self::NAME_PWD_BUTTON] === 'secure')); if ($this->isZip()) { if ( $result = BootstrapUtils::zipArchivePasswordCheck( $this->getArchiveFilePath(), $password, 'dup-installer/main.installer.php', $this->getZipMode() ) ) { $this->log('ZIP ARCHIVE PASSWORD OK '); } else { $this->log('ZIP ARCHIVE PASSWORD FAIL '); } } else { if ($result = DupArchive::checkPassword($this->getArchiveFilePath(), $password)) { $this->log('DUP ARCHIVE PASSWORD OK '); } else { $this->log('DUP ARCHIVE PASSWORD FAIL '); } } if ($result) { $this->archivePwd = $password; } else { if ($passwordSend) { $this->appendErrorMessage('Invalid password'); } sleep(1); } return $result; } protected function archiveCheck(): bool { $archiveFilePath = $this->getArchiveFilePath(); $archiveExpectedEasy = BootstrapUtils::readableByteSize($this->archiveExpectedSize); $archiveActualEasy = BootstrapUtils::readableByteSize($this->archiveActualSize); $archiveFileExists = file_exists($archiveFilePath); if ($this->isManualExtractFound() && !$archiveFileExists) { $this->log("[ERROR] Archive file not found!"); $archiveDir = dirname($archiveFilePath); $this->errorMessage = "" . "Archive not found! The archive file cannot be found in the extraction path:
" . "{$archiveDir}/
" . "Please make sure the archive remains until the installation process is completed."; return false; } elseif (!$archiveFileExists) { $this->log("[ERROR] Archive file not found!"); $this->errorMessage = "" . "Archive not found! The required archive file must be present in the 'Extraction Path' below. " . "When the archive file name was created " . "it was given a secure hashed file name. This file name must be the exact same " . "name as when it was created character for character. " . "Each archive file has a unique installer associated with it and must be used together. See the list below for more options:
" . "
" . "Extraction Path: {$this->targetRoot}/
"; return false; } if (strlen($this->archiveFileSize) > 0 && !self::checkInputValidInt($this->archiveFileSize)) { $noOfBits = PHP_INT_SIZE * 8; $this->errorMessage = 'Current is a ' . $noOfBits . '-bit SO. This archive is too large for ' . $noOfBits . '-bit PHP.' . '
'; $this->log('[ERROR] ' . $this->errorMessage); $this->errorMessage .= 'Possibibles solutions:
'; $this->errorMessage .= '- Use the file filters to get your package lower to support this server or try the package on a Linux server.' . '
'; $this->errorMessage .= '- Perform a ' . 'Manual Extract Install' . '
'; switch ($noOfBits == 32) { case 32: $this->errorMessage .= '- Ask your host to upgrade the server to 64-bit PHP or install on another system has 64-bit PHP
'; break; case 64: $this->errorMessage .= '- Ask your host to upgrade the server to 128-bit PHP or install on another system has 128-bit PHP' . '
'; break; } if (self::isWindows()) { $this->errorMessage .= '- Windows DupArchive extractor to extract all files from the archive.' . '
'; } return false; } if (($this->archiveRatio < 90) && ($this->archiveActualSize > 0) && ($this->archiveExpectedSize > 0)) { $this->log( "ERROR: The expected archive size should be around [{$archiveExpectedEasy}]. " . "The actual size is currently [{$archiveActualEasy}]." ); $this->log("ERROR: The archive file may not have fully been downloaded to the server"); $this->errorMessage = "Archive file size warning.
The expected archive size is [{$archiveExpectedEasy}]. " . "Currently the archive size is [{$archiveActualEasy}].
" . "The archive file may have not fully been uploaded to the server." . ""; return false; } return true; } protected function engineCheck(): bool { try { if ($this->isZip()) { if (!BootstrapUtils::isZipAvailable()) { $msg = "ZipArchive and Shell Exec are not enabled on this server. Please " . "talk to your host or server admin about enabling " . "ZipArchive " . "or Shell Exec " . "on this server or manually extract archive then choose Advanced > Manual Extract in installer."; throw new Exception($msg); } if ( $this->isArchiveEncrypted() && BootstrapUtils::isPhpZipAvailable() && !BootstrapUtils::isShellZipAvailable() && version_compare(BootstrapUtils::getLibzipVersion(), '1.2.0', '<') ) { ob_start(); ?> ZipArchive Error
This server is unable to decrypt the archive file (ZipArchive), Libzip version 1.2.0+ is required.
Current Libzip version: Please contact your host or server admin to update Libzip version. isArchiveEncrypted() && !DupArchive::isEncryptionAvaliable()) { ob_start(); ?> DupArchive Error
This server is unable to decrypt the archive file (DupArchive) without the PHP OpenSSL module.
Please contact your host or server admin to enable the OpenSSL module. errorMessage = $e->getMessage(); return false; } return true; } protected function extractInstaller() { $this->log("Ready to extract the installer"); $archive_filepath = $this->getArchiveFilePath(); $this->log("Checking permission of destination folder"); $destination = $this->targetRoot; if (!is_writable($destination)) { $this->log("destination folder for extraction is not writable"); if (BootstrapUtils::chmod($destination, 'u+rwx')) { $this->log("Permission of destination folder changed to u+rwx"); } else { $this->log("[ERROR] Permission of destination folder failed to change to u+rwx"); } } if (!is_writable($destination)) { $this->log("WARNING: The {$destination} directory is not writable."); $this->errorMessage = "NOTICE: The {$destination} directory is not writable on this server please talk to your host or server admin about making "; $this->errorMessage .= "" . "writable {$destination} directory on this server.
"; throw new Exception('Destination folter isn\'t writeable'); } if ($this->isZip()) { if ($this->extractInstallerZip() == false) { throw new Exception('Fail zip extraction'); } } else { try { DupArchiveExpandBasicEngine::setCallbacks( [ $this, 'log', ], [ $this, 'chmod', ], [ $this, 'mkdir', ] ); $offset = DupArchiveExpandBasicEngine::getExtraOffset($archive_filepath, $this->archivePwd); $this->log('Expand directory from offset ' . $offset); DupArchiveExpandBasicEngine::expandDirectory( $archive_filepath, $this->origDupInstFolder, $this->extractionTmpFolder, $this->archivePwd, false, $offset ); @unlink($this->extractionTmpFolder . "/" . $this->origDupInstFolder . "/" . $this->manualExtractFileName); } catch (Exception $ex) { $this->log("[ERROR] Error expanding installer subdirectory:" . $ex->getMessage()); throw $ex; } } if ($this->isCustomDupFolder) { $this->log("Move dup-installer folder to custom folder:" . $this->targetDupInst); if (file_exists($this->targetDupInst)) { $this->log('Custom folder already exists so delete it'); if (BootstrapUtils::rrmdir($this->targetDupInst) == false) { throw new Exception('Can\'t remove custom target folder'); } } if (rename($this->extractionTmpFolder . '/' . $this->origDupInstFolder, $this->targetDupInst) === false) { throw new Exception('Can\'t rename the tmp dup-installer folder'); } } $htaccessToRemove = $this->targetDupInst . '/.htaccess'; if (is_file($htaccessToRemove) && is_writable($htaccessToRemove)) { $this->log("Remove Htaccess in dup-installer folder"); @unlink($htaccessToRemove); } $is_apache = (strpos($_SERVER['SERVER_SOFTWARE'], 'Apache') !== false || strpos($_SERVER['SERVER_SOFTWARE'], 'LiteSpeed') !== false); $is_nginx = (strpos($_SERVER['SERVER_SOFTWARE'], 'nginx') !== false); $sapi_type = php_sapi_name(); $php_ini_data = [ 'max_execution_time' => 3600, 'max_input_time' => -1, 'ignore_user_abort' => 'On', 'post_max_size' => '4096M', 'upload_max_filesize' => '4096M', 'memory_limit' => DUPLICATOR_PHP_MAX_MEMORY, 'default_socket_timeout' => 3600, 'pcre.backtrack_limit' => 99999999999, ]; $sapi_type_first_three_chars = substr($sapi_type, 0, 3); if ('fpm' === $sapi_type_first_three_chars) { $this->log("SAPI: FPM"); if ($is_apache) { $this->log('Server: Apache'); } elseif ($is_nginx) { $this->log('Server: Nginx'); } if (($is_apache && function_exists('apache_get_modules') && in_array('mod_rewrite', apache_get_modules())) || $is_nginx) { $htaccess_data = []; foreach ($php_ini_data as $php_ini_key => $php_ini_val) { if ($is_apache) { $htaccess_data[] = 'SetEnv PHP_VALUE "' . $php_ini_key . ' = ' . $php_ini_val . '"'; } elseif ($is_nginx) { if ('On' == $php_ini_val || 'Off' == $php_ini_val) { // @phpstan-ignore equal.alwaysFalse $htaccess_data[] = 'php_flag ' . $php_ini_key . ' ' . $php_ini_val; } else { $htaccess_data[] = 'php_value ' . $php_ini_key . ' ' . $php_ini_val; } } } $htaccess_text = implode("\n", $htaccess_data); $htaccess_file_path = $this->targetDupInst . '/.htaccess'; $this->log("creating {$htaccess_file_path} with the content:"); $this->log($htaccess_text); @file_put_contents($htaccess_file_path, $htaccess_text); } } elseif ('cgi' === $sapi_type_first_three_chars || 'litespeed' === $sapi_type) { if ('cgi' === $sapi_type_first_three_chars) { $this->log("SAPI: CGI"); } else { $this->log("SAPI: litespeed"); } if (!$is_apache || 'litespeed' === $sapi_type) { $ini_data = []; foreach ($php_ini_data as $php_ini_key => $php_ini_val) { $ini_data[] = $php_ini_key . ' = ' . $php_ini_val; } $ini_text = implode("\n", $ini_data); $ini_file_path = $this->targetDupInst . '/.user.ini'; $this->log("creating {$ini_file_path} with the content:"); $this->log($ini_text); @file_put_contents($ini_file_path, $ini_text); } else { $this->log("No need to create " . $this->targetDupInst . "/.htaccess or " . $this->targetDupInst . "/.user.ini"); } } elseif ("apache2handler" === $sapi_type) { $this->log("No need to create " . $this->targetDupInst . "/.htaccess or " . $this->targetDupInst . "/.user.ini"); $this->log("SAPI: apache2handler"); } else { $this->log("No need to create " . $this->targetDupInst . "/.htaccess or " . $this->targetDupInst . "/.user.ini"); $this->log("ERROR: SAPI: Unrecognized"); } } protected function copyDeployAvailableAddons(): void { if (!isset($this->overwriteData['deploy_available_addons']['value'])) { return; } $addonsData = $this->overwriteData['deploy_available_addons']['value']; if (!is_array($addonsData) || empty($addonsData)) { return; } $targetAddons = $this->targetDupInst . '/addons'; if (!is_dir($targetAddons)) { BootstrapUtils::mkdir($targetAddons, 0755, true); } foreach ($addonsData as $slug => $sourceDir) { $slug = basename($slug); $targetDir = $targetAddons . '/' . $slug; if (is_dir($targetDir)) { continue; } if (!is_dir($sourceDir)) { $this->log("Import addon source not found: " . $sourceDir); continue; } if (BootstrapUtils::copyDirectory($sourceDir, $targetDir)) { $this->log("Copied import addon: " . $slug); } else { $this->log("[WARN] Failed to copy import addon: " . $slug); } } } protected function extractInstallerZip() { $success = false; switch ($this->getZipMode()) { case self::ZIP_MODE_ARCHIVE: $this->log("ZipArchive exists so using that"); $success = $this->extractInstallerZipArchive($this->getArchiveFilePath(), $this->origDupInstFolder, $this->extractionTmpFolder); if ($success) { $this->log('Successfully extracted with ZipArchive'); } else { if (0 == $this->installerFilesFound) { $this->errorMessage = "[ERROR] This archive is not properly formatted and does not contain a " . $this->origDupInstFolder . " directory. Please make sure you are attempting to install " . "the original archive and not one that has been reconstructed."; $this->log($this->errorMessage); } else { $this->errorMessage = '[ERROR] Error extracting with ZipArchive. '; $this->log($this->errorMessage); } } break; case self::ZIP_MODE_SHELL: $success = $this->extractInstallerShellexec($this->getArchiveFilePath(), $this->origDupInstFolder, $this->extractionTmpFolder); $this->log("Resetting perms of items in folder {$this->targetDupInst}"); self::setPermsToDefaultR($this->targetDupInst); if ($success) { $this->log('Successfully extracted with Shell Exec'); $this->errorMessage = ''; } else { $this->errorMessage .= '[ERROR] Error extracting with Shell Exec. ' . 'Please manually extract archive then choose Advanced > Manual Extract in installer.'; $this->log($this->errorMessage); } break; case self::ZIP_MODE_NONE: if (!BootstrapUtils::isZipAvailable()) { $this->log("WARNING: ZipArchive and Shell Exec are not enabled on this server."); $this->errorMessage = "NOTICE: ZipArchive and Shell Exec are not enabled on this server. Please " . "talk to your host or server admin about enabling " . "ZipArchive " . "or Shell Exec " . "on this server or manually extract archive then choose Advanced > Manual Extract in installer."; } break; } return $success; } protected function setCsrfData() { SecureCsrf::setKeyVal('installerOrigCall', BootstrapUtils::getCurrentUrl()); SecureCsrf::setKeyVal('installerOrigPath', __FILE__); SecureCsrf::setKeyVal('archive', $this->archive); SecureCsrf::setKeyVal('bootloader', $this->bootloader); SecureCsrf::setKeyVal(self::CSRF_KEY_ARCHIVE_PASSWORD, $this->archivePwd); SecureCsrf::setKeyVal('booturl', '//' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']); SecureCsrf::setKeyVal('bootLogFile', $this->getBootLogFilePath()); SecureCsrf::setKeyVal('package_hash', $this->packageHash); SecureCsrf::setKeyVal('secondaryHash', $this->secondaryHash); if (self::isBridgeInstall()) { if (!isset($_REQUEST['inst_main_url'])) { throw new Exception('Invalid input data, inst_main_url required'); } SecureCsrf::setKeyVal('originalDupInstallerUrl', $_REQUEST['inst_main_url']); } else { SecureCsrf::setKeyVal('originalDupInstallerUrl', ''); } SecureCsrf::setKeyVal('isManualExtractFound', $this->isManualExtractFound()); } public function getRedirectForm() { $mainInstallerURL = $this->getMainInstallerUrl(); $data = $this->getMainInstallerUrlData(); $id = uniqid(); ob_start(); ?>
$value) { if ('csrf_token' != $name) { $_SESSION[$name] = $value; } ?>
targetDupInst; $this->setPerms($installer_dir_path, $dir_perms, false); $this->setPerms($installer_dir_path, $file_perms, true); } private function setPerms($directory, string $perms, bool $do_files): void { if (!$do_files) { $this->setPermsOnItem($directory, $perms); } $item_names = array_diff(scandir($directory), ['.', '..']); foreach ($item_names as $item_name) { $path = "$directory/$item_name"; if (($do_files && is_file($path)) || (!$do_files && !is_file($path))) { $this->setPermsOnItem($path, $perms); } } } private function setPermsOnItem($path, string $perms) { if (($result = BootstrapUtils::chmod($path, $perms)) === false) { $this->log("ERROR: Couldn't set permissions of $path
"); } else { $this->log("Set permissions of $path
"); } return $result; } public function log($s, $deleteOld = false) { static $logfile = null; if (is_null($logfile)) { $logfile = $this->getBootLogFilePath(); } if ($deleteOld && file_exists($logfile)) { @unlink($logfile); } $timestamp = date('M j H:i:s'); return @file_put_contents($logfile, '[' . $timestamp . '] ' . $this->postprocessLog($s) . "\n", FILE_APPEND); } public function getBootLogFilePath(): string { return $this->targetRoot . '/dup-installer-bootlog__' . $this->secondaryHash . '.txt'; } protected function postprocessLog($str): string { return str_replace([ $this->getArchiveFileHash(), $this->packageHash, $this->secondaryHash, ], '[HASH]', $str); } public function getArchiveFileHash() { static $fileHash = null; if (is_null($fileHash)) { $fileHash = preg_replace('/^.+_([a-z0-9]+)_[0-9]{14}_archive\.(?:daf|zip)$/', '$1', $this->archiveFileName); } return $fileHash; } private function extractInstallerZipArchive($archive_filepath, $origDupInstFolder, $destination, bool $checkSubFolder = false) { $success = true; $zipArchive = new ZipArchive(); $subFolderArchiveList = []; if (($zipOpenRes = $zipArchive->open($archive_filepath)) !== true) { $this->log("[ERROR] Couldn't open archive archive file with ZipArchive CODE[" . $zipOpenRes . "]"); return false; } if (strlen($this->archivePwd)) { $zipArchive->setPassword($this->archivePwd); } $this->log("Successfully opened archive file."); $folder_prefix = $origDupInstFolder . '/'; $this->log("Extracting all files from archive within " . $origDupInstFolder); $this->installerFilesFound = 0; $manualExtractFound = false; for ($i = 0; $i < $zipArchive->numFiles; $i++) { $stat = $zipArchive->statIndex($i); if ($checkSubFolder == false) { $filenameCheck = $stat['name']; $filename = $stat['name']; $tmpSubFolder = null; } else { $safePath = rtrim(BootstrapUtils::setSafePath($stat['name']), '/'); $tmpArray = explode('/', $safePath); if (count($tmpArray) < 2) { continue; } $tmpSubFolder = $tmpArray[0]; array_shift($tmpArray); $filenameCheck = implode('/', $tmpArray); $filename = $stat['name']; } if (!BootstrapUtils::startsWith($filenameCheck, $folder_prefix)) { continue; } $this->installerFilesFound++; if (!empty($tmpSubFolder) && !in_array($tmpSubFolder, $subFolderArchiveList)) { $subFolderArchiveList[] = $tmpSubFolder; } if (!$manualExtractFound && substr($filename, -strlen($this->manualExtractFileName)) === $this->manualExtractFileName) { $this->log("Skipping manual extract file: {$filename}"); $manualExtractFound = true; continue; } if ($zipArchive->extractTo($destination, $filename) === true) { $this->log("Success: {$filename} >>> {$destination}"); } else { $this->log("[ERROR] Error extracting {$filename} >>> {$destination}"); $success = false; break; } } if ($checkSubFolder && count($subFolderArchiveList) !== 1) { $this->log("Error: Multiple dup subfolder archive"); $success = false; } else { if ($checkSubFolder) { $this->moveUpfromSubFolder($destination . '/' . $subFolderArchiveList[0], true); } $lib_directory = $destination . '/' . $origDupInstFolder . '/lib'; $snaplib_directory = $lib_directory . '/snaplib'; if (!file_exists($snaplib_directory)) { $folder_prefix = 'snaplib/'; $destination = $lib_directory; for ($i = 0; $i < $zipArchive->numFiles; $i++) { $stat = $zipArchive->statIndex($i); $filename = $stat['name']; if (BootstrapUtils::startsWith($filename, $folder_prefix)) { $this->installerFilesFound++; if ($zipArchive->extractTo($destination, $filename) === true) { $this->log("Success: {$filename} >>> {$destination}"); } else { $this->log("[ERROR] Error extracting {$filename} from archive archive file"); $success = false; break; } } } } } if ($zipArchive->close() === true) { $this->log("Successfully closed archive file"); } else { $this->log("[ERROR] Problem closing archive file"); $success = false; } if ($success != false && $this->installerFilesFound < 10) { if ($checkSubFolder) { $this->log("[ERROR] Couldn't find the installer directory in the archive!"); $success = false; } else { $this->log("[ERROR] Couldn't find the installer directory in archive root! Check subfolder"); return $this->extractInstallerZipArchive($archive_filepath, $origDupInstFolder, $destination, true); } } return $success; } public static function isWindows() { static $isWindows = null; if (is_null($isWindows)) { $isWindows = (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN'); } return $isWindows; } public static function setPermsToDefaultR($directory): void { $dir = new \RecursiveDirectoryIterator($directory, \FilesystemIterator::SKIP_DOTS); $iterator = new \RecursiveIteratorIterator($dir, \RecursiveIteratorIterator::SELF_FIRST); $defaultFilePermission = 0666 & ~umask(); $defaultDirPermission = 0777 & ~umask(); foreach ($iterator as $item) { if ($item->isFile()) { BootstrapUtils::chmod($item->getPathname(), $defaultFilePermission); } if ($item->isDir()) { BootstrapUtils::chmod($item->getPathname(), $defaultDirPermission); } } } public static function checkInputValidInt($input): bool { return (filter_var($input, FILTER_VALIDATE_INT) === 0 || filter_var($input, FILTER_VALIDATE_INT)); } private function moveUpfromSubFolder(string $subFolderName, bool $deleteSubFolder = false) { if (!is_dir($subFolderName)) { return false; } $parentFolder = dirname($subFolderName); if (!is_writable($parentFolder)) { return false; } $success = true; if (($subList = glob(rtrim($subFolderName, '/') . '/*', GLOB_NOSORT)) === false) { $this->log("[ERROR] Problem glob folder " . $subFolderName); return false; } else { foreach ($subList as $cName) { $destination = $parentFolder . '/' . basename($cName); if (file_exists($destination)) { $success = BootstrapUtils::rrmdir($destination); } if ($success) { $success = rename($cName, $destination); } else { break; } } if ($success && $deleteSubFolder) { $success = BootstrapUtils::rrmdir($subFolderName); } } if (!$success) { $this->log("[ERROR] Problem om moveUpfromSubFolder subFolder:" . $subFolderName); } return $success; } private function extractInstallerShellexec($archive_filepath, $origDupInstFolder, $destination) { $success = false; $this->log("Attempting to use Shell Exec"); $unzip_filepath = BootstrapUtils::getUnzipFilePath(); if ($unzip_filepath == null) { return false; } $params = "-o -q"; if (strlen($this->archivePwd)) { $params .= ' -P ' . escapeshellarg($this->archivePwd); } $unzip_command = escapeshellcmd($unzip_filepath) . ' ' . $params . ' ' . escapeshellarg($archive_filepath) . ' ' . escapeshellarg($origDupInstFolder . '/*') . ' -d ' . escapeshellarg($destination) . ' -x ' . escapeshellarg($origDupInstFolder . '/' . $this->manualExtractFileName) . ' 2>&1'; $this->log("Executing $unzip_command"); $shellOutput = Shell::runCommandBuffered($unzip_command); if ($shellOutput->getCode() >= 0 && $shellOutput->isEmpty()) { $this->log("Shell exec unzip succeeded"); $success = true; } else { $this->log("[ERROR] Shell exec unzip failed. Output={$shellOutput->getOutputAsString()}"); } return $success; } private function getArchiveFilePath() { $archiveInput = CliEnvironment::getArchiveLocation() ?? filter_input(INPUT_GET, 'archive', FILTER_SANITIZE_SPECIAL_CHARS); if ($archiveInput != false) { $archiveDir = is_dir($archiveInput) ? $archiveInput : dirname($archiveInput); $archive_filepath = $archiveDir . '/' . $this->archiveFileName; } else { $archive_filepath = $this->targetRoot . '/' . $this->archiveFileName; } if (($realPath = realpath($archive_filepath)) !== false) { return $realPath; } else { return $archive_filepath; } } private function getZipMode(): int { $zip_mode = self::ZIP_MODE_AUTO; if (isset($_GET['zipmode'])) { $zipmode_string = $_GET['zipmode']; $this->log("Unzip mode specified in querystring: $zipmode_string"); switch ($zipmode_string) { case 'autounzip': $zip_mode = self::ZIP_MODE_AUTO; break; case 'ziparchive': $zip_mode = self::ZIP_MODE_ARCHIVE; break; case 'shellexec': $zip_mode = self::ZIP_MODE_SHELL; break; } } switch ($zip_mode) { case self::ZIP_MODE_AUTO: case self::ZIP_MODE_ARCHIVE: if ( BootstrapUtils::isPhpZipAvailable() && ( !$this->isArchiveEncrypted() || !version_compare(BootstrapUtils::getLibzipVersion(), '1.2.0', '<') ) ) { return self::ZIP_MODE_ARCHIVE; } elseif (Shell::test()) { return self::ZIP_MODE_SHELL; } else { return self::ZIP_MODE_NONE; } case self::ZIP_MODE_SHELL: if (Shell::test()) { return self::ZIP_MODE_SHELL; } elseif ( BootstrapUtils::isPhpZipAvailable() && ( !$this->isArchiveEncrypted() || !version_compare(BootstrapUtils::getLibzipVersion(), '1.2.0', '<') ) ) { return self::ZIP_MODE_ARCHIVE; } else { return self::ZIP_MODE_NONE; } default: return self::ZIP_MODE_NONE; } } public function getFilesWithExtension($extension): array { $files = []; foreach (glob("*.{$extension}") as $name) { if (file_exists($name)) { $files[] = $name; } } if (count($files) > 0) { return $files; } if (($dh = opendir($this->targetRoot))) { while (false !== ($name = readdir($dh))) { $ext = substr($name, strrpos($name, '.') + 1); if ($ext == $extension) { $files[] = $name; } } closedir($dh); } return $files; } private function getManualExtractFileName(): string { return self::DESCRIPTORS_FOLDER_PREFIX . $this->packageHash . '/' . self::MANUAL_EXTRACT_FILE_NAME; } private function getArchiveConfigFileName(string $hash = ''): string { if (empty($hash)) { $hash = $this->packageHash; } return self::DESCRIPTORS_FOLDER_PREFIX . $hash . '/' . self::ARCHIVE_CONFIG_FILE_NAME; } public function getVersion() { return $this->version; } public function getSecondaryHash() { return $this->secondaryHash; } public static function isBridgeInstall(): bool { return defined('DUPLICATOR_MU_PLUGIN_VERSION'); } } } namespace Duplicator\Libs\Shell { use Duplicator\Utils\Logging\DupLog; use Exception; use Throwable; class Shell { public static function runCommandBuffered($command): ShellOutput { try { $handler = null; $output = null; $code = -1; if (($handler = popen($command, 'r')) === false) { throw new Exception('Failed to execute shell command on popen'); } while (($line = fgets($handler)) !== false) { $output[] = $line; } } catch (Throwable $e) { $code = -1; $output = 'Shell command exception:' . $e->getMessage(); } finally { if (is_resource($handler)) { $code = pclose($handler); } } return new ShellOutput($output, $code); } public static function runCommandStream( string $cmd, callable $callback ): int { try { $handler = null; $result = -1; $handler = popen($cmd, 'r'); if (! $handler) { throw new Exception('Failed to execute shell command'); } while (($line = fgets($handler)) !== false) { $callback($line); } } catch (Throwable $e) { $result = -1; } finally { if (is_resource($handler)) { $result = pclose($handler); } } return $result; } private static function isShellAvaliable(): bool { static $isAvaiable = null; if (is_null($isAvaiable)) { $isAvaiable = !self::hasDisabledFunctions( [ 'escapeshellarg', 'escapeshellcmd', 'extension_loaded', 'popen', 'pclose', ] ); } return $isAvaiable; } public static function hasDisabledFunctions($functions): bool { if (is_scalar($functions)) { $functions = [$functions]; } if (array_intersect($functions, self::getDisabledFunctions())) { return true; } foreach ($functions as $function) { if (!function_exists($function)) { return true; } } return false; } protected static function getDisabledFunctions(): array { static $funcsList = null; if (is_null($funcsList)) { $funcsList = []; if (function_exists('ini_get')) { if (($ini = ini_get('disable_functions')) === false) { $ini = ''; } $funcsList = array_map('trim', explode(',', $ini)); if (self::isSuhosinEnabled()) { if (($ini = ini_get("suhosin.executor.func.blacklist")) === false) { $ini = ''; } $funcsList = array_merge($funcsList, array_map('trim', explode(',', $ini))); $funcsList = array_values(array_unique($funcsList)); } } } return $funcsList; } public static function test(): bool { static $testResult = null; if ($testResult === null) { if (self::isShellAvaliable() === false) { $testResult = false; } else { if (($shellOutput = Shell::runCommandBuffered('echo test'))->getCode() < 0) { $testResult = false; } else { $testResult = (trim($shellOutput->getOutputAsString()) === 'test'); } } } return $testResult; } public static function escapeshellargWindowsSupport($string): string { if (strncasecmp(PHP_OS, 'WIN', 3) == 0) { if (strstr($string, '%') || strstr($string, '!')) { return '"' . str_replace('"', '', $string) . '"'; } } return escapeshellarg($string); } public static function getCompressionParam($isCompressed): string { return $isCompressed ? '-6' : '-0'; } public static function isSuhosinEnabled(): bool { return extension_loaded('suhosin'); } public static function getExeFilepath(string $exeFilename): ?string { $filepath = null; if (!self::test()) { return null; } $shellOutput = self::runCommandBuffered("hash $exeFilename 2>&1"); if ($shellOutput->getCode() >= 0 && $shellOutput->isEmpty()) { $filepath = $exeFilename; } else { $possible_paths = [ "/usr/bin/$exeFilename", "/opt/local/bin/$exeFilename", ]; foreach ($possible_paths as $path) { if (@file_exists($path)) { $filepath = $path; break; } } } return $filepath; } public static function isExecutable(string $cmd): bool { if (strlen($cmd) == 0) { return false; } if (is_executable($cmd)) { return true; } $result = self::runCommandBuffered($cmd); if ($result->getCode() >= 0 && !$result->isEmpty()) { return true; } $resultAlt = self::runCommandBuffered($cmd . ' -?'); if ($resultAlt->getCode() >= 0 && !$resultAlt->isEmpty()) { return true; } return false; } } } namespace Duplicator\Libs\Shell { class ShellOutput { private $output = []; private int $code; public function __construct($output, $code) { if (is_scalar($output) || is_null($output)) { $output = (string) $output; if (strlen($output) == 0) { $output = []; } elseif (($output = preg_split("/(\r\n|\n|\r)/", (string) $output)) === false) { $output = []; } } $this->output = self::formatOutput($output); $this->code = (int) $code; } private static function formatOutput($output) { foreach ($output as $key => $line) { $line = preg_replace('~\r\n?~', "\n", $line); if (strlen($line) == 0 || substr($line, -1) !== "\n") { $line .= "\n"; } $output[$key] = $line; } return $output; } public function getOutputAsString(int $limitLines = 0): string { if ($limitLines > 0) { $lines = array_slice($this->output, 0, $limitLines); } elseif ($limitLines < 0) { $lines = array_slice($this->output, $limitLines); } else { $lines = $this->output; } return implode('', $lines); } public function getArrayWithAllOutputLines() { return $this->output; } public function getCode(): int { return $this->code; } public function isEmpty(): bool { return (strlen(trim($this->getOutputAsString())) == 0); } } } namespace Duplicator\Installer\Bootstrap { use Duplicator\Installer\Bootstrap\BootstrapRunner; use Duplicator\Libs\Shell\Shell; use Exception; use Throwable; use ZipArchive; class BootstrapUtils { public static function isIniValChangeable($setting): bool { static $ini_all; if (!isset($ini_all)) { $ini_all = false; if (function_exists('ini_get_all')) { $ini_all = ini_get_all(); } } if (isset($ini_all[$setting]['access']) && (INI_ALL === ($ini_all[$setting]['access'] & 7) || INI_USER === ($ini_all[$setting]['access'] & 7))) { return true; } if (!is_array($ini_all)) { return true; } return false; } public static function phpVersionCheck($minPhpVer): void { if (version_compare(PHP_VERSION, $minPhpVer, '>=')) { return; } $match = null; $phpVersion = preg_match("#^\d+(\.\d+)*#", PHP_VERSION, $match) ? $match[0] : PHP_VERSION; ?> Duplicator Installer - issue

DUPLICATOR ISSUE: PHP REQUIRED

This server is running PHP: . A minimum of PHP is required.

Contact your hosting provider or server administrator and let them know you would like to upgrade your PHP version.

\s*(libzip.*\sver.+?)\s*<\/td>\s*\s*(.+?)\s*<\/td>/i', $info, $matches) !== 1) { $libzipVersion = "0"; } else { $libzipVersion = $matches[2]; } } return $libzipVersion; } public static function isZipAvailable(): bool { return (self::isPhpZipAvailable() || self::isShellZipAvailable()); } public static function isPhpZipAvailable() { return self::classExists(ZipArchive::class); } public static function isShellZipAvailable(): bool { return (self::getUnzipFilePath() !== false); } public static function isZipArchiveEncrypted($path, $fileToCheck) { if (self::isPhpZipAvailable()) { $zip = new ZipArchive(); if (($zipOpenRes = $zip->open($path)) !== true) { $message = "[ERROR] Couldn't open archive archive file with ZipArchive CODE[" . $zipOpenRes . "]"; throw new Exception($message); } if (($stats = $zip->statName($fileToCheck, ZipArchive::FL_NODIR)) == false) { throw new Exception('Formatting archive error, cannot find file ' . $fileToCheck); } if (isset($stats['encryption_method'])) { $isEncrypt = ($stats['encryption_method'] > 0); } else { $isEncrypt = ($zip->getFromIndex($stats['index']) === false); } $zip->close(); return $isEncrypt; } elseif (self::isShellZipAvailable()) { return self::isZipArchiveEncryptedShellUnzip($path, $fileToCheck); } else { throw new Exception('Zip archive isn\'t available'); } } protected static function isZipArchiveEncryptedShellUnzip($path, $fileToCheck) { $tempFolderName = "temp_0oA8wkOvxjKtngR_dir"; $unzipFilepath = self::getUnzipFilePath(); $unzipCommand = escapeshellcmd($unzipFilepath) . " -o " . escapeshellcmd($path) . " " . escapeshellcmd("dup-installer/$fileToCheck") . " -d " . escapeshellcmd(dirname($path)) . "/" . escapeshellcmd($tempFolderName) . "/ 2>&1"; $output = Shell::runCommandBuffered($unzipCommand); $encrypted = true; if (file_exists(dirname($path) . "/$tempFolderName/dup-installer/$fileToCheck")) { $encrypted = false; } BootstrapUtils::rrmdir(dirname($path) . "/$tempFolderName"); return $encrypted; } public static function zipArchivePasswordCheck($archivePath, $password, $fileToCheck, $zipMode) { if ($zipMode == BootstrapRunner::ZIP_MODE_NONE) { throw new Exception("NOTICE: ZipArchive and Shell Exec are not enabled on this server. Please " . "talk to your host or server admin about enabling " . "ZipArchive " . "or Shell Exec " . "on this server or manually extract archive then choose Advanced > Manual Extract in installer."); } if ($zipMode == BootstrapRunner::ZIP_MODE_ARCHIVE) { $zip = new ZipArchive(); if (($zipOpenRes = $zip->open($archivePath)) !== true) { $message = "[ERROR] Couldn't open archive archive file with ZipArchive CODE[" . $zipOpenRes . "]"; throw new Exception($message); } if (($stats = $zip->statName(basename($fileToCheck), ZipArchive::FL_NODIR)) == false) { throw new Exception("Formatting archive error, cannot find the file " . basename($fileToCheck)); } $zip->setPassword($password); $result = $zip->getFromIndex($stats['index']); $zip->close(); return $result; } if ($zipMode == BootstrapRunner::ZIP_MODE_SHELL) { if ($password == "") { return false; } $destinationDir = dirname($archivePath) . "/tmp"; $unzip_filepath = self::getUnzipFilePath(); if ($unzip_filepath == null) { throw new Exception("Could not find unzip app, and ZIP_MODE_SHELL is chosen."); } $params = "-o -P " . escapeshellarg($password); $unzip_command = escapeshellcmd($unzip_filepath) . ' ' . $params . ' ' . escapeshellarg($archivePath) . ' ' . escapeshellarg($fileToCheck) . ' -d ' . escapeshellarg($destinationDir) . ' 2>&1'; $shellOutput = Shell::runCommandBuffered($unzip_command); if ($shellOutput->getCode() < 0) { $errorMsg = "[ERROR] Shell exec unzip failed. Shell::runCommandBuffered returned false."; self::rrmdir($destinationDir); throw new Exception($errorMsg); } if (file_exists($destinationDir . "/" . $fileToCheck)) { self::rrmdir($destinationDir); return true; // Password is correct } $shellOutputAsString = $shellOutput->getOutputAsString(); $matchResult = preg_match('/skipping:.*incorrect password/', $shellOutputAsString); if ($matchResult) { self::rrmdir($destinationDir); return false; // Incorrect password } $errorMsg = "[ERROR] Shell exec unzip failed. Output={$shellOutputAsString}"; $matchResult = preg_match('/skipping:.*need PK compat./', $shellOutputAsString); if ($matchResult) { $errorMsg .= "
It looks like you haven't used 'shell zip' engine when you created this archive. " . "Either create new package and use 'shell zip' as archive engine, or " . "contact the hosting manager and ask them to activate the ZipArchive class, then try again."; } else { $errorMsg .= "
If you can't fix the problem with 'shell unzip', contact the hosting manager and " . "ask them to activate the ZipArchive class, then try again."; } self::rrmdir($destinationDir); throw new Exception($errorMsg); } throw new Exception("Unrecognised zipMode = $zipMode passed to function zipArchivePasswordCheck."); } public static function getCurrentUrl($queryString = true, $requestUri = false, $getParentDirLevel = 0): string { if (isset($_SERVER['HTTP_X_ORIGINAL_HOST'])) { $host = $_SERVER['HTTP_X_ORIGINAL_HOST']; } else { $host = $_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME']; //WAS SERVER_NAME and caused problems on some boxes } if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') { $_SERVER['HTTPS'] = 'on'; } if (isset($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] === 'https') { $_SERVER['HTTPS'] = 'on'; } if (isset($_SERVER['HTTP_CF_VISITOR'])) { $visitor = json_decode($_SERVER['HTTP_CF_VISITOR']); if (is_object($visitor) && property_exists($visitor, 'scheme') && $visitor->scheme == 'https') { $_SERVER['HTTPS'] = 'on'; } } $protocol = 'http' . ((isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) === 'on') ? 's' : ''); if ($requestUri) { $serverUrlSelf = preg_replace('/\?.*$/', '', $_SERVER['REQUEST_URI']); } else { $serverUrlSelf = $_SERVER['SCRIPT_NAME']; for ($i = 0; $i < $getParentDirLevel; $i++) { $serverUrlSelf = preg_match('/^[\\\\\/]?$/', dirname($serverUrlSelf)) ? '' : dirname($serverUrlSelf); } } $query = ($queryString && isset($_SERVER['QUERY_STRING']) && strlen($_SERVER['QUERY_STRING']) > 0) ? '?' . $_SERVER['QUERY_STRING'] : ''; return $protocol . '://' . $host . $serverUrlSelf . $query; } public static function chmod($file, $mode) { if (!file_exists($file)) { return false; } $octalMode = 0; if (is_int($mode)) { $octalMode = $mode; } elseif (is_string($mode)) { $mode = trim($mode); if (preg_match('/([0-7]{1,3})/', $mode)) { $octalMode = intval(('0' . $mode), 8); } elseif (preg_match_all('/(a|[ugo]{1,3})([-=+])([rwx]{1,3})/', $mode, $gMatch, PREG_SET_ORDER)) { if (!function_exists('fileperms')) { return false; } $octalMode = (fileperms($file) & 0777); foreach ($gMatch as $matches) { $group = $matches[1]; if ($group === 'a') { $group = 'ugo'; } $action = $matches[2]; $gPerms = $matches[3]; $octalGroupMode = 0; $subPerm = 0; $subPerm += strpos($gPerms, 'x') !== false ? 1 : 0; // mask 001 $subPerm += strpos($gPerms, 'w') !== false ? 2 : 0; // mask 010 $subPerm += strpos($gPerms, 'r') !== false ? 4 : 0; // mask 100 $ugoLen = strlen($group); if ($action === '=') { $ugoMaskInvert = 0777; for ($i = 0; $i < $ugoLen; $i++) { switch ($group[$i]) { case 'u': $octalGroupMode |= $subPerm << 6; // mask xxx000000 $ugoMaskInvert &= 077; break; case 'g': $octalGroupMode |= $subPerm << 3; // mask 000xxx000 $ugoMaskInvert &= 0707; break; case 'o': $octalGroupMode |= $subPerm; // mask 000000xxx $ugoMaskInvert &= 0770; break; } } $octalMode &= $ugoMaskInvert | $octalGroupMode; } else { for ($i = 0; $i < $ugoLen; $i++) { switch ($group[$i]) { case 'u': $octalGroupMode |= $subPerm << 6; // mask xxx000000 break; case 'g': $octalGroupMode |= $subPerm << 3; // mask 000xxx000 break; case 'o': $octalGroupMode |= $subPerm; // mask 000000xxx break; } } switch ($action) { case '+': $octalMode |= $octalGroupMode; break; case '-': $octalMode &= ~$octalGroupMode; break; } } } } } if (function_exists('fileperms') && $octalMode === (fileperms($file) & 0777)) { return true; } if (!function_exists('chmod')) { return false; } return @chmod($file, $octalMode); } public static function mkdir($path, $mode = 0777, $recursive = false, $context = null) { if (strlen($path) > PHP_MAXPATHLEN) { throw new Exception('Skipping a file that exceeds allowed max path length [' . PHP_MAXPATHLEN . ']. File: ' . $path); } if (!file_exists($path)) { if (!function_exists('mkdir')) { return false; } if (!@mkdir($path, 0777, $recursive)) { return false; } } return self::chmod($path, $mode); } public static function startsWith($haystack, $needle): bool { return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== false; } public static function hasShellExec(): bool { if (!Shell::test()) { return false; } return true; } public static function getUnzipFilePath() { static $filepath = null; if ($filepath === null) { if (!self::hasShellExec()) { $filepath = false; } elseif (Shell::runCommandBuffered('hash unzip 2>&1')->getCode() >= 0) { $filepath = 'unzip'; } else { $filepath = false; $possible_paths = [ '/usr/bin/unzip', '/opt/local/bin/unzip', '/bin/unzip', '/usr/local/bin/unzip', '/usr/sfw/bin/unzip', '/usr/xdg4/bin/unzip', '/opt/bin/unzip', ]; foreach ($possible_paths as $path) { if (file_exists($path)) { $filepath = $path; break; } } } } return $filepath; } public static function readableByteSize($size): string { try { $units = [ 'B', 'KB', 'MB', 'GB', 'TB', ]; for ($i = 0; $size >= 1024 && $i < 4; $i++) { $size /= 1024; } return round($size, 2) . $units[$i]; } catch (Throwable $e) { // @phpstan-ignore catch.neverThrown (defensive guard kept on purpose) return "n/a"; } } public static function rrmdir($path) { if (is_dir($path)) { if (($dh = opendir($path)) === false) { return false; } while (($object = readdir($dh)) !== false) { if ($object == "." || $object == "..") { continue; } if (!self::rrmdir($path . "/" . $object)) { closedir($dh); return false; } } closedir($dh); return @rmdir($path); } else { if (is_writable($path)) { return @unlink($path); } else { return false; } } } public static function setSafePath($path): string { return str_replace("\\", "/", $path); } public static function sanitizeNSCharsNewline($string): string { return (string) preg_replace( '/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F\r\n]/u', '', (string) $string ); } public static function classExists($className, $autoload = true) { if (function_exists("ini_get")) { $disabled = explode(',', ini_get('disable_classes')); return !in_array($className, $disabled); } if (!class_exists($className, $autoload)) { return false; } return true; } public static function readOverwriteData(string $rootPath, string $packageHash): array { $result = []; $phpOverwritePath = $rootPath . '/duplicator_params_overwrite.php'; if (is_readable($phpOverwritePath)) { $json = null; include($phpOverwritePath); if (is_string($json) && strlen($json) > 0) { $data = json_decode($json, true); if (is_array($data)) { $result = array_merge($result, $data); } } } $jsonOverwritePath = $rootPath . '/duplicator_params_overwrite_' . $packageHash . '.json'; if (is_readable($jsonOverwritePath)) { $json = file_get_contents($jsonOverwritePath); if ($json !== false) { $data = json_decode($json, true); if (is_array($data)) { $result = array_merge($result, $data); } } } return $result; } public static function copyDirectory(string $source, string $destination): bool { if (!is_dir($source)) { return false; } if (!self::mkdir($destination, 0755, true)) { return false; } $sourceLen = strlen($source); $iterator = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($source, \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::SELF_FIRST ); foreach ($iterator as $item) { $relativePath = substr($item->getPathname(), $sourceLen); $targetPath = $destination . $relativePath; if ($item->isDir()) { if (!self::mkdir($targetPath, 0755, true)) { self::rrmdir($destination); return false; } } elseif (!@copy($item->getPathname(), $targetPath)) { self::rrmdir($destination); return false; } } return true; } } } namespace Duplicator\Installer\Bootstrap { use Duplicator\Libs\DupArchive\DupArchive; class BootstrapView { const VIEW_ERROR = 'error'; const VIEW_REDIRECT = 'redirect'; const VIEW_PASSWORD = 'pwd'; protected $boot; public function __construct() { $this->boot = BootstrapRunner::getInstance(); } public function redirectToInsaller(): void { $this->renderHeader(); ?>
Initializing Installer. Please wait...
boot->getRedirectForm(); $this->renderFooter(); } public function renderPassword(): void { $this->renderHeader(); $errorMsg = $this->boot->getErrorMessage(); if (strlen($errorMsg) > 0) { $this->renderTopMessages($errorMsg); } ?>

Password Required
This archive was created with an encryption enabled password. Please provide the password to extract the archive file.
Lost passwords for encrypted archives cannot be recovered by support. If the password was lost then a new archive will need to be created.
renderFooter(); } protected function renderTopMessages($message) { ?>
renderExclamationCircle(); ?>
renderHeader(); ?>

Setup Notice:

An error has occurred. In order to load the full installer please resolve the issue below.
boot->getErrorMessage(); ?>


Server Settings:

boot->isZip()) { ?>
ZipArchive: Enabled' : 'Disabled'; ?>
ShellExec Unzip: Enabled' : 'Disabled'; ?>
PHP OpenSSL Module: Enabled' : 'Disabled'; ?>
Extraction Path: boot->targetRoot; ?>
Installer Path: boot->targetDupInstFolder; ?>
Archive Size: Expected Size: boot->archiveExpectedSize); ?>   Actual Size: boot->archiveActualSize); ?>
Boot Log dup-installer-bootlog__[HASH].txt


Please Note: ZipArchive or ShellExec Unzip will need to be enabled for the installer to run automatically otherwise a manual extraction will need to be performed. In order to run the installer manually follow the instructions to manually extract before running the installer.
renderFooter(); } protected function renderHeader() { ?> Duplicator Installer renderCSS(); ?>
renderBoltFont(); ?> Duplicator Installer
version: boot->getVersion(); ?>
' . htmlspecialchars($log_message) . ''); case E_NOTICE: case E_WARNING: default: $log_message = self::getMessage($errno, $errstr, $errfile, $errline); call_user_func(self::$logCallback, $log_message); break; } return true; } private static function getMessage($errno, $errstr, $errfile, $errline): string { $result = '[PHP ERR]'; switch ($errno) { case E_ERROR: $result .= '[FATAL]'; break; case E_WARNING: $result .= '[WARN]'; break; case E_NOTICE: $result .= '[NOTICE]'; break; default: $result .= '[ISSUE]'; break; } $result .= ' MSG:'; $result .= $errstr; return $result . (' [CODE:' . $errno . '|FILE:' . $errfile . '|LINE:' . $errline . ']'); } public static function shutdown(): void { if (($error = error_get_last())) { LogHandler::error($error['type'], $error['message'], $error['file'], $error['line']); } } } } namespace Duplicator\Installer\Cli { final class CliInstallation { public array $params; public bool $acceptWarnings; public bool $yes; public string $url; public bool $hasUrl; public ?string $info; public function __construct(array $params, bool $acceptWarnings, bool $yes, string $url, bool $hasUrl, ?string $info) { $this->params = $params; $this->acceptWarnings = $acceptWarnings; $this->yes = $yes; $this->url = $url; $this->hasUrl = $hasUrl; $this->info = $info; } } } namespace Duplicator\Installer\Cli { use Exception; class CliEnvironment { const EXIT_OK = 0; const EXIT_ERROR = 1; const EXIT_USAGE = 2; const PARAM_OPTIONS = [ 'url' => 'url_new', 'dbaction' => 'dbaction', 'dbhost' => 'dbhost', 'dbname' => 'dbname', 'dbuser' => 'dbuser', 'dbpass' => 'dbpass', ]; const VALUE_OPTIONS = [ 'params', 'archive-path', 'archive-password', 'format', ]; const FLAG_OPTIONS = [ 'accept-warnings', 'yes', 'ignore-owner', 'info', 'help', ]; const STYLES = [ 'bold' => '1', 'red' => '1;31', 'green' => '1;32', 'yellow' => '1;33', ]; const MIN_HIDDEN_SECRET_LEN = 4; const INFO_FORMATS = [ 'text', 'json', ]; private static ?CliInstallation $installation = null; private static ?string $archiveLocation = null; public static function parseOptions(array $argv): array { $options = array_fill_keys(array_merge(array_keys(self::PARAM_OPTIONS), self::VALUE_OPTIONS), null); $options = array_merge($options, array_fill_keys(self::FLAG_OPTIONS, false)); foreach (array_slice($argv, 1) as $arg) { if (strpos($arg, '--') !== 0) { throw new Exception('Unexpected argument ' . $arg); } $parts = explode('=', substr($arg, 2), 2); $name = $parts[0]; $value = $parts[1] ?? null; if (in_array($name, self::FLAG_OPTIONS, true)) { if ($value !== null) { throw new Exception('--' . $name . ' takes no value'); } $options[$name] = true; } elseif (isset(self::PARAM_OPTIONS[$name]) || in_array($name, self::VALUE_OPTIONS, true)) { if ($value === null || (strlen($value) === 0 && $name !== 'dbpass')) { throw new Exception('--' . $name . ' needs a value'); } $options[$name] = $value; } else { throw new Exception('Unknown option --' . $name); } } return $options; } public static function getInstallerParams(array $options): array { $params = []; if ($options['params'] !== null) { if (!is_readable($options['params'])) { throw new Exception('can\'t read ' . $options['params'] . '.'); } $params = json_decode((string) file_get_contents($options['params']), true); if (!is_array($params)) { throw new Exception($options['params'] . ' is not a JSON object.'); } } foreach (self::PARAM_OPTIONS as $option => $key) { if ($options[$option] !== null) { $params[$key] = (isset($params[$key]) && is_array($params[$key]) ? $params[$key] : []); $params[$key]['value'] = $options[$option]; } } return $params; } public static function setArchiveLocation(?string $location): void { self::$archiveLocation = $location; } public static function getArchiveLocation(): ?string { return self::$archiveLocation; } public static function startInstallation(CliInstallation $installation): void { self::$installation = $installation; } public static function getInstallation(): ?CliInstallation { return self::$installation; } public static function setServerVars(string $siteUrl, string $scriptPath): void { $vars = self::getServerVars($siteUrl, $scriptPath); if (!isset($vars['HTTPS'])) { unset($_SERVER['HTTPS']); } $_SERVER = array_merge($_SERVER, $vars); } public static function getServerVars(string $siteUrl, string $scriptPath): array { $parts = parse_url($siteUrl); if (!is_array($parts) || !isset($parts['host']) || !in_array($parts['scheme'] ?? '', ['http', 'https'], true)) { throw new Exception('The URL ' . $siteUrl . ' is not a valid http or https URL'); } $isHttps = ($parts['scheme'] === 'https'); $port = (int) ($parts['port'] ?? ($isHttps ? 443 : 80)); $script = rtrim($parts['path'] ?? '', '/') . '/' . ltrim($scriptPath, '/'); $vars = [ 'HTTP_HOST' => $parts['host'] . (isset($parts['port']) ? ':' . $parts['port'] : ''), 'SERVER_NAME' => $parts['host'], 'SERVER_PORT' => (string) $port, 'REQUEST_METHOD' => 'GET', 'REQUEST_URI' => $script, 'SCRIPT_NAME' => $script, 'PHP_SELF' => $script, 'QUERY_STRING' => '', 'REMOTE_ADDR' => '127.0.0.1', 'SERVER_SOFTWARE' => 'cli', 'HTTP_USER_AGENT' => 'Duplicator installer CLI', ]; if ($isHttps) { $vars['HTTPS'] = 'on'; } return $vars; } public static function getOwnerError(string $folder): ?string { if (!function_exists('posix_geteuid') || ($owner = @fileowner($folder)) === false) { return null; } $user = posix_geteuid(); if ($user === $owner) { return null; } $userName = self::userName($user); $ownerName = self::userName($owner); return 'run as ' . $ownerName . ', the owner of ' . $folder . ' (now ' . $userName . '), or pass --ignore-owner.'; } private static function userName(int $uid): string { $info = (function_exists('posix_getpwuid') ? posix_getpwuid($uid) : false); return (is_array($info) ? $info['name'] : 'user ' . $uid); } public static function isInteractive(): bool { return function_exists('stream_isatty') && @stream_isatty(STDIN); } public static function ask(string $question, string $default = '', bool $hidden = false): string { $shownDefault = ($hidden || strlen($default) === 0 ? '' : ' [' . $default . ']'); fwrite(STDOUT, $question . $shownDefault . ': '); $echoOff = ($hidden && function_exists('shell_exec')); if ($echoOff) { shell_exec('stty -echo 2>/dev/null'); } $line = fgets(STDIN); if ($echoOff) { shell_exec('stty echo 2>/dev/null'); fwrite(STDOUT, "\n"); } if ($line === false) { throw new Exception('no answer.'); } $line = rtrim($line, "\r\n"); return (strlen($line) > 0 ? $line : $default); } public static function confirm(string $question): bool { return in_array(strtolower(trim(self::ask($question . ' [y/N]'))), ['y', 'yes'], true); } public static function out(string $message): void { fwrite(STDOUT, $message . "\n"); fflush(STDOUT); } public static function err(string $message): void { fwrite(STDERR, $message . "\n"); } public static function error(string $message): void { self::err(self::style('Error:', 'red', STDERR) . ' ' . $message); } public static function style(string $text, string $style, $stream = STDOUT): string { if (!isset(self::STYLES[$style]) || getenv('NO_COLOR') !== false || !function_exists('stream_isatty') || !@stream_isatty($stream)) { return $text; } return "\033[" . self::STYLES[$style] . 'm' . $text . "\033[0m"; } public static function toText(string $html): string { $html = (string) preg_replace('#<(style|script)\b[^>]*>.*?#is', '', $html); $html = (string) preg_replace('/\s+/', ' ', $html); $html = (string) preg_replace('#||(?=<(?:ul|table)\b)#i', "\n", $html); $html = (string) preg_replace('#]*>#i', "\n- ", $html); $html = (string) preg_replace('##i', ' ', $html); $text = str_replace("\u{00A0}", ' ', html_entity_decode(strip_tags($html), ENT_QUOTES, 'UTF-8')); $text = (string) preg_replace('/^ +| +$/m', '', (string) preg_replace('/ +/', ' ', $text)); return trim((string) preg_replace("/\n+/", "\n", $text)); } public static function hideSecrets(string $text, array $secrets): string { foreach ($secrets as $secret) { if (is_array($secret)) { $text = self::hideSecrets($text, array_values($secret)); continue; } if (strlen((string) $secret) >= self::MIN_HIDDEN_SECRET_LEN) { $text = str_replace($secret, '*****', $text); } } return $text; } } } namespace Duplicator\Installer\Cli { use Duplicator\Installer\Bootstrap\BootstrapRunner; use Duplicator\Installer\Bootstrap\BootstrapUtils; use Duplicator\Installer\Bootstrap\BootstrapView; use Duplicator\Installer\Bootstrap\LogHandler; use Exception; class CliBootstrap { const INFO_URL = 'http://localhost'; const BACKUPS_FOLDER_NAMES = [ 'duplicator-backups', 'backups-dup-pro', 'backups-dup-lite', ]; public static function run(array $argv, string $packageHash): int { if (count($argv) <= 1) { CliEnvironment::out(self::usage()); return CliEnvironment::EXIT_OK; } try { $options = CliEnvironment::parseOptions($argv); if ($options['format'] !== null && !in_array($options['format'], CliEnvironment::INFO_FORMATS, true)) { throw new Exception('--format takes ' . implode(' or ', CliEnvironment::INFO_FORMATS)); } } catch (Exception $e) { CliEnvironment::error($e->getMessage()); CliEnvironment::err(self::usage()); return CliEnvironment::EXIT_USAGE; } if ($options['help']) { CliEnvironment::out(self::usage()); return CliEnvironment::EXIT_OK; } if (($locationError = self::getLocationError(__FILE__, $packageHash)) !== null) { CliEnvironment::error($locationError); return CliEnvironment::EXIT_ERROR; } if (!$options['ignore-owner'] && ($ownerError = CliEnvironment::getOwnerError(dirname(__FILE__))) !== null) { CliEnvironment::error($ownerError); return CliEnvironment::EXIT_ERROR; } try { $params = CliEnvironment::getInstallerParams($options); $info = ($options['info'] ? ($options['format'] ?? 'text') : null); [ $url, $hasUrl, ] = self::resolveUrl($params, $info !== null, CliEnvironment::isInteractive()); if ($hasUrl) { $params['url_new']['value'] = $url; } CliEnvironment::setServerVars($url, basename(__FILE__)); CliEnvironment::setArchiveLocation($options['archive-path']); $boot = BootstrapRunner::getInstance(); LogHandler::initErrorHandler([$boot, 'log']); if ($info === null) { CliEnvironment::out(CliEnvironment::style('Extracting the installer...', 'bold')); } $view = self::runBootstrap($boot, $options['archive-password']); } catch (Exception $e) { CliEnvironment::error($e->getMessage()); return CliEnvironment::EXIT_ERROR; } if ($view !== BootstrapView::VIEW_REDIRECT) { CliEnvironment::error(CliEnvironment::toText($boot->getErrorMessage())); CliEnvironment::err('Details are in ' . $boot->getBootLogFilePath()); return CliEnvironment::EXIT_ERROR; } CliEnvironment::startInstallation( new CliInstallation($params, (bool) $options['accept-warnings'], (bool) $options['yes'], $url, $hasUrl, $info) ); require $boot->targetDupInst . '/main.installer.php'; CliEnvironment::error('the main installer did not run.'); return CliEnvironment::EXIT_ERROR; } public static function getLocationError(string $installerFile, string $packageHash): ?string { $copyHint = 'copy the installer and the archive to the folder of the destination site and run installer.php there.'; if (strtolower(substr($installerFile, -4)) !== '.php') { return 'the installer file name must end with .php: ' . $copyHint; } $installerFolder = dirname($installerFile); $folders = explode('/', str_replace('\\', '/', $installerFolder)); if ( array_intersect($folders, self::BACKUPS_FOLDER_NAMES) !== [] && BootstrapUtils::readOverwriteData($installerFolder, $packageHash) === [] ) { return 'the installer is inside the Backups folder of a site: ' . $copyHint; } return null; } public static function resolveUrl(array $params, bool $info, bool $interactive): array { $url = (string) ($params['url_new']['value'] ?? ''); if (strlen($url) > 0) { return [ $url, true, ]; } if ($info) { return [ self::INFO_URL, false, ]; } if (!$interactive) { throw new Exception('--url is required.'); } while (strlen($url = trim(CliEnvironment::ask('Site URL'))) === 0) { continue; } return [ $url, true, ]; } private static function runBootstrap(BootstrapRunner $boot, ?string $password): string { if ($password !== null) { $_REQUEST[BootstrapRunner::NAME_PWD] = $password; } $view = $boot->run(); for ($attempt = 0; $view === BootstrapView::VIEW_PASSWORD && $attempt < 3 && CliEnvironment::isInteractive(); $attempt++) { if ($attempt > 0 || $password !== null) { CliEnvironment::error('invalid archive password.'); } $password = CliEnvironment::ask('Archive password', '', true); $_REQUEST[BootstrapRunner::NAME_PWD] = $password; $view = $boot->run(); } if ($view === BootstrapView::VIEW_PASSWORD) { throw new Exception( $password === null ? 'the archive is encrypted, pass its password with --archive-password.' : 'invalid archive password.' ); } return $view; } private static function usage(): string { return implode("\n", [ 'Usage: php installer.php [options]', '', 'Installs the Backup whose archive is in the same folder. On a terminal it asks the missing values and a', 'confirmation; otherwise it never asks and fails on a missing value.', 'Run php installer.php --info first: it describes the Backup and the parameters it can be installed with.', '', ' --url= URL the site answers on (url_new)', ' --dbaction= What to do with the existing database, such as empty or rename (dbaction)', ' --dbhost= Database host, with :port when needed (dbhost)', ' --dbname= Database name (dbname)', ' --dbuser= Database user (dbuser)', ' --dbpass= Database password (dbpass)', ' --params= JSON file of installer parameters, described below; only read; the options', ' above take precedence over it', ' --archive-path= Folder of the archive, or the archive itself; default: the installer folder', ' --archive-password= Password of an encrypted archive', ' --accept-warnings Install even when the validation reports warnings that need to be accepted', ' --yes Install without asking for confirmation; required without a terminal when', ' the installation overwrites an existing site or database', ' --ignore-owner Run even when the user is not the owner of the installer folder; by default the', ' command stops, as the site could not write the files it installs', ' --info Describe the Backup and the parameters meant for the command line, with their', ' values and defaults for this Backup, then exit without installing; with --params,', ' it also checks the file', ' --format= Output of --info: text, the default, or json', ' --help Show this help', '', 'The --params file is a JSON object of installer parameters by key, each with its value, for example:', ' {"dbaction": {"value": "empty"}, "blogname": {"value": "My site"}}', '', 'Command line arguments are visible to the other users of the server: pass passwords in the --params file.', '', 'Exit status: 0 installed or described, 1 failed, 2 invalid usage.', ]); } } } namespace Duplicator\Installer\Utils { use Exception; class SecureCsrf { const PREFIX = '_DUPX_CSRF'; private static $packagHash = ''; private static $mainFolder = ''; private static $CSRFVars; public static function init($mainFolderm, $packageHash): void { self::$mainFolder = $mainFolderm; self::$packagHash = $packageHash; self::$CSRFVars = null; } public static function setKeyVal($key, $val): void { self::getCSRFVars(); self::$CSRFVars[$key] = $val; self::saveCSRFVars(); } public static function removeKeyVal($key): void { self::getCSRFVars(); if (isset(self::$CSRFVars[$key])) { unset(self::$CSRFVars[$key]); self::saveCSRFVars(); } } public static function getVal($key) { self::getCSRFVars(); if (isset(self::$CSRFVars[$key])) { return self::$CSRFVars[$key]; } else { return false; } } public static function generate($form = null) { $keyName = self::getKeyName($form); $existingToken = self::getVal($keyName); $token = false !== $existingToken ? $existingToken : self::token() . self::fingerprint(); self::setKeyVal($keyName, $token); return $token; } public static function check($token, $form = null) { if (empty($form)) { return false; } $keyName = self::getKeyName($form); self::getCSRFVars(); return (isset(self::$CSRFVars[$keyName]) && self::$CSRFVars[$keyName] == $token); } protected static function token(): string { $microtime = (int) (microtime(true) * 10000); mt_srand($microtime); $charid = strtoupper(md5(uniqid((string) random_int(0, mt_getrandmax()), true))); return substr($charid, 0, 8) . substr($charid, 8, 4) . substr($charid, 12, 4) . substr($charid, 16, 4) . substr($charid, 20, 12); } protected static function fingerprint(): string { return strtoupper(md5(implode('|', [$_SERVER['REMOTE_ADDR'], $_SERVER['HTTP_USER_AGENT']]))); } private static function getKeyName($form): string { return self::PREFIX . '_' . $form; } private static function getPackageHash() { if (strlen(self::$packagHash) == 0) { throw new Exception('Not init CSFR CLASS'); } return self::$packagHash; } public static function getFilePath(): string { if (strlen(self::$mainFolder) == 0) { throw new Exception('Not init CSFR CLASS'); } $dupInstallerfolderPath = self::$mainFolder; $packageHash = self::getPackageHash(); $fileName = 'dup_descriptors_' . $packageHash . '/installer-csrf.txt'; return $dupInstallerfolderPath . '/' . $fileName; } private static function getCSRFVars() { if (is_null(self::$CSRFVars)) { $filePath = self::getFilePath(); if (file_exists($filePath)) { $contents = file_get_contents($filePath); if (empty($contents)) { self::$CSRFVars = []; } else { $CSRFobjs = json_decode($contents); foreach ($CSRFobjs as $key => $value) { self::$CSRFVars[$key] = $value; } } } else { self::$CSRFVars = []; } } return self::$CSRFVars; } private static function saveCSRFVars(): void { $contents = json_encode(self::$CSRFVars); $filePath = self::getFilePath(); file_put_contents($filePath, $contents); } } } namespace Duplicator\Libs\DupArchive { use Duplicator\Libs\DupArchive\Headers\DupArchiveDirectoryHeader; use Duplicator\Libs\DupArchive\Headers\DupArchiveFileHeader; use Duplicator\Libs\DupArchive\Headers\DupArchiveGlobHeader; use Duplicator\Libs\DupArchive\Headers\DupArchiveHeader; use Exception; use Throwable; class DupArchive { const EXCEPTION_CODE_FILE_DONT_EXISTS = 10; const EXCEPTION_CODE_OPEN_ERROR = 11; const EXCEPTION_CODE_INVALID_PASSWORD = 12; const EXCEPTION_CODE_INVALID_MARKER = 13; const EXCEPTION_CODE_INVALID_PARAM = 14; const EXCEPTION_CODE_ADD_ERROR = 15; const EXCEPTION_CODE_EXTRACT_ERROR = 16; const EXCEPTION_CODE_VALIDATION_ERROR = 17; const EXCEPTION_CODE_ENCRYPTION_UNAVAILABLE = 18; const DUPARCHIVE_VERSION = '5.0.1'; const INDEX_FILE_NAME = '__dup__archive__index.json'; const INDEX_FILE_SIZE = 2000; // reserver 2K const EXTRA_FILES_POS_KEY = 'extraPos'; const HEADER_TYPE_NONE = 0; const HEADER_TYPE_FILE = 1; const HEADER_TYPE_DIR = 2; const HEADER_TYPE_GLOB = 3; const FLAG_COMPRESS = 1; //bitmask const FLAG_CRYPT = 2; //bitmask const HASH_ALGO = 'crc32b'; const PWD_ALGO = '$6$rounds=50000$'; // SHA-512 50000 times with salt const PWD_SALT_CHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789./'; // crypt() salt alphabet, system libcrypt rejects others const CRYPT_ALGO = 'AES-256-CBC'; protected static function getNextHeaderType($archiveHandle): int { $retVal = self::HEADER_TYPE_NONE; $marker = fgets($archiveHandle, 4); if (feof($archiveHandle) === false) { switch ($marker) { case '': $retVal = self::HEADER_TYPE_DIR; break; case '': $retVal = self::HEADER_TYPE_FILE; break; case '': $retVal = self::HEADER_TYPE_GLOB; break; default: throw new Exception("Invalid header marker {$marker}. Location:" . ftell($archiveHandle), self::EXCEPTION_CODE_INVALID_MARKER); } } return $retVal; } public static function isEncrypted($path): bool { return !self::checkPassword($path, ''); } public static function checkPassword($path, $password): bool { try { $header = self::getArchiveHeader($path, $password); } catch (Exception $e) { if ($e->getCode() == self::EXCEPTION_CODE_INVALID_PASSWORD) { return false; } else { throw $e; } } return true; } public static function getArchiveHeader($path, $password) { try { $archiveHandle = null; if (!file_exists($path)) { throw new Exception('Archive file don\'t exists', self::EXCEPTION_CODE_FILE_DONT_EXISTS); } if (($archiveHandle = fopen($path, 'r')) == false) { throw new Exception('Can\'t open archive file', self::EXCEPTION_CODE_OPEN_ERROR); } $result = (new DupArchiveHeader())->readFromArchive($archiveHandle, $password); } finally { if (is_resource($archiveHandle)) { fclose($archiveHandle); } } return $result; } public static function isEncryptionAvaliable() { static $isAvaliable = null; if ($isAvaliable === null) { $isAvaliable = ( function_exists('openssl_cipher_iv_length') && function_exists('openssl_encrypt') && function_exists('openssl_decrypt') ); } return $isAvaliable; } public static function getIndexData($archivePath, $password) { try { $indexContent = self::getSrcFile($archivePath, self::INDEX_FILE_NAME, $password, 0, 3000); if ($indexContent === false) { return false; } $indexData = json_decode(rtrim($indexContent, "\0"), true); if (!is_array($indexData)) { return false; } } catch (Throwable $e) { return false; } return $indexData; } public static function getExtraOffset($archivePath, $password) { if (($indexData = self::getIndexData($archivePath, $password)) === false) { return 0; } return ($indexData[self::EXTRA_FILES_POS_KEY] ?? 0); } public static function seachPathInArchive($archivePath, $relativePath, $password, $offset = 0, $sizeToSearch = 0) { try { $archiveHandle = null; if (($archiveHandle = fopen($archivePath, 'rb')) === false) { throw new Exception("Can’t open archive at $archivePath!", self::EXCEPTION_CODE_OPEN_ERROR); } $archiveHeader = (new DupArchiveHeader())->readFromArchive($archiveHandle, $password); $result = self::searchPath($archiveHandle, $archiveHeader, $relativePath, $offset, $sizeToSearch); } finally { if (is_resource($archiveHandle)) { fclose($archiveHandle); } } return $result; } public static function searchPath($archiveHandle, DupArchiveHeader $archiveHeader, $relativePath, $offset = 0, $sizeToSearch = 0) { if (!is_resource($archiveHandle)) { throw new Exception('Archive handle must be a resource', self::EXCEPTION_CODE_INVALID_PARAM); } if (fseek($archiveHandle, $offset, SEEK_SET) < 0) { return false; } if ($offset == 0) { $hd = (new DupArchiveHeader())->readFromArchive($archiveHandle, $archiveHeader->getPassword()); } $result = false; $position = ftell($archiveHandle); $continue = true; do { switch (($type = self::getNextHeaderType($archiveHandle))) { case self::HEADER_TYPE_FILE: $currentFileHeader = (new DupArchiveFileHeader($archiveHeader))->readFromArchive($archiveHandle, true, true); if ($currentFileHeader->relativePath == $relativePath) { $continue = false; $result = $position; } break; case self::HEADER_TYPE_DIR: $directoryHeader = (new DupArchiveDirectoryHeader($archiveHeader))->readFromArchive($archiveHandle, true); if ($directoryHeader->relativePath == $relativePath) { $continue = false; $result = $position; } break; case self::HEADER_TYPE_NONE: $continue = false; break; default: throw new Exception('Invali header type "' . $type . '"', self::EXCEPTION_CODE_INVALID_MARKER); } $position = ftell($archiveHandle); if ($sizeToSearch > 0 && ($position - $offset) >= $sizeToSearch) { break; } } while ($continue); if ($result !== false) { if (fseek($archiveHandle, $result, SEEK_SET) < 0) { return false; } } return $result; } public static function seachRegexInArchive( $archivePath, $pattern, $password, $offset = 0, $sizeToSearch = 0 ) { try { $archiveHandle = null; if (($archiveHandle = fopen($archivePath, 'rb')) === false) { throw new Exception("Can’t open archive at $archivePath!", self::EXCEPTION_CODE_OPEN_ERROR); } $archiveHeader = (new DupArchiveHeader())->readFromArchive($archiveHandle, $password); $result = self::searchRegex($archiveHandle, $archiveHeader, $pattern, $offset, $sizeToSearch); } finally { if (is_resource($archiveHandle)) { fclose($archiveHandle); } } return $result; } public static function searchRegex( $archiveHandle, DupArchiveHeader $archiveHeader, $pattern, $offset = 0, $sizeToSearch = 0 ) { if (!is_resource($archiveHandle)) { throw new Exception('Archive handle must be a resource', self::EXCEPTION_CODE_INVALID_PARAM); } if (fseek($archiveHandle, $offset, SEEK_SET) < 0) { return false; } if ($offset == 0) { $hd = (new DupArchiveHeader())->readFromArchive($archiveHandle, $archiveHeader->getPassword()); } $result = false; $position = ftell($archiveHandle); $continue = true; do { switch (($type = self::getNextHeaderType($archiveHandle))) { case self::HEADER_TYPE_FILE: $currentFileHeader = (new DupArchiveFileHeader($archiveHeader))->readFromArchive($archiveHandle, true, true); if (preg_match($pattern, $currentFileHeader->relativePath)) { $continue = false; $result = [ 'name' => $currentFileHeader->relativePath, 'position' => $position, ]; } break; case self::HEADER_TYPE_DIR: $directoryHeader = (new DupArchiveDirectoryHeader($archiveHeader))->readFromArchive($archiveHandle, true); if (preg_match($pattern, $directoryHeader->relativePath)) { $continue = false; $result = [ 'name' => $directoryHeader->relativePath, 'position' => $position, ]; } break; case self::HEADER_TYPE_NONE: $continue = false; break; default: throw new Exception('Invali header type "' . $type . '"', self::EXCEPTION_CODE_INVALID_MARKER); } $position = ftell($archiveHandle); if ($sizeToSearch > 0 && ($position - $offset) >= $sizeToSearch) { break; } } while ($continue); if ($result !== false) { if (fseek($archiveHandle, $result['position'], SEEK_SET) < 0) { return false; } } return $result; } public static function getSrcFile($archivePath, $relativePath, $password, $offset = 0, $sizeToSearch = 0) { try { $archiveHandle = null; if (($archiveHandle = fopen($archivePath, 'rb')) === false) { throw new Exception("Can’t open archive at $archivePath!", self::EXCEPTION_CODE_OPEN_ERROR); } $archiveHeader = (new DupArchiveHeader())->readFromArchive($archiveHandle, $password); if (self::searchPath($archiveHandle, $archiveHeader, $relativePath, $offset, $sizeToSearch) === false) { return false; } if (self::getNextHeaderType($archiveHandle) != self::HEADER_TYPE_FILE) { return false; } $header = (new DupArchiveFileHeader($archiveHeader))->readFromArchive($archiveHandle, false, true); $result = self::getSrcFromHeader($archiveHandle, $header); } finally { if (is_resource($archiveHandle)) { fclose($archiveHandle); } } return $result; } protected static function getSrcFromHeader($archiveHandle, DupArchiveFileHeader $fileHeader): string { if ($fileHeader->fileSize == 0) { return ''; } $dataSize = 0; $result = ''; $globHeader = new DupArchiveGlobHeader($fileHeader); do { $globHeader->readFromArchive($archiveHandle); $result .= $globHeader->readContent($archiveHandle); $dataSize += $globHeader->originalSize; } while ($dataSize < $fileHeader->fileSize); return $result; } protected static function skipFileInArchive($archiveHandle, DupArchiveFileHeader $fileHeader) { if ($fileHeader->fileSize == 0) { return; } $dataSize = 0; $globHeader = new DupArchiveGlobHeader($fileHeader); do { $globHeader->readFromArchive($archiveHandle, true); $dataSize += $globHeader->originalSize; } while ($dataSize < $fileHeader->fileSize); } protected static function skipToNextHeader($archiveHandle, DupArchiveHeader $archiveHeader) { $headerType = self::getNextHeaderType($archiveHandle); switch ($headerType) { case self::HEADER_TYPE_FILE: $fileHeader = (new DupArchiveFileHeader($archiveHeader))->readFromArchive($archiveHandle, false, true); self::skipFileInArchive($archiveHandle, $fileHeader); break; case self::HEADER_TYPE_DIR: $directoryHeader = (new DupArchiveDirectoryHeader($archiveHeader))->readFromArchive($archiveHandle, true); break; case self::HEADER_TYPE_NONE: default: break; } } public static function generateSalt($length): string { $maxRand = (strlen(self::PWD_SALT_CHARS) - 1); $password = ''; for ($i = 0; $i < $length; $i++) { $cIndex = random_int(0, $maxRand); $password .= substr(self::PWD_SALT_CHARS, $cIndex, 1); } return $password; } public static function encrypt($content, $key, $hashKey = false) { static $ivLen = null; if ($ivLen === null) { if (!self::isEncryptionAvaliable()) { throw new Exception('Encryption is unavailable', self::EXCEPTION_CODE_OPEN_ERROR); } $ivLen = openssl_cipher_iv_length(DupArchive::CRYPT_ALGO); } $iv = openssl_random_pseudo_bytes($ivLen); if ($hashKey) { $key = hash('sha256', $key); } if (($result = openssl_encrypt($content, DupArchive::CRYPT_ALGO, $key, OPENSSL_RAW_DATA, $iv)) === false) { return false; } return $iv . $result; } public static function decrypt($content, $key, $hashKey = false) { static $ivLen = null; if ($ivLen === null) { if (!self::isEncryptionAvaliable()) { throw new Exception('Encryption is unavailable', self::EXCEPTION_CODE_OPEN_ERROR); } $ivLen = openssl_cipher_iv_length(DupArchive::CRYPT_ALGO); } $iv = substr($content, 0, $ivLen); if ($hashKey) { $key = hash('sha256', $key); } return openssl_decrypt(substr($content, $ivLen), DupArchive::CRYPT_ALGO, $key, OPENSSL_RAW_DATA, $iv); } } } namespace Duplicator\Libs\DupArchive { use Duplicator\Libs\DupArchive\Headers\DupArchiveDirectoryHeader; use Duplicator\Libs\DupArchive\Headers\DupArchiveFileHeader; use Duplicator\Libs\DupArchive\Headers\DupArchiveGlobHeader; use Duplicator\Libs\DupArchive\Headers\DupArchiveHeader; use Duplicator\Libs\DupArchive\Info\DupArchiveExpanderInfo; use Exception; class DupArchiveExpandBasicEngine extends DupArchive { protected static $logCallback; protected static $chmodCallback; protected static $mkdirCallback; public static function setCallbacks($log, $chmod, $mkdir): void { self::$logCallback = (is_callable($log) ? $log : null); self::$chmodCallback = (is_callable($chmod) ? $chmod : null); self::$mkdirCallback = (is_callable($mkdir) ? $mkdir : null); } public static function log($s, $flush = false): void { if (self::$logCallback == null) { return; } call_user_func(self::$logCallback, "MINI EXPAND:$s", $flush); } public static function expandDirectory($archivePath, $relativePath, $destPath, $password, $ignoreErrors = false, $offset = 0): void { self::expandItems($archivePath, $relativePath, $destPath, $password, $ignoreErrors, $offset); } private static function expandItems($archivePath, $inclusionFilter, $destDirectory, $password, $ignoreErrors = false, $offset = 0): void { $archiveHandle = fopen($archivePath, 'rb'); if ($archiveHandle === false) { throw new Exception("Can’t open archive at $archivePath!", self::EXCEPTION_CODE_OPEN_ERROR); } $archiveHeader = (new DupArchiveHeader())->readFromArchive($archiveHandle, $password); $writeInfo = new DupArchiveExpanderInfo(); $writeInfo->destDirectory = $destDirectory; if ($offset > 0) { fseek($archiveHandle, $offset); } $moreToRead = true; while ($moreToRead) { if ($writeInfo->currentFileHeader != null) { try { if (self::passesInclusionFilter($inclusionFilter, $writeInfo->currentFileHeader->relativePath)) { self::writeToFile($archiveHandle, $writeInfo); $writeInfo->fileWriteCount++; } elseif ($writeInfo->currentFileHeader->fileSize > 0) { self::skipFileInArchive($archiveHandle, $writeInfo->currentFileHeader); } $writeInfo->currentFileHeader = null; } catch (Exception $ex) { if (!$ignoreErrors) { throw $ex; } } } else { $headerType = self::getNextHeaderType($archiveHandle); switch ($headerType) { case self::HEADER_TYPE_FILE: $writeInfo->currentFileHeader = (new DupArchiveFileHeader($archiveHeader))->readFromArchive($archiveHandle, false, true); break; case self::HEADER_TYPE_DIR: $directoryHeader = (new DupArchiveDirectoryHeader($archiveHeader))->readFromArchive($archiveHandle, true); if (self::passesInclusionFilter($inclusionFilter, $directoryHeader->relativePath)) { $directory = "{$writeInfo->destDirectory}/{$directoryHeader->relativePath}"; if (is_callable(self::$mkdirCallback)) { call_user_func(self::$mkdirCallback, $directory, 'u+rwx', true); } else { mkdir($directory, 0755, true); } $writeInfo->directoryWriteCount++; } else { } break; case self::HEADER_TYPE_NONE: $moreToRead = false; } } } fclose($archiveHandle); } private static function writeToFile($archiveHandle, DupArchiveExpanderInfo $writeInfo): void { $destFilePath = $writeInfo->getCurrentDestFilePath(); if ($writeInfo->currentFileHeader->fileSize > 0) { $parentDir = dirname($destFilePath); if (!file_exists($parentDir)) { if (is_callable(self::$mkdirCallback)) { $res = call_user_func(self::$mkdirCallback, $parentDir, 'u+rwx', true); } else { $res = mkdir($parentDir, 0755, true); } if (!$res) { throw new Exception("Couldn't create {$parentDir}", self::EXCEPTION_CODE_EXTRACT_ERROR); } } $destFileHandle = fopen($destFilePath, 'wb+'); if ($destFileHandle === false) { throw new Exception("Couldn't open {$destFilePath} for writing.", self::EXCEPTION_CODE_OPEN_ERROR); } do { self::appendGlobToFile($archiveHandle, $destFileHandle, $writeInfo); $currentFileOffset = ftell($destFileHandle); $moreGlobstoProcess = $currentFileOffset < $writeInfo->currentFileHeader->fileSize; } while ($moreGlobstoProcess); fclose($destFileHandle); if (is_callable(self::$chmodCallback)) { call_user_func(self::$chmodCallback, $destFilePath, 'u+rw'); } else { chmod($destFilePath, 0644); } if ($writeInfo->currentFileHeader->validateFile($destFilePath) == false) { throw new Exception("HASH Validation fails for {$destFilePath}", self::EXCEPTION_CODE_VALIDATION_ERROR); } } else { if (touch($destFilePath) === false) { throw new Exception("Couldn't create $destFilePath", self::EXCEPTION_CODE_EXTRACT_ERROR); } if (is_callable(self::$chmodCallback)) { call_user_func(self::$chmodCallback, $destFilePath, 'u+rw'); } else { chmod($destFilePath, 0644); } } } private static function appendGlobToFile($archiveHandle, $destFileHandle, DupArchiveExpanderInfo $writeInfo): void { $globHeader = (new DupArchiveGlobHeader($writeInfo->currentFileHeader))->readFromArchive($archiveHandle); $globContent = $globHeader->readContent($archiveHandle); if (fwrite($destFileHandle, $globContent) !== strlen($globContent)) { throw new Exception("Unable to write all bytes of data glob to storage.", self::EXCEPTION_CODE_EXTRACT_ERROR); } } private static function passesInclusionFilter($filter, $candidate): bool { return (substr($candidate, 0, strlen($filter)) == $filter); } } } namespace Duplicator\Libs\DupArchive\Headers { use Duplicator\Libs\DupArchive\DupArchive; use Exception; abstract class AbstractDupArchiveHeader { const MAX_FILED_LEN = 1024; abstract public function readFromArchive($archiveHandle); abstract public function writeToArchive($archiveHandle); public static function getHeaderField($archiveHandle, $ename) { $expectedStart = '<' . $ename . '>'; $expectedEnd = ''; $startingElement = fread($archiveHandle, strlen($expectedStart)); if ($startingElement !== $expectedStart) { throw new Exception( "Invalid starting element. Was expecting {$expectedStart} but got {$startingElement}", DupArchive::EXCEPTION_CODE_INVALID_MARKER ); } $headerString = stream_get_line($archiveHandle, self::MAX_FILED_LEN, $expectedEnd); if ($headerString === false) { throw new Exception('Error reading line.', DupArchive::EXCEPTION_CODE_EXTRACT_ERROR); } return $headerString; } } } namespace Duplicator\Libs\DupArchive\Headers { use Duplicator\Libs\DupArchive\DupArchive; use Duplicator\Libs\Snap\SnapIO; use Exception; class DupArchiveDirectoryHeader extends AbstractDupArchiveHeader { public $mtime = 0; public $permissions = ''; public $relativePathLength = 1; public $relativePath = ''; public function __construct(DupArchiveHeader $archiveHeader) // @phpstan-ignore-line { } public function readFromArchive($archiveHandle, $skipStartElement = false) { if (!$skipStartElement) { $startElement = fread($archiveHandle, 3); if ($startElement === false) { if (feof($archiveHandle)) { return false; } else { throw new Exception('Error reading directory header', DupArchive::EXCEPTION_CODE_INVALID_MARKER); } } if ($startElement != '') { throw new Exception( "Invalid directory header marker found [{$startElement}] : location " . ftell($archiveHandle), DupArchive::EXCEPTION_CODE_EXTRACT_ERROR ); } } $this->mtime = (int) self::getHeaderField($archiveHandle, 'MT'); $this->permissions = self::getHeaderField($archiveHandle, 'P'); $length = self::getHeaderField($archiveHandle, 'RPL'); if (!is_numeric($length)) { throw new Exception('Header RPL must be numeric'); } $this->relativePathLength = (int) $length; fread($archiveHandle, 4); $this->relativePath = fread($archiveHandle, $this->relativePathLength); fread($archiveHandle, 9); return $this; } public function writeToArchive($archiveHandle): int { if ($this->relativePathLength == 0) { return 0; } $headerString = '' . $this->mtime . '

' . $this->permissions . '

' . $this->relativePathLength . '' . $this->relativePath . '
'; return SnapIO::fwrite( $archiveHandle, $headerString, 'Error writing directory header to archive.', DupArchive::EXCEPTION_CODE_ADD_ERROR ); } } } namespace Duplicator\Libs\DupArchive\Headers { use Duplicator\Libs\DupArchive\DupArchive; use Duplicator\Libs\Snap\SnapIO; use Exception; class DupArchiveFileHeader extends AbstractDupArchiveHeader { const MAX_SIZE_FOR_HASHING = 100 * MB_IN_BYTES; public $fileSize = 0; public $mtime = 0; public $permissions = ''; public $hash = ''; public $relativePathLength = 0; public $relativePath = ''; protected int $flags = 0; protected $version = ''; protected $password = ''; protected bool $applyExtraHash; public function __construct(DupArchiveHeader $archiveHeader) { $this->flags = $archiveHeader->getFlags(); $this->version = $archiveHeader->getVersion(); $this->password = $archiveHeader->getPassword(); $this->applyExtraHash = version_compare($this->version, '5.0.1', '>='); } public function getVersion() { return $this->version; } public function getFlags(): int { return $this->flags; } public function setFlags($flags): void { $this->flags = (int) $flags; } public function isCompressed(): bool { return (bool) ($this->flags & DupArchive::FLAG_COMPRESS); } public function isCrypt(): bool { return (bool) ($this->flags & DupArchive::FLAG_CRYPT); } public function getPassword() { return $this->password; } public function isApplyExtraHash(): bool { return $this->applyExtraHash; } public function createFromFile($filepath, $relativeFilePath) { if (!file_exists($filepath)) { throw new Exception("File does not exist: $filepath"); } $this->fileSize = SnapIO::filesize($filepath); $this->permissions = substr(sprintf('%o', fileperms($filepath)), -4); $this->mtime = SnapIO::filemtime($filepath); if ($this->fileSize > self::MAX_SIZE_FOR_HASHING) { $this->hash = "00000000000000000000000000000000"; } else { if (($this->hash = hash_file(DupArchive::HASH_ALGO, $filepath)) === false) { $this->hash = "00000000000000000000000000000000"; } } $this->relativePath = $relativeFilePath; $this->relativePathLength = strlen($this->relativePath); return $this; } public function createFromSrc($src, $relativeFilePath, $forceSize = 0) { $this->fileSize = strlen($src); $this->permissions = '0644'; $this->mtime = time(); $srcLen = strlen($src); if ($forceSize > 0 && $srcLen < $forceSize) { $charsToAdd = $forceSize - $srcLen; $src .= str_repeat("\0", $charsToAdd); } if ($this->fileSize > self::MAX_SIZE_FOR_HASHING) { $this->hash = "00000000000000000000000000000000"; } else { $this->hash = hash(DupArchive::HASH_ALGO, $src); } $this->relativePath = $relativeFilePath; $this->relativePathLength = strlen($this->relativePath); return $this; } public function validateFile($filePath) { if ($this->hash === '00000000000000000000000000000000') { return true; } $hash = hash_file(DupArchive::HASH_ALGO, $filePath); return ($hash === $this->hash); } public function writeToArchive($archiveHandle): int { $headerString = ''; $headerString .= '' . $this->fileSize . ''; $headerString .= '' . $this->mtime . ''; $headerString .= '

' . $this->permissions . '

'; $headerString .= '' . pack('v', $this->flags) . ''; $headerString .= '' . $this->hash . ''; $headerString .= '' . $this->relativePathLength . ''; $headerString .= '' . $this->relativePath . ''; $headerString .= '
'; return SnapIO::fwrite( $archiveHandle, $headerString, 'Error writing file header to archive.', DupArchive::EXCEPTION_CODE_EXTRACT_ERROR ); } public function readFromArchive($archiveHandle, $skipContents = false, $skipMarker = false) { if (!$skipMarker) { $marker = @fread($archiveHandle, 3); if ($marker === false) { if (feof($archiveHandle)) { return false; } else { throw new Exception('Error reading file header', DupArchive::EXCEPTION_CODE_EXTRACT_ERROR); } } if ($marker != '') { throw new Exception( "Invalid file header marker found [{$marker}] : location " . ftell($archiveHandle), DupArchive::EXCEPTION_CODE_INVALID_MARKER ); } } $this->fileSize = (int) self::getHeaderField($archiveHandle, 'FS'); $this->mtime = (int) self::getHeaderField($archiveHandle, 'MT'); $this->permissions = self::getHeaderField($archiveHandle, 'P'); if (version_compare($this->version, '5.0.0', '<')) { } else { $falgs = self::getHeaderField($archiveHandle, 'X'); $this->flags = unpack('vflags', $falgs)['flags']; } $this->hash = self::getHeaderField($archiveHandle, 'HA'); $this->relativePathLength = (int) self::getHeaderField($archiveHandle, 'RPL'); fread($archiveHandle, 4); $this->relativePath = fread($archiveHandle, $this->relativePathLength); fread($archiveHandle, 9); if ($skipContents && ($this->fileSize > 0)) { $dataSize = 0; $moreGlobs = true; $globHeader = new DupArchiveGlobHeader($this); while ($moreGlobs) { $globHeader->readFromArchive($archiveHandle, true); $dataSize += $globHeader->originalSize; $moreGlobs = ($dataSize < $this->fileSize); } } return $this; } } } namespace Duplicator\Libs\DupArchive\Headers { use Duplicator\Libs\DupArchive\DupArchive; use Duplicator\Libs\Snap\SnapIO; use Exception; class DupArchiveGlobHeader extends AbstractDupArchiveHeader { public $originalSize = 0; public $storedSize = 0; protected $hash = ''; protected \Duplicator\Libs\DupArchive\Headers\DupArchiveFileHeader $fileHeader; public function __construct(DupArchiveFileHeader $fileHeader) { $this->fileHeader = $fileHeader; } public function setHash($content): void { $this->hash = hash(DupArchive::HASH_ALGO, $content); } public function checkHash($content, $storedContent): bool { if (version_compare($this->fileHeader->getVersion(), '5.0.0', '<')) { $hash = hash(DupArchive::HASH_ALGO, $storedContent); } else { $hash = hash(DupArchive::HASH_ALGO, $content); } return ($hash === $this->hash); } public function writeToArchive($archiveHandle): int { $headerString = '' . $this->originalSize . '' . $this->storedSize . '' . $this->hash . ''; return SnapIO::fwrite($archiveHandle, $headerString, 'Error writing glob header to archive.'); } public function readFromArchive($archiveHandle, $skipGlob = false) { $startElement = fread($archiveHandle, 3); if ($startElement !== '') { throw new Exception("Invalid glob header marker found {$startElement}. location:" . ftell($archiveHandle)); } $this->originalSize = intval(self::getHeaderField($archiveHandle, 'OS')); $this->storedSize = intval(self::getHeaderField($archiveHandle, 'SS')); $this->hash = self::getHeaderField($archiveHandle, 'HA'); fread($archiveHandle, 4); if ($skipGlob) { if (fseek($archiveHandle, $this->storedSize, SEEK_CUR) === -1) { throw new Exception("Can't fseek when skipping glob at location:" . ftell($archiveHandle)); } } return $this; } public function getContentToWrite($content) { if ($this->fileHeader->isCompressed()) { if (($content = gzdeflate($content, 2)) === false) { throw new Exception("Error gzdeflate glob content", DupArchive::EXCEPTION_CODE_EXTRACT_ERROR); } } if ($this->fileHeader->isCrypt()) { if (($content = DupArchive::encrypt($content, $this->fileHeader->getPassword(), true)) === false) { throw new Exception("Error encrypt glob content", DupArchive::EXCEPTION_CODE_EXTRACT_ERROR); } } return $content; } public function readContent($archiveHandle, $validate = false) { if ($this->storedSize == 0) { return ''; } if (($content = fread($archiveHandle, $this->storedSize)) === false) { throw new Exception("Error reading glob content"); } $result = $content; if ($this->fileHeader->isCrypt()) { if (($result = DupArchive::decrypt($result, $this->fileHeader->getPassword(), $this->fileHeader->isApplyExtraHash())) === false) { throw new Exception("Error decrypt glob content"); } } if ($this->fileHeader->isCompressed()) { if (($result = @gzinflate($result)) === false) { throw new Exception("Error gzinflate glob content"); } } if ($validate && $this->checkHash($result, $content) == false) { throw new Exception('Glob validation fail'); } return $result; } } } namespace Duplicator\Libs\DupArchive\Headers { use Duplicator\Libs\DupArchive\DupArchive; use Duplicator\Libs\Snap\SnapIO; use Exception; class DupArchiveHeader extends AbstractDupArchiveHeader { private const HASH_PASSWORD_REGEX = '/^\$(\d)\$rounds=(\d+)\$(.+)\$(.+)$/'; protected $version = ''; protected int $flags; protected $password = ''; protected $hashPassword = ''; public function __construct($flags = 0, $verison = '') { $this->version = (strlen($verison) ? $verison : DupArchive::DUPARCHIVE_VERSION); $this->flags = (int) $flags; } public function getVersion() { return $this->version; } public function getFlags(): int { return $this->flags; } public function setFlags($flags): void { $this->flags = (int) $flags; } public function setPassword($pwd): void { if (strlen($pwd) == 0) { $this->flags &= ~DupArchive::FLAG_CRYPT; $this->password = ''; $this->hashPassword = ''; } else { $hashPassword = self::pwdToHash($pwd, DupArchive::generateSalt(16)); if (!self::isValidHashPassword($hashPassword)) { throw new Exception( 'The server crypt() output is not a valid archive password hash.', DupArchive::EXCEPTION_CODE_ENCRYPTION_UNAVAILABLE ); } $this->flags |= DupArchive::FLAG_CRYPT; $this->password = $pwd; $this->hashPassword = $hashPassword; } } private static function isValidHashPassword(string $hashPassword): bool { return preg_match(self::HASH_PASSWORD_REGEX, $hashPassword) === 1; } public function getPassword() { return $this->password; } public function writeToArchive($archiveHandle) { $content = ''; $content .= '' . $this->version . ''; $content .= '' . pack('v', $this->flags) . ''; $content .= '

' . $this->hashPassword . '

'; $content .= '
'; return SnapIO::fwrite($archiveHandle, $content); } public function isCompressed(): bool { return (bool) ($this->flags & DupArchive::FLAG_COMPRESS); } public function isCrypt(): bool { return (bool) ($this->flags & DupArchive::FLAG_CRYPT); } public function readFromArchive($archiveHandle, $password = '') { $startElement = fgets($archiveHandle, 4); if ($startElement != '') { throw new Exception("Invalid archive header marker found {$startElement}", DupArchive::EXCEPTION_CODE_INVALID_MARKER); } $version = self::getHeaderField($archiveHandle, 'V'); $flags = 0; $hashPassword = ''; if (version_compare($version, '5.0.0', '<')) { if (filter_var(self::getHeaderField($archiveHandle, 'C'), FILTER_VALIDATE_BOOLEAN)) { $flags = DupArchive::FLAG_COMPRESS; } $password = ''; } else { $falgs = self::getHeaderField($archiveHandle, 'X'); $flags = unpack('vflags', $falgs)['flags']; $hashPassword = self::getHeaderField($archiveHandle, 'P'); } if (strlen($hashPassword)) { if (preg_match(self::HASH_PASSWORD_REGEX, $hashPassword, $matches) !== 1) { throw new Exception("Invalid archive stored password", DupArchive::EXCEPTION_CODE_EXTRACT_ERROR); } $algo = $matches[1]; $rounds = $matches[2]; $salt = $matches[3]; $hash = $matches[4]; if (!hash_equals($hashPassword, self::pwdToHash($password, $salt))) { throw new Exception("Invalid archive password", DupArchive::EXCEPTION_CODE_INVALID_PASSWORD); } } $this->flags = $flags; $this->version = $version; $this->password = $password; $this->hashPassword = $hashPassword; fgets($archiveHandle, 5); return $this; } protected function pwdToHash($password, $salt): string { return crypt($password, DupArchive::PWD_ALGO . $salt . '$'); } } } namespace Duplicator\Libs\DupArchive\Info { use Duplicator\Libs\DupArchive\Headers\DupArchiveFileHeader; class DupArchiveExpanderInfo { public $archiveHandle; public $currentFileHeader; public $destDirectory; public $directoryWriteCount = 0; public $fileWriteCount = 0; public $enableWrite = false; public function getCurrentDestFilePath(): string { if ($this->destDirectory != null) { return "{$this->destDirectory}/{$this->currentFileHeader->relativePath}"; } else { return ''; } } } } namespace { use Duplicator\Installer\Bootstrap\BootstrapRunner; use Duplicator\Installer\Bootstrap\BootstrapUtils; use Duplicator\Installer\Bootstrap\BootstrapView; use Duplicator\Installer\Bootstrap\LogHandler; use Duplicator\Installer\Cli\CliBootstrap; class InstallerBootstrapData { const ARCHIVE_FILENAME = '20261129_licovant_6fff7f931820a6e24741_20261129171550_archive.daf'; const ARCHIVE_SIZE = '218384638'; const INSTALLER_DIR_NAME = 'dup-installer'; const PACKAGE_HASH = '6fff7f9-29171550'; const SECONDARY_PACKAGE_HASH = 'a62e5cc-29171550'; const VERSION = '5.2.0'; } BootstrapUtils::phpVersionCheck(BootstrapRunner::MINIMUM_PHP_VERSION); BootstrapRunner::initSetValues(); if (PHP_SAPI === 'cli' && !isset($_SERVER['REQUEST_METHOD'])) { exit(CliBootstrap::run($_SERVER['argv'], InstallerBootstrapData::PACKAGE_HASH)); } $bootError = null; $view = ''; try { $boot = BootstrapRunner::getInstance(); LogHandler::initErrorHandler(array($boot, 'log')); $bootView = new BootstrapView(); $view = $boot->run(); } catch (Exception $e) { $boot->log("[ERROR] Boot msg:" . $e->getMessage() . "\n" . $e->getTraceAsString()); $boot->appendErrorMessage($e->getMessage()); $view = BootstrapView::VIEW_ERROR; } switch ($view) { case BootstrapView::VIEW_REDIRECT: $bootView->redirectToInsaller(); break; case BootstrapView::VIEW_ERROR: $bootView->renderError(); break; case BootstrapView::VIEW_PASSWORD: $bootView->renderPassword(); break; } } /* DUPLICATOR_INSTALLER_EOF */