first commit

This commit is contained in:
2026-04-20 13:11:14 +02:00
commit e0b63ca5f9
7793 changed files with 1844488 additions and 0 deletions

View File

@@ -0,0 +1,9 @@
<Files *.php>
Order Deny,Allow
Deny from all
</Files>
<Files index.php>
Order Allow,Deny
Allow from all
</Files>

View File

@@ -0,0 +1,104 @@
<?php
defined("DUPXABSPATH") or die("");
/**
* Class used to update and edit web server configuration files
* for .htaccess, web.config and user.ini
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\Crypt
*/
class DUPX_Crypt
{
/**
* Encrypt a string
*
* @param string $key The key to use for encryption
* @param string $string The string to encrypt
*
* @return string
*/
public static function encrypt($key, $string)
{
$result = '';
for ($i = 0; $i < strlen($string); $i++) {
$char = substr($string, $i, 1);
$keychar = substr($key, ($i % strlen($key)) - 1, 1);
$char = chr(ord($char) + ord($keychar));
$result .= $char;
}
return urlencode(base64_encode($result));
}
/**
* Decrypt a string
*
* @param string $key The key to use for decryption
* @param string $string The string to decrypt
*
* @return string
*/
public static function decrypt($key, $string)
{
$result = '';
$string = urldecode($string);
$string = base64_decode($string);
for ($i = 0; $i < strlen($string); $i++) {
$char = substr($string, $i, 1);
$keychar = substr($key, ($i % strlen($key)) - 1, 1);
$char = chr(ord($char) - ord($keychar));
$result .= $char;
}
return $result;
}
/**
* Scramble a string
*
* @param string $string The string to scramble
*
* @return string
*/
public static function scramble($string)
{
return self::encrypt(self::sk1() . self::sk2(), $string);
}
/**
* Unscramble a string
*
* @param string $string The string to unscramble
*
* @return string
*/
public static function unscramble($string)
{
return self::decrypt(self::sk1() . self::sk2(), $string);
}
/**
* Get the first key
*
* @return string
*/
public static function sk1()
{
return 'fdas' . self::encrypt('abx', 'v1');
}
/**
* Get the second key
*
* @return string
*/
public static function sk2()
{
return 'fres' . self::encrypt('ad3x', 'v2');
}
}

View File

@@ -0,0 +1,87 @@
<?php
defined("DUPXABSPATH") or die("");
/**
* Http Class Utility
*/
class DUPX_HTTP
{
/**
* Do an http post request with curl or php code
*
* @param string $url A URL to get. If $params is not null then all query strings will be removed.
* @param string[] $params A valid key/pair combo $data = array('key1' => 'value1', 'key2' => 'value2');
* @param ?string[] $headers Optional header elements
*
* @return string|bool a string or FALSE on failure.
*/
public static function get($url, $params = array(), $headers = null)
{
//PHP GET
if (!function_exists('curl_init')) {
return self::php_get_post($url, $params, $headers = null, 'GET');
}
//Remove query string if $params are passed
$full_url = $url;
if (count($params)) {
$url = preg_replace('/\?.*/', '', $url);
$full_url = $url . '?' . http_build_query($params);
}
$headers_on = isset($headers) && array_count_values($headers);
$ch = curl_init();
// Return contents of transfer on curl_exec
// Allow self-signed certs
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_URL, $full_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, $headers_on);
if ($headers_on) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
/**
* Do an http post request with curl or php code
*
* @param string $url A URL to get. If $params is not null then all query strings will be removed.
* @param string[] $params A valid key/pair combo $data = array('key1' => 'value1', 'key2' => 'value2');
* @param ?string[] $headers Optional header elements
* @param string $method The method to use
*
* @return string
*/
private static function php_get_post($url, $params, $headers = null, $method = 'POST')
{
$full_url = $url;
if ($method == 'GET' && count($params)) {
$url = preg_replace('/\?.*/', '', $url);
$full_url = $url . '?' . http_build_query($params);
}
$data = array(
'http' => array(
'method' => $method,
'content' => http_build_query($params),
),
);
if ($headers !== null) {
$data['http']['header'] = $headers;
}
$ctx = stream_context_create($data);
$fp = @fopen($full_url, 'rb', false, $ctx);
if (!$fp) {
throw new Exception("Problem with $full_url");
}
$response = @stream_get_contents($fp);
if ($response === false) {
throw new Exception("Problem reading data from $full_url");
}
return $response;
}
}

View File

@@ -0,0 +1,236 @@
<?php
/**
* Class used to update and edit web server configuration files
* for .htaccess, web.config and user.ini
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\Crypt
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Core\Security;
use Duplicator\Installer\Core\Bootstrap;
use Duplicator\Installer\Core\Deploy\ServerConfigs;
use Duplicator\Installer\Utils\InstallerOrigFileMng;
/**
* Package related functions
*/
final class DUPX_Package
{
/**
*
* @return bool|string false if fail
*/
public static function getPackageHash()
{
static $packageHash = null;
if (is_null($packageHash)) {
if (($packageHash = Bootstrap::getPackageHash()) === false) {
throw new Exception('PACKAGE ERROR: can\'t find package hash');
}
}
return $packageHash;
}
/**
*
* @return string
*/
public static function getArchiveFileHash()
{
static $fileHash = null;
if (is_null($fileHash)) {
$fileHash = preg_replace('/^.+_([a-z0-9]+)_[0-9]{14}_archive\.(?:daf|zip)$/', '$1', Security::getInstance()->getArchivePath());
}
return $fileHash;
}
/**
*
* @return bool|string false if fail
*/
public static function getPackageArchivePath()
{
static $archivePath = null;
if (is_null($archivePath)) {
$path = DUPX_INIT . '/' . Bootstrap::ARCHIVE_PREFIX . self::getPackageHash() . Bootstrap::ARCHIVE_EXTENSION;
if (!file_exists($path)) {
throw new Exception('PACKAGE ERROR: can\'t read package path: ' . $path);
} else {
$archivePath = $path;
}
}
return $archivePath;
}
/**
* Returns a save-to-edit wp-config file
*
* @return string
*/
public static function getWpconfigArkPath()
{
return InstallerOrigFileMng::getInstance()->getEntryStoredPath(ServerConfigs::CONFIG_ORIG_FILE_WPCONFIG_ID);
}
/**
*
* @return string
*/
public static function getManualExtractFile()
{
return DUPX_INIT . '/dup-manual-extract__' . self::getPackageHash();
}
/**
*
* @return string
*/
public static function getWpconfigSamplePath()
{
static $path = null;
if (is_null($path)) {
$path = DUPX_INIT . '/assets/wp-config-sample.php';
}
return $path;
}
/**
* Get sql file relative path
*
* @return string
*/
public static function getSqlFilePathInArchive()
{
return 'dup-installer/dup-database__' . self::getPackageHash() . '.sql';
}
/**
*
* @return string
*/
public static function getSqlFilePath()
{
static $path = null;
if (is_null($path)) {
$path = DUPX_INIT . '/dup-database__' . self::getPackageHash() . '.sql';
}
return $path;
}
/**
*
* @return string
*/
public static function getDirsListPath()
{
static $path = null;
if (is_null($path)) {
$path = DUPX_INIT . '/dup-scanned-dirs__' . self::getPackageHash() . '.txt';
}
return $path;
}
/**
*
* @return string
*/
public static function getFilesListPath()
{
static $path = null;
if (is_null($path)) {
$path = DUPX_INIT . '/dup-scanned-files__' . self::getPackageHash() . '.txt';
}
return $path;
}
/**
*
* @return string
*/
public static function getScanJsonPath()
{
static $path = null;
if (is_null($path)) {
$path = DUPX_INIT . '/dup-scan__' . self::getPackageHash() . '.json';
}
return $path;
}
/**
*
* @return int
*/
public static function getSqlFileSize()
{
return (is_readable(self::getSqlFilePath())) ? (int) filesize(self::getSqlFilePath()) : 0;
}
/**
*
* @param callable $callback callback function
*
* @return boolean
*/
public static function foreachDirCallback($callback)
{
if (!is_callable($callback)) {
throw new Exception('Not valid callback');
}
$dirFiles = DUPX_Package::getDirsListPath();
if (($handle = fopen($dirFiles, "r")) === false) {
throw new Exception('Can\'t open dirs file list');
}
while (($line = fgets($handle)) !== false) {
if (($info = json_decode($line)) === null) {
throw new Exception('Invalid json line in dirs file: ' . $line);
}
call_user_func($callback, $info);
}
fclose($handle);
return true;
}
/**
*
* @param callable $callback callback
*
* @return boolean
*/
public static function foreachFileCallback($callback)
{
if (!is_callable($callback)) {
throw new Exception('Not valid callback');
}
$filesPath = DUPX_Package::getFilesListPath();
if (($handle = fopen($filesPath, "r")) === false) {
throw new Exception('Can\'t open files file list');
}
while (($line = fgets($handle)) !== false) {
if (($info = json_decode($line)) === null) {
throw new Exception('Invalid json line in files file: ' . $line);
}
call_user_func($callback, $info);
}
fclose($handle);
return true;
}
}

View File

@@ -0,0 +1,109 @@
<?php
defined("DUPXABSPATH") or die("");
use Duplicator\Installer\Core\Params\PrmMng;
use Duplicator\Libs\Shell\Shell;
use Duplicator\Libs\Snap\SnapIO;
use Duplicator\Libs\Snap\SnapWP;
/**
* DUPX_cPanel
* Wrapper Class for cPanel API */
class DUPX_Server
{
/** @var string[] A list of the core WordPress directories */
public static $wpCoreDirsList = array(
'wp-admin',
'wp-includes',
);
/**
* Return PHP safe nome, on PHP 5.4 is always false
*
* @return bool
*/
public static function phpSafeModeOn()
{
// safe_mode has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.
return false;
}
/**
* Returns the path this this server where the zip command can be called
*
* @return null|string // null if can't find unzip
*/
public static function get_unzip_filepath()
{
$filepath = null;
if (Shell::runCommand('echo duplicator', Shell::AVAILABLE_COMMANDS) !== false) {
$shellOutput = Shell::runCommand('hash unzip 2>&1', Shell::AVAILABLE_COMMANDS);
if ($shellOutput !== false && $shellOutput->isEmpty()) {
$filepath = 'unzip';
} else {
$possible_paths = array(
'/usr/bin/unzip',
'/opt/local/bin/unzip',
);
foreach ($possible_paths as $path) {
if (file_exists($path)) {
$filepath = $path;
break;
}
}
}
}
return $filepath;
}
/**
*
* @return string[]
*/
public static function getWpAddonsSiteLists()
{
$addonsSites = array();
$pathsToCheck = DUPX_ArchiveConfig::getInstance()->getPathsMapping();
if (is_scalar($pathsToCheck)) {
$pathsToCheck = array($pathsToCheck);
}
foreach ($pathsToCheck as $mainPath) {
SnapIO::regexGlobCallback($mainPath, function ($path) use (&$addonsSites) {
if (SnapWP::isWpHomeFolder($path)) {
$addonsSites[] = $path;
}
}, array(
'regexFile' => false,
'recursive' => true,
));
}
return $addonsSites;
}
/**
* Does the site look to be a WordPress site
*
* @return bool Returns true if the site looks like a WP site
*/
public static function isWordPress()
{
$absPathNew = PrmMng::getInstance()->getValue(PrmMng::PARAM_PATH_WP_CORE_NEW);
if (!is_dir($absPathNew)) {
return false;
}
if (($root_files = scandir($absPathNew)) == false) {
return false;
}
$file_count = 0;
foreach ($root_files as $file) {
if (in_array($file, self::$wpCoreDirsList)) {
$file_count++;
}
}
return (count(self::$wpCoreDirsList) == $file_count);
}
}

View File

@@ -0,0 +1,87 @@
<?php
/**
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX
*/
use Duplicator\Installer\Core\Security;
use Duplicator\Libs\Snap\FunctionalityCheck;
use Duplicator\Libs\Snap\SnapUtil;
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
/**
* In this class all the utility functions related to the wordpress configuration and the package are defined.
*/
class DUPX_Conf_Utils
{
/**
*
* @staticvar bool $present
* @return bool
*/
public static function isManualExtractFilePresent()
{
static $present = null;
if (is_null($present)) {
$present = file_exists(DUPX_Package::getManualExtractFile());
}
return $present;
}
/**
*
* @staticvar null|bool $enable
* @return bool
*/
public static function isShellZipAvailable()
{
static $enable = null;
if (is_null($enable)) {
$enable = DUPX_Server::get_unzip_filepath() != null;
}
return $enable;
}
/**
*
* @return bool
*/
public static function isPhpZipAvailable()
{
return SnapUtil::classExists(ZipArchive::class);
}
/**
*
* @staticvar bool $exists
* @return bool
*/
public static function archiveExists()
{
static $exists = null;
if (is_null($exists)) {
$exists = file_exists(Security::getInstance()->getArchivePath());
}
return $exists;
}
/**
* Get archive size
*
* @return int
*/
public static function archiveSize()
{
static $arcSize = null;
if (is_null($arcSize)) {
$archivePath = Security::getInstance()->getArchivePath();
$arcSize = file_exists($archivePath) ? (int) @filesize($archivePath) : 0;
}
return $arcSize;
}
}

View File

@@ -0,0 +1,131 @@
<?php
/**
* Class used to update and edit web server configuration files
* for both Apache and IIS files .htaccess and web.config
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\WPConfig
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Core\Deploy\ServerConfigs;
use Duplicator\Installer\Core\Params\PrmMng;
use Duplicator\Installer\Utils\InstallerOrigFileMng;
use Duplicator\Installer\Utils\Log\Log;
use Duplicator\Libs\Snap\SnapIO;
use Duplicator\Libs\WpConfig\WPConfigTransformer;
class DUPX_WPConfig
{
const ADMIN_SERIALIZED_SECURITY_STRING = 'a:1:{s:13:"administrator";b:1;}';
const ADMIN_LEVEL = 10;
/**
* get wp-config default path (not relative to orig file manger)
*
* @return string
*/
public static function getWpConfigDeafultPath()
{
return PrmMng::getInstance()->getValue(PrmMng::PARAM_PATH_NEW) . '/wp-config.php';
}
/**
*
* @return bool|string false if fail
*/
public static function getWpConfigPath()
{
$origWpConfTarget = InstallerOrigFileMng::getInstance()->getEntryTargetPath(ServerConfigs::CONFIG_ORIG_FILE_WPCONFIG_ID, self::getWpConfigDeafultPath());
$origWpDir = SnapIO::safePath(dirname($origWpConfTarget));
if ($origWpDir === PrmMng::getInstance()->getValue(PrmMng::PARAM_PATH_NEW)) {
return $origWpConfTarget;
} else {
return PrmMng::getInstance()->getValue(PrmMng::PARAM_PATH_WP_CORE_NEW) . "/wp-config.php";
}
}
/**
*
*
* @return boolean|WPConfigTransformer
*/
public static function getLocalConfigTransformer()
{
static $confTransformer = null;
if (is_null($confTransformer)) {
try {
if (($wpConfigPath = ServerConfigs::getWpConfigLocalStoredPath()) === false) {
$wpConfigPath = DUPX_WPConfig::getWpConfigPath();
}
if (is_readable($wpConfigPath)) {
$confTransformer = new WPConfigTransformer($wpConfigPath);
} else {
$confTransformer = false;
}
} catch (Exception $e) {
$confTransformer = false;
}
}
return $confTransformer;
}
/**
*
* @param string $name constant name
* @param string $type constant | variable
* @param mixed $default default value
*
* @return mixed
*/
public static function getValueFromLocalWpConfig($name, $type = 'constant', $default = '')
{
if (($confTransformer = self::getLocalConfigTransformer()) !== false) {
return $confTransformer->exists($type, $name) ? $confTransformer->getValue($type, $name) : $default;
} else {
return null;
}
}
/**
* Check if the wp-config of the source site is valid.
*
* @return bool true on success, false on failure
*/
public static function isSourceWpConfigValid()
{
static $wpConfigValid = null;
if (is_null($wpConfigValid)) {
try {
if (($wpConfigPath = ServerConfigs::getSourceWpConfigPath()) == false) {
throw new Exception('Source wp-config.php don\'t exists');
}
$configTransformer = new WPConfigTransformer($wpConfigPath);
$requiredConst = array(
'DB_NAME',
'DB_USER',
'DB_PASSWORD',
'DB_HOST',
);
foreach ($requiredConst as $constName) {
if (!$configTransformer->exists('constant', $constName)) {
throw new Exception($constName . ' don\'t exist');
}
}
$wpConfigValid = true;
} catch (Exception $e) {
Log::info('CHECK WP CONFIG FAIL msg: ' . $e->getMessage());
$wpConfigValid = false;
} catch (Error $e) {
Log::info('CHECK WP CONFIG FAIL msg: ' . $e->getMessage());
$wpConfigValid = false;
}
}
return $wpConfigValid;
}
}

View File

@@ -0,0 +1,86 @@
<?php
/**
* Class used to group all global constants
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\Constants
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Core\Bootstrap;
use Duplicator\Libs\Shell\Shell;
class DUPX_Constants
{
const CHUNK_EXTRACTION_TIMEOUT_TIME_ZIP = 5;
const CHUNK_EXTRACTION_TIMEOUT_TIME_DUP = 5;
const CHUNK_DBINSTALL_TIMEOUT_TIME = 5;
const CHUNK_MAX_TIMEOUT_TIME = 5;
const DEFAULT_MAX_STRLEN_SERIALIZED_CHECK_IN_M = 4; // 0 no limit
const DUP_SITE_URL = 'https://duplicator.com/';
const FAQ_URL = 'https://duplicator.com/knowledge-base/';
const MIN_NEW_PASSWORD_LEN = 6;
const BACKUP_RENAME_PREFIX = 'dp___bk_';
/**
* Init method used to auto initialize the global params
* This function init all params before read from request
*
* @return void
*/
public static function init()
{
//DATABASE SETUP: all time in seconds
//max_allowed_packet: max value 1073741824 (1268MB) see my.ini
$GLOBALS['DB_MAX_TIME'] = 5000;
$GLOBALS['DATABASE_PAGE_SIZE'] = 3500;
$GLOBALS['DB_MAX_PACKETS'] = 268435456;
$GLOBALS['DBCHARSET_DEFAULT'] = 'utf8';
$GLOBALS['DBCOLLATE_DEFAULT'] = 'utf8_general_ci';
$GLOBALS['DB_RENAME_PREFIX'] = self::BACKUP_RENAME_PREFIX . date("dHi") . '_';
$GLOBALS['DB_INSTALL_MULTI_THREADED_MAX_RETRIES'] = 3;
if (!defined('MAX_SITES_TO_DEFAULT_ENABLE_CORSS_SEARCH')) {
define('MAX_SITES_TO_DEFAULT_ENABLE_CORSS_SEARCH', 10);
}
//UPDATE TABLE SETTINGS
$GLOBALS['REPLACE_LIST'] = array();
$GLOBALS['DEBUG_JS'] = false;
//CONSTANTS
if (!defined("DUPLICATOR_PRO_SSDIR_NAME")) {
define("DUPLICATOR_PRO_SSDIR_NAME", 'wp-snapshots-dup-pro'); //This should match DUPLICATOR_PRO_SSDIR_NAME in duplicator.php
}
//GLOBALS
$GLOBALS["NOTICES_FILE_PATH"] = DUPX_INIT . '/' . "dup-installer-notices__" . Bootstrap::getPackageHash() . ".json";
$GLOBALS["CHUNK_DATA_FILE_PATH"] = DUPX_INIT . '/' . "dup-installer-chunk__" . Bootstrap::getPackageHash() . ".json";
$GLOBALS['PHP_MEMORY_LIMIT'] = ini_get('memory_limit') === false ? 'n/a' : ini_get('memory_limit');
$GLOBALS['PHP_SUHOSIN_ON'] = Shell::isSuhosinEnabled() ? 'enabled' : 'disabled';
$GLOBALS['DISPLAY_MAX_OBJECTS_FAILED_TO_SET_PERM'] = 5;
// Displaying notice for slow zip chunk extraction
$GLOBALS['ZIP_ARC_CHUNK_EXTRACT_DISP_NOTICE_AFTER'] = 5 * 60 * 60; // 5 minutes
$GLOBALS['ZIP_ARC_CHUNK_EXTRACT_DISP_NOTICE_MIN_EXPECTED_EXTRACT_TIME'] = 10 * 60 * 60; // 10 minutes
$GLOBALS['ZIP_ARC_CHUNK_EXTRACT_DISP_NEXT_NOTICE_INTERVAL'] = 5 * 60 * 60; // 5 minutes
$additional_msg = ' for additional details <a href="' . self::FAQ_URL . 'how-to-handle-various-install-scenarios/" target="_blank">click here</a>.';
$GLOBALS['ZIP_ARC_CHUNK_EXTRACT_NOTICES'] = array(
'This server looks to be under load or throttled, the extraction process may take some time',
'This host is currently experiencing very slow I/O. You can continue to wait or try a manual extraction.',
'This host I/O is currently having issues. It is recommended to try a manual extraction.',
);
foreach ($GLOBALS['ZIP_ARC_CHUNK_EXTRACT_NOTICES'] as $key => $val) {
$GLOBALS['ZIP_ARC_CHUNK_EXTRACT_NOTICES'][$key] = $val . $additional_msg;
}
$GLOBALS['FW_USECDN'] = false;
$GLOBALS['NOW_TIME'] = @date("His");
}
}

View File

@@ -0,0 +1,862 @@
<?php
/**
* Database functions
*
* Standard: PSR-2
*
* @package SC\DUPX\DB
* @link http://www.php-fig.org/psr/psr-2/
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Utils\Log\Log;
use Duplicator\Installer\Core\Params\PrmMng;
use Duplicator\Installer\Core\Params\Descriptors\ParamDescUsers;
use Duplicator\Libs\Snap\SnapDB;
class DUPX_DB_Functions
{
const TABLE_NAME_DUPLICATOR_PACKAGES = 'duplicator_backups';
const TABLE_NAME_DUPLICAT_ENTITIES = 'duplicator_entities';
const TABLE_NAME_WP_USERS = 'users';
const TABLE_NAME_WP_USERMETA = 'usermeta';
/** @var ?self */
protected static $instance = null;
/** @var ?mysqli */
private $dbh = null;
/** @var float */
protected $timeStart = 0;
/** @var ?array<string, string> current data connection */
private $dataConnection = null;
/** @var ?array<int,array{name:string,isDefault:bool}> list of supported engine types */
private $engineData = null;
/** @var ?array<string,array{defCollation:bool,collations:string[]}> supported charset and collation data */
private $charsetData = null;
/** @var ?array<string,string> default charset in dwtabase connection */
private $defaultCharset = null;
/** @var int */
private $rename_tbl_log = 0;
/**
* Class constructor
*/
private function __construct()
{
$this->timeStart = DUPX_U::getMicrotime();
}
/**
*
* @return self
*/
public static function getInstance()
{
if (is_null(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Returns mysqli handle
*
* @param ?array<string, string> $customConnection custom connection data
*
* @return ?mysqli
*/
public function dbConnection($customConnection = null)
{
if (!is_null($this->dbh)) {
return $this->dbh;
}
$paramsManager = PrmMng::getInstance();
if (is_null($customConnection)) {
if (!DUPX_Validation_manager::isValidated()) {
throw new Exception('Installer isn\'t validated');
}
$dbhost = $paramsManager->getValue(PrmMng::PARAM_DB_HOST);
$dbname = $paramsManager->getValue(PrmMng::PARAM_DB_NAME);
$dbuser = $paramsManager->getValue(PrmMng::PARAM_DB_USER);
$dbpass = $paramsManager->getValue(PrmMng::PARAM_DB_PASS);
} else {
$dbhost = $customConnection['dbhost'];
$dbname = $customConnection['dbname'];
$dbuser = $customConnection['dbuser'];
$dbpass = $customConnection['dbpass'];
}
$dbflag = $paramsManager->getValue(PrmMng::PARAM_DB_FLAG);
if ($dbflag === DUPX_DB::DB_CONNECTION_FLAG_NOT_SET) {
$dbh = self::checkFlagsDbConnection($dbhost, $dbuser, $dbpass, $dbname);
$dbflag = $paramsManager->getValue(PrmMng::PARAM_DB_FLAG);
} else {
$dbh = DUPX_DB::connect($dbhost, $dbuser, $dbpass, $dbname, $dbflag);
}
if ($dbh != false) {
$this->dbh = $dbh;
$this->dataConnection = array(
'dbhost' => $dbhost,
'dbname' => $dbname,
'dbuser' => $dbuser,
'dbpass' => $dbpass,
'dbflag' => $dbflag,
);
} else {
$dbConnError = (mysqli_connect_error()) ? 'Error: ' . mysqli_connect_error() : 'Unable to Connect';
$msg = "Unable to connect with the following parameters:<br/>"
. "HOST: " . Log::v2str($dbhost) . "\n"
. "DBUSER: " . Log::v2str($dbuser) . "\n"
. "DATABASE: " . Log::v2str($dbname) . "\n"
. "MESSAGE: " . $dbConnError;
Log::error($msg);
}
if (is_null($customConnection)) {
$db_max_time = mysqli_real_escape_string($this->dbh, $GLOBALS['DB_MAX_TIME']);
DUPX_DB::mysqli_query($this->dbh, "SET wait_timeout = " . mysqli_real_escape_string($this->dbh, $db_max_time));
DUPX_DB::setCharset($this->dbh, $paramsManager->getValue(PrmMng::PARAM_DB_CHARSET), $paramsManager->getValue(PrmMng::PARAM_DB_COLLATE));
}
return $this->dbh;
}
/**
* Check flags dbconnection
*
* @param string $dbhost host
* @param string $dbuser user
* @param string $dbpass password
* @param string $dbname database name
*
* @return bool|mysqli
*/
protected static function checkFlagsDbConnection($dbhost, $dbuser, $dbpass, $dbname = null)
{
$paramsManager = PrmMng::getInstance();
$wpConfigFalgsVal = $paramsManager->getValue(PrmMng::PARAM_WP_CONF_MYSQL_CLIENT_FLAGS);
$isLocalhost = $dbhost == "localhost";
if (($dbh = DUPX_DB::connect($dbhost, $dbuser, $dbpass, $dbname)) != false) {
$dbflag = DUPX_DB::MYSQLI_CLIENT_NO_FLAGS;
$wpConfigFalgsVal['inWpConfig'] = false;
$wpConfigFalgsVal['value'] = array();
} elseif (!$isLocalhost && ($dbh = DUPX_DB::connect($dbhost, $dbuser, $dbpass, $dbname, MYSQLI_CLIENT_SSL)) != false) {
$dbflag = MYSQLI_CLIENT_SSL;
$wpConfigFalgsVal['inWpConfig'] = true;
$wpConfigFalgsVal['value'] = array(MYSQLI_CLIENT_SSL);
} elseif (
!$isLocalhost &&
defined("MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT") &&
(
$dbh = DUPX_DB::connect(
$dbhost,
$dbuser,
$dbpass,
$dbname,
MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT // phpcs:ignore PHPCompatibility.Constants.NewConstants.mysqli_client_ssl_dont_verify_server_certFound
)
) != false
) {
// phpcs:ignore PHPCompatibility.Constants.NewConstants.mysqli_client_ssl_dont_verify_server_certFound
$dbflag = MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT;
$wpConfigFalgsVal['inWpConfig'] = true;
$wpConfigFalgsVal['value'] = array($dbflag);
} else {
$dbflag = DUPX_DB::MYSQLI_CLIENT_NO_FLAGS;
}
$paramsManager->setValue(PrmMng::PARAM_DB_FLAG, $dbflag);
$paramsManager->setValue(PrmMng::PARAM_WP_CONF_MYSQL_CLIENT_FLAGS, $wpConfigFalgsVal);
$paramsManager->save();
return $dbh;
}
/**
* close db connection if is open
*
* @return void
*/
public function closeDbConnection()
{
if (!is_null($this->dbh)) {
mysqli_close($this->dbh);
$this->dbh = null;
$this->dataConnection = null;
$this->charsetData = null;
$this->defaultCharset = null;
}
}
/**
* get default charset
*
* @return string
*/
public function getDefaultCharset()
{
if (is_null($this->defaultCharset)) {
$this->dbConnection();
// SHOW VARIABLES LIKE "character_set_database"
if (($result = DUPX_DB::mysqli_query($this->dbh, "SHOW VARIABLES LIKE 'character_set_database'")) === false) {
throw new Exception('SQL ERROR:' . mysqli_error($this->dbh));
}
if ($result->num_rows != 1) {
throw new Exception('DEFAULT CHARSET NUMBER NOT VALID NUM ' . $result->num_rows);
}
while ($row = $result->fetch_array()) {
$this->defaultCharset = $row[1];
}
$result->free();
}
return $this->defaultCharset;
}
/**
*
* @param string $charset charset
*
* @return string|bool false if charset don't exists
*/
public function getDefaultCollateOfCharset($charset)
{
$this->getCharsetAndCollationData();
return isset($this->charsetData[$charset]) ? $this->charsetData[$charset]['defCollation'] : false;
}
/**
* Get list of supported MySQL engine
*
* @return array<int,array{name:string,isDefault:bool}>
*/
public function getEngineData()
{
if (is_null($this->engineData)) {
$this->dbConnection();
if (($result = DUPX_DB::mysqli_query($this->dbh, "SHOW ENGINES")) === false) {
throw new Exception('SQL ERROR:' . mysqli_error($this->dbh));
}
$this->engineData = array();
while ($row = $result->fetch_array()) {
if ($row[1] !== "YES" && $row[1] !== "DEFAULT") {
continue;
}
$this->engineData[] = array(
"name" => $row[0],
"isDefault" => $row[1] === "DEFAULT",
);
}
}
return $this->engineData;
}
/**
* @return string[] list of supported MySQL engine names
*/
public function getSupportedEngineList()
{
return array_map(function ($engine) {
return $engine["name"];
}, $this->getEngineData());
}
/**
* Returns default MySQL engine of the database
*
* @return string
*/
public function getDefaultEngine()
{
foreach ($this->engineData as $engine) {
if ($engine["isDefault"]) {
return $engine["name"];
}
}
return $this->engineData[0]["name"];
}
/**
* Get charset and collation data
*
* @return array<string,array{defCollation:bool,collations:string[]}>
*/
public function getCharsetAndCollationData()
{
if (is_null($this->charsetData)) {
$this->dbConnection();
if (($result = DUPX_DB::mysqli_query($this->dbh, "SHOW COLLATION")) === false) {
throw new Exception('SQL ERROR:' . mysqli_error($this->dbh));
}
while ($row = $result->fetch_array()) {
$collation = $row[0];
$charset = $row[1];
$default = filter_var($row[3], FILTER_VALIDATE_BOOLEAN);
$compiled = filter_var($row[4], FILTER_VALIDATE_BOOLEAN);
if (!$compiled) {
continue;
}
if (!isset($this->charsetData[$charset])) {
$this->charsetData[$charset] = array(
'defCollation' => false,
'collations' => array(),
);
}
$this->charsetData[$charset]['collations'][] = $collation;
if ($default) {
$this->charsetData[$charset]['defCollation'] = $collation;
}
}
$result->free();
ksort($this->charsetData);
foreach (array_keys($this->charsetData) as $charset) {
sort($this->charsetData[$charset]['collations']);
}
}
return $this->charsetData;
}
/**
*
* @return string[]
*/
public function getCharsetsList()
{
return array_keys($this->getCharsetAndCollationData());
}
/**
*
* @return string[]
*/
public function getCollationsList()
{
$result = array();
foreach ($this->getCharsetAndCollationData() as $charsetInfo) {
$result = array_merge($result, $charsetInfo['collations']);
}
return array_unique($result);
}
/**
* Get real charset by param
*
* @return string
*/
public function getRealCharsetByParam()
{
$this->getCharsetAndCollationData();
//$sourceCharset = DUPX_ArchiveConfig::getInstance()->getWpConfigDefineValue('DB_CHARSET', '');
$sourceCharset = PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_CHARSET);
return (array_key_exists($sourceCharset, $this->charsetData) ? $sourceCharset : $this->getDefaultCharset());
}
/**
* Get real collate by param
*
* @return string
*/
public function getRealCollateByParam()
{
$this->getCharsetAndCollationData();
$charset = $this->getRealCharsetByParam();
//$sourceCollate = DUPX_ArchiveConfig::getInstance()->getWpConfigDefineValue('DB_COLLATE', '');
$sourceCollate = PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_COLLATE);
return (strlen($sourceCollate) == 0 || !in_array($sourceCollate, $this->charsetData[$charset]['collations'])) ?
$this->getDefaultCollateOfCharset($charset) :
$sourceCollate;
}
/**
* Return option name table.
*
* @param ?string $prefix table prefix, if null take wp table prefix by default
*
* @return string
*/
public static function getOptionsTableName($prefix = null)
{
if (is_null($prefix)) {
$prefix = PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_TABLE_PREFIX);
}
return $prefix . 'options';
}
/**
*
* @param null|string $prefix table prefix, if null take wp table prefix by default
*
* @return string
*/
public static function getPostsTableName($prefix = null)
{
if (is_null($prefix)) {
$prefix = PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_TABLE_PREFIX);
}
return $prefix . 'posts';
}
/**
*
* @param null|string $prefix table prefix, if null take wp table prefix by default
*
* @return string
*/
public static function getUserTableName($prefix = null)
{
if (is_null($prefix)) {
$prefix = PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_TABLE_PREFIX);
}
return $prefix . self::TABLE_NAME_WP_USERS;
}
/**
*
* @param null|string $prefix table prefix, if null take wp table prefix by default
*
* @return string
*/
public static function getUserMetaTableName($prefix = null)
{
if (is_null($prefix)) {
$prefix = PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_TABLE_PREFIX);
}
return $prefix . self::TABLE_NAME_WP_USERMETA;
}
/**
*
* @param null|string $prefix table prefix, if null take wp table prefix by default
*
* @return string
*/
public static function getPackagesTableName($prefix = null)
{
if (is_null($prefix)) {
$prefix = PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_TABLE_PREFIX);
}
return $prefix . self::TABLE_NAME_DUPLICATOR_PACKAGES;
}
/**
*
* @param null|string $prefix table prefix, if null take wp table prefix by default
*
* @return string
*/
public static function getEntitiesTableName($prefix = null)
{
if (is_null($prefix)) {
$prefix = PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_TABLE_PREFIX);
}
return $prefix . self::TABLE_NAME_DUPLICAT_ENTITIES;
}
/**
*
* @param string $userLogin user login
*
* @return boolean return true if user login name exists in users table
*/
public function checkIfUserNameExists($userLogin)
{
if (!$this->tablesExist(self::getUserTableName())) {
return false;
}
$query = 'SELECT ID FROM `' . mysqli_real_escape_string($this->dbh, self::getUserTableName()) . '` '
. 'WHERE user_login="' . mysqli_real_escape_string($this->dbh, $userLogin) . '"';
if (($result = DUPX_DB::mysqli_query($this->dbh, $query)) === false) {
throw new Exception('SQL ERROR:' . mysqli_error($this->dbh));
}
return ($result->num_rows > 0);
}
/**
* User password reset
*
* @param int $userId user id
* @param string $newPassword new password
*
* @return bool
*/
public function userPwdReset($userId, $newPassword)
{
$tableName = mysqli_real_escape_string($this->dbh, self::getUserTableName());
$query = 'UPDATE `' . $tableName . '` '
. 'SET `user_pass` = MD5("' . mysqli_real_escape_string($this->dbh, $newPassword) . '") '
. 'WHERE `' . $tableName . '`.`ID` = ' . $userId;
if (($result = DUPX_DB::mysqli_query($this->dbh, $query)) === false) {
throw new Exception('SQL ERROR:' . mysqli_error($this->dbh));
} else {
return true;
}
}
/**
* return true if all tables passed in list exists
*
* @param string|string[] $tables list of table names
*
* @return bool
*/
public function tablesExist($tables)
{
//SHOW TABLES FROM c1_temptest WHERE Tables_in_c1_temptest IN ('i5tr4_users','i5tr4_usermeta')
$this->dbConnection();
if (empty($this->dataConnection['dbname'])) {
return false;
}
if (is_scalar($tables)) {
$tables = array($tables);
}
$dbName = mysqli_real_escape_string($this->dbh, $this->dataConnection['dbname']);
$dbh = $this->dbh;
$escapedTables = array_map(function ($table) use ($dbh) {
return "'" . mysqli_real_escape_string($dbh, $table) . "'";
}, $tables);
$sql = 'SHOW TABLES FROM `' . $dbName . '` WHERE `Tables_in_' . $dbName . '` IN (' . implode(',', $escapedTables) . ')';
if (($result = DUPX_DB::mysqli_query($this->dbh, $sql)) === false) {
return false;
}
return $result->num_rows === count($tables);
}
/**
* Get table replace names from regex pattern
*
* @param string[] $tableList list of table names
* @param string $pattern regex search string
* @param string $replacement regex replace string
*
* @return array<array{old:string,new:string}> list of table names
*/
protected static function getTablesReplaceList($tableList, $pattern, $replacement)
{
$result = array();
if (count($tableList) == 0) {
return $result;
}
sort($tableList);
$newNames = $tableList;
foreach ($tableList as $index => $oldName) {
$newName = substr(preg_replace($pattern, $replacement, $oldName), 0, 64); // Truncate too long table names
$nSuffix = 1;
while (in_array($newName, $newNames)) {
$suffix = '_' . base_convert((string) $nSuffix, 10, 36);
$newName = substr($newName, 0, -strlen($suffix)) . $suffix;
$nSuffix++;
}
$newNames[$index] = $newName;
$result[] = array(
'old' => $oldName,
'new' => $newName,
);
}
return $result;
}
/**
* Replace table name with regex
*
* @param string $pattern regex pattern
* @param string $replacement regex replacement
* @param array<string,mixed> $options options
*
* @return void
*/
public function pregReplaceTableName($pattern, $replacement, $options = array())
{
$this->dbConnection();
$options = array_merge(array(
'exclude' => array(), // exclude table list,
'prefixFilter' => false,
'regexFilter' => false, // filter tables with regexp
'notRegexFilter' => false, // filter tables with not regexp
'regexTablesDropFkeys' => false,
'copyTables' => array(),// tables that needs to be copied instead of renamed
), $options);
$escapedDbName = mysqli_real_escape_string($this->dbh, PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_NAME));
$tablesIn = 'Tables_in_' . $escapedDbName;
$where = ' WHERE TRUE';
if ($options['prefixFilter'] !== false) {
$where .= ' AND `' . $tablesIn . '` NOT REGEXP "^' . mysqli_real_escape_string($this->dbh, SnapDB::quoteRegex($options['prefixFilter'])) . '.+"';
}
if ($options['regexFilter'] !== false) {
$where .= ' AND `' . $tablesIn . '` REGEXP "' . mysqli_real_escape_string($this->dbh, $options['regexFilter']) . '"';
}
if ($options['notRegexFilter'] !== false) {
$where .= ' AND `' . $tablesIn . '` NOT REGEXP "' . mysqli_real_escape_string($this->dbh, $options['notRegexFilter']) . '"';
}
$tablesList = DUPX_DB::queryColumnToArray($this->dbh, 'SHOW TABLES FROM `' . $escapedDbName . '`' . $where);
if (is_array($options['exclude'])) {
$tablesList = array_diff($tablesList, $options['exclude']);
}
$this->rename_tbl_log = 0;
if (count($tablesList) == 0) {
return;
}
$replaceList = self::getTablesReplaceList($tablesList, $pattern, $replacement);
DUPX_DB::mysqli_query($this->dbh, "SET FOREIGN_KEY_CHECKS = 0;");
foreach ($replaceList as $replace) {
$table = $replace['old'];
$newName = $replace['new'];
if (in_array($table, $options['copyTables'])) {
$this->copyTable($table, $newName, true);
} else {
$this->renameTable($table, $newName, true);
}
$this->rename_tbl_log++;
}
if ($options['regexTablesDropFkeys'] !== false) {
Log::info('DROP FOREING KEYS');
$this->dropForeignKeys($options['regexTablesDropFkeys']);
}
DUPX_DB::mysqli_query($this->dbh, "SET FOREIGN_KEY_CHECKS = 1;");
}
/**
*
* @param false|string $tableNamePatten table name pattern
*
* @return array<array{tableName:string, fKeyName:string}>
*/
public function getForeinKeysData($tableNamePatten = false)
{
$this->dbConnection();
//SELECT CONSTRAINT_NAME FROM information_schema.table_constraints WHERE `CONSTRAINT_TYPE` = 'FOREIGN KEY AND constraint_schema = 'temp_db_test_1234' AND `TABLE_NAME` = 'renamed''
$escapedDbName = mysqli_real_escape_string($this->dbh, PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_NAME));
$escapePattenr = mysqli_real_escape_string($this->dbh, $tableNamePatten);
$where = " WHERE `CONSTRAINT_TYPE` = 'FOREIGN KEY' AND constraint_schema = '" . $escapedDbName . "'";
if ($tableNamePatten !== false) {
$where .= " AND `TABLE_NAME` REGEXP '" . $escapePattenr . "'";
}
if (($result = DUPX_DB::mysqli_query($this->dbh, "SELECT TABLE_NAME as tableName, CONSTRAINT_NAME as fKeyName FROM information_schema.table_constraints " . $where)) === false) {
Log::error('SQL ERROR:' . mysqli_error($this->dbh));
}
return $result->fetch_all(MYSQLI_ASSOC);
}
/**
*
* @param false|string $tableNamePatten table name pattern
*
* @return boolean
*/
public function dropForeignKeys($tableNamePatten = false)
{
foreach ($this->getForeinKeysData($tableNamePatten) as $fKeyData) {
$escapedTableName = mysqli_real_escape_string($this->dbh, $fKeyData['tableName']);
$escapedFKeyName = mysqli_real_escape_string($this->dbh, $fKeyData['fKeyName']);
if (DUPX_DB::mysqli_query($this->dbh, 'ALTER TABLE `' . $escapedTableName . '` DROP CONSTRAINT `' . $escapedFKeyName . '`') === false) {
Log::error('SQL ERROR:' . mysqli_error($this->dbh));
}
}
return true;
}
/**
* Copy table
*
* @param string $existing_name existing table name
* @param string $new_name new table name
* @param bool $delete_if_conflict delete table if conflict
*
* @return void
*/
public function copyTable($existing_name, $new_name, $delete_if_conflict = false)
{
$this->dbConnection();
DUPX_DB::copyTable($this->dbh, $existing_name, $new_name, $delete_if_conflict);
}
/**
* Rename table
*
* @param string $existing_name existing table name
* @param string $new_name new table name
* @param bool $delete_if_conflict delete table if conflict
*
* @return void
*/
public function renameTable($existing_name, $new_name, $delete_if_conflict = false)
{
$this->dbConnection();
DUPX_DB::renameTable($this->dbh, $existing_name, $new_name, $delete_if_conflict);
}
/**
* Drop table
*
* @param string $name table name
*
* @return void
*/
public function dropTable($name)
{
$this->dbConnection();
DUPX_DB::dropTable($this->dbh, $name);
}
/**
*
* @param string $prefix table prefix
*
* @return false|array<array{id:int,user_login:string}>
*/
public function getAdminUsers($prefix)
{
$escapedPrefix = mysqli_real_escape_string($this->dbh, $prefix);
$userTable = mysqli_real_escape_string($this->dbh, $this->getUserTableName($prefix));
$userMetaTable = mysqli_real_escape_string($this->dbh, $this->getUserMetaTableName($prefix));
$sql = 'SELECT `' . $userTable . '`.`id` AS id, `' . $userTable . '`.`user_login` AS user_login FROM `' . $userTable . '` '
. 'INNER JOIN `' . $userMetaTable . '` ON ( `' . $userTable . '`.`id` = `' . $userMetaTable . '`.`user_id` ) '
. 'WHERE `' . $userMetaTable . '`.`meta_key` = "' . $escapedPrefix . 'capabilities" AND `' . $userMetaTable . '`.`meta_value` LIKE "%\"administrator\"%" '
. 'ORDER BY user_login ASC';
if (($queryResult = DUPX_DB::mysqli_query($this->dbh, $sql)) === false) {
return false;
}
$result = array();
while ($row = $queryResult->fetch_assoc()) {
$result[] = [
'id' => (int) $row['id'],
'user_login' => $row['user_login'],
];
}
return $result;
}
/**
* Returns the Duplicator Pro version if it exists, otherwise false
*
* @param string $prefix table prefix
*
* @return false|string Duplicator Pro version
*/
public function getDuplicatorVersion($prefix)
{
$optionsTable = self::getOptionsTableName($prefix);
$sql = "SELECT `option_value` FROM `{$optionsTable}` WHERE `option_name` = 'duplicator_pro_plugin_version'";
if (($queryResult = DUPX_DB::mysqli_query($this->dbh, $sql)) === false || $queryResult->num_rows === 0) {
return false;
}
$row = $queryResult->fetch_row();
return $row[0];
}
/**
* Return ustat identifier
*
* @param string $prefix table prefix
*
* @return string ustat identifier
*/
public function getUstatIdentifier($prefix)
{
$optionsTable = self::getOptionsTableName($prefix);
$sql = "SELECT `option_value` FROM `{$optionsTable}` WHERE `option_name` = 'duplicator_pro_plugin_data_stats'";
if (($queryResult = DUPX_DB::mysqli_query($this->dbh, $sql)) === false || $queryResult->num_rows === 0) {
return '';
}
$dataStat = $queryResult->fetch_row();
$dataStat = json_decode($dataStat[0], true);
return isset($dataStat['identifier']) ? $dataStat['identifier'] : '';
}
/**
*
* @param int $userId user id
* @param null|string $prefix table prefix, if null take wp table prefix by default
*
* @return boolean
*/
public function updatePostsAuthor($userId, $prefix = null)
{
$this->dbConnection();
//UPDATE `i5tr4_posts` SET `post_author` = 7 WHERE TRUE
$postsTable = mysqli_real_escape_string($this->dbh, $this->getPostsTableName($prefix));
$sql = 'UPDATE `' . $postsTable . '` SET `post_author` = ' . ((int) $userId) . ' WHERE TRUE';
Log::info('EXECUTE QUERY ' . $sql);
if (($result = DUPX_DB::mysqli_query($this->dbh, $sql)) === false) {
return false;
}
return true;
}
/**
*
* @return string[] Array of tables to be excluded
*/
public static function getExcludedTables()
{
$excludedTables = array();
if (ParamDescUsers::getUsersMode() !== ParamDescUsers::USER_MODE_OVERWRITE) {
$overwriteData = PrmMng::getInstance()->getValue(PrmMng::PARAM_OVERWRITE_SITE_DATA);
$excludedTables[] = self::getUserTableName($overwriteData['table_prefix']);
$excludedTables[] = self::getUserMetaTableName($overwriteData['table_prefix']);
}
return $excludedTables;
}
}

View File

@@ -0,0 +1,743 @@
<?php
/**
* Lightweight abstraction layer for common simple database routines
*
* Standard: PSR-2
*
* @package SC\DUPX\DB
* @link http://www.php-fig.org/psr/psr-2/
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Utils\Log\Log;
class DUPX_DB
{
const DELETE_CHUNK_SIZE = 500;
const MYSQLI_CLIENT_NO_FLAGS = 0;
const DB_CONNECTION_FLAG_NOT_SET = -1;
/**
* Modified version of https://developer.wordpress.org/reference/classes/wpdb/db_connect/
*
* @param string $host The server host name
* @param string $username The server DB user name
* @param string $password The server DB password
* @param string $dbname The server DB name
* @param int $flag Extra flags for connection
*
* @return mysqli|null Database connection handle
*/
public static function connect($host, $username, $password, $dbname = null, $flag = self::MYSQLI_CLIENT_NO_FLAGS)
{
try {
$port = null;
$socket = null;
$is_ipv6 = false;
$host_data = self::parseDBHost($host);
if ($host_data) {
list($host, $port, $socket, $is_ipv6) = $host_data;
}
/*
* If using the `mysqlnd` library, the IPv6 address needs to be
* enclosed in square brackets, whereas it doesn't while using the
* `libmysqlclient` library.
* @see https://bugs.php.net/bug.php?id=67563
*/
if ($is_ipv6 && extension_loaded('mysqlnd')) {
$host = "[$host]";
}
$dbh = mysqli_init();
@mysqli_real_connect($dbh, $host, $username, $password, null, $port, $socket, $flag);
if ($dbh->connect_errno) {
$dbh = null;
Log::info('DATABASE CONNECTION ERROR: ' . mysqli_connect_error() . '[ERRNO:' . mysqli_connect_errno() . ']');
} else {
if (method_exists($dbh, 'options')) {
$dbh->options(MYSQLI_OPT_LOCAL_INFILE, 'disable');
}
}
if (!empty($dbname)) {
if (mysqli_select_db($dbh, mysqli_real_escape_string($dbh, $dbname)) == false) {
Log::info('DATABASE SELECT DB ERROR: ' . $dbname . ' BUT IS CONNECTED SO CONTINUE');
}
}
} catch (Exception $e) {
Log::info('DATABASE CONNECTION EXCEPTION ERROR: ' . $e->getMessage());
return null;
}
return $dbh;
}
/**
* Modified version of https://developer.wordpress.org/reference/classes/wpdb/parse_db_host/
* Return Array containing the host, the port, the socket and whether it is an IPv6 address, in that order. If $host couldn't be parsed, returns false
*
* @param string $host The DB_HOST setting to parse
*
* @return false|array{0:string,1:?int,2:?string,3:bool}
*/
public static function parseDBHost($host)
{
$port = null;
$socket = null;
$is_ipv6 = false;
// First peel off the socket parameter from the right, if it exists.
$socket_pos = strpos($host, ':/');
if (false !== $socket_pos) {
$socket = substr($host, $socket_pos + 1);
$host = substr($host, 0, $socket_pos);
}
// We need to check for an IPv6 address first.
// An IPv6 address will always contain at least two colons.
if (substr_count($host, ':') > 1) {
$pattern = '#^(?:\[)?(?P<host>[0-9a-fA-F:]+)(?:\]:(?P<port>[\d]+))?#';
$is_ipv6 = true;
} else {
// We seem to be dealing with an IPv4 address.
$pattern = '#^(?P<host>[^:/]*)(?::(?P<port>[\d]+))?#';
}
$matches = array();
$result = preg_match($pattern, $host, $matches);
if (1 !== $result) {
// Couldn't parse the address, bail.
return false;
}
$host = '';
foreach (array('host', 'port') as $component) {
if (!empty($matches[$component])) {
$$component = $matches[$component];
}
}
return array(
$host,
$port,
$socket,
$is_ipv6,
);
}
/**
*
* @param string $host The server host name
* @param string $username The server DB user name
* @param string $password The server DB password
* @param string $dbname The server DB name
*
* @return boolean
*/
public static function testConnection($host, $username, $password, $dbname = '')
{
if (($dbh = DUPX_DB::connect($host, $username, $password, $dbname))) {
mysqli_close($dbh);
return true;
} else {
return false;
}
}
/**
* Count the tables in a given database
*
* @param mysqli $dbh A valid database link handle
* @param string $dbname Database to count tables in
*
* @return int The number of tables in the database
*/
public static function countTables($dbh, $dbname)
{
$res = self::mysqli_query($dbh, "SELECT COUNT(*) AS count FROM information_schema.tables WHERE table_schema = '" . mysqli_real_escape_string($dbh, $dbname) . "' ");
$row = mysqli_fetch_row($res);
return is_null($row) ? 0 : $row[0];
}
/**
* Returns the number of rows in a table
*
* @param mysqli $dbh A valid database link handle
* @param string $name A valid table name
*
* @return int The number of rows in the table
*/
public static function countTableRows($dbh, $name)
{
$total = self::mysqli_query($dbh, "SELECT COUNT(*) FROM `" . mysqli_real_escape_string($dbh, $name) . "`");
if ($total) {
$total = @mysqli_fetch_array($total);
return $total[0];
} else {
return 0;
}
}
/**
* Get default character set
*
* @param mysqli $dbh A valid database link handle
*
* @return string Default charset
*/
public static function getDefaultCharSet($dbh)
{
static $defaultCharset = null;
if (is_null($defaultCharset)) {
$query = 'SHOW VARIABLES LIKE "character_set_database"';
if (($result = self::mysqli_query($dbh, $query))) {
if (($row = $result->fetch_assoc())) {
$defaultCharset = $row["Value"];
}
$result->free();
} else {
$defaultCharset = '';
}
}
return $defaultCharset;
}
/**
* Get Supported charset list
*
* @param mysqli $dbh A valid database link handle
*
* @return string[] Supported charset list
*/
public static function getSupportedCharSetList($dbh)
{
static $charsetList = null;
if (is_null($charsetList)) {
$charsetList = array();
$query = "SHOW CHARACTER SET;";
if (($result = self::mysqli_query($dbh, $query))) {
while ($row = $result->fetch_assoc()) {
$charsetList[] = $row["Charset"];
}
$result->free();
}
sort($charsetList);
}
return $charsetList;
}
/**
* Get Supported collations along with character set
*
* @param mysqli $dbh A valid database link handle
*
* @return array<array{Collation:string,Charset:string,Id:int,Default:string,Sortlen:int}>
*/
public static function getSupportedCollates($dbh)
{
static $collations = null;
if (is_null($collations)) {
$collations = array();
$query = "SHOW COLLATION";
if (($result = self::mysqli_query($dbh, $query))) {
while ($row = $result->fetch_assoc()) {
$collations[] = $row;
}
$result->free();
}
usort($collations, function ($a, $b) {
return strcmp($a['Collation'], $b['Collation']);
});
}
return $collations;
}
/**
* Get Supported collations along with character set
*
* @param mysqli $dbh A valid database link handle
*
* @return string[] Supported collation
*/
public static function getSupportedCollateList($dbh)
{
static $collates = null;
if (is_null($collates)) {
$collates = array();
$query = "SHOW COLLATION";
if (($result = self::mysqli_query($dbh, $query))) {
while ($row = $result->fetch_assoc()) {
$collates[] = $row['Collation'];
}
$result->free();
}
sort($collates);
}
return $collates;
}
/**
* Returns the database names as an array
*
* @param mysqli $dbh A valid database link handle
* @param string $dbuser An optional dbuser name to search by
*
* @return string[] A list of all database names
*/
public static function getDatabases($dbh, $dbuser = '')
{
$sql = strlen($dbuser) ? "SHOW DATABASES LIKE '%" . mysqli_real_escape_string($dbh, $dbuser) . "%'" : 'SHOW DATABASES';
$query = self::mysqli_query($dbh, $sql);
if ($query) {
while ($db = @mysqli_fetch_array($query)) {
$all_dbs[] = $db[0];
}
if (isset($all_dbs) && is_array($all_dbs)) {
return $all_dbs;
}
}
return array();
}
/**
* Check if database exists
*
* @param mysqli $dbh DB connection
* @param string $dbname database name
*
* @return bool
*/
public static function databaseExists($dbh, $dbname)
{
$sql = 'SELECT COUNT(SCHEMA_NAME) AS databaseExists ' .
'FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = "' . mysqli_real_escape_string($dbh, $dbname) . '"';
$res = self::mysqli_query($dbh, $sql);
$row = mysqli_fetch_row($res);
return (!is_null($row) && $row[0] >= 1);
}
/**
* Check if table exists
*
* @param mysqli $dbh A valid database link handle
* @param string $tablename Table name to check for
*
* @return bool Whether or not if given table exists
*/
public static function tableExists($dbh, $tablename)
{
$query = self::mysqli_query($dbh, "SHOW TABLES LIKE '" . mysqli_real_escape_string($dbh, $tablename) . "'");
return $query && mysqli_num_rows($query) == 1;
}
/**
* Select database if exists
*
* @param mysqli $dbh DB connection
* @param string $dbname database name
*
* @return bool false on failure
*/
public static function selectDB($dbh, $dbname)
{
if (!self::databaseExists($dbh, $dbname)) {
return false;
}
return mysqli_select_db($dbh, $dbname);
}
/**
* Returns the tables for a database as an array
*
* @param mysqli $dbh A valid database link handle
*
* @return string[] A list of all table names
*/
public static function getTables(mysqli $dbh)
{
$query = self::mysqli_query($dbh, 'SHOW TABLES');
if ($query) {
$all_tables = array();
while ($table = @mysqli_fetch_array($query)) {
$all_tables[] = $table[0];
}
return $all_tables;
}
return array();
}
/**
* Get the requested MySQL system variable
*
* @param mysqli $dbh A valid database link handle
* @param string $name The database variable name to lookup
* @param mixed $default default value if query fail
*
* @return mixed the server variable to query for
*/
public static function getVariable($dbh, $name, $default = null)
{
if (($result = self::mysqli_query($dbh, "SHOW VARIABLES LIKE '" . mysqli_real_escape_string($dbh, $name) . "'")) == false) {
return $default;
}
$row = @mysqli_fetch_array($result);
@mysqli_free_result($result);
return isset($row[1]) ? $row[1] : $default;
}
/**
* Gets the MySQL database version number
*
* @param mysqli $dbh A valid database link handle
* @param bool $full True: Gets the full version
* False: Gets only the numeric
* portion i.e. 5.5.6 or 10.1.2
* (for MariaDB)
*
* @return string '0' on failure, version number on success
*/
public static function getVersion($dbh, $full = false)
{
if ($full) {
$version = self::getVariable($dbh, 'version', '');
} else {
$version = preg_replace('/[^0-9.].*/', '', self::getVariable($dbh, 'version', ''));
}
//Fall-back for servers that have restricted SQL for SHOW statement
//Note: For MariaDB this will report something like 5.5.5 when it is really 10.2.1.
//This mainly is due to mysqli_get_server_info method which gets the version comment
//and uses a regex vs getting just the int version of the value. So while the former
//code above is much more accurate it may fail in rare situations
if (empty($version)) {
$version = mysqli_get_server_info($dbh);
$version = preg_replace('/[^0-9.].*/', '', $version);
}
return empty($version) ? '0' : $version;
}
/**
* Determine if a MySQL database supports a particular feature
*
* @param mysqli $dbh Database connection handle
* @param string $feature the feature to check for
*
* @return bool
*/
public static function hasAbility($dbh, $feature)
{
$version = self::getVersion($dbh);
switch (strtolower($feature)) {
case 'collation':
case 'group_concat':
case 'subqueries':
return version_compare($version, '4.1', '>=');
case 'set_charset':
return version_compare($version, '5.0.7', '>=');
};
return false;
}
/**
* Runs a query and returns the results as an array with the column names
*
* @param mysqli $dbh A valid database link handle
* @param string $sql The sql to run
* @param int $column_index The column index to use as the key
*
* @return scalar[] The result of the query as an array with the column name as the key
*/
public static function queryColumnToArray($dbh, $sql, $column_index = 0)
{
$result_array = array();
$full_result_array = self::queryToArray($dbh, $sql);
for ($i = 0; $i < count($full_result_array); $i++) {
$result_array[] = $full_result_array[$i][$column_index];
}
return $result_array;
}
/**
* Runs a query with no result
*
* @param mysqli $dbh A valid database link handle
* @param string $sql The sql to run
*
* @return scalar[][] The result of the query as an array
*/
public static function queryToArray($dbh, $sql)
{
$result = array();
$query_result = self::mysqli_query($dbh, $sql);
if ($query_result !== false) {
if (mysqli_num_rows($query_result) > 0) {
while ($row = mysqli_fetch_row($query_result)) {
$result[] = $row;
}
}
} else {
$error = mysqli_error($dbh);
throw new Exception("Error executing query {$sql}.<br/>{$error}");
}
return $result;
}
/**
* Runs a query with no result
*
* @param mysqli $dbh A valid database link handle
* @param string $sql The sql to run
*
* @return void
*/
public static function queryNoReturn($dbh, $sql)
{
if (self::mysqli_query($dbh, $sql) === false) {
$error = mysqli_error($dbh);
throw new Exception("Error executing query {$sql}.<br/>{$error}");
}
}
/**
* Drops the table given
*
* @param mysqli $dbh A valid database link handle
* @param string $name A valid table name to remove
*
* @return void
*/
public static function dropTable($dbh, $name)
{
Log::info('DROP TABLE ' . $name, Log::LV_DETAILED);
$escapedName = mysqli_real_escape_string($dbh, $name);
self::queryNoReturn($dbh, 'DROP TABLE IF EXISTS `' . $escapedName . '`');
}
/**
* Empty the table given
*
* @param mysqli $dbh A valid database link handle
* @param string $name A valid table name to remove
*
* @return void
*/
public static function emptyTable($dbh, $name)
{
Log::info('TRUNCATE TABLE ' . $name, Log::LV_DETAILED);
$escapedName = mysqli_real_escape_string($dbh, $name);
self::queryNoReturn($dbh, 'TRUNCATE TABLE `' . $escapedName . '`');
}
/**
* Renames an existing table
*
* @param mysqli $dbh A valid database link handle
* @param string $existing_name The current tables name
* @param string $new_name The new table name to replace the existing name
* @param bool $delete_if_conflict Delete the table name if there is a conflict
*
* @return void
*/
public static function renameTable($dbh, $existing_name, $new_name, $delete_if_conflict = false)
{
if ($delete_if_conflict) {
self::dropTable($dbh, $new_name);
}
Log::info('RENAME TABLE ' . $existing_name . ' TO ' . $new_name);
$escapedOldName = mysqli_real_escape_string($dbh, $existing_name);
$escapedNewName = mysqli_real_escape_string($dbh, $new_name);
self::queryNoReturn($dbh, 'RENAME TABLE `' . $escapedOldName . '` TO `' . $escapedNewName . '`');
}
/**
* Renames an existing table
*
* @param mysqli $dbh A valid database link handle
* @param string $existing_name The current tables name
* @param string $new_name The new table name to replace the existing name
* @param bool $delete_if_conflict Delete the table name if there is a conflict
*
* @return void
*/
public static function copyTable($dbh, $existing_name, $new_name, $delete_if_conflict = false)
{
if ($delete_if_conflict) {
self::dropTable($dbh, $new_name);
}
Log::info('COPY TABLE ' . $existing_name . ' TO ' . $new_name);
$escapedOldName = mysqli_real_escape_string($dbh, $existing_name);
$escapedNewName = mysqli_real_escape_string($dbh, $new_name);
self::queryNoReturn($dbh, 'CREATE TABLE `' . $escapedNewName . '` LIKE `' . $escapedOldName . '`');
self::queryNoReturn($dbh, 'INSERT INTO `' . $escapedNewName . '` SELECT * FROM `' . $escapedOldName . '`');
}
/**
* Sets the MySQL connection's character set.
*
* @param mysqli $dbh The resource given by mysqli_connect
* @param ?string $charset The character set, null default value
* @param ?string $collate The collation, null default value
*
* @return bool
*/
public static function setCharset($dbh, $charset = null, $collate = null)
{
if (!self::hasAbility($dbh, 'collation')) {
return false;
}
$charset = (!isset($charset) ) ? $GLOBALS['DBCHARSET_DEFAULT'] : $charset;
$collate = (!isset($collate) ) ? '' : $collate;
if (empty($charset)) {
return true;
}
if (function_exists('mysqli_set_charset') && self::hasAbility($dbh, 'set_charset')) {
try {
if (($result1 = mysqli_set_charset($dbh, $charset)) === false) {
$errMsg = mysqli_error($dbh);
Log::info('DATABASE ERROR: mysqli_set_charset ' . Log::v2str($charset) . ' MSG: ' . $errMsg);
} else {
Log::info('DATABASE: mysqli_set_charset ' . Log::v2str($charset), Log::LV_DETAILED);
}
} catch (Exception $e) {
Log::info('DATABASE ERROR: mysqli_set_charset ' . Log::v2str($charset) . ' MSG: ' . $e->getMessage());
$result1 = false;
}
if (!empty($collate)) {
$sql = "SET collation_connection = " . mysqli_real_escape_string($dbh, $collate);
if (($result2 = self::mysqli_query($dbh, $sql)) === false) {
$errMsg = mysqli_error($dbh);
Log::info('DATABASE ERROR: SET collation_connection ' . Log::v2str($collate) . ' MSG: ' . $errMsg);
} else {
Log::info('DATABASE: SET collation_connection ' . Log::v2str($collate), Log::LV_DETAILED);
}
} else {
$result2 = true;
}
return $result1 && $result2;
} else {
$sql = " SET NAMES " . mysqli_real_escape_string($dbh, $charset);
if (!empty($collate)) {
$sql .= " COLLATE " . mysqli_real_escape_string($dbh, $collate);
}
if (($result = self::mysqli_query($dbh, $sql)) === false) {
$errMsg = mysqli_error($dbh);
Log::info('DATABASE SQL ERROR: ' . Log::v2str($sql) . ' MSG: ' . $errMsg);
} else {
Log::info('DATABASE SQL: ' . Log::v2str($sql), Log::LV_DETAILED);
}
return $result;
}
}
/**
*
* @param mysqli $dbh The resource given by mysqli_connect\
*
* @return bool|string return false if current database isent selected or the string name
*/
public static function getCurrentDatabase($dbh)
{
// SELECT DATABASE() as db;
if (($result = self::mysqli_query($dbh, 'SELECT DATABASE() as db')) === false) {
return false;
}
$assoc = $result->fetch_assoc();
return isset($assoc['db']) ? $assoc['db'] : false;
}
/**
* mysqli_query wrapper with logging
*
* @param mysqli $link db connection
* @param string $query query string
* @param int $logFailLevel Write in the log only if the log level is equal to or greater than level
* @param int $resultmode The result mode can be one of 3 constants indicating how the result will be returned from the MySQL server.
*
* @return mysqli_result|bool For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries, mysqli_query() will return a mysqli_result object.
* For other successful queries mysqli_query() will return TRUE. Returns FALSE on failure
*/
public static function mysqli_query(
mysqli $link,
$query,
$logFailLevel = Log::LV_DEFAULT,
$resultmode = MYSQLI_STORE_RESULT
) {
try {
$result = mysqli_query($link, $query, $resultmode);
} catch (Exception $e) {
$result = false;
}
self::query_log_callback($link, $result, $query, $logFailLevel);
return $result;
}
/**
* Query log callback
*
* @param mysqli $link db connection
* @param mysqli_result|bool $result mysqli_result object or false on failure
* @param string $query query string
* @param int $logFailLevel ENUM Log::LV_*
*
* @return void
*/
public static function query_log_callback(mysqli $link, $result, $query, $logFailLevel = Log::LV_DEFAULT)
{
if ($result === false) {
if (Log::isLevel($logFailLevel)) {
$callers = debug_backtrace(); // phpcs:ignore PHPCompatibility.FunctionUse.ArgumentFunctionsReportCurrentValue.NeedsInspection
$file = $callers[0]['file'];
$line = $callers[0]['line'];
$queryLog = substr($query, 0, Log::isLevel(Log::LV_DEBUG) ? 10000 : 500);
Log::info('DB QUERY [ERROR][' . $file . ':' . $line . '] MSG: ' . mysqli_error($link) . "\n\tSQL: " . $queryLog);
Log::info(Log::traceToString($callers, 1));
}
} else {
if (Log::isLevel(Log::LV_HARD_DEBUG)) {
$callers = debug_backtrace(); // phpcs:ignore PHPCompatibility.FunctionUse.ArgumentFunctionsReportCurrentValue.NeedsInspection
$file = $callers[0]['file'];
$line = $callers[0]['line'];
Log::info('DB QUERY [' . $file . ':' . $line . ']: ' . Log::v2str(substr($query, 0, 2000)), Log::LV_HARD_DEBUG);
}
}
}
/**
* Chunks delete
*
* @param mysqli $dbh database connection
* @param string $table table name
* @param string $where where contidions
*
* @return int affected rows
*/
public static function chunksDelete($dbh, $table, $where)
{
$sql = 'DELETE FROM ' . mysqli_real_escape_string($dbh, $table) . ' WHERE ' . $where . ' LIMIT ' . self::DELETE_CHUNK_SIZE;
$totalAffectedRows = 0;
do {
DUPX_DB::queryNoReturn($dbh, $sql);
$affectRows = mysqli_affected_rows($dbh);
$totalAffectedRows += $affectRows;
} while ($affectRows >= self::DELETE_CHUNK_SIZE);
return $totalAffectedRows;
}
}

View File

@@ -0,0 +1,457 @@
<?php
/**
* database table item descriptor
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Core\InstState;
use Duplicator\Installer\Core\Params\Descriptors\ParamDescMultisite;
use Duplicator\Installer\Core\Params\Descriptors\ParamDescUsers;
use Duplicator\Installer\Core\Params\Models\SiteOwrMap;
use Duplicator\Installer\Core\Params\PrmMng;
use Duplicator\Libs\Snap\SnapWP;
/**
* This class manages the installer table, all table management refers to the table name in the original site.
*/
class DUPX_DB_Table_item
{
/** @var string */
protected $originalName = '';
/** @var string */
protected $tableWithoutPrefix = '';
/** @var int */
protected $rows = 0;
/** @var int */
protected $size = 0;
/** @var bool */
protected $havePrefix = false;
/** @var int */
protected $subsiteId = -1;
/** @var string */
protected $subsitePrefix = '';
/**
*
* @param string $name table name
* @param int $rows number of rows
* @param int $size size in bytes
*/
public function __construct($name, $rows = 0, $size = 0)
{
if (strlen($this->originalName = $name) == 0) {
throw new Exception('The table name can\'t be empty.');
}
$this->rows = max(0, (int) $rows);
$this->size = max(0, (int) $size);
$oldPrefix = DUPX_ArchiveConfig::getInstance()->wp_tableprefix;
if (strlen($oldPrefix) === 0) {
$this->havePrefix = true;
$this->tableWithoutPrefix = $this->originalName;
} if (strpos($this->originalName, $oldPrefix) === 0) {
$this->havePrefix = true;
$this->tableWithoutPrefix = substr($this->originalName, strlen($oldPrefix));
} else {
$this->havePrefix = false;
$this->tableWithoutPrefix = $this->originalName;
}
if (DUPX_ArchiveConfig::getInstance()->isNetwork() && $this->havePrefix) {
$matches = null;
if (preg_match('/^(' . preg_quote($oldPrefix, '/') . '(\d+)_)(.+)/', $this->originalName, $matches)) {
$this->subsitePrefix = $matches[1];
$this->subsiteId = (int) $matches[2];
$this->tableWithoutPrefix = $matches[3]; // update tabel without prefix without subsite prefix
} elseif (in_array($this->tableWithoutPrefix, SnapWP::getMultisiteTables())) {
$this->subsiteId = -1;
} else {
$this->subsiteId = 1;
$this->subsitePrefix = $oldPrefix;
}
} else {
$this->subsiteId = 1;
$this->subsitePrefix = $oldPrefix;
}
}
/**
* return the original talbe name in source site
*
* @return string
*/
public function getOriginalName()
{
return $this->originalName;
}
/**
* return table name without prefix, if the table has no prefix then the original name returns.
*
* @param bool $includeSubsiteId if true then the subsite id is included in the name
*
* @return string
*/
public function getNameWithoutPrefix($includeSubsiteId = false)
{
return (($includeSubsiteId && $this->subsiteId > 1) ? $this->subsiteId . '_' : '') . $this->tableWithoutPrefix;
}
/**
*
* @param array{oldPrefix:string,newPrefix:string,commonPart:string} $diffData output
*
* @return boolean
*/
public function isDiffPrefix(&$diffData)
{
$oldPos = strlen(($oldName = $this->getOriginalName()));
$newPos = strlen(($newName = $this->getNewName()));
if ($oldName == $newName) {
$diffData = array(
'oldPrefix' => '',
'newPrefix' => '',
'commonPart' => $oldName,
);
return false;
}
while ($oldPos > 0 && $newPos > 0) {
if ($oldName[$oldPos - 1] != $newName[$newPos - 1]) {
break;
}
$oldPos--;
$newPos--;
}
$diffData = array(
'oldPrefix' => substr($oldName, 0, $oldPos),
'newPrefix' => substr($newName, 0, $newPos),
'commonPart' => substr($oldName, $oldPos),
);
return true;
}
/**
*
* @return bool
*/
public function havePrefix()
{
return $this->havePrefix;
}
/**
* return new name extracted on target site
*
* @return string
*/
public function getNewName()
{
if (!$this->canBeExctracted()) {
return '';
}
if (!$this->havePrefix) {
return $this->originalName;
}
$paramsManager = PrmMng::getInstance();
switch (InstState::getInstType()) {
case InstState::TYPE_SINGLE:
case InstState::TYPE_MSUBDOMAIN:
case InstState::TYPE_MSUBFOLDER:
case InstState::TYPE_RBACKUP_SINGLE:
case InstState::TYPE_RBACKUP_MSUBDOMAIN:
case InstState::TYPE_RBACKUP_MSUBFOLDER:
case InstState::TYPE_RECOVERY_SINGLE:
case InstState::TYPE_RECOVERY_MSUBDOMAIN:
case InstState::TYPE_RECOVERY_MSUBFOLDER:
return $paramsManager->getValue(PrmMng::PARAM_DB_TABLE_PREFIX) . $this->getNameWithoutPrefix(true);
case InstState::TYPE_STANDALONE:
if (
$this->subsiteId === $paramsManager->getValue(PrmMng::PARAM_SUBSITE_ID) &&
$this->subsiteId > 1
) {
// convert standalon subsite prefix
return $paramsManager->getValue(PrmMng::PARAM_DB_TABLE_PREFIX) . $this->getNameWithoutPrefix(false);
} else {
return $paramsManager->getValue(PrmMng::PARAM_DB_TABLE_PREFIX) . $this->getNameWithoutPrefix(true);
}
case InstState::TYPE_SINGLE_ON_SUBDOMAIN:
case InstState::TYPE_SINGLE_ON_SUBFOLDER:
case InstState::TYPE_SUBSITE_ON_SUBDOMAIN:
case InstState::TYPE_SUBSITE_ON_SUBFOLDER:
if ($this->isUserTable()) {
return $paramsManager->getValue(PrmMng::PARAM_DB_TABLE_PREFIX) . $this->getNameWithoutPrefix(false);
}
if ($this->subsiteId <= 0) {
throw new Exception('Curretn talbe site id isn\'t defined');
}
if (($map = ParamDescMultisite::getOwrMapBySourceId($this->subsiteId)) == false) {
throw new Exception('Map by id ' . $this->subsiteId . ' don\'t exists');
}
switch ($map->getTargetId()) {
case SiteOwrMap::NEW_SUBSITE_WITH_SLUG:
case SiteOwrMap::NEW_SUBSITE_WITH_FULL_DOMAIN:
// Site must be created
return '';
default:
break;
}
if (($targetInfo = $map->getTargetSiteInfo()) == false) {
throw new Exception('Target site info ' . $map->getTargetId() . ' don\'t exists');
}
return $targetInfo['blog_prefix'] . $this->getNameWithoutPrefix(false);
case InstState::TYPE_NOT_SET:
throw new Exception('Cannot change setup with current installation type [' . InstState::getInstType() . ']');
default:
throw new Exception('Unknown mode');
}
}
/**
*
* @return int
*/
public function getRows()
{
return $this->rows;
}
/**
* Return table size
*
* @param bool $formatted if true then return size in human readable format
*
* @return int|string
*/
public function getSize($formatted = false)
{
return $formatted ? DUPX_U::readableByteSize($this->size) : $this->size;
}
/**
* Get table subsite id
*
* @return int if -1 isn't a subsite sable
*/
public function getSubsisteId()
{
return $this->subsiteId;
}
/**
* Check if table can be extracted
*
* @return bool
*/
public function canBeExctracted()
{
if (InstState::isInstType(InstState::TYPE_STANDALONE)) {
return $this->standAloneExtractCheck();
}
if (InstState::isAddSiteOnMultisite()) {
return $this->addSiteOnMultisiteCheck();
}
if (InstState::isRestoreBackup()) {
return $this->restoreBackupCheck();
}
return true;
}
/**
* If false the current table create query is skipped
*
* @return bool
*/
public function createTable()
{
if ($this->usersTablesCreateCheck() === false) {
return false;
}
return true;
}
/**
* Check if create users table
*
* @return bool
*/
protected function usersTablesCreateCheck()
{
if (!$this->isUserTable()) {
return true;
}
return (ParamDescUsers::getUsersMode() !== ParamDescUsers::USER_MODE_IMPORT_USERS);
}
/**
* Return true if current table is user or usermeta table
*
* @return boolean
*/
public function isUserTable()
{
return (
$this->havePrefix &&
in_array(
$this->tableWithoutPrefix,
array(
DUPX_DB_Functions::TABLE_NAME_WP_USERS,
DUPX_DB_Functions::TABLE_NAME_WP_USERMETA,
)
)
);
}
/**
*
* @return boolean
*/
protected function standAloneExtractCheck()
{
if ($this->isUserTable()) {
return true;
}
// extract tables without prefix
if (!$this->havePrefix) {
return true;
}
$standaloneId = PrmMng::getInstance()->getValue(PrmMng::PARAM_SUBSITE_ID);
// exclude multisite tables
if ($this->subsiteId < 0) {
return false;
}
if ($standaloneId == 1) {
// exclude all subsites tables
if ($this->subsiteId > 1) {
return false;
}
} else {
if ($this->subsiteId > 1) {
// exclude all subsite tables except tables with id 1
if ($this->subsiteId != $standaloneId) {
return false;
}
} else {
if (in_array($this->tableWithoutPrefix, SnapWP::getSiteCoreTables())) {
// exclude wordpress common main tables
return false;
}
if (in_array($this->tableWithoutPrefix, DUPX_DB_Tables::getInstance()->getStandaoneTablesWithoutPrefix())) {
// I exclude the tables of the standalone site that will be converted into main tables
return false;
}
}
}
return true;
}
/**
* returns true if the table is to be extracted
*
* @return boolean
*/
protected function addSiteOnMultisiteCheck()
{
if ($this->isUserTable()) {
return true;
}
$originalPrefix = DUPX_ArchiveConfig::getInstance()->wp_tableprefix;
if ($this->originalName == DUPX_DB_Functions::getEntitiesTableName($originalPrefix)) {
return false;
}
if ($this->originalName == DUPX_DB_Functions::getPackagesTableName($originalPrefix)) {
return false;
}
return (ParamDescMultisite::getOwrMapBySourceId($this->subsiteId) !== false);
}
/**
* Returns true if the table is to be extracted
*
* @return boolean
*/
protected function restoreBackupCheck()
{
if (!$this->havePrefix || $this->tableWithoutPrefix != DUPX_DB_Functions::TABLE_NAME_DUPLICATOR_PACKAGES) {
return true;
}
$overwriteData = PrmMng::getInstance()->getValue(PrmMng::PARAM_OVERWRITE_SITE_DATA);
// Extract table only if don't exists on restore backup mode
return (!$overwriteData['packagesTableExists']);
}
/**
* returns true if the table is to be extracted
*
* @return boolean
*/
public function extract()
{
if (!$this->canBeExctracted()) {
return false;
}
$tablesVals = PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_TABLES);
if (!isset($tablesVals[$this->originalName])) {
throw new Exception('Table ' . $this->originalName . ' not in table vals');
}
return $tablesVals[$this->originalName]['extract'];
}
/**
* returns true if a search and replace is to be performed
*
* @return boolean
*/
public function replaceEngine()
{
if (!$this->extract()) {
return false;
}
$tablesVals = PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_TABLES);
if (!isset($tablesVals[$this->originalName])) {
throw new Exception('Table ' . $this->originalName . ' not in table vals');
}
return $tablesVals[$this->originalName]['replace'];
}
}

View File

@@ -0,0 +1,379 @@
<?php
/**
* Original installer files manager
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Utils\Log\Log;
use Duplicator\Installer\Core\Params\PrmMng;
use Duplicator\Installer\Core\Params\Items\ParamFormTables;
/**
* Original installer files manager
* singleton class
*/
final class DUPX_DB_Tables
{
/** @var ?self */
private static $instance = null;
/** @var DUPX_DB_Table_item[] */
private $tables = array();
/**
*
* @return self
*/
public static function getInstance()
{
if (is_null(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Class constructor
*/
private function __construct()
{
$confTables = (array) DUPX_ArchiveConfig::getInstance()->dbInfo->tablesList;
foreach ($confTables as $tableName => $tableInfo) {
$rows = ($tableInfo->insertedRows === false ? $tableInfo->inaccurateRows : $tableInfo->insertedRows);
$this->tables[$tableName] = new DUPX_DB_Table_item($tableName, $rows, $tableInfo->size);
}
Log::info('CONSTRUCT TABLES: ' . Log::v2str($this->tables), Log::LV_HARD_DEBUG);
}
/**
*
* @return DUPX_DB_Table_item[]
*/
public function getTables()
{
return $this->tables;
}
/**
*
* @return string[]
*/
public function getTablesNames()
{
return array_keys($this->tables);
}
/**
* get the list of extracted tables names
*
* @return string[]
*/
public function getNewTablesNames()
{
$result = array();
foreach ($this->tables as $tableObj) {
if (!$tableObj->extract()) {
continue;
}
$newName = $tableObj->getNewName();
if (strlen($newName) == 0) {
continue;
}
$result[] = $newName;
}
return $result;
}
/**
*
* @return string[]
*/
public function getReplaceTablesNames()
{
$result = array();
foreach ($this->tables as $tableObj) {
if (!$tableObj->replaceEngine()) {
continue;
}
$newName = $tableObj->getNewName();
if (strlen($newName) == 0) {
continue;
}
$result[] = $newName;
}
return $result;
}
/**
* Get tables new subsite table names
*
* @param int $subsiteId susbsit ID
*
* @return string[]
*/
public function getSubsiteTablesNewNames($subsiteId)
{
$result = array();
foreach ($this->tables as $tableObj) {
if (!$tableObj->extract()) {
continue;
}
if ($tableObj->getSubsisteId() != $subsiteId) {
continue;
}
$newName = $tableObj->getNewName();
if (strlen($newName) == 0) {
continue;
}
$result[] = $newName;
}
return $result;
}
/**
* Returns all tables that have a given name without prefix.
* for example all posts tables of a multisite if filter is equal to posts
*
* @param string $filter filter name
*
* @return string[]
*/
public function getTablesByNameWithoutPrefix($filter)
{
$result = array();
foreach ($this->tables as $tableObj) {
$newName = $tableObj->getNewName();
if (strlen($newName) == 0) {
continue;
}
if (
$tableObj->extract() &&
$tableObj->havePrefix() &&
$tableObj->getNameWithoutPrefix() == $filter
) {
$result[] = $newName;
}
}
return $result;
}
/**
* return list of current standalone site tables without prefix
*
* @return string[]
*/
public function getStandaoneTablesWithoutPrefix()
{
$standaloneTables = null;
if (is_null($standaloneTables)) {
$standaloneTables = array();
$standaloneId = PrmMng::getInstance()->getValue(PrmMng::PARAM_SUBSITE_ID);
foreach ($this->tables as $tableObj) {
if ($tableObj->getSubsisteId() === $standaloneId) {
$standaloneTables[] = $tableObj->getNameWithoutPrefix();
}
}
}
return $standaloneTables;
}
/**
* Retust tables to skip
*
* @return string[]
*/
public function getTablesToSkip()
{
$result = array();
foreach ($this->tables as $tableObj) {
if (!$tableObj->extract()) {
$result[] = $tableObj->getOriginalName();
}
}
return $result;
}
/**
* Restun lsit of tables where skip create but not insert
*
* @return string[]
*/
public function getTablesCreateSkip()
{
$result = array();
foreach ($this->tables as $tableObj) {
if ($tableObj->extract() && !$tableObj->createTable()) {
$result[] = $tableObj->getOriginalName();
}
}
return $result;
}
/**
* Get table object by table name
*
* @param string $table table name
*
* @return DUPX_DB_Table_item false if table don't exists
*/
public function getTableObjByName($table)
{
if (!isset($this->tables[$table])) {
throw new Exception('TABLE ' . $table . ' Isn\'t in list');
}
return $this->tables[$table];
}
/**
* Retrun rename tables mapping
*
* @return array<string,array<string,array<int, string>>>
*/
public function getRenameTablesMapping()
{
$mapping = array();
$diffData = array();
foreach ($this->tables as $tableObj) {
if (!$tableObj->extract()) {
// skip stable not extracted
continue;
}
if (!$tableObj->isDiffPrefix($diffData)) {
continue;
}
if (!isset($mapping[$diffData['oldPrefix']])) {
$mapping[$diffData['oldPrefix']] = array();
}
if (!isset($mapping[$diffData['oldPrefix']][$diffData['newPrefix']])) {
$mapping[$diffData['oldPrefix']][$diffData['newPrefix']] = array();
}
$mapping[$diffData['oldPrefix']][$diffData['newPrefix']][] = $diffData['commonPart'];
}
uksort($mapping, function ($a, $b) {
$lenA = strlen($a);
$lenB = strlen($b);
if ($lenA == $lenB) {
return 0;
} elseif ($lenA > $lenB) {
return -1;
} else {
return 1;
}
});
// maximise prefix length
$optimizedMapping = array();
$char = '';
foreach ($mapping as $oldPrefix => $newMapping) {
foreach ($newMapping as $newPrefix => $commons) {
for ($pos = 0; /* break inside */; $pos++) {
for ($current = 0; $current < count($commons); $current++) {
if (strlen($commons[$current]) <= $pos) {
break 2;
}
if ($current == 0) {
$char = $commons[$current][$pos];
continue;
}
if ($commons[$current][$pos] != $char) {
break 2;
}
}
}
$optOldPrefix = $oldPrefix . substr($commons[0], 0, $pos);
$optNewPrefix = $newPrefix . substr($commons[0], 0, $pos);
if (!isset($optimizedMapping[$optOldPrefix])) {
$optimizedMapping[$optOldPrefix] = array();
}
$optimizedMapping[$optOldPrefix][$optNewPrefix] = array_map(function ($val) use ($pos) {
return substr($val, $pos);
}, $commons);
}
}
return $optimizedMapping;
}
/**
* return param table default
*
* @return array<array{name: string, extract: bool, replace: bool}>
*/
public function getDefaultParamValue()
{
$result = array();
foreach ($this->tables as $table) {
$result[$table->getOriginalName()] = ParamFormTables::getParamItemValueFromData(
$table->getOriginalName(),
$table->canBeExctracted(),
$table->canBeExctracted()
);
}
return $result;
}
/**
* return param table default filtered
*
* @param string[] $filterTables Table names to filter
*
* @return array<string, array{name: string, extract: bool, replace: bool}>
*/
public function getFilteredParamValue($filterTables)
{
$result = array();
foreach ($this->tables as $table) {
$extract = !in_array($table->getOriginalName(), $filterTables) ? $table->canBeExctracted() : false;
$result[$table->getOriginalName()] = ParamFormTables::getParamItemValueFromData(
$table->getOriginalName(),
$extract,
$extract
);
}
return $result;
}
}

View File

@@ -0,0 +1,239 @@
<?php
/**
* custom hosting manager
* singleton class
*
* Standard: PSR-2
*
* @package SC\DUPX\DB
* @link http://www.php-fig.org/psr/psr-2/
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Core\Deploy\Plugins\PluginsManager;
use Duplicator\Installer\Core\InstState;
use Duplicator\Installer\Core\Params\Items\ParamForm;
use Duplicator\Installer\Core\Params\PrmMng;
use Duplicator\Libs\Snap\SnapWP;
require_once(DUPX_INIT . '/classes/host/interface.host.php');
require_once(DUPX_INIT . '/classes/host/class.godaddy.host.php');
require_once(DUPX_INIT . '/classes/host/class.wpengine.host.php');
require_once(DUPX_INIT . '/classes/host/class.wordpresscom.host.php');
require_once(DUPX_INIT . '/classes/host/class.liquidweb.host.php');
require_once(DUPX_INIT . '/classes/host/class.pantheon.host.php');
require_once(DUPX_INIT . '/classes/host/class.flywheel.host.php');
require_once(DUPX_INIT . '/classes/host/class.siteground.host.php');
class DUPX_Custom_Host_Manager
{
const HOST_GODADDY = 'godaddy';
const HOST_WPENGINE = 'wpengine';
const HOST_WORDPRESSCOM = 'wordpresscom';
const HOST_LIQUIDWEB = 'liquidweb';
const HOST_PANTHEON = 'pantheon';
const HOST_FLYWHEEL = 'flywheel';
const HOST_SITEGROUND = 'siteground';
/** @var ?self */
protected static $instance = null;
/**
* this var prevent multiple params inizialization.
* it's useful on development to prevent an infinite loop in class constructor
*
* @var bool
*/
private $initialized = false;
/**
* custom hostings list
*
* @var DUPX_Host_interface[]
*/
private $customHostings = array();
/**
*
* @return self
*/
public static function getInstance()
{
if (is_null(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
/**
* init custom histings
*/
private function __construct()
{
$this->customHostings[DUPX_WPEngine_Host::getIdentifier()] = new DUPX_WPEngine_Host();
$this->customHostings[DUPX_GoDaddy_Host::getIdentifier()] = new DUPX_GoDaddy_Host();
$this->customHostings[DUPX_WordpressCom_Host::getIdentifier()] = new DUPX_WordpressCom_Host();
$this->customHostings[DUPX_Liquidweb_Host::getIdentifier()] = new DUPX_Liquidweb_Host();
$this->customHostings[DUPX_Pantheon_Host::getIdentifier()] = new DUPX_Pantheon_Host();
$this->customHostings[DUPX_Flywheel_Host::getIdentifier()] = new DUPX_Flywheel_Host();
$this->customHostings[DUPX_Siteground_Host::getIdentifier()] = new DUPX_Siteground_Host();
}
/**
* execute the active custom hostings inizialization only one time.
*
* @return boolean
* @throws Exception
*/
public function init()
{
if ($this->initialized) {
return true;
}
foreach ($this->customHostings as $cHost) {
if (!($cHost instanceof DUPX_Host_interface)) {
throw new Exception('Host must implemnete DUPX_Host_interface');
}
if ($cHost->isHosting()) {
$cHost->init();
}
}
$this->initialized = true;
return true;
}
/**
* return the lisst of current custom active hostings
*
* @return string[]
*/
public function getActiveHostings()
{
$result = array();
foreach ($this->customHostings as $cHost) {
if ($cHost->isHosting()) {
$result[] = $cHost->getIdentifier();
}
}
return $result;
}
/**
* return true if current identifier hostoing is active
*
* @param string $identifier hosting identifier
*
* @return bool
*/
public function isHosting($identifier)
{
return isset($this->customHostings[$identifier]) && $this->customHostings[$identifier]->isHosting();
}
/**
*
* @return boolean|string return false if isn't managed manage hosting of manager hosting
*/
public function isManaged()
{
if ($this->isHosting(self::HOST_WPENGINE)) {
return self::HOST_WPENGINE;
} elseif ($this->isHosting(self::HOST_LIQUIDWEB)) {
return self::HOST_LIQUIDWEB;
} elseif ($this->isHosting(self::HOST_GODADDY)) {
return self::HOST_GODADDY;
} elseif ($this->isHosting(self::HOST_WORDPRESSCOM)) {
return self::HOST_WORDPRESSCOM;
} elseif ($this->isHosting(self::HOST_PANTHEON)) {
return self::HOST_PANTHEON;
} elseif ($this->isHosting(self::HOST_FLYWHEEL)) {
return self::HOST_FLYWHEEL;
} else {
return false;
}
}
/**
* @param string $identifier hosting identifier
*
* @return bool|DUPX_Host_interface
*/
public function getHosting($identifier)
{
if ($this->isHosting($identifier)) {
return $this->customHostings[$identifier];
} else {
return false;
}
}
/**
* @todo temp function fot prevent the warnings on managed hosting.
* This function must be removed in favor of right extraction mode will'be implemented
*
* @param string $extract_filename filename
*
* @return boolean
*/
public function skipWarningExtractionForManaged($extract_filename)
{
if (!$this->isManaged()) {
return false;
} elseif (SnapWP::isWpCore($extract_filename, SnapWP::PATH_RELATIVE)) {
return true;
} elseif (DUPX_ArchiveConfig::getInstance()->isChildOfArchivePath($extract_filename, array('abs', 'plugins', 'muplugins', 'themes'))) {
return true;
} elseif (in_array($extract_filename, PluginsManager::getInstance()->getDropInsPaths())) {
return true;
} else {
return false;
}
}
/**
* Set default params for manage hosting
*
* @return void
*/
public function setManagedHostParams()
{
if (($managedSlug = $this->isManaged()) === false) {
return;
}
$paramsManager = PrmMng::getInstance();
$paramsManager->setValue(PrmMng::PARAM_WP_CONFIG, 'nothing');
$paramsManager->setFormStatus(PrmMng::PARAM_WP_CONFIG, ParamForm::STATUS_INFO_ONLY);
$paramsManager->setValue(PrmMng::PARAM_HTACCESS_CONFIG, 'nothing');
$paramsManager->setFormStatus(PrmMng::PARAM_HTACCESS_CONFIG, ParamForm::STATUS_INFO_ONLY);
$paramsManager->setValue(PrmMng::PARAM_OTHER_CONFIG, 'nothing');
$paramsManager->setFormStatus(PrmMng::PARAM_OTHER_CONFIG, ParamForm::STATUS_INFO_ONLY);
if (InstState::getInstance()->getMode() === InstState::MODE_OVR_INSTALL) {
$overwriteData = $paramsManager->getValue(PrmMng::PARAM_OVERWRITE_SITE_DATA);
$paramsManager->setValue(PrmMng::PARAM_VALIDATION_ACTION_ON_START, DUPX_Validation_manager::ACTION_ON_START_AUTO);
$paramsManager->setValue(PrmMng::PARAM_DB_DISPLAY_OVERWIRE_WARNING, false);
$paramsManager->setValue(PrmMng::PARAM_CPNL_CAN_SELECTED, false);
$paramsManager->setValue(PrmMng::PARAM_DB_HOST, $overwriteData['dbhost']);
$paramsManager->setValue(PrmMng::PARAM_DB_NAME, $overwriteData['dbname']);
$paramsManager->setValue(PrmMng::PARAM_DB_USER, $overwriteData['dbuser']);
$paramsManager->setValue(PrmMng::PARAM_DB_PASS, $overwriteData['dbpass']);
$paramsManager->setValue(PrmMng::PARAM_DB_TABLE_PREFIX, $overwriteData['table_prefix']);
$paramsManager->setFormStatus(PrmMng::PARAM_DB_ACTION, ParamForm::STATUS_INFO_ONLY);
$paramsManager->setFormStatus(PrmMng::PARAM_DB_HOST, ParamForm::STATUS_INFO_ONLY);
$paramsManager->setFormStatus(PrmMng::PARAM_DB_NAME, ParamForm::STATUS_INFO_ONLY);
$paramsManager->setFormStatus(PrmMng::PARAM_DB_USER, ParamForm::STATUS_INFO_ONLY);
$paramsManager->setFormStatus(PrmMng::PARAM_DB_PASS, ParamForm::STATUS_INFO_ONLY);
$paramsManager->setFormStatus(PrmMng::PARAM_DB_TABLE_PREFIX, ParamForm::STATUS_INFO_ONLY);
}
$paramsManager->setFormStatus(PrmMng::PARAM_URL_NEW, ParamForm::STATUS_INFO_ONLY);
$paramsManager->setFormStatus(PrmMng::PARAM_SITE_URL, ParamForm::STATUS_INFO_ONLY);
$paramsManager->setFormStatus(PrmMng::PARAM_PATH_NEW, ParamForm::STATUS_INFO_ONLY);
$this->getHosting($managedSlug)->setCustomParams();
}
}

View File

@@ -0,0 +1,74 @@
<?php
/**
* Flywheel custom hosting class
*
* Standard: PSR-2
*
* @package SC\DUPX\DB
* @link http://www.php-fig.org/psr/psr-2/
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Core\Params\PrmMng;
/**
* class for wordpress.com managed hosting
*
* @todo not yet implemneted
*/
class DUPX_Flywheel_Host implements DUPX_Host_interface
{
/**
* return the current host itentifier
*
* @return string
*/
public static function getIdentifier()
{
return DUPX_Custom_Host_Manager::HOST_FLYWHEEL;
}
/**
* @return bool true if is current host
*/
public function isHosting()
{
// check only mu plugin file exists
$testFile = PrmMng::getInstance()->getValue(PrmMng::PARAM_PATH_NEW) . '/.fw-config.php';
return file_exists($testFile);
}
/**
* the init function.
* is called only if isHosting is true
*
* @return void
*/
public function init()
{
}
/**
*
* @return string
*/
public function getLabel()
{
return 'Flywheel';
}
/**
* this function is called if current hosting is this
*
* @return void
*/
public function setCustomParams()
{
$paramsManager = PrmMng::getInstance();
$paramsManager->setValue(PrmMng::PARAM_ARCHIVE_ENGINE_SKIP_WP_FILES, DUP_PRO_Extraction::FILTER_SKIP_WP_CORE);
}
}

View File

@@ -0,0 +1,75 @@
<?php
/**
* godaddy custom hosting class
*
* Standard: PSR-2
*
* @package SC\DUPX\DB
* @link http://www.php-fig.org/psr/psr-2/
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Core\Params\PrmMng;
/**
* class for GoDaddy managed hosting
*
* @todo not yet implemneted
*/
class DUPX_GoDaddy_Host implements DUPX_Host_interface
{
/**
* return the current host itentifier
*
* @return string
*/
public static function getIdentifier()
{
return DUPX_Custom_Host_Manager::HOST_GODADDY;
}
/**
* @return bool true if is current host
*/
public function isHosting()
{
// check only mu plugin file exists
$file = PrmMng::getInstance()->getValue(PrmMng::PARAM_PATH_MUPLUGINS_NEW) . '/gd-system-plugin.php';
return file_exists($file);
}
/**
* the init function.
* is called only if isHosting is true
*
* @return void
*/
public function init()
{
}
/**
*
* @return string
*/
public function getLabel()
{
return 'GoDaddy';
}
/**
* this function is called if current hosting is this
*
* @return void
*/
public function setCustomParams()
{
PrmMng::getInstance()->setValue(PrmMng::PARAM_IGNORE_PLUGINS, array(
'gd-system-plugin.php',
'object-cache.php',
));
}
}

View File

@@ -0,0 +1,73 @@
<?php
/**
* liquidweb custom hosting class
*
* Standard: PSR-2
*
* @package SC\DUPX\DB
* @link http://www.php-fig.org/psr/psr-2/
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Core\Params\PrmMng;
class DUPX_Liquidweb_Host implements DUPX_Host_interface
{
/**
* return the current host itentifier
*
* @return string
*/
public static function getIdentifier()
{
return DUPX_Custom_Host_Manager::HOST_LIQUIDWEB;
}
/**
* @return bool true if is current host
*/
public function isHosting()
{
// check only mu plugin file exists
$testFile = PrmMng::getInstance()->getValue(PrmMng::PARAM_PATH_MUPLUGINS_NEW) . '/liquid-web.php';
return file_exists($testFile);
}
/**
* the init function.
* is called only if isHosting is true
*
* @return void
*/
public function init()
{
}
/**
* return the label of current hosting
*
* @return string
*/
public function getLabel()
{
return 'Liquid Web';
}
/**
* this function is called if current hosting is this
*
* @return void
*/
public function setCustomParams()
{
PrmMng::getInstance()->setValue(PrmMng::PARAM_IGNORE_PLUGINS, array(
'liquidweb_mwp.php',
'000-liquidweb-config.php',
'liquid-web.php',
'lw_disable_nags.php',
));
}
}

View File

@@ -0,0 +1,72 @@
<?php
/**
* godaddy custom hosting class
*
* Standard: PSR-2
*
* @package SC\DUPX\DB
* @link http://www.php-fig.org/psr/psr-2/
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Core\Params\PrmMng;
/**
* class for GoDaddy managed hosting
*
* @todo not yet implemneted
*/
class DUPX_Pantheon_Host implements DUPX_Host_interface
{
/**
* return the current host itentifier
*
* @return string
*/
public static function getIdentifier()
{
return DUPX_Custom_Host_Manager::HOST_PANTHEON;
}
/**
* @return bool true if is current host
* @throws Exception
*/
public function isHosting()
{
// check only mu plugin file exists
$testFile = PrmMng::getInstance()->getValue(PrmMng::PARAM_PATH_MUPLUGINS_NEW) . '/pantheon.php';
return file_exists($testFile);
}
/**
* the init function.
* is called only if isHosting is true
*
* @return void
*/
public function init()
{
}
/**
*
* @return string
*/
public function getLabel()
{
return 'Pantheon';
}
/**
* this function is called if current hosting is this
*
* @return void
*/
public function setCustomParams()
{
}
}

View File

@@ -0,0 +1,65 @@
<?php
/**
* Siteground custom hosting class
*
* Standard: PSR-2
*
* @package SC\DUPX\DB
* @link http://www.php-fig.org/psr/psr-2/
*/
use Duplicator\Libs\Snap\SnapUtil;
class DUPX_Siteground_Host implements DUPX_Host_interface
{
/**
* return the current host identifier
*
* @return string
*/
public static function getIdentifier()
{
return DUPX_Custom_Host_Manager::HOST_SITEGROUND;
}
/**
* @return bool true if is current host
*/
public function isHosting()
{
ob_start();
SnapUtil::phpinfo(INFO_GENERAL);
$serverinfo = ob_get_clean();
return (strpos($serverinfo, "siteground") !== false);
}
/**
* the init function.
* is called only if isHosting is true
*
* @return void
*/
public function init()
{
}
/**
*
* @return string
*/
public function getLabel()
{
return 'SiteGround';
}
/**
* this function is called if current hosting is this
*
* @return void
*/
public function setCustomParams()
{
}
}

View File

@@ -0,0 +1,81 @@
<?php
/**
* godaddy custom hosting class
*
* Standard: PSR-2
*
* @package SC\DUPX\DB
* @link http://www.php-fig.org/psr/psr-2/
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Core\InstState;
use Duplicator\Installer\Core\Params\Descriptors\ParamDescUsers;
use Duplicator\Installer\Utils\Log\Log;
use Duplicator\Installer\Core\Params\PrmMng;
/**
* class for wordpress.com managed hosting
*
* @todo not yet implemneted
*/
class DUPX_WordpressCom_Host implements DUPX_Host_interface
{
/**
* return the current host itentifier
*
* @return string
*/
public static function getIdentifier()
{
return DUPX_Custom_Host_Manager::HOST_WORDPRESSCOM;
}
/**
* @return bool true if is current host
*/
public function isHosting()
{
// check only mu plugin file exists
$testFile = PrmMng::getInstance()->getValue(PrmMng::PARAM_PATH_MUPLUGINS_NEW) . '/wpcomsh-loader.php';
return file_exists($testFile);
}
/**
* the init function.
* is called only if isHosting is true
*
* @return void
*/
public function init()
{
}
/**
*
* @return string
*/
public function getLabel()
{
return 'Wordpress.com';
}
/**
* this function is called if current hosting is this
*
* @return void
*/
public function setCustomParams()
{
$paramsManager = PrmMng::getInstance();
$paramsManager->setValue(PrmMng::PARAM_ARCHIVE_ENGINE_SKIP_WP_FILES, DUP_PRO_Extraction::FILTER_SKIP_WP_CORE);
if (!InstState::isRecoveryMode()) {
$paramsManager->setValue(PrmMng::PARAM_USERS_MODE, ParamDescUsers::USER_MODE_IMPORT_USERS);
}
}
}

View File

@@ -0,0 +1,160 @@
<?php
/**
* wpengine custom hosting class
*
* Standard: PSR-2
*
* @package SC\DUPX\DB
* @link http://www.php-fig.org/psr/psr-2/
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Core\Params\PrmMng;
use Duplicator\Libs\Snap\SnapUtil;
/**
* class for wpengine managed hosting
*
* @todo not yet implemneted
*/
class DUPX_WPEngine_Host implements DUPX_Host_interface
{
/**
* return the current host itentifier
*
* @return string
*/
public static function getIdentifier()
{
return DUPX_Custom_Host_Manager::HOST_WPENGINE;
}
/**
* @return bool true if is current host
*/
public function isHosting()
{
ob_start();
SnapUtil::phpinfo(INFO_ENVIRONMENT);
$serverinfo = ob_get_clean();
return (strpos($serverinfo, "WPENGINE_ACCOUNT") !== false);
}
/**
* the init function.
* is called only if isHosting is true
*
* @return void
*/
public function init()
{
}
/**
*
* @return string
*/
public function getLabel()
{
return 'WP Engine';
}
/**
* this function is called if current hosting is this
*
* @return void
*/
public function setCustomParams()
{
PrmMng::getInstance()->setValue(PrmMng::PARAM_IGNORE_PLUGINS, array(
'mu-plugin.php',
'advanced-cache.php',
'wpengine-security-auditor.php',
'stop-long-comments.php',
'slt-force-strong-passwords.php',
));
$this->force_disable_plugins();
}
/**
* force disable disallowed plugins
*
* @link https://wpengine.com/support/disallowed-plugins/
*
* @return void
*/
private function force_disable_plugins()
{
$fdPlugins = PrmMng::getInstance()->getValue(PrmMng::PARAM_FORCE_DIABLE_PLUGINS);
if (!is_array($fdPlugins)) {
$fdPlugins = array();
}
$fdPlugins = array_merge($fdPlugins, array(
'gd-system-plugin.php',
'hcs.php',
'hello.php',
'adminer/adminer.php',
'async-google-analytics/asyncgoogleanalytics.php',
'backup/backup.php',
'backup-scheduler/backup-scheduler.php',
'backupwordpress/backupwordpress.php',
'backwpup/backwpup.php',
'bad-behavior/bad-behavior-wordpress.php',
'broken-link-checker/broken-link-checker.php',
'content-molecules/emc2_content_molecules.php',
'contextual-related-posts/contextual-related-posts.php',
'dynamic-related-posts/drpp.php',
'ewww-image-optimizer/ewww-image-optimizer.php',
'ezpz-one-click-backup/ezpz-ocb.php',
'file-commander/wp-plugin-file-commander.php',
'fuzzy-seo-booster/seoqueries.php',
'google-xml-sitemaps-with-multisite-support/sitemap.php',
'hc-custom-wp-admin-url/hc-custom-wp-admin-url.php',
'jr-referrer/jr-referrer.php',
'jumpple/sweetcaptcha.php',
'missed-schedule/missed-schedule.php',
'no-revisions/norevisions.php',
'ozh-who-sees-ads/wp_ozh_whoseesads.php',
'pipdig-power-pack/p3.php',
'portable-phpmyadmin/wp-phpmyadmin.php',
'quick-cache/quick-cache.php',
'quick-cache-pro/quick-cache-pro.php',
'recommend-a-friend/recommend-to-a-friend.php',
'seo-alrp/seo-alrp.php',
'si-captcha-for-wordpress/si-captcha.php',
'similar-posts/similar-posts.php',
'spamreferrerblock/spam_referrer_block.php',
'super-post/super-post.php',
'superslider/superslider.php',
'sweetcaptcha-revolutionary-free-captcha-service/sweetcaptcha.php',
'the-codetree-backup/codetree-backup.php',
'ToolsPack/ToolsPack.php',
'tweet-blender/tweet-blender.php',
'versionpress/versionpress.php',
'w3-total-cache/w3-total-cache.php',
'wordpress-gzip-compression/ezgz.php',
'wp-cache/wp-cache.php',
'wp-database-optimizer/wp_database_optimizer.php',
'wp-db-backup/wp-db-backup.php',
'wp-dbmanager/wp-dbmanager.php',
'wp-engine-snapshot/plugin.php',
'wp-file-cache/file-cache.php',
'wp-mailinglist/wp-mailinglist.php',
'wp-phpmyadmin/wp-phpmyadmin.php',
'wp-postviews/wp-postviews.php',
'wp-slimstat/wp-slimstat.php',
'wp-super-cache/wp-cache.php',
'wp-symposium-alerts/wp-symposium-alerts.php',
'wponlinebackup/wponlinebackup.php',
'yet-another-featured-posts-plugin/yafpp.php',
'yet-another-related-posts-plugin/yarpp.php',
));
PrmMng::getInstance()->setValue(PrmMng::PARAM_FORCE_DIABLE_PLUGINS, $fdPlugins);
}
}

View File

@@ -0,0 +1,52 @@
<?php
/**
* interface for specific hostings class
*
* Standard: PSR-2
*
* @package SC\DUPX\DB
* @link http://www.php-fig.org/psr/psr-2/
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
/**
* instaler custom host interface for cusotm hosting classes
*/
interface DUPX_Host_interface
{
/**
* return the current host itentifier
*
* @return string
*/
public static function getIdentifier();
/**
* @return bool true if is current host
*/
public function isHosting();
/**
* the init function.
* is called only if isHosting is true
*
* @return void
*/
public function init();
/**
* return the label of current hosting
*
* @return string
*/
public function getLabel();
/**
* this function is called if current hosting is this
*
* @return void
*/
public function setCustomParams();
}

View File

@@ -0,0 +1,3 @@
<?php
//silent

View File

@@ -0,0 +1,112 @@
<?php
/**
* Custom exceptions
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
/**
* Dup installer custom exception
*/
class DupxException extends Exception
{
/** @var string formatted html string */
protected $longMsg = '';
/** @var false|array{url: string, label: string} */
protected $faqLink = false;
/**
* Class constructor
*
* @param string $shortMsg Short message
* @param string $longMsg Long message
* @param string $faqLinkUrl FAQ link URL
* @param string $faqLinkLabel FAQ link label
* @param int $code Exception code
* @param Exception $previous Previous exception
*/
public function __construct($shortMsg, $longMsg = '', $faqLinkUrl = '', $faqLinkLabel = '', $code = 0, Exception $previous = null)
{
parent::__construct($shortMsg, $code, $previous);
$this->longMsg = (string) $longMsg;
if (strlen($faqLinkUrl) > 0) {
$this->faqLink = array(
'url' => $faqLinkUrl,
'label' => $faqLinkLabel,
);
}
}
/**
* Get the long message
*
* @return string
*/
public function getLongMsg()
{
return $this->longMsg;
}
/**
* Check is have faq link
*
* @return bool
*/
public function haveFaqLink()
{
return $this->faqLink !== false;
}
/**
* Get FAQ URL
*
* @return string
*/
public function getFaqLinkUrl()
{
if ($this->haveFaqLink()) {
return $this->faqLink['url'];
} else {
return '';
}
}
/**
* Get FAQ label
*
* @return string
*/
public function getFaqLinkLabel()
{
if ($this->haveFaqLink()) {
return $this->faqLink['label'];
} else {
return '';
}
}
/**
* Custom string representation of object
*
* @return string
*/
public function __toString()
{
$result = __CLASS__ . ": [{$this->code}]: {$this->message}";
if ($this->haveFaqLink()) {
$result .= "\n\tSee FAQ " . $this->faqLink['label'] . ': ' . $this->faqLink['url'];
}
if (!empty($this->longMsg)) {
$result .= "\n\t" . strip_tags($this->longMsg);
}
$result .= "\n";
return $result;
}
}

View File

@@ -0,0 +1,108 @@
<?php
/**
* Search and reaplace manager
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Libs\Snap\SnapIO;
class DUPX_TemplateItem
{
/** @var string */
protected $name = null;
/** @var string */
protected $mainFolder = null;
/** @var null|DUPX_TemplateItem */
protected $parent = null;
/**
* Class contructor
*
* @param string $name Template name
* @param string $mainFolder Main folder
* @param ?DUPX_TemplateItem $parent Parent template
*/
public function __construct($name, $mainFolder, $parent = null)
{
if (empty($name)) {
throw new Exception('The name of template can\'t be empty');
}
if (!is_dir($mainFolder) || !is_readable($mainFolder)) {
throw new Exception('The main main folder doesn\'t exist');
}
if (!is_null($parent) && !$parent instanceof self) {
throw new Exception('the parent must be a instance of ' . __CLASS__);
}
$this->name = $name;
$this->mainFolder = SnapIO::safePathUntrailingslashit($mainFolder);
$this->parent = $parent;
}
/**
* Render template
*
* @param string $fileTpl Template file is a relative path from root template folder
* @param array<string, mixed> $args Array key / val where key is the var name in template
* @param bool $echo If false return template in string
*
* @return string
*/
public function render($fileTpl, $args = array(), $echo = true)
{
ob_start();
if (($renderFile = $this->getFileTemplate($fileTpl)) !== false) {
foreach ($args as $var => $value) {
${$var} = $value;
}
require($renderFile);
} else {
echo '<p>FILE TPL NOT FOUND: ' . $fileTpl . '</p>';
}
if ($echo) {
ob_end_flush();
return '';
} else {
return ob_get_clean();
}
}
/**
* Acctept html of php extensions. if the file have unknown extension automatic add the php extension
*
* @param string $fileTpl File template
*
* @return boolean|string return false if don\'t find the template file
*/
protected function getFileTemplate($fileTpl)
{
$fileExtension = strtolower(pathinfo($fileTpl, PATHINFO_EXTENSION));
switch ($fileExtension) {
case 'php':
case 'html':
$fileName = $fileTpl;
break;
default:
$fileName = $fileTpl . '.php';
}
$fullPath = $this->mainFolder . '/' . $fileName;
if (file_exists($fullPath)) {
return $fullPath;
} elseif (!is_null($this->parent)) {
return $this->parent->getFileTemplate($fileName);
} else {
return false;
}
}
}

View File

@@ -0,0 +1,133 @@
<?php
/**
* Search and reaplace manager
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
require_once(DUPX_INIT . '/classes/utilities/template/class.u.template.item.php');
/**
* DUPX_Template
*/
final class DUPX_Template
{
const TEMPLATE_ADVANCED = 'default';
const TEMPLATE_BASE = 'base';
const TEMPLATE_IMPORT_BASE = 'import-base';
const TEMPLATE_IMPORT_ADVANCED = 'import-advanced';
const TEMPLATE_RECOVERY = 'recovery';
/** @var ?self */
private static $instance = null;
/** @var DUPX_TemplateItem[] */
private $templates = array();
/** @var string */
private $currentTemplate = null;
/**
* Get instance
*
* @return DUPX_Template
*/
public static function getInstance()
{
if (is_null(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Class constructor
*/
private function __construct()
{
// ADD DEFAULT TEMPLATE
$this->addTemplate(DUPX_Template::TEMPLATE_ADVANCED, DUPX_INIT . '/templates/default');
$this->setTemplate(DUPX_Template::TEMPLATE_ADVANCED);
}
/**
* Set template
*
* @param string $name Template name
*
* @return boolean
*/
public function setTemplate($name)
{
if (!isset($this->templates[$name])) {
throw new Exception('The template ' . $name . ' doesn\'t exist');
}
$this->currentTemplate = $name;
return true;
}
/**
* Add template
*
* @param string $name Template name
* @param string $mainFolder Main folder
* @param ?string $parentName Parent template name
*
* @return boolean
*/
public function addTemplate($name, $mainFolder, $parentName = null)
{
if (isset($this->templates[$name])) {
throw new Exception('The template "' . $name . '" already exists');
}
if (is_null($parentName)) {
$parent = null;
} elseif (isset($this->templates[$parentName])) {
$parent = $this->templates[$parentName];
} else {
throw new Exception('The parent template "' . $parentName . '" doesn\'t exist');
}
$this->templates[$name] = new DUPX_TemplateItem($name, $mainFolder, $parent);
return true;
}
/**
* Render template
*
* @param string $fileTpl Template file is a relative path from root template folder
* @param array<string, mixed> $args Array key / val where key is the var name in template
* @param bool $echo If false return template in string
*
* @return string
*/
public function render($fileTpl, $args = array(), $echo = true)
{
return $this->templates[$this->currentTemplate]->render($fileTpl, $args, $echo);
}
}
/**
* Render template
*
* @param string $fileTpl Template file is a relative path from root template folder
* @param array<string, mixed> $args Array key / val where key is the var name in template
* @param bool $echo If false return template in string
*
* @return string
*/
function dupxTplRender($fileTpl, $args = array(), $echo = true)
{
static $tplMng = null;
if (is_null($tplMng)) {
$tplMng = DUPX_Template::getInstance();
}
return $tplMng->render($fileTpl, $args, $echo);
}

View File

@@ -0,0 +1,294 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Utils\Log\Log;
/**
* Validation abstract item
*/
abstract class DUPX_Validation_abstract_item
{
const LV_FAIL = 0;
const LV_HARD_WARNING = 1;
const LV_SOFT_WARNING = 2;
const LV_GOOD = 3;
const LV_PASS = 4;
const LV_SKIP = 1000;
/** @var string */
protected $category = '';
/** @var ?int Enum LV_* */
protected $testResult = null;
/**
* Class Constructor
*
* @param string $category Category
*/
public function __construct($category = '')
{
$this->category = $category;
}
/**
*
* @param bool $reset Reset test result
*
* @return int test result level
*/
public function test($reset = false)
{
if ($reset || is_null($this->testResult)) {
try {
Log::resetTime(Log::LV_DEBUG);
Log::info('START TEST "' . $this->getTitle() . '" [CLASS: ' . get_called_class() . ']');
$this->testResult = $this->runTest();
} catch (Exception $e) {
Log::logException($e, Log::LV_DEFAULT, ' TEST "' . $this->getTitle() . '" EXCEPTION:');
$this->testResult = self::LV_FAIL;
} catch (Error $e) {
Log::logException($e, Log::LV_DEFAULT, ' TEST "' . $this->getTitle() . '" EXCEPTION:');
$this->testResult = self::LV_FAIL;
}
Log::logTime('TEST "' . $this->getTitle() . '" RESULT: ' . $this->resultString() . "\n", Log::LV_DEFAULT, false);
}
return $this->testResult;
}
/**
* Run the test
*
* @return int Enum LV_* result
*/
abstract protected function runTest();
/**
* If true the test will be displayed in the validation section else will be skipped
*
* @return bool
*/
public function display()
{
if ($this->testResult === self::LV_SKIP) {
return false;
} else {
return true;
}
}
/**
* Get test category
*
* @return string
*/
public function getCategory()
{
return $this->category;
}
/**
* Get test title
*
* @return string
*/
public function getTitle()
{
return 'Test class ' . get_called_class();
}
/**
* Get test content
*
* @return string
*/
public function getContent()
{
try {
switch ($this->test(false)) {
case self::LV_SKIP:
return $this->skipContent();
case self::LV_GOOD:
return $this->goodContent();
case self::LV_PASS:
return $this->passContent();
case self::LV_SOFT_WARNING:
return $this->swarnContent();
case self::LV_HARD_WARNING:
return $this->hwarnContent();
case self::LV_FAIL:
default:
return $this->failContent();
}
} catch (Exception $e) {
Log::logException($e, Log::LV_DEFAULT, 'VALIDATION DISPLAY CONTENT ' . get_called_class() . ' RESULT: ' . $this->resultString() . ' EXCEPTION:');
return 'DISPLAY CONTENT PROBLEM <br>'
. 'MESSAGE: ' . $e->getMessage() . '<br>'
. 'TRACE:'
. '<pre>' . $e->getTraceAsString() . '</pre>';
} catch (Error $e) {
Log::logException($e, Log::LV_DEFAULT, 'VALIDATION DISPLAY CONTENT ' . get_called_class() . ' ERROR:');
return 'DISPLAY CONTENT PROBLEM <br>'
. 'MESSAGE: ' . $e->getMessage() . '<br>'
. 'TRACE:'
. '<pre>' . $e->getTraceAsString() . '</pre>';
}
}
/**
* Get badge class for result level
*
* @return string
*/
public function getBadgeClass()
{
return self::resultLevelToBadgeClass($this->test(false));
}
/**
* Get unique selector
*
* @return string
*/
public function getUniqueSelector()
{
return strtolower(str_replace("_", "-", get_called_class()));
}
/**
* Get level label
*
* @return string
*/
public function resultString()
{
return self::resultLevelToString($this->test(false));
}
/**
* Level to string
*
* @param int $level Enum LV_*
*
* @return string
*/
public static function resultLevelToString($level)
{
switch ($level) {
case self::LV_SKIP:
return 'skip';
case self::LV_GOOD:
return 'good';
case self::LV_PASS:
return 'passed';
case self::LV_SOFT_WARNING:
return 'soft warning';
case self::LV_HARD_WARNING:
return 'hard warning';
case self::LV_FAIL:
default:
return 'failed';
}
}
/**
* Get badge class for result level
*
* @param int $level Enum LV_*
*
* @return string
*/
public static function resultLevelToBadgeClass($level)
{
switch ($level) {
case self::LV_SKIP:
return '';
case self::LV_GOOD:
return 'good';
case self::LV_PASS:
return 'pass';
case self::LV_SOFT_WARNING:
return 'warn';
case self::LV_HARD_WARNING:
return 'hwarn';
case self::LV_FAIL:
default:
return 'fail';
}
}
/**
* Return content for test status: fail warning
*
* @return string
*/
protected function failContent()
{
return 'test result: fail';
}
/**
* Return content for test status: hard warning
*
* @return string
*/
protected function hwarnContent()
{
return 'test result: hard warning';
}
/**
* Return content for test status: soft warning
*
* @return string
*/
protected function swarnContent()
{
return 'test result: soft warning';
}
/**
* Return content for test status: good
*
* @return string
*/
protected function goodContent()
{
return 'test result: good';
}
/**
* Return content for test status: pass
*
* @return string
*/
protected function passContent()
{
return 'test result: pass';
}
/**
* Return content for test status: skip
*
* @return string
*/
protected function skipContent()
{
return 'test result: skipped';
}
}

View File

@@ -0,0 +1,342 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Core\Bootstrap;
use Duplicator\Installer\Core\Params\PrmMng;
require_once(DUPX_INIT . '/classes/validation/class.validation.database.service.php');
require_once(DUPX_INIT . '/classes/validation/class.validation.abstract.item.php');
require_once(DUPX_INIT . '/classes/validation/tests/class.validation.test.owrinstall.php');
require_once(DUPX_INIT . '/classes/validation/tests/class.validation.test.addon.sites.php');
require_once(DUPX_INIT . '/classes/validation/tests/class.validation.test.manual.extraction.php');
require_once(DUPX_INIT . '/classes/validation/tests/class.validation.test.dbonly.iswordpress.php');
require_once(DUPX_INIT . '/classes/validation/tests/class.validation.test.package.age.php');
require_once(DUPX_INIT . '/classes/validation/tests/class.validation.test.php.version.php');
require_once(DUPX_INIT . '/classes/validation/tests/class.validation.test.open.basedir.php');
require_once(DUPX_INIT . '/classes/validation/tests/class.validation.test.memory.limit.php');
require_once(DUPX_INIT . '/classes/validation/tests/class.validation.test.php.extensions.php');
require_once(DUPX_INIT . '/classes/validation/tests/class.validation.test.timeout.php');
require_once(DUPX_INIT . '/classes/validation/tests/class.validation.test.wordfence.php');
require_once(DUPX_INIT . '/classes/validation/tests/class.validation.test.disk.space.php');
require_once(DUPX_INIT . '/classes/validation/tests/class.validation.test.importer.version.php');
require_once(DUPX_INIT . '/classes/validation/tests/class.validation.test.importable.php');
require_once(DUPX_INIT . '/classes/validation/tests/class.validation.test.rest.api.php');
require_once(DUPX_INIT . '/classes/validation/tests/class.validation.test.managed.tprefix.php');
require_once(DUPX_INIT . '/classes/validation/tests/class.validation.test.iswritable.php');
require_once(DUPX_INIT . '/classes/validation/tests/class.validation.test.iswritable.configs.php');
require_once(DUPX_INIT . '/classes/validation/tests/class.validation.test.mysql.connect.php');
require_once(DUPX_INIT . '/classes/validation/tests/class.validation.test.php.functionalities.php');
require_once(DUPX_INIT . '/classes/validation/tests/class.validation.test.replace.paths.php');
require_once(DUPX_INIT . '/classes/validation/tests/class.validation.test.managed.supported.php');
require_once(DUPX_INIT . '/classes/validation/tests/class.validation.test.siteground.php');
require_once(DUPX_INIT . '/classes/validation/tests/class.validation.test.multisite.subfolder.php');
require_once(DUPX_INIT . '/classes/validation/tests/class.validation.test.archive.check.php');
require_once(DUPX_INIT . '/classes/validation/tests/class.validation.test.recovery.link.php');
require_once(DUPX_INIT . '/classes/validation/database-tests/class.validation.test.db.excluded.php');
require_once(DUPX_INIT . '/classes/validation/database-tests/class.validation.test.cpnl.connection.php');
require_once(DUPX_INIT . '/classes/validation/database-tests/class.validation.test.cpnl.new.user.php');
require_once(DUPX_INIT . '/classes/validation/database-tests/class.validation.test.db.host.name.php');
require_once(DUPX_INIT . '/classes/validation/database-tests/class.validation.test.db.connection.php');
require_once(DUPX_INIT . '/classes/validation/database-tests/class.validation.test.db.version.php');
require_once(DUPX_INIT . '/classes/validation/database-tests/class.validation.test.db.create.php');
require_once(DUPX_INIT . '/classes/validation/database-tests/class.validation.test.db.user.cleanup.php');
require_once(DUPX_INIT . '/classes/validation/database-tests/class.validation.test.db.cleanup.php');
require_once(DUPX_INIT . '/classes/validation/database-tests/class.validation.test.db.affected.tables.php');
require_once(DUPX_INIT . '/classes/validation/database-tests/class.validation.test.db.prefix.too.long.php');
require_once(DUPX_INIT . '/classes/validation/database-tests/class.validation.test.db.visibility.php');
require_once(DUPX_INIT . '/classes/validation/database-tests/class.validation.test.db.manual.tables.count.php');
require_once(DUPX_INIT . '/classes/validation/database-tests/class.validation.test.db.multiple.wp.installs.php');
require_once(DUPX_INIT . '/classes/validation/database-tests/class.validation.test.db.user.perms.php');
require_once(DUPX_INIT . '/classes/validation/database-tests/class.validation.test.db.user.resources.php');
require_once(DUPX_INIT . '/classes/validation/database-tests/class.validation.test.db.triggers.php');
require_once(DUPX_INIT . '/classes/validation/database-tests/class.validation.test.db.show.variables.php');
require_once(DUPX_INIT . '/classes/validation/database-tests/class.validation.test.db.supported.charset.php');
require_once(DUPX_INIT . '/classes/validation/database-tests/class.validation.test.db.supported.engine.php');
require_once(DUPX_INIT . '/classes/validation/database-tests/class.validation.test.db.gtid.mode.php');
require_once(DUPX_INIT . '/classes/validation/database-tests/class.validation.test.db.case.sentivie.tables.php');
require_once(DUPX_INIT . '/classes/validation/database-tests/class.validation.test.db.supported.default.charset.php');
require_once(DUPX_INIT . '/classes/validation/tests/class.validation.test.wp.config.php');
class DUPX_Validation_manager
{
const CAT_GENERAL = 'general';
const CAT_FILESYSTEM = 'filesystem';
const CAT_PHP = 'php';
const CAT_DATABASE = 'database';
const ACTION_ON_START_NORMAL = 'normal';
const ACTION_ON_START_AUTO = 'auto';
const MIN_LEVEL_VALID = DUPX_Validation_abstract_item::LV_HARD_WARNING;
/** @var ?self */
private static $instance = null;
/** @var DUPX_Validation_abstract_item[] */
private $tests = array();
/** @var array<string, mixed> */
private $extraData = array();
/**
*
* @return self
*/
public static function getInstance()
{
if (is_null(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Class constructor
*/
private function __construct()
{
// GENERAL
$this->tests[] = new DUPX_Validation_test_archive_check(self::CAT_GENERAL);
$this->tests[] = new DUPX_Validation_test_importer_version(self::CAT_GENERAL);
$this->tests[] = new DUPX_Validation_test_owrinstall(self::CAT_GENERAL);
$this->tests[] = new DUPX_Validation_test_recovery(self::CAT_GENERAL);
$this->tests[] = new DUPX_Validation_test_importable(self::CAT_GENERAL);
$this->tests[] = new DUPX_Validation_test_rest_api(self::CAT_GENERAL);
$this->tests[] = new DUPX_Validation_test_manual_extraction(self::CAT_GENERAL);
$this->tests[] = new DUPX_Validation_test_dbonly_iswordpress(self::CAT_GENERAL);
$this->tests[] = new DUPX_Validation_test_package_age(self::CAT_GENERAL);
$this->tests[] = new DUPX_Validation_test_replace_paths(self::CAT_GENERAL);
$this->tests[] = new DUPX_Validation_test_managed_supported(self::CAT_GENERAL);
$this->tests[] = new DUPX_Validation_test_siteground(self::CAT_GENERAL);
$this->tests[] = new DUPX_Validation_test_multisite_subfolder(self::CAT_GENERAL);
$this->tests[] = new DUPX_Validation_test_addon_sites(self::CAT_GENERAL);
$this->tests[] = new DUPX_Validation_test_wordfence(self::CAT_GENERAL);
$this->tests[] = new DUPX_Validation_test_managed_tprefix(self::CAT_GENERAL);
$this->tests[] = new DUPX_Validation_test_wp_config(self::CAT_GENERAL);
// PHP
$this->tests[] = new DUPX_Validation_test_php_version(self::CAT_PHP);
$this->tests[] = new DUPX_Validation_test_open_basedir(self::CAT_PHP);
$this->tests[] = new DUPX_Validation_test_memory_limit(self::CAT_PHP);
$this->tests[] = new DUPX_Validation_test_extensions(self::CAT_PHP);
$this->tests[] = new DUPX_Validation_test_mysql_connect(self::CAT_PHP);
$this->tests[] = new DUPX_Validation_test_php_functionalities(self::CAT_PHP);
$this->tests[] = new DUPX_Validation_test_timeout(self::CAT_PHP);
// FILESYSTEM
$this->tests[] = new DUPX_Validation_test_disk_space(self::CAT_FILESYSTEM);
$this->tests[] = new DUPX_Validation_test_iswritable(self::CAT_FILESYSTEM);
$this->tests[] = new DUPX_Validation_test_iswritable_configs(self::CAT_FILESYSTEM);
// DATABASE
$this->tests[] = new DUPX_Validation_test_db_excluded(self::CAT_DATABASE);
$this->tests[] = new DUPX_Validation_test_cpnl_connection(self::CAT_DATABASE);
$this->tests[] = new DUPX_Validation_test_cpnl_new_user(self::CAT_DATABASE);
$this->tests[] = new DUPX_Validation_test_db_host_name(self::CAT_DATABASE);
$this->tests[] = new DUPX_Validation_test_db_connection(self::CAT_DATABASE);
$this->tests[] = new DUPX_Validation_test_db_version(self::CAT_DATABASE);
$this->tests[] = new DUPX_Validation_test_db_create(self::CAT_DATABASE);
$this->tests[] = new DUPX_Validation_test_db_supported_engine(self::CAT_DATABASE);
$this->tests[] = new DUPX_Validation_test_db_gtid_mode(self::CAT_DATABASE);
$this->tests[] = new DUPX_Validation_test_db_visibility(self::CAT_DATABASE);
$this->tests[] = new DUPX_Validation_test_db_manual_tabels_count(self::CAT_DATABASE);
$this->tests[] = new DUPX_Validation_test_db_multiple_wp_installs(self::CAT_DATABASE);
$this->tests[] = new DUPX_Validation_test_db_user_resources(self::CAT_DATABASE);
$this->tests[] = new DUPX_Validation_test_db_user_perms(self::CAT_DATABASE);
$this->tests[] = new DUPX_Validation_test_db_custom_queries(self::CAT_DATABASE);
$this->tests[] = new DUPX_Validation_test_db_triggers(self::CAT_DATABASE);
$this->tests[] = new DUPX_Validation_test_db_supported_default_charset(self::CAT_DATABASE);
$this->tests[] = new DUPX_Validation_test_db_supported_charset(self::CAT_DATABASE);
$this->tests[] = new DUPX_Validation_test_db_case_sensitive_tables(self::CAT_DATABASE);
$this->tests[] = new DUPX_Validation_test_db_affected_tables(self::CAT_DATABASE);
$this->tests[] = new DUPX_Validation_test_db_prefix_too_long(self::CAT_DATABASE);
// after all database tests
$this->tests[] = new DUPX_Validation_test_db_cleanup(self::CAT_DATABASE);
$this->tests[] = new DUPX_Validation_test_db_user_cleanup(self::CAT_DATABASE);
}
/**
* True if the validation is valid
*
* @return bool
*/
public static function isValidated()
{
$paramsManager = PrmMng::getInstance();
return $paramsManager->getValue(PrmMng::PARAM_VALIDATION_LEVEL) >= self::MIN_LEVEL_VALID;
}
/**
* True if start is validated on load
*
* @return bool
*/
public static function isFirstValidationOnLoad()
{
return (
Bootstrap::isInit() &&
PrmMng::getInstance()->getValue(PrmMng::PARAM_VALIDATION_ACTION_ON_START) === DUPX_Validation_manager::ACTION_ON_START_AUTO
);
}
/**
* True if start validation is set to auto
*
* @return bool
*/
public static function validateOnLoad()
{
$paramsManager = PrmMng::getInstance();
if ($paramsManager->getValue(PrmMng::PARAM_VALIDATION_ACTION_ON_START) === DUPX_Validation_manager::ACTION_ON_START_AUTO) {
return true;
}
if ($paramsManager->getValue(PrmMng::PARAM_STEP_ACTION) === DUPX_CTRL::ACTION_STEP_ON_VALIDATE) {
return true;
}
return false;
}
/**
* Get validation data
*
* @return array<string, mixed>
*/
public function getValidateData()
{
$this->runTests();
$mainResult = $this->getMainResult();
$paramsManager = PrmMng::getInstance();
$paramsManager->setValue(PrmMng::PARAM_VALIDATION_LEVEL, $mainResult);
$paramsManager->save();
return array(
'mainLevel' => $mainResult,
'mainBagedClass' => DUPX_Validation_abstract_item::resultLevelToBadgeClass($mainResult),
'mainText' => DUPX_Validation_abstract_item::resultLevelToString($mainResult),
'categoriesLevels' => array(
'database' => $this->getCagegoryResult(self::CAT_DATABASE),
'php' => $this->getCagegoryResult(self::CAT_PHP),
'general' => $this->getCagegoryResult(self::CAT_GENERAL),
'filesystem' => $this->getCagegoryResult(self::CAT_FILESYSTEM),
),
'htmlResult' => DUPX_CTRL::renderPostProcessings($this->getValidationHtmlResult()),
'extraData' => $this->extraData,
);
}
/**
* Run all tests
*
* @return void
*/
protected function runTests()
{
$this->extraData = array();
foreach ($this->tests as $test) {
$test->test(true);
}
}
/**
* Gte validation main result
*
* @return string
*/
protected function getValidationHtmlResult()
{
return dupxTplRender('parts/validation/validation-result', array('validationManager' => $this), false);
}
/**
* Add extra data
*
* @param string $key data key
* @param mixed $value data value
*
* @return void
*/
public function addExtraData($key, $value)
{
$this->extraData[$key] = $value;
}
/**
* Get category result
*
* @param string $category category
*
* @return DUPX_Validation_abstract_item[]
*/
public function getTestsCategory($category)
{
$result = array();
foreach ($this->tests as $test) {
if ($test->getCategory() === $category) {
$result[] = $test;
}
}
return $result;
}
/**
* Get category result
*
* @param string $category category
*
* @return int result level enum LV_*
*/
public function getCagegoryResult($category)
{
$result = PHP_INT_MAX;
foreach ($this->tests as $test) {
if ($test->getCategory() === $category && $test->test() < $result) {
$result = $test->test();
}
}
if ($result === DUPX_Validation_abstract_item::LV_GOOD) {
$result = DUPX_Validation_abstract_item::LV_PASS;
}
return $result;
}
/**
* Get category badge
*
* @param string $category category
*
* @return string
*/
public function getCagegoryBadge($category)
{
return DUPX_Validation_abstract_item::resultLevelToBadgeClass($this->getCagegoryResult($category));
}
/**
* Get main result
*
* @return int result level enum LV_*
*/
public function getMainResult()
{
$result = PHP_INT_MAX;
foreach ($this->tests as $test) {
if ($test->test() < $result) {
$result = $test->test();
}
}
if ($result === DUPX_Validation_abstract_item::LV_GOOD) {
$result = DUPX_Validation_abstract_item::LV_PASS;
}
return $result;
}
}

View File

@@ -0,0 +1,62 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Core\Params\PrmMng;
class DUPX_Validation_test_cpnl_connection extends DUPX_Validation_abstract_item
{
protected function runTest()
{
if (
DUPX_Validation_database_service::getInstance()->skipDatabaseTests() ||
PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_VIEW_MODE) !== 'cpnl'
) {
return self::LV_SKIP;
}
DUPX_Validation_database_service::getInstance()->setSkipOtherTests(true);
if (DUPX_Validation_database_service::getInstance()->getCpnlConnection() === false) {
return self::LV_FAIL;
} else {
DUPX_Validation_database_service::getInstance()->setSkipOtherTests(false);
return self::LV_PASS;
}
}
public function getTitle()
{
return 'Cpanel connection';
}
protected function failContent()
{
return dupxTplRender('parts/validation/database-tests/cpnl-connection', array(
'isOk' => false,
'cpnlHost' => PrmMng::getInstance()->getValue(PrmMng::PARAM_CPNL_HOST),
'cpnlUser' => PrmMng::getInstance()->getValue(PrmMng::PARAM_CPNL_USER),
'cpnlPass' => PrmMng::getInstance()->getValue(PrmMng::PARAM_CPNL_PASS),
), false);
}
protected function passContent()
{
return dupxTplRender('parts/validation/database-tests/cpnl-connection', array(
'isOk' => true,
'cpnlHost' => PrmMng::getInstance()->getValue(PrmMng::PARAM_CPNL_HOST),
'cpnlUser' => PrmMng::getInstance()->getValue(PrmMng::PARAM_CPNL_USER),
'cpnlPass' => '*****',
), false);
}
}

View File

@@ -0,0 +1,65 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Core\Params\PrmMng;
class DUPX_Validation_test_cpnl_new_user extends DUPX_Validation_abstract_item
{
/** @var ?mixed[] */
private $user = null;
protected function runTest()
{
if (
DUPX_Validation_database_service::getInstance()->skipDatabaseTests() ||
PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_VIEW_MODE) !== 'cpnl' ||
PrmMng::getInstance()->getValue(PrmMng::PARAM_CPNL_DB_USER_CHK) != true
) {
return self::LV_SKIP;
}
DUPX_Validation_database_service::getInstance()->setSkipOtherTests(true);
if ((DUPX_Validation_database_service::getInstance()->cpnlCreateDbUser($this->user)) === false) {
return self::LV_FAIL;
} else {
DUPX_Validation_database_service::getInstance()->setSkipOtherTests(false);
return self::LV_PASS;
}
}
public function getTitle()
{
return 'Create Database User';
}
protected function failContent()
{
return dupxTplRender('parts/validation/database-tests/cpnl-create-user', array(
'isOk' => false,
'dbuser' => PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_USER),
'dbpass' => PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_PASS),
'errorMessage' => $this->user['status'],
), false);
}
protected function passContent()
{
return dupxTplRender('parts/validation/database-tests/cpnl-create-user', array(
'isOk' => true,
'dbuser' => PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_USER),
'dbpass' => '*****',
'errorMessage' => '',
), false);
}
}

View File

@@ -0,0 +1,102 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Core\InstState;
use Duplicator\Installer\Core\Params\PrmMng;
class DUPX_Validation_test_db_affected_tables extends DUPX_Validation_abstract_item
{
const MAX_DISPLAY_TABLE_COUNT = 1000;
/** @var int */
private $affectedTableCount = 0;
/** @var string[] */
private $affectedTables = [];
/** @var string */
private $message = "";
/**
* @return int
* @throws Exception
*/
protected function runTest()
{
$dbAction = PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_ACTION);
if (
DUPX_Validation_database_service::getInstance()->skipDatabaseTests()
|| $dbAction === DUPX_DBInstall::DBACTION_MANUAL
|| $dbAction === DUPX_DBInstall::DBACTION_CREATE
) {
return self::LV_SKIP;
}
if (DUPX_Validation_database_service::getInstance()->dbTablesCount() === 0) {
return self::LV_PASS;
}
$this->affectedTables = DUPX_Validation_database_service::getInstance()->getDBActionAffectedTables($dbAction);
$this->affectedTableCount = count($this->affectedTables);
$partialText = $this->affectedTableCount > self::MAX_DISPLAY_TABLE_COUNT ? self::MAX_DISPLAY_TABLE_COUNT . " of " . $this->affectedTableCount : "All";
if ($dbAction === DUPX_DBInstall::DBACTION_REMOVE_ONLY_TABLES || $dbAction === DUPX_DBInstall::DBACTION_EMPTY) {
$this->message = "{$partialText} tables flagged for <b>removal</b> are list below:";
} else {
$this->message = "{$partialText} tables flagged for <b>back-up and rename</b> are list below:";
}
if (
$this->affectedTableCount > 0 &&
!InstState::isRestoreBackup()
) {
return self::LV_SOFT_WARNING;
}
return self::LV_PASS;
}
/**
* @return string
*/
public function getTitle()
{
return 'Tables Flagged for Removal or Backup';
}
/**
* @return string
*/
protected function passContent()
{
return dupxTplRender('parts/validation/database-tests/db-affected-tables', array(
'isOk' => true,
'message' => $this->message,
'affectedTableCount' => $this->affectedTableCount,
'affectedTables' => array_slice($this->affectedTables, 0, self::MAX_DISPLAY_TABLE_COUNT),
), false);
}
/**
* @return string
*/
protected function swarnContent()
{
return dupxTplRender('parts/validation/database-tests/db-affected-tables', array(
'isOk' => false,
'message' => $this->message,
'affectedTableCount' => $this->affectedTableCount,
'affectedTables' => array_slice($this->affectedTables, 0, self::MAX_DISPLAY_TABLE_COUNT),
), false);
}
}

View File

@@ -0,0 +1,89 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
class DUPX_Validation_test_db_case_sensitive_tables extends DUPX_Validation_abstract_item
{
/** @var string */
protected $errorMessage = '';
/** @var int<-1, max> */
protected $lowerCaseTableNames = -1;
/** @var int<0, max> */
protected $lowerCaseTableNamesSource = 0;
/** @var array<string[]> */
protected $duplicateTables = [];
/** @var string[] */
protected $redundantTables = [];
protected function runTest()
{
$archiveConfig = DUPX_ArchiveConfig::getInstance();
$caseSensitiveTablePresent = $archiveConfig->isTablesCaseSensitive();
if (DUPX_Validation_database_service::getInstance()->skipDatabaseTests() || !$caseSensitiveTablePresent) {
return self::LV_SKIP;
}
$this->duplicateTables = DUPX_ArchiveConfig::getInstance()->getDuplicateTableNames();
$this->redundantTables = DUPX_ArchiveConfig::getInstance()->getRedundantDuplicateTableNames();
$this->lowerCaseTableNames = DUPX_Validation_database_service::getInstance()->caseSensitiveTablesValue();
$this->lowerCaseTableNamesSource = $archiveConfig->dbInfo->lowerCaseTableNames;
$destIsCaseInsensitive = $this->lowerCaseTableNames !== 0;
$sourceIsCaseSensitive = $this->lowerCaseTableNamesSource === 0;
if ($destIsCaseInsensitive && $sourceIsCaseSensitive && count($this->duplicateTables) > 0) {
return self::LV_HARD_WARNING;
}
if ($destIsCaseInsensitive) {
return self::LV_SOFT_WARNING;
}
return self::LV_PASS;
}
public function getTitle()
{
return 'Tables Case Sensitivity';
}
protected function swarnContent()
{
return dupxTplRender('parts/validation/database-tests/db-case-sensitive-tables', array(
'isOk' => false,
'errorMessage' => $this->errorMessage,
'lowerCaseTableNames' => $this->lowerCaseTableNames,
), false);
}
protected function hwarnContent()
{
return dupxTplRender('parts/validation/database-tests/db-case-sensitive-duplicates', array(
'lowerCaseTableNames' => $this->lowerCaseTableNames,
'duplicateTableNames' => $this->duplicateTables,
'reduntantTableNames' => $this->redundantTables,
), false);
}
protected function passContent()
{
return dupxTplRender('parts/validation/database-tests/db-case-sensitive-tables', array(
'isOk' => true,
'errorMessage' => $this->errorMessage,
'lowerCaseTableNames' => $this->lowerCaseTableNames,
), false);
}
}

View File

@@ -0,0 +1,59 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Core\Params\PrmMng;
class DUPX_Validation_test_db_cleanup extends DUPX_Validation_abstract_item
{
/** @var string */
protected $errorMessage = '';
protected function runTest()
{
if (DUPX_Validation_database_service::getInstance()->isDatabaseCreated() === false) {
return self::LV_SKIP;
}
if (DUPX_Validation_database_service::getInstance()->cleanUpDatabase($this->errorMessage)) {
return self::LV_PASS;
} else {
return self::LV_HARD_WARNING;
}
}
public function getTitle()
{
return 'Database cleanup';
}
protected function hwarnContent()
{
return dupxTplRender('parts/validation/database-tests/db-cleanup', array(
'isOk' => false,
'dbname' => PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_NAME),
'isCpanel' => (PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_VIEW_MODE) === 'cpnl'),
'errorMessage' => $this->errorMessage,
), false);
}
protected function passContent()
{
return dupxTplRender('parts/validation/database-tests/db-cleanup', array(
'isOk' => true,
'dbname' => PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_NAME),
'isCpanel' => (PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_VIEW_MODE) === 'cpnl'),
'errorMessage' => $this->errorMessage,
), false);
}
}

View File

@@ -0,0 +1,60 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Core\Params\PrmMng;
class DUPX_Validation_test_db_connection extends DUPX_Validation_abstract_item
{
protected function runTest()
{
if (DUPX_Validation_database_service::getInstance()->skipDatabaseTests()) {
return self::LV_SKIP;
}
DUPX_Validation_database_service::getInstance()->setSkipOtherTests(true);
if (DUPX_Validation_database_service::getInstance()->getDbConnection() === false) {
return self::LV_FAIL;
} else {
DUPX_Validation_database_service::getInstance()->setSkipOtherTests(false);
return self::LV_PASS;
}
}
public function getTitle()
{
return 'Host Connection';
}
protected function failContent()
{
return dupxTplRender('parts/validation/database-tests/db-connection', array(
'isOk' => false,
'dbhost' => PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_HOST),
'dbuser' => PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_USER),
'dbpass' => PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_PASS),
'mysqlConnErr' => mysqli_connect_error(),
), false);
}
protected function passContent()
{
return dupxTplRender('parts/validation/database-tests/db-connection', array(
'isOk' => true,
'dbhost' => PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_HOST),
'dbuser' => PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_USER),
'dbpass' => '*****',
'mysqlConnErr' => '',
), false);
}
}

View File

@@ -0,0 +1,80 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Core\Params\PrmMng;
class DUPX_Validation_test_db_create extends DUPX_Validation_abstract_item
{
/**
*
* @var bool
*/
protected $alreadyExists = false;
/**
*
* @var string
*/
protected $errorMessage = '';
protected function runTest()
{
if (
DUPX_Validation_database_service::getInstance()->skipDatabaseTests() ||
PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_ACTION) !== DUPX_DBInstall::DBACTION_CREATE
) {
return self::LV_SKIP;
}
// already exists test
if (DUPX_Validation_database_service::getInstance()->databaseExists()) {
$this->errorMessage = 'Database already exists';
$this->alreadyExists = true;
return self::LV_FAIL;
}
if (DUPX_Validation_database_service::getInstance()->createDatabase($this->errorMessage) === false) {
return self::LV_FAIL;
}
return self::LV_PASS;
}
public function getTitle()
{
return 'Create New Database';
}
protected function failContent()
{
return dupxTplRender('parts/validation/database-tests/db-create', array(
'isOk' => false,
'alreadyExists' => $this->alreadyExists,
'errorMessage' => $this->errorMessage,
'isCpanel' => (PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_VIEW_MODE) === 'cpnl'),
'dbname' => PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_NAME),
), false);
}
protected function passContent()
{
return dupxTplRender('parts/validation/database-tests/db-create', array(
'isOk' => true,
'alreadyExists' => $this->alreadyExists,
'errorMessage' => $this->errorMessage,
'isCpanel' => (PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_VIEW_MODE) === 'cpnl'),
'dbname' => PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_NAME),
), false);
}
}

View File

@@ -0,0 +1,62 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Core\InstState;
class DUPX_Validation_test_db_excluded extends DUPX_Validation_abstract_item
{
/**
* @return int
*/
protected function runTest()
{
if (!InstState::dbDoNothing()) {
return self::LV_PASS;
}
DUPX_Validation_database_service::getInstance()->setSkipOtherTests();
return self::LV_SOFT_WARNING;
}
/**
* @return string
*/
public function getTitle()
{
return 'Extract only files';
}
/**
* @return string
*/
protected function swarnContent()
{
return dupxTplRender('parts/validation/database-tests/db-excluded', array(
'dbExcluded' => DUPX_ArchiveConfig::getInstance()->isDBExcluded(),
'isOk' => false,
), false);
}
/**
* @return string
*/
protected function passContent()
{
return dupxTplRender('parts/validation/database-tests/db-excluded', array(
'dbExcluded' => false,
'isOk' => true,
), false);
}
}

View File

@@ -0,0 +1,53 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
class DUPX_Validation_test_db_gtid_mode extends DUPX_Validation_abstract_item
{
/** @var string */
protected $errorMessage = '';
protected function runTest()
{
if (DUPX_Validation_database_service::getInstance()->skipDatabaseTests()) {
return self::LV_SKIP;
}
if (DUPX_Validation_database_service::getInstance()->dbGtidModeEnabled($this->errorMessage)) {
return self::LV_SOFT_WARNING;
} else {
return self::LV_PASS;
}
}
public function getTitle()
{
return 'Database GTID Mode';
}
protected function swarnContent()
{
return dupxTplRender('parts/validation/database-tests/db-gtid-mode', array(
'isOk' => false,
'errorMessage' => $this->errorMessage,
), false);
}
protected function passContent()
{
return dupxTplRender('parts/validation/database-tests/db-gtid-mode', array(
'isOk' => true,
'errorMessage' => $this->errorMessage,
), false);
}
}

View File

@@ -0,0 +1,67 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Core\Params\PrmMng;
use Duplicator\Libs\Snap\SnapIO;
class DUPX_Validation_test_db_host_name extends DUPX_Validation_abstract_item
{
/** @var string */
protected $fixedHost = '';
protected function runTest()
{
if (DUPX_Validation_database_service::getInstance()->skipDatabaseTests()) {
return self::LV_SKIP;
}
DUPX_Validation_database_service::getInstance()->setSkipOtherTests(true);
$host = PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_HOST);
//Host check
$parsed_host_info = DUPX_DB::parseDBHost($host);
$parsed_host = $parsed_host_info[0];
$isInvalidHost = $parsed_host == 'http' || $parsed_host == "https";
if ($isInvalidHost) {
$this->fixedHost = SnapIO::untrailingslashit(str_replace($parsed_host . "://", "", $host));
return self::LV_FAIL;
} else {
DUPX_Validation_database_service::getInstance()->setSkipOtherTests(false);
return self::LV_PASS;
}
}
public function getTitle()
{
return 'Host Name';
}
protected function failContent()
{
return dupxTplRender('parts/validation/database-tests/db-host-name', array(
'isOk' => false,
'host' => PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_HOST),
'fixedHost' => $this->fixedHost,
), false);
}
protected function passContent()
{
return dupxTplRender('parts/validation/database-tests/db-host-name', array(
'isOk' => true,
'host' => PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_HOST),
'fixedHost' => '',
), false);
}
}

View File

@@ -0,0 +1,76 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Core\Params\PrmMng;
class DUPX_Validation_test_db_manual_tabels_count extends DUPX_Validation_abstract_item
{
const MIN_TABLES_NUM = 10;
/** @var string */
protected $errorMessage = '';
/** @var int<0, max> */
protected $numTables = 0;
protected function runTest()
{
if (
DUPX_Validation_database_service::getInstance()->skipDatabaseTests() ||
PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_ACTION) !== DUPX_DBInstall::DBACTION_MANUAL
) {
return self::LV_SKIP;
}
$this->numTables = DUPX_Validation_database_service::getInstance()->dbTablesCount($this->errorMessage);
if ($this->numTables >= self::MIN_TABLES_NUM) {
return self::LV_PASS;
} else {
return self::LV_HARD_WARNING;
}
}
public function getTitle()
{
return 'Manual Table Check';
}
protected function hwarnContent()
{
return dupxTplRender(
'parts/validation/database-tests/db-manual-tables-count',
array(
'isOk' => false,
'dbname' => PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_NAME),
'numTables' => $this->numTables,
'errorMessage' => $this->errorMessage,
),
false
);
}
protected function passContent()
{
return dupxTplRender(
'parts/validation/database-tests/db-manual-tables-count',
array(
'isOk' => true,
'dbname' => PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_NAME),
'numTables' => $this->numTables,
'errorMessage' => $this->errorMessage,
),
false
);
}
}

View File

@@ -0,0 +1,91 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Core\InstState;
use Duplicator\Installer\Core\Params\PrmMng;
use Duplicator\Libs\Snap\SnapWP;
class DUPX_Validation_test_db_multiple_wp_installs extends DUPX_Validation_abstract_item
{
/**
* @var string[] unique wp prefixes in the DB
*/
protected $uniquePrefixes = array();
/**
* Check mutiple db install in database
*
* @return int
*/
protected function runTest()
{
$dbAction = PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_ACTION);
if (
DUPX_Validation_database_service::getInstance()->skipDatabaseTests()
|| $dbAction === DUPX_DBInstall::DBACTION_MANUAL
|| $dbAction === DUPX_DBInstall::DBACTION_CREATE
) {
return self::LV_SKIP;
}
if (DUPX_Validation_database_service::getInstance()->dbTablesCount() === 0 || InstState::isAddSiteOnMultisite()) {
return self::LV_PASS;
}
$affectedTables = DUPX_Validation_database_service::getInstance()->getDBActionAffectedTables($dbAction);
$this->uniquePrefixes = SnapWP::getUniqueWPTablePrefixes($affectedTables);
if (count($this->uniquePrefixes) > 1) {
return self::LV_SOFT_WARNING;
}
return self::LV_PASS;
}
/**
* Get test title
*
* @return string
*/
public function getTitle()
{
return 'Multiple WP Installs';
}
/**
* Return content for test status: soft warning
*
* @return string
*/
protected function swarnContent()
{
return dupxTplRender('parts/validation/database-tests/db-multiple-wp-installs', array(
'isOk' => false,
'uniquePrefixes' => $this->uniquePrefixes,
), false);
}
/**
* Return content for test status: pass
*
* @return string
*/
protected function passContent()
{
return dupxTplRender('parts/validation/database-tests/db-multiple-wp-installs', array(
'isOk' => true,
'uniquePrefixes' => $this->uniquePrefixes,
), false);
}
}

View File

@@ -0,0 +1,59 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Core\Params\PrmMng;
class DUPX_Validation_test_db_prefix_too_long extends DUPX_Validation_abstract_item
{
/** @var string */
protected $errorMessage = '';
protected function runTest()
{
if (DUPX_Validation_database_service::getInstance()->skipDatabaseTests()) {
return self::LV_SKIP;
}
DUPX_Validation_database_service::getInstance()->setSkipOtherTests(true);
if (DUPX_Validation_database_service::getInstance()->checkDbPrefixTooLong($this->errorMessage)) {
DUPX_Validation_database_service::getInstance()->setSkipOtherTests(false);
return self::LV_PASS;
} else {
return self::LV_FAIL;
}
}
public function getTitle()
{
return 'Prefix too long';
}
protected function failContent()
{
return dupxTplRender('parts/validation/database-tests/db-prefix-too-long', array(
'isOk' => false,
'errorMessage' => $this->errorMessage,
'tooLongNewTableNames' => DUPX_Validation_database_service::getInstance()->getTooLongNewTableNames(),
), false);
}
protected function passContent()
{
return dupxTplRender('parts/validation/database-tests/db-prefix-too-long', array(
'isOk' => true,
'errorMessage' => $this->errorMessage,
'tooLongNewTableNames' => DUPX_Validation_database_service::getInstance()->getTooLongNewTableNames(),
), false);
}
}

View File

@@ -0,0 +1,44 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
class DUPX_Validation_test_db_custom_queries extends DUPX_Validation_abstract_item
{
protected function runTest()
{
if (DUPX_Validation_database_service::getInstance()->skipDatabaseTests()) {
return self::LV_SKIP;
}
if (!DUPX_Validation_database_service::getInstance()->isQueryWorking('SHOW VARIABLES LIKE "version"')) {
return self::LV_FAIL;
}
return self::LV_PASS;
}
public function getTitle()
{
return "Privileges: 'Show Variables' Query";
}
protected function failContent()
{
return dupxTplRender('parts/validation/database-tests/db-show-variables', array('pass' => false), false);
}
protected function passContent()
{
return dupxTplRender('parts/validation/database-tests/db-show-variables', array('pass' => true), false);
}
}

View File

@@ -0,0 +1,86 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
class DUPX_Validation_test_db_supported_charset extends DUPX_Validation_abstract_item
{
/** @var string */
protected $errorMessage = '';
/** @var string[] */
protected $charsetsList = array();
/** @var string[] */
protected $collationsList = array();
/** @var string[] */
protected $invalidCharsets = array();
/** @var string[] */
protected $invalidCollations = array();
/** @var mixed[] */
protected $extraData = array();
protected function runTest()
{
if (DUPX_Validation_database_service::getInstance()->skipDatabaseTests()) {
return self::LV_SKIP;
}
try {
$archiveConfig = DUPX_ArchiveConfig::getInstance();
$this->charsetsList = $archiveConfig->dbInfo->charSetList;
$this->collationsList = $archiveConfig->dbInfo->collationList;
$this->invalidCharsets = $archiveConfig->invalidCharsets();
$this->invalidCollations = $archiveConfig->invalidCollations();
if (empty($this->invalidCharsets) && empty($this->invalidCollations)) {
return self::LV_PASS;
} else {
return self::LV_HARD_WARNING;
}
} catch (Exception $e) {
$this->errorMessage = $e->getMessage();
return self::LV_FAIL;
}
}
public function getTitle()
{
return 'Character Set and Collation Capability';
}
protected function failContent()
{
$dbFuncs = DUPX_DB_Functions::getInstance();
return dupxTplRender('parts/validation/database-tests/db-supported-charset', array(
'testResult' => $this->testResult,
'extraData' => $this->extraData,
'charsetsList' => $this->charsetsList,
'collationsList' => $this->collationsList,
'invalidCharsets' => $this->invalidCharsets,
'invalidCollations' => $this->invalidCollations,
'usedCharset' => $dbFuncs->getRealCharsetByParam(),
'usedCollate' => $dbFuncs->getRealCollateByParam(),
'errorMessage' => $this->errorMessage,
), false);
}
protected function hwarnContent()
{
return $this->failContent();
}
protected function passContent()
{
return $this->failContent();
}
}

View File

@@ -0,0 +1,105 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
class DUPX_Validation_test_db_supported_default_charset extends DUPX_Validation_abstract_item
{
/** @var string */
protected $errorMessage = '';
/** @var bool */
protected $charsetOk = true;
/** @var bool */
protected $collateOk = true;
/** @var string */
protected $sourceCharset = '';
/** @var string */
protected $sourceCollate = '';
/**
* Run the test
*
* @return int Enum LV_* result
*/
protected function runTest()
{
if (DUPX_Validation_database_service::getInstance()->skipDatabaseTests()) {
return self::LV_SKIP;
}
try {
$archiveConfig = DUPX_ArchiveConfig::getInstance();
$dbFuncs = DUPX_DB_Functions::getInstance();
$this->sourceCharset = $archiveConfig->getWpConfigDefineValue('DB_CHARSET', '');
$this->sourceCollate = $archiveConfig->getWpConfigDefineValue('DB_COLLATE', '');
$data = $dbFuncs->getCharsetAndCollationData();
if (!array_key_exists($this->sourceCharset, $data)) {
$this->charsetOk = false;
} elseif (strlen($this->sourceCollate) > 0 && !in_array($this->sourceCollate, $data[$this->sourceCharset]['collations'])) {
$this->collateOk = false;
}
if ($this->charsetOk && $this->collateOk) {
return self::LV_PASS;
} else {
return self::LV_SOFT_WARNING;
}
} catch (Exception $e) {
$this->errorMessage = $e->getMessage();
return self::LV_FAIL;
}
}
/**
* @return string
*/
public function getTitle()
{
return 'Character Set and Collation Support';
}
/**
* @return string
*/
protected function failContent()
{
$dbFuncs = DUPX_DB_Functions::getInstance();
return dupxTplRender('parts/validation/database-tests/db-supported-default-charset', array(
'testResult' => $this->testResult,
'charsetOk' => $this->charsetOk,
'collateOk' => $this->collateOk,
'sourceCharset' => $this->sourceCharset,
'sourceCollate' => $this->sourceCollate,
'usedCharset' => $dbFuncs->getRealCharsetByParam(),
'usedCollate' => $dbFuncs->getRealCollateByParam(),
'errorMessage' => $this->errorMessage,
), false);
}
/**
* @return string
*/
protected function swarnContent()
{
return $this->failContent();
}
/**
* @return string
*/
protected function passContent()
{
return $this->failContent();
}
}

View File

@@ -0,0 +1,74 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
class DUPX_Validation_test_db_supported_engine extends DUPX_Validation_abstract_item
{
/** @var string */
protected $errorMessage = '';
/** @var string[] */
protected $invalidEngines = [];
/** @var string */
protected $defaultEngine = "";
/** @var bool */
protected $engineListRead = false;
protected function runTest()
{
if (DUPX_Validation_database_service::getInstance()->skipDatabaseTests()) {
return self::LV_SKIP;
}
try {
$this->invalidEngines = DUPX_ArchiveConfig::getInstance()->invalidEngines();
$this->defaultEngine = DUPX_DB_Functions::getInstance()->getDefaultEngine();
$this->engineListRead = true;
if (empty($this->invalidEngines)) {
return self::LV_PASS;
} else {
return self::LV_HARD_WARNING;
}
} catch (Exception $e) {
$this->errorMessage = $e->getMessage();
$this->engineListRead = false;
return self::LV_HARD_WARNING;
}
}
public function getTitle()
{
return 'Database Engine Support';
}
protected function failContent()
{
return dupxTplRender('parts/validation/database-tests/db-supported-engine', array(
'testResult' => $this->testResult,
'invalidEngines' => $this->invalidEngines,
'defaultEngine' => $this->defaultEngine,
'errorMessage' => $this->errorMessage,
'engineListRead' => $this->engineListRead,
), false);
}
protected function hwarnContent()
{
return $this->failContent();
}
protected function passContent()
{
return $this->failContent();
}
}

View File

@@ -0,0 +1,50 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
class DUPX_Validation_test_db_triggers extends DUPX_Validation_abstract_item
{
protected function runTest()
{
if (DUPX_Validation_database_service::getInstance()->skipDatabaseTests()) {
return self::LV_SKIP;
}
if (count(DUPX_ArchiveConfig::getInstance()->dbInfo->triggerList) > 0) {
return self::LV_SOFT_WARNING;
}
return self::LV_PASS;
}
public function getTitle()
{
return 'Source Database Triggers';
}
protected function passContent()
{
return dupxTplRender('parts/validation/database-tests/db-triggers', array(
'isOk' => true,
'triggers' => DUPX_ArchiveConfig::getInstance()->dbInfo->triggerList,
), false);
}
protected function swarnContent()
{
return dupxTplRender('parts/validation/database-tests/db-triggers', array(
'isOk' => false,
'triggers' => DUPX_ArchiveConfig::getInstance()->dbInfo->triggerList,
), false);
}
}

View File

@@ -0,0 +1,57 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Core\Params\PrmMng;
class DUPX_Validation_test_db_user_cleanup extends DUPX_Validation_abstract_item
{
/** @var string */
protected $errorMessage = '';
protected function runTest()
{
if (DUPX_Validation_database_service::getInstance()->isUserCreated() === false) {
return self::LV_SKIP;
}
if (DUPX_Validation_database_service::getInstance()->cleanUpUser($this->errorMessage)) {
return self::LV_PASS;
} else {
return self::LV_HARD_WARNING;
}
}
public function getTitle()
{
return 'User created cleanup';
}
protected function hwarnContent()
{
return dupxTplRender('parts/validation/database-tests/db-user-cleanup', array(
'isOk' => false,
'dbuser' => PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_USER),
'errorMessage' => $this->errorMessage,
), false);
}
protected function passContent()
{
return dupxTplRender('parts/validation/database-tests/db-user-cleanup', array(
'isOk' => true,
'dbuser' => PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_USER),
'errorMessage' => $this->errorMessage,
), false);
}
}

View File

@@ -0,0 +1,94 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Core\Params\PrmMng;
class DUPX_Validation_test_db_user_perms extends DUPX_Validation_abstract_item
{
/** @var array<string, bool> */
protected $perms = array();
/** @var array<string, bool> */
protected $errorMessages = array();
protected function runTest()
{
if (DUPX_Validation_database_service::getInstance()->skipDatabaseTests()) {
return self::LV_SKIP;
}
return DUPX_Validation_database_service::getInstance()->dbCheckUserPerms($this->perms, $this->errorMessages);
}
public function getTitle()
{
return 'Privileges: User Table Access';
}
/**
* @return string
*/
protected function failContent()
{
return dupxTplRender('parts/validation/database-tests/db-user-perms', array(
'testResult' => self::LV_FAIL,
'perms' => $this->perms,
'failedPerms' => array_keys($this->perms, false, true),
'dbname' => PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_NAME),
'dbuser' => PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_USER),
'errorMessages' => $this->errorMessages,
), false);
}
/**
* @return string
*/
protected function passContent()
{
return dupxTplRender('parts/validation/database-tests/db-user-perms', array(
'testResult' => self::LV_PASS,
'perms' => $this->perms,
'dbname' => PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_NAME),
'dbuser' => PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_USER),
'errorMessages' => $this->errorMessages,
), false);
}
/**
* @return string
*/
protected function swarnContent()
{
return dupxTplRender('parts/validation/database-tests/db-user-perms', array(
'testResult' => self::LV_HARD_WARNING,
'perms' => $this->perms,
'dbname' => PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_NAME),
'dbuser' => PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_USER),
'errorMessages' => $this->errorMessages,
), false);
}
/**
* @return string
*/
protected function hwarnContent()
{
return dupxTplRender('parts/validation/database-tests/db-user-perms', array(
'testResult' => self::LV_HARD_WARNING,
'perms' => $this->perms,
'dbname' => PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_NAME),
'dbuser' => PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_USER),
'errorMessages' => $this->errorMessages,
), false);
}
}

View File

@@ -0,0 +1,72 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Libs\Snap\SnapUtil;
class DUPX_Validation_test_db_user_resources extends DUPX_Validation_abstract_item
{
/** @var array<string, int|string> */
private $userResources = array();
/** @var bool */
private $userHasRestrictedResource = false;
protected function runTest()
{
if (DUPX_Validation_database_service::getInstance()->skipDatabaseTests()) {
return self::LV_SKIP;
}
if (($this->userResources = DUPX_Validation_database_service::getInstance()->getUserResources()) !== false) {
$this->userHasRestrictedResource = SnapUtil::inArrayExtended($this->userResources, function ($value) {
return $value > 0;
});
}
if ($this->userHasRestrictedResource) {
return self::LV_SOFT_WARNING;
}
return self::LV_PASS;
}
/**
* @return string
*/
public function getTitle()
{
return 'Privileges: User Resources';
}
/**
* @return string
*/
protected function passContent()
{
return dupxTplRender('parts/validation/database-tests/db-user-resources', array(
'isOk' => !$this->userHasRestrictedResource,
'userResources' => $this->userResources,
), false);
}
/**
* @return string
*/
protected function swarnContent()
{
return dupxTplRender('parts/validation/database-tests/db-user-resources', array(
'isOk' => !$this->userHasRestrictedResource,
'userResources' => $this->userResources,
), false);
}
}

View File

@@ -0,0 +1,110 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Utils\Log\Log;
use Duplicator\Libs\Snap\SnapDB;
class DUPX_Validation_test_db_version extends DUPX_Validation_abstract_item
{
/** @var string */
protected $sourceDBVersion = '';
/** @var string */
protected $hostDBVersion = '';
/** @var string */
protected $hostDBEngine = '';
/** @var string */
protected $sourceDBEngine = '';
/** @var bool */
protected $dbsOfSameType = true;
/**
* Run the test
*
* @return int Enum LV_* result
*/
protected function runTest()
{
if (DUPX_Validation_database_service::getInstance()->skipDatabaseTests()) {
return self::LV_SKIP;
}
DUPX_Validation_database_service::getInstance()->setSkipOtherTests(true);
$this->hostDBVersion = DUPX_DB::getVersion(DUPX_Validation_database_service::getInstance()->getDbConnection());
$this->sourceDBVersion = DUPX_ArchiveConfig::getInstance()->version_db;
Log::info('Current DB version: ' . Log::v2str($this->hostDBVersion) . ' Source DB version: ' . Log::v2str($this->sourceDBVersion), Log::LV_DETAILED);
if (version_compare($this->hostDBVersion, '5.0.0', '<')) {
return self::LV_FAIL;
}
DUPX_Validation_database_service::getInstance()->setSkipOtherTests(false);
$this->hostDBEngine = SnapDB::getDBEngine(DUPX_Validation_database_service::getInstance()->getDbConnection());
$this->sourceDBEngine = DUPX_ArchiveConfig::getInstance()->dbInfo->dbEngine;
$this->dbsOfSameType = $this->sourceDBEngine === $this->hostDBEngine;
if (!$this->dbsOfSameType || intval($this->hostDBVersion) < intval($this->sourceDBVersion)) {
return self::LV_SOFT_WARNING;
}
return self::LV_PASS;
}
/**
* Get the title of the test
*
* @return string
*/
public function getTitle()
{
return 'Database Version';
}
/**
* @return string
*/
protected function failContent()
{
return dupxTplRender('parts/validation/database-tests/db-version', array(
'isOk' => false,
'hostDBVersion' => $this->hostDBVersion,
), false);
}
/**
* @return string
*/
protected function swarnContent()
{
return dupxTplRender('parts/validation/database-tests/db-version-swarn', array(
'hostDBVersion' => $this->hostDBVersion,
'sourceDBVersion' => $this->sourceDBVersion,
'hostDBEngine' => $this->hostDBEngine,
'sourceDBEngine' => $this->sourceDBEngine,
'dbsOfSameType' => $this->dbsOfSameType,
), false);
}
/**
* @return string
*/
protected function passContent()
{
return dupxTplRender('parts/validation/database-tests/db-version', array(
'isOk' => true,
'hostDBVersion' => $this->hostDBVersion,
), false);
}
}

View File

@@ -0,0 +1,72 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Core\Params\PrmMng;
class DUPX_Validation_test_db_visibility extends DUPX_Validation_abstract_item
{
/** @var string */
protected $errorMessage = '';
protected function runTest()
{
if (DUPX_Validation_database_service::getInstance()->skipDatabaseTests()) {
return self::LV_SKIP;
}
DUPX_Validation_database_service::getInstance()->setSkipOtherTests(true);
if (DUPX_Validation_database_service::getInstance()->checkDbVisibility($this->errorMessage)) {
DUPX_Validation_database_service::getInstance()->setSkipOtherTests(false);
return self::LV_PASS;
} else {
return self::LV_FAIL;
}
}
/**
* @return string
*/
public function getTitle()
{
return 'Privileges: User Visibility';
}
/**
* @return string
*/
protected function failContent()
{
return dupxTplRender('parts/validation/database-tests/db-visibility', array(
'isOk' => false,
'databases' => DUPX_Validation_database_service::getInstance()->getDatabases(),
'dbname' => PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_NAME),
'dbuser' => PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_USER),
'errorMessage' => $this->errorMessage,
), false);
}
/**
* @return string
*/
protected function passContent()
{
return dupxTplRender('parts/validation/database-tests/db-visibility', array(
'isOk' => true,
'databases' => DUPX_Validation_database_service::getInstance()->getDatabases(),
'dbname' => PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_NAME),
'dbuser' => PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_USER),
'errorMessage' => $this->errorMessage,
), false);
}
}

View File

@@ -0,0 +1,70 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Core\Params\PrmMng;
class DUPX_Validation_test_addon_sites extends DUPX_Validation_abstract_item
{
/**
*
* @return int
*/
protected function runTest()
{
$list = self::getAddonsListsFolders();
if (PrmMng::getInstance()->getValue(PrmMng::PARAM_ARCHIVE_ACTION) === DUP_PRO_Extraction::ACTION_DO_NOTHING) {
return self::LV_GOOD;
}
if (count($list) > 0) {
return self::LV_SOFT_WARNING;
} else {
return self::LV_GOOD;
}
}
/**
*
* @staticvar string[] $addonListFolder
*
* @return string[]
*/
public static function getAddonsListsFolders()
{
static $addonListFolder = null;
if (is_null($addonListFolder)) {
$addonListFolder = DUPX_Server::getWpAddonsSiteLists();
}
return $addonListFolder;
}
public function getTitle()
{
return 'Addon Sites';
}
protected function swarnContent()
{
return dupxTplRender('parts/validation/tests/addon-sites', array(
'testResult' => $this->testResult,
'pathsList' => self::getAddonsListsFolders(),
), false);
}
protected function goodContent()
{
return $this->swarnContent();
}
}

View File

@@ -0,0 +1,47 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
class DUPX_Validation_test_archive_check extends DUPX_Validation_abstract_item
{
protected function runTest()
{
if (DUPX_Conf_Utils::archiveExists()) {
return self::LV_PASS;
} else {
return self::LV_SOFT_WARNING;
}
}
public function getTitle()
{
return 'Archive Check';
}
protected function failContent()
{
return dupxTplRender('parts/validation/tests/archive-check', array(
'testResult' => $this->testResult,
), false);
}
protected function swarnContent()
{
return $this->failContent();
}
protected function passContent()
{
return $this->failContent();
}
}

View File

@@ -0,0 +1,43 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
class DUPX_Validation_test_dbonly_iswordpress extends DUPX_Validation_abstract_item
{
protected function runTest()
{
if (!DUPX_ArchiveConfig::getInstance()->isDBOnly()) {
return self::LV_SKIP;
}
if (DUPX_Server::isWordPress()) {
return self::LV_GOOD;
} else {
return self::LV_SOFT_WARNING;
}
}
public function getTitle()
{
return 'Database Only';
}
protected function swarnContent()
{
return dupxTplRender('parts/validation/tests/dbonly-iswordpress', array(), false);
}
protected function goodContent()
{
return dupxTplRender('parts/validation/tests/dbonly-iswordpress', array(), false);
}
}

View File

@@ -0,0 +1,70 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Core\InstState;
use Duplicator\Installer\Core\Params\PrmMng;
use Duplicator\Installer\Models\ScanInfo;
use Duplicator\Libs\Snap\SnapIO;
class DUPX_Validation_test_disk_space extends DUPX_Validation_abstract_item
{
/** @var int */
private $freeSpace = 0;
/** @var int */
private $archiveSize = 0;
/** @var int */
private $extractedSize = 0;
protected function runTest()
{
if (!function_exists('disk_free_space') || InstState::isRecoveryMode()) {
return self::LV_SKIP;
}
// if home path is root path is necessary do a trailingslashit
$realPath = SnapIO::safePathTrailingslashit(PrmMng::getInstance()->getValue(PrmMng::PARAM_PATH_NEW));
$this->freeSpace = (int) @disk_free_space($realPath);
$this->archiveSize = DUPX_Conf_Utils::archiveExists() ? DUPX_Conf_Utils::archiveSize() : 1;
$this->extractedSize = ScanInfo::getInstance()->getUSize();
if ($this->freeSpace && $this->archiveSize > 0 && $this->freeSpace > ($this->extractedSize + $this->archiveSize)) {
return self::LV_GOOD;
} else {
return self::LV_SOFT_WARNING;
}
}
public function getTitle()
{
return 'Disk Space';
}
protected function swarnContent()
{
return dupxTplRender('parts/validation/tests/diskspace', array(
'freeSpace' => DUPX_U::readableByteSize($this->freeSpace),
'requiredSpace' => DUPX_U::readableByteSize($this->archiveSize + $this->extractedSize),
'isOk' => false,
), false);
}
protected function goodContent()
{
return dupxTplRender('parts/validation/tests/diskspace', array(
'freeSpace' => DUPX_U::readableByteSize($this->freeSpace),
'requiredSpace' => DUPX_U::readableByteSize($this->archiveSize + $this->extractedSize),
'isOk' => true,
), false);
}
}

View File

@@ -0,0 +1,170 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Core\InstState;
use Duplicator\Installer\Models\ScanInfo;
use Duplicator\Installer\Package\PComponents;
class DUPX_Validation_test_importable extends DUPX_Validation_abstract_item
{
/** @var string[] */
protected $failMessages = [];
/**
* Run test
*
* @return int test status enum
*/
protected function runTest()
{
$archiveConf = DUPX_ArchiveConfig::getInstance();
$coreFoldersCheck = false;
$subsitesCheck = false;
$globalTablesCheck = false;
$partialSubsitesCheck = false;
switch (InstState::getInstType()) {
case InstState::TYPE_SINGLE:
case InstState::TYPE_RBACKUP_SINGLE:
case InstState::TYPE_RECOVERY_SINGLE:
$coreFoldersCheck = true;
$globalTablesCheck = true;
break;
case InstState::TYPE_MSUBDOMAIN:
case InstState::TYPE_MSUBFOLDER:
case InstState::TYPE_RBACKUP_MSUBDOMAIN:
case InstState::TYPE_RBACKUP_MSUBFOLDER:
case InstState::TYPE_RECOVERY_MSUBDOMAIN:
case InstState::TYPE_RECOVERY_MSUBFOLDER:
$coreFoldersCheck = true;
$subsitesCheck = true;
$globalTablesCheck = true;
$partialSubsitesCheck = true;
break;
case InstState::TYPE_STANDALONE:
$coreFoldersCheck = true;
$subsitesCheck = true;
break;
case InstState::TYPE_SINGLE_ON_SUBDOMAIN:
case InstState::TYPE_SINGLE_ON_SUBFOLDER:
$globalTablesCheck = true;
break;
case InstState::TYPE_SUBSITE_ON_SUBDOMAIN:
case InstState::TYPE_SUBSITE_ON_SUBFOLDER:
$subsitesCheck = true;
break;
case InstState::TYPE_NOT_SET:
default:
throw new Exception('Unknown mode');
}
$result = self::LV_PASS;
foreach (PComponents::COMPONENTS_DEFAULT as $component) {
if (
in_array($component, $archiveConf->components)
) {
$this->failMessages[] = 'Component <b>' . PComponents::getLabel($component) . '</b> ' .
'<i class="fas fa-check-circle green"></i>' . ' included.';
} else {
$this->failMessages[] = 'Component <b>' . PComponents::getLabel($component) . '</b> ' .
'<i class="fas fa-times-circle maroon"></i>' . ' excluded.';
if ($component != PComponents::COMP_OTHER) {
$result = self::LV_HARD_WARNING;
}
}
}
if ($coreFoldersCheck) {
if (ScanInfo::getInstance()->hasFilteredCoreFolders()) {
$this->failMessages[] = '<i class="fas fa-times-circle maroon"></i>' .
' Some Wordpress core folders are missing. (e.g. wp-admin, wp-content, wp-includes, uploads, plugins, and themes folders)';
$result = self::LV_HARD_WARNING;
}
}
if ($partialSubsitesCheck) {
if ($archiveConf->mu_is_filtered) {
$this->failMessages[] = '<i class="fas fa-times-circle maroon"></i>' .
' In This Backup, some sub-sites of the multisite installation have been excluded.';
$result = self::LV_HARD_WARNING;
}
}
if ($subsitesCheck) {
for ($i = 0; $i < count($archiveConf->subsites); $i++) {
if (
empty($archiveConf->subsites[$i]->filteredTables) &&
empty($archiveConf->subsites[$i]->filteredPaths)
) {
break;
}
}
if ($i >= count($archiveConf->subsites)) {
$this->failMessages[] = '<i class="fas fa-times-circle maroon"></i>' .
' The Backup does not have any importable subsite.';
$result = self::LV_HARD_WARNING;
}
}
if ($globalTablesCheck && !InstState::dbDoNothing()) {
if ($archiveConf->dbInfo->tablesBaseCount != $archiveConf->dbInfo->tablesFinalCount) {
$this->failMessages[] = '<i class="fas fa-times-circle maroon"></i>' .
' The Backup is missing some of the site tables.';
$result = self::LV_HARD_WARNING;
}
}
return $result;
}
/**
* Get test title
*
* @return string
*/
public function getTitle()
{
return 'Partial Backup Check';
}
/**
* Render fail content
*
* @return string
*/
protected function hwarnContent()
{
return dupxTplRender(
'parts/validation/tests/importable-package',
array(
'testResult' => $this->testResult,
'failMessages' => $this->failMessages,
),
false
);
}
/**
* Render pass content
*
* @return string
*/
protected function passContent()
{
return $this->hwarnContent();
}
}

View File

@@ -0,0 +1,62 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
use Duplicator\Installer\Core\InstState;
use Duplicator\Installer\Core\Params\PrmMng;
use Duplicator\Libs\Snap\SnapUtil;
class DUPX_Validation_test_importer_version extends DUPX_Validation_abstract_item
{
/**
*
* @return int
*/
protected function runTest()
{
if (!InstState::isImportFromBackendMode()) {
return self::LV_SKIP;
}
$overwriteData = PrmMng::getInstance()->getValue(PrmMng::PARAM_OVERWRITE_SITE_DATA);
if (SnapUtil::versionCompare($overwriteData['dupVersion'], DUPX_VERSION, '<', 3)) {
return self::LV_FAIL;
}
return self::LV_PASS;
}
/**
* Return test ticekt
*
* @return string
*/
public function getTitle()
{
return 'Duplicator importer version';
}
protected function failContent()
{
$overwriteData = PrmMng::getInstance()->getValue(PrmMng::PARAM_OVERWRITE_SITE_DATA);
return dupxTplRender('parts/validation/tests/importer-version', array(
'testResult' => $this->testResult,
'importerVer' => ($overwriteData['dupVersion'] == '0' ? 'Unknown' : $overwriteData['dupVersion']),
), false);
}
protected function passContent()
{
return $this->failContent();
}
}

View File

@@ -0,0 +1,131 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Core\InstState;
use Duplicator\Installer\Core\Params\PrmMng;
use Duplicator\Libs\Snap\SnapIO;
class DUPX_Validation_test_iswritable_configs extends DUPX_Validation_abstract_item
{
/** @var bool[] */
protected $configsCheck = array(
'wpconfig' => false,
'htaccess' => false,
'other' => false,
);
/** @var string[] */
protected $notWritableConfigsList = array();
/**
* Run test
*
* @return int
*/
protected function runTest()
{
$this->configsCheck = self::configsWritableChecks();
foreach ($this->configsCheck as $check) {
if ($check === false) {
if (
InstState::isRestoreBackup() ||
DUPX_Custom_Host_Manager::getInstance()->isManaged() !== false
) {
return self::LV_SOFT_WARNING;
} else {
return self::LV_HARD_WARNING;
}
}
}
return self::LV_PASS;
}
/**
* try to set wigth config permission and check if configs files are writeable
*
* @return array<string, bool>
*/
public static function configsWritableChecks()
{
$result = array();
// if home path is root path is necessary do a trailingslashit
$homePath = SnapIO::safePathTrailingslashit(PrmMng::getInstance()->getValue(PrmMng::PARAM_PATH_NEW));
if (!SnapIO::dirAddFullPermsAndCheckResult($homePath)) {
$result['wpconfig'] = false;
$result['htaccess'] = false;
$result['other'] = false;
} else {
$configFile = $homePath . 'wp-config.php';
if (file_exists($configFile)) {
$result['wpconfig'] = SnapIO::fileAddFullPermsAndCheckResult($configFile);
} else {
$result['wpconfig'] = true;
}
$configFile = $homePath . '.htaccess';
if (file_exists($configFile)) {
$result['htaccess'] = SnapIO::fileAddFullPermsAndCheckResult($configFile);
} else {
$result['htaccess'] = true;
}
$result['other'] = true;
$configFile = $homePath . 'web.config';
if (file_exists($configFile) && !SnapIO::fileAddFullPermsAndCheckResult($configFile)) {
$result['other'] = false;
}
$configFile = $homePath . '.user.ini';
if (file_exists($configFile) && !SnapIO::fileAddFullPermsAndCheckResult($configFile)) {
$result['other'] = false;
}
$configFile = $homePath . 'php.ini';
if (file_exists($configFile) && !SnapIO::fileAddFullPermsAndCheckResult($configFile)) {
$result['other'] = false;
}
}
return $result;
}
/**
*
* @return string
*/
public function getTitle()
{
return 'Permissions: Configs Files ';
}
protected function hwarnContent()
{
return dupxTplRender('parts/validation/tests/configs-is-writable', array(
'testResult' => $this->testResult,
'configsCheck' => $this->configsCheck,
), false);
}
protected function swarnContent()
{
return $this->hwarnContent();
}
protected function passContent()
{
return $this->hwarnContent();
}
}

View File

@@ -0,0 +1,193 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Core\InstState;
use Duplicator\Installer\Core\Params\PrmMng;
use Duplicator\Libs\Snap\SnapIO;
use Duplicator\Libs\Snap\SnapWP;
class DUPX_Validation_test_iswritable extends DUPX_Validation_abstract_item
{
const TEMP_PHP_FILE_NAME = 'dup_tmp_php_file_test.php';
/** @var string[] */
protected $faildDirPerms = array();
/** @var mixed[] */
protected $phpPerms = array();
/**
* Runs Test
*
* @return int
* @throws Exception
*/
protected function runTest()
{
$this->faildDirPerms = $this->checkWritePermissions();
$testPass = (count($this->faildDirPerms) == 0);
$prmMng = PrmMng::getInstance();
if ($prmMng->getValue(PrmMng::PARAM_ARCHIVE_ENGINE_SKIP_WP_FILES) === DUP_PRO_Extraction::FILTER_NONE) {
$abspath = $prmMng->getValue(PrmMng::PARAM_PATH_WP_CORE_NEW);
$this->phpPerms = array(
array(
'dir' => $abspath . '/wp-admin',
'pass' => false,
'message' => '',
),
array(
'dir' => $abspath . '/wp-includes',
'pass' => false,
'message' => '',
),
);
for ($i = 0; $i < count($this->phpPerms); $i++) {
$this->phpPerms[$i]['pass'] = self::checkPhpFileCreation(
$this->phpPerms[$i]['dir'],
$this->phpPerms[$i]['message']
);
if ($this->phpPerms[$i]['pass'] == false) {
$testPass = false;
}
}
}
if ($testPass) {
return self::LV_PASS;
} else {
if (InstState::isRecoveryMode() || DUPX_Custom_Host_Manager::getInstance()->isManaged()) {
return self::LV_SOFT_WARNING;
} else {
return self::LV_HARD_WARNING;
}
}
}
/**
* Returns list of paths that we don't have "write" permissions on
*
* @return string[]
* @throws Exception
*/
protected function checkWritePermissions()
{
$prmMng = PrmMng::getInstance();
$failResult = array();
$dirFiles = DUPX_Package::getDirsListPath();
$archiveConfig = DUPX_ArchiveConfig::getInstance();
$skipWpCore = ($prmMng->getValue(PrmMng::PARAM_ARCHIVE_ENGINE_SKIP_WP_FILES) !== DUP_PRO_Extraction::FILTER_NONE);
if (($handle = fopen($dirFiles, "r")) === false) {
throw new Exception('Can\'t open dirs file list');
}
while (($line = fgets($handle)) !== false) {
if (($info = json_decode($line)) === null) {
throw new Exception('Invalid json line in dirs file: ' . $line);
}
if ($skipWpCore && SnapWP::isWpCore($info->p, SnapWP::PATH_RELATIVE)) {
continue;
}
$destPath = $archiveConfig->destFileFromArchiveName($info->p);
if (file_exists($destPath) && !SnapIO::dirAddFullPermsAndCheckResult($destPath)) {
$failResult[] = $destPath;
}
}
fclose($handle);
return $failResult;
}
/**
* Check if PHP files can be creatend in passed folder
*
* @param string $dir folder to check
* @param string $message error message
*
* @return bool
*/
protected static function checkPhpFileCreation($dir, &$message = '')
{
$removeDir = false;
$exception = null;
try {
if (!file_exists($dir)) {
if (!SnapIO::mkdirP($dir)) {
throw new Exception('Don\'t have permissition to create folder "' . $dir . '"');
}
$removeDir = true;
} elseif (!is_dir($dir)) {
throw new Exception('"' . $dir . '" must be a folder');
} elseif (!is_writable($dir) || !is_executable($dir)) {
if (SnapIO::chmod($dir, 'u+rwx') == false) {
throw new Exception('"' . $dir . '" don\'t have write permissions');
}
}
$tmpFile = SnapIO::trailingslashit($dir) . self::TEMP_PHP_FILE_NAME;
if (file_exists($tmpFile) && unlink($tmpFile) == false) {
throw new Exception('Can\'t remove temp php file \"' . $tmpFile . '\" to check if php files are writable');
}
if (file_put_contents($tmpFile, "<?php\n\n//silent") == false) {
throw new Exception('Cannot create PHP files even if the "' . basename($dir) . '" folder has permissions');
}
unlink($tmpFile);
} catch (Exception $e) {
$exception = $e;
}
if ($removeDir) {
rmdir($dir);
}
if (is_null($exception)) {
return true;
} else {
$message = $exception->getMessage();
return false;
}
}
public function getTitle()
{
return 'Permissions: General';
}
protected function hwarnContent()
{
$result = dupxTplRender('parts/validation/tests/writeable-checks', array(
'testResult' => $this->testResult,
'phpPerms' => $this->phpPerms,
'faildDirPerms' => $this->faildDirPerms,
), false);
return $result;
}
protected function swarnContent()
{
return $this->hwarnContent();
}
protected function passContent()
{
return $this->hwarnContent();
}
}

View File

@@ -0,0 +1,90 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
use Duplicator\Installer\Core\InstState;
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
class DUPX_Validation_test_managed_supported extends DUPX_Validation_abstract_item
{
/** @var bool */
private $managed = false;
/** @var string */
private $failMessage = '';
protected function runTest()
{
if (!($this->managed = DUPX_Custom_Host_Manager::getInstance()->isManaged())) {
return self::LV_SKIP;
}
if (InstState::isRecoveryMode()) {
return self::LV_PASS;
}
if (InstState::isNewSiteIsMultisite()) {
$this->failMessage = "Installing multisites on managed hosts is not supported";
return self::LV_FAIL;
}
if (InstState::isImportFromBackendMode()) {
return self::LV_PASS;
}
switch ($this->managed) {
case DUPX_Custom_Host_Manager::HOST_GODADDY:
case DUPX_Custom_Host_Manager::HOST_LIQUIDWEB:
case DUPX_Custom_Host_Manager::HOST_WPENGINE:
return self::LV_PASS;
case DUPX_Custom_Host_Manager::HOST_PANTHEON:
case DUPX_Custom_Host_Manager::HOST_WORDPRESSCOM:
case DUPX_Custom_Host_Manager::HOST_FLYWHEEL:
$this->failMessage = 'Standard installations on this managed host are not supported because it uses a non-standard configuration that can ' .
'only be read at runtime. Use Drop and Drop install to overwrite the site instead.';
return self::LV_FAIL;
default:
$this->failMessage = "Unknown managed host type.";
return self::LV_FAIL;
}
}
public function getTitle()
{
return 'Managed hosting supported';
}
protected function failContent()
{
return dupxTplRender(
'parts/validation/tests/managed-supported',
array(
'isOk' => false,
'managedHosting' => $this->managed,
'failMessage' => $this->failMessage,
),
false
);
}
protected function passContent()
{
return dupxTplRender(
'parts/validation/tests/managed-supported',
array(
'isOk' => true,
'managedHosting' => $this->managed,
'failMessage' => $this->failMessage,
),
false
);
}
}

View File

@@ -0,0 +1,47 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Core\Params\PrmMng;
class DUPX_Validation_test_managed_tprefix extends DUPX_Validation_abstract_item
{
protected function runTest()
{
if (!DUPX_Custom_Host_Manager::getInstance()->isManaged()) {
return self::LV_SKIP;
}
$overwriteData = PrmMng::getInstance()->getValue(PrmMng::PARAM_OVERWRITE_SITE_DATA);
if (DUPX_ArchiveConfig::getInstance()->wp_tableprefix != $overwriteData['table_prefix']) {
return self::LV_SOFT_WARNING;
} else {
return self::LV_GOOD;
}
}
public function getTitle()
{
return 'Table prefix of managed hosting';
}
protected function swarnContent()
{
return dupxTplRender('parts/validation/tests/managed-tprefix', array('isOk' => false), false);
}
protected function goodContent()
{
return dupxTplRender('parts/validation/tests/managed-tprefix', array('isOk' => true), false);
}
}

View File

@@ -0,0 +1,49 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
class DUPX_Validation_test_manual_extraction extends DUPX_Validation_abstract_item
{
protected function runTest()
{
if (DUPX_Conf_Utils::isManualExtractFilePresent()) {
return self::LV_SOFT_WARNING;
} else {
return self::LV_GOOD;
}
}
public function getTitle()
{
return 'Manual extraction detected';
}
public function display()
{
if ($this->testResult === self::LV_SKIP) {
return false;
} else {
return DUPX_Conf_Utils::isManualExtractFilePresent();
}
}
protected function swarnContent()
{
return dupxTplRender('parts/validation/tests/manual-extraction', array(), false);
}
protected function goodContent()
{
return dupxTplRender('parts/validation/tests/manual-extraction', array(), false);
}
}

View File

@@ -0,0 +1,64 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Libs\Snap\SnapUtil;
class DUPX_Validation_test_memory_limit extends DUPX_Validation_abstract_item
{
const MIN_MEMORY_LIMIT = '256M';
/** @var int */
private $memoryLimit = -1;
protected function runTest()
{
if (($memoryLimit = @ini_get('memory_limit')) === false || strlen($memoryLimit) == 0) {
return self::LV_SKIP;
}
$this->memoryLimit = is_numeric($memoryLimit) ? (int) $memoryLimit : SnapUtil::convertToBytes($memoryLimit);
if ($this->memoryLimit < 0) {
return self::LV_SKIP;
}
if ($this->memoryLimit >= SnapUtil::convertToBytes(self::MIN_MEMORY_LIMIT)) {
return self::LV_GOOD;
}
return self::LV_SOFT_WARNING;
}
public function getTitle()
{
return 'PHP Memory Limit';
}
protected function swarnContent()
{
return dupxTplRender('parts/validation/tests/memory-limit', array(
'memoryLimit' => $this->memoryLimit,
'minMemoryLimit' => self::MIN_MEMORY_LIMIT,
'isOk' => false,
), false);
}
protected function goodContent()
{
return dupxTplRender('parts/validation/tests/memory-limit', array(
'memoryLimit' => DUPX_U::readableByteSize($this->memoryLimit),
'minMemoryLimit' => self::MIN_MEMORY_LIMIT,
'isOk' => true,
), false);
}
}

View File

@@ -0,0 +1,57 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Core\InstState;
use Duplicator\Installer\Core\Params\PrmMng;
class DUPX_Validation_test_multisite_subfolder extends DUPX_Validation_abstract_item
{
protected function runTest()
{
if (InstState::isRecoveryMode() || !InstState::isNewSiteIsMultisite()) {
return self::LV_SKIP;
}
if (InstState::isInstType(InstState::TYPE_MSUBDOMAIN) && $this->newUrlIsInSubFolder()) {
return self::LV_HARD_WARNING;
}
return self::LV_PASS;
}
/**
* Check if the new url is in a subfolder
*
* @return bool
*/
private function newUrlIsInSubFolder()
{
return parse_url(PrmMng::getInstance()->getValue(PrmMng::PARAM_URL_NEW), PHP_URL_PATH) !== null;
}
public function getTitle()
{
return 'Subomain multisite installation in subfolder';
}
protected function hwarnContent()
{
return dupxTplRender('parts/validation/tests/multisite-subfolder', array("isOk" => false), false);
}
protected function passContent()
{
return dupxTplRender('parts/validation/tests/multisite-subfolder', array("isOk" => true), false);
}
}

View File

@@ -0,0 +1,40 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
class DUPX_Validation_test_mysql_connect extends DUPX_Validation_abstract_item
{
protected function runTest()
{
if (function_exists('mysqli_connect')) {
return self::LV_PASS;
} else {
return self::LV_FAIL;
}
}
public function getTitle()
{
return 'PHP Mysqli';
}
protected function failContent()
{
return dupxTplRender('parts/validation/tests/mysql-connect', array(), false);
}
protected function passContent()
{
return dupxTplRender('parts/validation/tests/mysql-connect', array(), false);
}
}

View File

@@ -0,0 +1,78 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Core\InstState;
use Duplicator\Libs\Snap\SnapIO;
class DUPX_Validation_test_open_basedir extends DUPX_Validation_abstract_item
{
/** @var bool */
private $openBaseDirEnabled = false;
/** @var string[] */
private $pathsOutsideOpenBaseDir = array();
protected function runTest()
{
if (InstState::isRecoveryMode()) {
return self::LV_SKIP;
}
if (($this->openBaseDirEnabled = SnapIO::isOpenBaseDirEnabled()) === false) {
return self::LV_GOOD;
}
$archivePaths = array();
$pathMapping = DUPX_ArchiveConfig::getInstance()->getPathsMapping();
if (is_array($pathMapping)) {
$archivePaths = $pathMapping;
} else {
$archivePaths[] = $pathMapping;
}
foreach ($archivePaths as $archivePath) {
if (SnapIO::getOpenBaseDirRootOfPath($archivePath) === false) {
$this->pathsOutsideOpenBaseDir[] = $archivePath;
}
}
if (empty($this->pathsOutsideOpenBaseDir)) {
return self::LV_GOOD;
} else {
return self::LV_HARD_WARNING;
}
}
public function getTitle()
{
return 'PHP Open Base';
}
protected function hwarnContent()
{
return dupxTplRender('parts/validation/tests/open-basedir', array(
'openBaseDirEnabled' => $this->openBaseDirEnabled,
'pathsOutsideOpenBaseDir' => $this->pathsOutsideOpenBaseDir,
'isOk' => false,
), false);
}
protected function goodContent()
{
return dupxTplRender('parts/validation/tests/open-basedir', array(
'openBaseDirEnabled' => $this->openBaseDirEnabled,
'pathsOutsideOpenBaseDir' => $this->pathsOutsideOpenBaseDir,
'isOk' => true,
), false);
}
}

View File

@@ -0,0 +1,49 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
use Duplicator\Installer\Core\InstState;
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
class DUPX_Validation_test_owrinstall extends DUPX_Validation_abstract_item
{
protected function runTest()
{
if (
InstState::isRecoveryMode() ||
InstState::isImportFromBackendMode()
) {
return self::LV_SKIP;
}
if (InstState::getInstance()->getMode() === InstState::MODE_OVR_INSTALL) {
return self::LV_SOFT_WARNING;
} else {
return self::LV_GOOD;
}
}
public function getTitle()
{
return 'Overwrite Install';
}
protected function swarnContent()
{
return dupxTplRender('parts/validation/tests/overwrite-install', array(), false);
}
protected function goodContent()
{
return dupxTplRender('parts/validation/tests/overwrite-install', array(), false);
}
}

View File

@@ -0,0 +1,58 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
class DUPX_Validation_test_package_age extends DUPX_Validation_abstract_item
{
const PACKAGE_DAYS_BEFORE_WARNING = 180;
protected function runTest()
{
if ($this->getPackageDays() <= self::PACKAGE_DAYS_BEFORE_WARNING) {
return self::LV_GOOD;
} else {
return self::LV_SOFT_WARNING;
}
}
/**
* Get package age in days
*
* @return int
*/
protected function getPackageDays()
{
return (int) round((time() - strtotime(DUPX_ArchiveConfig::getInstance()->created)) / 86400);
}
public function getTitle()
{
return 'Package Age';
}
protected function swarnContent()
{
return dupxTplRender('parts/validation/tests/package-age', array(
'packageDays' => $this->getPackageDays(),
'maxPackageDays' => self::PACKAGE_DAYS_BEFORE_WARNING,
), false);
}
protected function goodContent()
{
return dupxTplRender('parts/validation/tests/package-age', array(
'packageDays' => $this->getPackageDays(),
'maxPackageDays' => self::PACKAGE_DAYS_BEFORE_WARNING,
), false);
}
}

View File

@@ -0,0 +1,76 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Utils\Log\Log;
class DUPX_Validation_test_extensions extends DUPX_Validation_abstract_item
{
/** @var array<string, mixed> */
public $extensionTests = array(
"json" => array(
"failLevel" => self::LV_FAIL,
"pass" => false,
),
);
protected function runTest()
{
$result = self::LV_GOOD;
foreach ($this->extensionTests as $extensionName => $extensionTest) {
$this->extensionTests[$extensionName]["pass"] = extension_loaded($extensionName);
if (!$this->extensionTests[$extensionName]["pass"]) {
Log::info("The '{$extensionName}' extension is not loaded.");
//update fail level
if ($extensionTest["failLevel"] < $result) {
$result = $extensionTest["failLevel"];
}
}
}
return $result;
}
public function getTitle()
{
return 'PHP Extensions';
}
protected function swarnContent()
{
return dupxTplRender('parts/validation/tests/php-extensions', array(
'extensionTests' => $this->extensionTests,
), false);
}
protected function hwarnContent()
{
return dupxTplRender('parts/validation/tests/php-extensions', array(
'extensionTests' => $this->extensionTests,
), false);
}
protected function failContent()
{
return dupxTplRender('parts/validation/tests/php-extensions', array(
'extensionTests' => $this->extensionTests,
), false);
}
protected function goodContent()
{
return dupxTplRender('parts/validation/tests/php-extensions', array(
'extensionTests' => $this->extensionTests,
), false);
}
}

View File

@@ -0,0 +1,135 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Core\Params\PrmMng;
use Duplicator\Libs\Snap\FunctionalityCheck;
class DUPX_Validation_test_php_functionalities extends DUPX_Validation_abstract_item
{
/** @var FunctionalityCheck[] */
protected $functionalities = array();
/**
* Class contructor
*
* @param string $category Category
*/
public function __construct($category = '')
{
parent::__construct($category);
$this->functionalities = self::getFunctionalitiesCheckList();
}
protected function runTest()
{
if (FunctionalityCheck::checkList($this->functionalities)) {
return self::LV_PASS;
} elseif (FunctionalityCheck::checkList($this->functionalities, true)) {
return self::LV_HARD_WARNING;
} else {
return self::LV_FAIL;
}
}
public function getTitle()
{
return 'PHP Functions and Classes';
}
protected function failContent()
{
return dupxTplRender('parts/validation/tests/php-functionalities', array(
'functionalities' => $this->functionalities,
'testResult' => $this->testResult,
), false);
}
protected function passContent()
{
return $this->failContent();
}
protected function hwarnContent()
{
return $this->failContent();
}
/**
* Get list of functionalities to check
*
* @return FunctionalityCheck[]
*/
protected static function getFunctionalitiesCheckList()
{
$result = [];
$archiveEngine = PrmMng::getInstance()->getValue(PrmMng::PARAM_ARCHIVE_ENGINE);
if ($archiveEngine == DUP_PRO_Extraction::ENGINE_ZIP || $archiveEngine == DUP_PRO_Extraction::ENGINE_ZIP_CHUNK) {
$result[] = new FunctionalityCheck(
FunctionalityCheck::TYPE_CLASS,
\ZipArchive::class,
true,
'https://www.php.net/manual/en/class.ziparchive.php',
'<i style="font-size:12px">'
. '<a href="' . DUPX_Constants::FAQ_URL . 'how-to-work-with-the-different-zip-engines" target="_blank">'
. 'Overview on how to enable ZipArchive</i></a>'
);
}
$result[] = new FunctionalityCheck(
FunctionalityCheck::TYPE_FUNCTION,
'json_encode',
true,
'https://www.php.net/manual/en/function.json-encode.php'
);
$functionality = new FunctionalityCheck(
FunctionalityCheck::TYPE_FUNCTION,
'token_get_all',
false,
'https://www.php.net/manual/en/function.token-get-all',
"Required for parsing the contents of the wp-config.php file. "
. "If test failed, to avoid problems during the installation the handling of the wp-config.php "
. "file has been disabled (the setting 'Wordpress wp-config.php' under Advanced Mode > Options > "
. "Advanced > Configuration files has been set to 'Do nothing'.)"
);
$functionality->setFailCallback(function (FunctionalityCheck $item) {
PrmMng::getInstance()->setValue(PrmMng::PARAM_WP_CONFIG, 'nothing');
PrmMng::getInstance()->save();
});
$result[] = $functionality;
$result[] = new FunctionalityCheck(
FunctionalityCheck::TYPE_FUNCTION,
'file_get_contents',
true,
'https://www.php.net/manual/en/function.file-get-contents.php'
);
$result[] = new FunctionalityCheck(
FunctionalityCheck::TYPE_FUNCTION,
'file_put_contents',
true,
'https://www.php.net/manual/en/function.file-put-contents.php'
);
$result[] = new FunctionalityCheck(
FunctionalityCheck::TYPE_FUNCTION,
'mb_strlen',
true,
'https://www.php.net/manual/en/mbstring.installation.php'
);
return $result;
}
}

View File

@@ -0,0 +1,67 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
use Duplicator\Installer\Core\InstState;
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
class DUPX_Validation_test_php_version extends DUPX_Validation_abstract_item
{
protected function runTest()
{
$archiveConfig = DUPX_ArchiveConfig::getInstance();
if ($archiveConfig->isDBOnly()) {
return self::LV_GOOD;
}
// compare only major version ex 5 and 7 not 5.6 and 5.5
if (intval($archiveConfig->version_php) === intval(phpversion())) {
return self::LV_GOOD;
} elseif (InstState::isImportFromBackendMode()) {
return self::LV_HARD_WARNING;
} else {
return self::LV_SOFT_WARNING;
}
}
public function getTitle()
{
return 'PHP Version Mismatch';
}
protected function swarnContent()
{
return dupxTplRender('parts/validation/tests/php-version', array(
'fromPhp' => DUPX_ArchiveConfig::getInstance()->version_php,
'toPhp' => phpversion(),
'isOk' => false,
), false);
}
protected function hwarnContent()
{
return dupxTplRender('parts/validation/tests/php-version', array(
'fromPhp' => DUPX_ArchiveConfig::getInstance()->version_php,
'toPhp' => phpversion(),
'isOk' => false,
), false);
}
protected function goodContent()
{
return dupxTplRender('parts/validation/tests/php-version', array(
'fromPhp' => DUPX_ArchiveConfig::getInstance()->version_php,
'toPhp' => phpversion(),
'isOk' => true,
), false);
}
}

View File

@@ -0,0 +1,92 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Core\InstState;
use Duplicator\Installer\Core\Params\PrmMng;
class DUPX_Validation_test_recovery extends DUPX_Validation_abstract_item
{
/** @var array<string, mixed> */
protected $importSiteInfo = array();
/** @var bool */
protected $recoveryPage = false;
/** @var bool */
protected $importPage = false;
/** @var bool */
protected $recoveryIsOutToDate = false;
/** @var int */
protected $recoveryPackageLife = -1;
protected function runTest()
{
$paramsManager = PrmMng::getInstance();
if (!InstState::isImportFromBackendMode()) {
return self::LV_SKIP;
}
$this->importSiteInfo = PrmMng::getInstance()->getValue(PrmMng::PARAM_FROM_SITE_IMPORT_INFO);
$this->importPage = $this->importSiteInfo['import_page'];
$this->recoveryPage = $this->importSiteInfo['recovery_page'];
$this->recoveryIsOutToDate = $this->importSiteInfo['recovery_is_out_to_date'];
$this->recoveryPackageLife = $this->importSiteInfo['recovery_package_life'];
$recoveryLink = $paramsManager->getValue(PrmMng::PARAM_RECOVERY_LINK);
if (empty($recoveryLink)) {
return self::LV_HARD_WARNING;
} else {
if ($this->importSiteInfo['recovery_is_out_to_date']) {
return self::LV_SOFT_WARNING;
} else {
return self::LV_GOOD;
}
}
}
public function getTitle()
{
return 'Disaster Recovery';
}
protected function hwarnContent()
{
return dupxTplRender('parts/validation/tests/recovery', array(
'testResult' => $this->testResult,
'importPage' => $this->importPage,
'recoveryPage' => $this->recoveryPage,
'recoveryIsOutToDate' => $this->recoveryIsOutToDate,
'recoveryPackageLife' => $this->recoveryPackageLife,
), false);
}
protected function swarnContent()
{
return dupxTplRender('parts/validation/tests/recovery', array(
'testResult' => $this->testResult,
'importPage' => $this->importPage,
'recoveryPage' => $this->recoveryPage,
'recoveryIsOutToDate' => $this->recoveryIsOutToDate,
'recoveryPackageLife' => $this->recoveryPackageLife,
), false);
}
protected function goodContent()
{
return dupxTplRender('parts/validation/tests/recovery', array(
'testResult' => $this->testResult,
'importPage' => $this->importPage,
'recoveryPage' => $this->recoveryPage,
'recoveryIsOutToDate' => $this->recoveryIsOutToDate,
'recoveryPackageLife' => $this->recoveryPackageLife,
), false);
}
}

View File

@@ -0,0 +1,63 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Core\Params\PrmMng;
class DUPX_Validation_test_replace_paths extends DUPX_Validation_abstract_item
{
/** @var string */
protected $message = '';
protected function runTest()
{
$paramsManager = PrmMng::getInstance();
if (
$paramsManager->getValue(PrmMng::PARAM_REPLACE_ENGINE) === DUPX_S3_Funcs::MODE_SKIP ||
$paramsManager->getValue(PrmMng::PARAM_SKIP_PATH_REPLACE) === false
) {
return self::LV_SKIP;
}
$archivePaths = DUPX_ArchiveConfig::getInstance()->getRealValue("archivePaths");
if (strlen($archivePaths->home) == 0) {
// if new path is equal at old path the replace isn't necessary so skip message
if (strlen($paramsManager->getValue(PrmMng::PARAM_PATH_NEW)) === 0) {
return self::LV_SKIP;
}
$this->message = "It was found that the home path of the source was equal to '/'. In this case it's" .
" impossible to automatically replace paths, because of that path replacements have been disabled.";
}
return self::LV_HARD_WARNING;
}
public function getTitle()
{
return 'Replace PATHs in database';
}
protected function hwarnContent()
{
return dupxTplRender(
'parts/validation/tests/replace-paths',
array(
"message" => $this->message,
"isOk" => false,
),
false
);
}
}

View File

@@ -0,0 +1,78 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
use Duplicator\Installer\Core\InstState;
use Duplicator\Installer\Core\Params\PrmMng;
use Duplicator\Installer\REST\RESTPoints;
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
class DUPX_Validation_test_rest_api extends DUPX_Validation_abstract_item
{
/** @var string */
protected $errorMessage = '';
/** @var string */
protected $restUrl = '';
protected function runTest()
{
if (!InstState::isAddSiteOnMultisite()) {
return self::LV_SKIP;
}
$overwriteData = PrmMng::getInstance()->getValue(PrmMng::PARAM_OVERWRITE_SITE_DATA);
if (is_array($overwriteData) && isset($overwriteData['restUrl']) && strlen($overwriteData['restUrl']) > 0) {
$this->restUrl = $overwriteData['restUrl'];
} else {
$this->restUrl = PrmMng::getInstance()->getValue(PrmMng::PARAM_URL_NEW) . '/wp-json';
}
$this->errorMessage = "REST API call to WordPress backend failed";
if (RESTPoints::getInstance()->checkRest(true, $this->errorMessage)) {
return self::LV_PASS;
}
return self::LV_FAIL;
}
public function getTitle()
{
return 'REST API test';
}
protected function passContent()
{
return dupxTplRender(
'parts/validation/tests/rest-api',
array(
"isOk" => true,
"restUrl" => $this->restUrl,
),
false
);
}
protected function failContent()
{
return dupxTplRender(
'parts/validation/tests/rest-api',
array(
"isOk" => false,
"errorMessage" => $this->errorMessage,
"restUrl" => $this->restUrl,
),
false
);
}
}

View File

@@ -0,0 +1,35 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
class DUPX_Validation_test_siteground extends DUPX_Validation_abstract_item
{
protected function runTest()
{
if (!DUPX_Custom_Host_Manager::getInstance()->isHosting(DUPX_Custom_Host_Manager::HOST_SITEGROUND)) {
return self::LV_SKIP;
}
return self::LV_SOFT_WARNING;
}
public function getTitle()
{
return 'Siteground';
}
protected function swarnContent()
{
return dupxTplRender('parts/validation/tests/siteground', array(), false);
}
}

View File

@@ -0,0 +1,60 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
class DUPX_Validation_test_timeout extends DUPX_Validation_abstract_item
{
const MAX_TIME_SIZE = 314572800; //300MB
/** @var bool|int */
protected $maxTimeZero = false;
protected function runTest()
{
$max_time_ini = ini_get('max_execution_time');
$this->maxTimeZero = ($GLOBALS['DUPX_ENFORCE_PHP_INI']) ? false : @set_time_limit(0);
if ((is_numeric($max_time_ini) && $max_time_ini < 31 && $max_time_ini > 0) && DUPX_Conf_Utils::archiveSize() > self::MAX_TIME_SIZE) {
return self::LV_SOFT_WARNING;
} else {
return self::LV_GOOD;
}
}
public function getTitle()
{
return 'PHP Timeout';
}
protected function swarnContent()
{
return dupxTplRender('parts/validation/tests/timeout', array(
'maxTimeZero' => $this->maxTimeZero,
'maxTimeIni' => ini_get('max_execution_time'),
'archiveSize' => DUPX_U::readableByteSize(DUPX_Conf_Utils::archiveSize()),
'maxSize' => DUPX_U::readableByteSize(self::MAX_TIME_SIZE),
'isOk' => true,
), false);
}
protected function goodContent()
{
return dupxTplRender('parts/validation/tests/timeout', array(
'maxTimeZero' => $this->maxTimeZero,
'maxTimeIni' => ini_get('max_execution_time'),
'archiveSize' => DUPX_U::readableByteSize(DUPX_Conf_Utils::archiveSize()),
'maxSize' => DUPX_U::readableByteSize(self::MAX_TIME_SIZE),
'isOk' => true,
), false);
}
}

View File

@@ -0,0 +1,138 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Utils\Log\LogHandler;
use Duplicator\Installer\Core\Params\PrmMng;
use Duplicator\Libs\Snap\SnapIO;
class DUPX_Validation_test_wordfence extends DUPX_Validation_abstract_item
{
/** @var string */
private $wordFencePath = "";
protected function runTest()
{
return $this->parentHasWordfence() ? self::LV_HARD_WARNING : self::LV_GOOD;
}
/**
* Get test title
*
* @return string
*/
public function getTitle()
{
return 'Wordfence';
}
/**
* Return content for test status
*
* @return string
*/
protected function swarnContent()
{
return dupxTplRender('parts/validation/tests/wordfence/wordfence-detected', array(
'wordFencePath' => $this->wordFencePath,
), false);
}
/**
* Return content for test status
*
* @return string
*/
protected function hwarnContent()
{
return dupxTplRender('parts/validation/tests/wordfence/wordfence-detected', array(
'wordFencePath' => $this->wordFencePath,
), false);
}
/**
* Return content for test status
*
* @return string
*/
protected function goodContent()
{
return dupxTplRender('parts/validation/tests/wordfence/wordfence-not-detected', array(), false);
}
/**
* Check if the Wordfence firewall is enabled in the parent path
*
* @return bool
*/
protected function parentHasWordfence()
{
$scanPath = PrmMng::getInstance()->getValue(PrmMng::PARAM_PATH_NEW);
$rootPath = SnapIO::getMaxAllowedRootOfPath($scanPath);
$result = false;
if ($rootPath === false) {
//$scanPath is not contained in open_basedir paths skip
return false;
}
LogHandler::setMode(LogHandler::MODE_OFF);
$continueScan = true;
while ($continueScan) {
if ($this->wordFenceFirewallEnabled($scanPath)) {
$this->wordFencePath = $scanPath;
$result = true;
break;
}
$continueScan = $scanPath !== $rootPath && $scanPath != dirname($scanPath);
$scanPath = dirname($scanPath);
}
LogHandler::setMode();
return $result;
}
/**
* Check if the Wordfence firewall is enabled in the given path
*
* @param string $path The path to check
*
* @return bool
*/
protected function wordFenceFirewallEnabled($path)
{
$configFiles = array(
'php.ini',
'.user.ini',
'.htaccess',
);
foreach ($configFiles as $configFile) {
$file = $path . '/' . $configFile;
if (!@is_readable($file)) {
continue;
}
if (($content = @file_get_contents($file)) === false) {
continue;
}
if (strpos($content, 'wordfence-waf.php') !== false) {
return true;
}
}
return false;
}
}

View File

@@ -0,0 +1,63 @@
<?php
/**
* Validation object
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Core\Deploy\ServerConfigs;
use Duplicator\Installer\Core\InstState;
class DUPX_Validation_test_wp_config extends DUPX_Validation_abstract_item
{
/**
* @return int
* @throws Exception
*/
protected function runTest()
{
if (!InstState::isClassicInstall()) {
return self::LV_SKIP;
}
if (DUPX_WPConfig::isSourceWpConfigValid()) {
return self::LV_PASS;
} else {
return self::LV_SOFT_WARNING;
}
}
/**
* @return string
*/
public function getTitle()
{
return 'Wordpress Configuration';
}
/**
* @return string
*/
protected function swarnContent()
{
return dupxTplRender('parts/validation/tests/wp-config-check', array(
'testResult' => $this->testResult,
'configPath' => ServerConfigs::getSourceWpConfigPath(),
), false);
}
/**
* @return string
*/
protected function passContent()
{
return $this->swarnContent();
}
}

View File

@@ -0,0 +1,707 @@
<?php
/**
* Various html elements
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
/**
* HTIMO UTILE
*/
class DUPX_U_Html
{
/** @var int */
protected static $uniqueId = 0;
/**
* Initialize css for html elements
*
* @return void
*/
public static function css()
{
self::lightBoxCss();
self::inputPasswordToggleCss();
self::checkboxSwitchCss();
}
/**
* Initialize js for html elements
*
* @return void
*/
public static function js()
{
self::lightBoxJs();
self::inputPasswordToggleJs();
}
/**
* Get unique id
*
* @return string
*/
private static function getUniqueId()
{
self::$uniqueId++;
return 'dup-html-id-' . self::$uniqueId . '-' . str_replace('.', '-', (string) microtime(true));
}
/**
* This function returns a string with all the html attributes with this format key = "value" key2 = "value2"
* an esc_attr is executed automatically
*
* @param array<string, mixed> $attrs attributes
*
* @return string
*/
public static function arrayAttrToHtml($attrs)
{
$sttrsStr = array();
foreach ($attrs as $key => $val) {
$sttrsStr[] = $key . '="' . DUPX_U::esc_attr($val) . '"';
}
return implode(' ', $sttrsStr);
}
/**
* Get header main
*
* @param string $htmlTitle Title
*
* @return void
*/
public static function getHeaderMain($htmlTitle)
{
?>
<div id="header-main-wrapper" >
<div class="dupx-logfile-link">
<?php DUPX_View_Funcs::installerLogLink(); ?>
</div>
<div class="hdr-main">
<?php echo $htmlTitle; ?>
</div>
</div>
<?php
}
/**
* Get light box
*
* @param string $linkLabelHtml the link label
* @param string $titleContent the title of the light box
* @param string $htmlContent the content of the light box
* @param bool $echo if true the light box is echoed
* @param string $htmlAfterContent html after content
*
* @return string
*/
public static function getLigthBox($linkLabelHtml, $titleContent, $htmlContent, $echo = true, $htmlAfterContent = '')
{
ob_start();
$id = self::getUniqueId();
?>
<span class="link-style dup-ligthbox-link" data-dup-ligthbox="<?php echo $id; ?>" ><?php echo $linkLabelHtml; ?></span>
<div id="<?php echo $id; ?>" class="dub-ligthbox-content close">
<div class="wrapper" >
<h2 class="title" ><?php echo htmlspecialchars($titleContent); ?></h2>
<div class="content" ><?php echo $htmlContent; ?></div><?php echo $htmlAfterContent; ?>
<button class="close-button" title="Close" ><i class="fa fa-2x fa-times"></i></button>
</div>
</div>
<?php
if ($echo) {
ob_end_flush();
return '';
} else {
return ob_get_clean();
}
}
/**
* Light box from file content
*
* @param string $linkLabelHtml the link label
* @param string $titleContent the title of the light box
* @param string $path the path of the file
* @param bool $echo if true the light box is echoed
*
* @return string
*/
public static function getLightBoxFileContent($linkLabelHtml, $titleContent, $path, $echo = true)
{
if (file_exists($path) && (($fileContent = file_get_contents($path)) !== false)) {
$lightBoxContent =
'<div class="row-cols-1">' .
'<div class="col col-1">' .
'<pre>' . DUPX_U::esc_html($fileContent) . '</pre>' .
'</div>' .
'</div>';
} else {
$lightBoxContent = '<p>File not found.</b>';
}
return DUPX_U_Html::getLigthBox($linkLabelHtml, $titleContent, $lightBoxContent, $echo);
}
/**
* getLightBoxIframe
*
* @param string $linkLabelHtml the link label
* @param string $titleContent the title of the light box
* @param string $url the url of the iframe
* @param bool $autoUpdate if true the iframe is auto updated
* @param bool $enableTargetDownload Download button enabled
* @param bool $echo if true the light box is echoed
*
* @return string
*/
public static function getLightBoxIframe(
$linkLabelHtml,
$titleContent,
$url,
$autoUpdate = false,
$enableTargetDownload = false,
$echo = true
) {
$classes = array('dup-lightbox-iframe');
$afterContent = '<div class="tool-box">';
if ($autoUpdate) {
//$classes[] = 'auto-update';
$afterContent .= '<button class="button toggle-auto-update disabled" title="Enable auto reload" ><i class="fa fa-2x fa-redo-alt"></i></button>';
}
if ($enableTargetDownload) {
$path = parse_url($url, PHP_URL_PATH);
if (!empty($path)) {
$urlPath = parse_url($url, PHP_URL_PATH);
$fileName = basename($urlPath);
} else {
$fileName = parse_url($url, PHP_URL_HOST);
}
$afterContent .= '<a target="_blank" class="button download-button" title="Download" download="' . DUPX_U::esc_attr($fileName) . '" href="' . DUPX_U::esc_attr($url) . '"><i class="fa fa-2x fa-download"></i></a>';
}
$afterContent .= '</div>';
$lightBoxContent = '<iframe class="' . implode(' ', $classes) . '" data-iframe-url="' . DUPX_U::esc_attr($url) . '"></iframe> ';
return DUPX_U_Html::getLigthBox($linkLabelHtml, $titleContent, $lightBoxContent, $echo, $afterContent);
}
/**
* Light box CSS
*
* @return void
*/
protected static function lightBoxCss()
{
?>
<style>
.dup-ligthbox-link {
text-decoration: underline;
cursor: pointer;
}
.dub-ligthbox-content {
position: fixed;
top: 0;
left: 0;
width: calc(100vw - 120px);
height: 100vh;
background-color: #FFFFFF;
background-color: rgba(255,255,255,0.95);
z-index: 999999;
overflow: hidden;
margin: 0 60px;
}
.dub-ligthbox-content.close {
width: 0;
height: 0;
}
.dub-ligthbox-content.open {
width: calc(100vw - 120px);
height: 100vh;
}
.dub-ligthbox-content > .wrapper {
width: calc(100vw - 120px);
height: 100vh;
}
.dub-ligthbox-content > .wrapper > .title {
height: 40px;
line-height: 40px;
margin: 0;
padding: 0 15px;
}
.dub-ligthbox-content > .wrapper > .content {
margin: 0 15px 15px;
border: 1px solid darkgray;
padding: 15px;
height: calc(100% - 15px - 40px);
box-sizing: border-box;
}
.dub-ligthbox-content > .wrapper > .tool-box {
position: absolute;
top: 0px;
left: 200px;
}
.dub-ligthbox-content .tool-box .button {
display: inline-block;
background: transparent;
border: 0 none;
padding: 5px;
margin: 0 10px;
height: 40px;
line-height: 40px;
box-sizing: border-box;
color: #000;
cursor: pointer;
}
.dub-ligthbox-content .tool-box .button.disabled {
color: #BABABA;
}
.dub-ligthbox-content > .wrapper > .close-button {
position: absolute;
top: 0px;
right: 23px;
background: transparent;
border: 0 none;
padding: 5px;
margin: 0;
height: 40px;
line-height: 40px;
box-sizing: border-box;
color: #000;
cursor: pointer;
}
.dub-ligthbox-content .row-cols-2,
.dub-ligthbox-content .row-cols-1 {
height: 100%;
}
.dub-ligthbox-content .row-cols-1 .col {
width: 100%;
box-sizing: border-box;
float: left;
height: 100%;
overflow: auto;
}
.dub-ligthbox-content .row-cols-2 .col {
width: 50%;
box-sizing: border-box;
float: left;
border-right: 1px solid black;
height: 100%;
overflow: auto;
}
.dub-ligthbox-content .row-cols-2 .col-2 {
padding-left: 15px;
}
.dub-ligthbox-content .dup-lightbox-iframe {
border: 0 none;
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
</style>
<?php
}
/**
* Lightbox js
*
* @return void
*/
protected static function lightBoxJs()
{
?>
<script>
$(document).ready(function ()
{
var currentLightboxOpen = null;
var toggleLightbox = function (target) {
if (target.hasClass('close')) {
target.removeClass('close').addClass('open').trigger('dup-lightbox-open');
currentLightboxOpen = target;
} else {
target.removeClass('open').addClass('close').trigger('dup-lightbox-close');
currentLightboxOpen = null;
}
};
function dupIframeLoaded(iframe, content) {
if (iframe.hasClass('auto-update')) {
setTimeout(function () {
dupIframeReload(iframe, content);
}, 3000);
}
}
;
function dupIframeReload(iframe, content) {
if (content.hasClass('open')) {
iframe[0].contentDocument.location.reload(true);
iframe.ready(function () {
dupIframeLoaded(iframe, content);
});
}
}
;
$('.dup-lightbox-iframe').on("load", function () {
$(this).contents().find('body').css({
'background': '#FFFFFF',
'color': "#000000"
});
this.contentWindow.scrollBy(0, 100000);
});
$('.dub-ligthbox-content').each(function () {
var content = $(this).detach().appendTo('body');
var iframe = content.find('.dup-lightbox-iframe');
if (iframe.length) {
content.
bind('dup-lightbox-open', function () {
iframe.attr('src', iframe.data('iframe-url')).ready(function () {
dupIframeLoaded(iframe, content);
});
}).
bind('dup-lightbox-close', function () {
iframe.attr('src', '');
});
}
});
$('[data-dup-ligthbox]').off().click(function (event) {
event.stopPropagation();
var target = $('#' + $(this).data('dup-ligthbox'));
toggleLightbox(target);
});
$('.dub-ligthbox-content .toggle-auto-update').off().click(function (event) {
event.stopPropagation();
var elem = $(this);
var content = elem.closest('.dub-ligthbox-content');
var iframe = content.find('.dup-lightbox-iframe');
if (iframe.hasClass('auto-update')) {
iframe.removeClass('auto-update');
elem.addClass('disabled').attr('title', 'Enable auto reload');
} else {
iframe.addClass('auto-update');
elem.removeClass('disabled').attr('title', 'Disable auto reload');
dupIframeReload(iframe, content);
}
});
$('.dub-ligthbox-content .close-button').off().click(function (event) {
event.stopPropagation();
toggleLightbox($(this).closest('.dub-ligthbox-content'));
});
$(window).keydown(function (event) {
if (event.key === 'Escape' && currentLightboxOpen !== null) {
currentLightboxOpen.find('.close-button').trigger('click');
}
});
});
</script>
<?php
}
/**
*
* @param string $htmlContent html content
* @param string|string[] $classes additional classes on main div
* @param int $step pixel foreach more step
* @param string $id id on main div
* @param bool $echo echo or return
*
* @return string|void
*/
public static function getMoreContent($htmlContent, $classes = array(), $step = 200, $id = '', $echo = true)
{
$inputCls = filter_var($classes, FILTER_SANITIZE_SPECIAL_CHARS, FILTER_FORCE_ARRAY);
$mainClasses = array_merge(array('more-content'), $inputCls);
$atStep = max(100, $step);
$idAttr = empty($id) ? '' : 'id="' . $id . '" ';
ob_start();
?>
<div <?php echo $idAttr; ?>class="<?php echo implode(' ', $mainClasses); ?>" data-more-step="<?php echo $atStep; ?>" style="max-height: <?php echo $atStep; ?>px">
<div class="more-wrapper" ><?php echo $htmlContent; ?></div>
<p class="more-faq-link align-">
Please search the <a href="https://duplicator.com/knowledge-base-article-categories/troubleshooting" target="_blank">Online Technical FAQs</a>
for solutions to these issues.
</p>
<button class="more-button" type="button">[show more]</button>
<button class="all-button" type="button" >[show all]</button>
</div>
<?php
if ($echo) {
ob_end_flush();
} else {
return ob_get_clean();
}
}
/**
* Input password with toggle button
*
* @param string $name name of input
* @param string $id id of input
* @param string[] $classes classes of input
* @param array<string, string|int> $attrs attributes of input
* @param bool $pwdSimulation if true emulate password type
*
* @return void
*/
public static function inputPasswordToggle($name, $id = '', $classes = array(), $attrs = array(), $pwdSimulation = false)
{
if (!is_array($attrs)) {
$attrs = array();
}
if (!is_array($classes)) {
if (empty($classes)) {
$classes = array();
} else {
$classes = array($classes);
}
}
$idAttr = empty($id) ? '_id_' . $name : $id;
$classes[] = 'input-password-group input-postfix-btn-group';
if ($pwdSimulation) {
$attrs['type'] = 'text';
$attrs['class'] = 'pwd-simulation text-security-disc';
} else {
$attrs['type'] = 'password';
}
$attrs['name'] = $name;
$attrs['id'] = $idAttr;
$attrsHtml = array();
foreach ($attrs as $atName => $atValue) {
$attrsHtml[] = $atName . '="' . DUPX_U::esc_attr($atValue) . '"';
}
?>
<span class="<?php echo implode(' ', $classes); ?>" >
<input <?php echo implode(' ', $attrsHtml); ?> />
<button type="button" class="postfix" title="Show the password"><i class="fas fa-eye fa-xs"></i></button>
</span>
<?php
}
/**
* Input password toggle css
*
* @return void
*/
protected static function inputPasswordToggleCss()
{
?>
<style>
.input-password-group {
position: relative;
}
.input-password-group button i {
line-height: 30px;
margin: 0;
padding: 0;
}
.input-password-group .parsley-errors-list {
position: absolute;
top: 50%;
transform: translateY(-50%);
left: 10px;
}
</style>
<?php
}
/**
* Input password toggle js
*
* @return void
*/
protected static function inputPasswordToggleJs()
{
?>
<script>
$(document).ready(function () {
$('.input-password-group').each(function () {
var group = $(this);
var pwdInput = group.find('input');
var pwdLock = group.find('button');
pwdLock.click(function () {
if (pwdInput.attr('type') === 'password' || pwdInput.hasClass('text-security-disc')) {
if (pwdInput.hasClass('pwd-simulation')) {
pwdInput.removeClass('text-security-disc');
} else {
pwdInput.attr('type', 'text');
}
pwdInput.attr('title', 'Hide the password');
pwdLock.find('i')
.removeClass('fa-eye')
.addClass('fa-eye-slash');
} else {
if (pwdInput.hasClass('pwd-simulation')) {
pwdInput.addClass('text-security-disc');
} else {
pwdInput.attr('type', 'password');
}
pwdInput.attr('title', 'Show the password');
pwdLock.find('i')
.removeClass('fa-eye-slash')
.addClass('fa-eye');
}
});
});
});
</script>
<?php
}
/**
* CheckboxSwitch
*
* @param array<string, string|int> $inputAttrs input attributes
* @param array<string, string|int> $switchAttrs switch attributes
*
* @return void
*/
public static function checkboxSwitch($inputAttrs = array(), $switchAttrs = array())
{
$inputAttrs['type'] = 'checkbox';
if (!isset($switchAttrs['class'])) {
$switchAttrs['class'] = array();
}
$switchAttrs['class'] = implode(' ', array_merge(array('checkbox-switch'), (array) $switchAttrs['class']));
?>
<span <?php echo self::arrayAttrToHtml($switchAttrs); ?> >
<input <?php echo self::arrayAttrToHtml($inputAttrs); ?> >
<span class="slider"></span>
</span>
<?php
}
/**
* Checkbox Switch Css
*
* @return void
*/
protected static function checkboxSwitchCss()
{
?>
<style>
.checkbox-switch {
position: relative;
display: inline-block;
width: 48px;
height: 26px;
box-sizing: border-box;
bottom: 0;
border-radius: 4px;
}
.checkbox-switch input {
position: absolute;
opacity: 0;
width: 100%;
height: 100%;
z-index: 90;
top: 0;
left: 0;
}
.checkbox-switch .slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: .4s;
transition: .4s;
border-radius: 4px;
overflow: hidden;
}
.checkbox-switch .slider:before {
position: absolute;
content: "";
height: 20px;
width: 20px;
left: 3px;
bottom: 3px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
border-radius: 4px;
overflow: hidden;
}
.checkbox-switch input:checked + .slider {
background-color: #2196F3;
}
.checkbox-switch input:focus + .slider {
box-shadow: 0 0 1px #2196F3;
}
.checkbox-switch input:disabled + .slider {
background-color: #ddd;
}
.checkbox-switch input:disabled:checked + .slider {
background-color: #cbe1f2;
}
.checkbox-switch input:disabled:focus + .slider {
box-shadow: 0 0 1px #cbe1f2;
}
.checkbox-switch input:disabled + .slider:before {
background-color: #ccc;
}
.checkbox-switch input:checked + .slider:before {
-webkit-transform: translateX(20px);
-ms-transform: translateX(20px);
transform: translateX(20px);
}
/* Rounded sliders */
.checkbox-switch.round .slider {
border-radius: 30px;
}
.checkbox-switch.round .slider:before {
border-radius: 50%;
}
</style>
<?php
}
}

View File

@@ -0,0 +1,146 @@
<?php
/**
* This is the class that manages the functions related to the views
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Core\Security;
use Duplicator\Installer\Utils\Log\Log;
use Duplicator\Installer\Core\Params\PrmMng;
use Duplicator\Installer\Utils\SecureCsrf;
use Duplicator\Libs\Snap\SnapURL;
/**
* View functions
*/
class DUPX_View_Funcs
{
/**
* Installer log link
*
* @param bool $echo Echo or return
*
* @return string
*/
public static function installerLogLink($echo = true)
{
return DUPX_U_Html::getLightBoxIframe('installer-log.txt', 'installer-log.txt', Log::getLogFileUrl(), true, true, $echo);
}
/**
* Get help link
*
* @param string $section Help section
*
* @return string
*/
public static function getHelpLink($section = '')
{
switch ($section) {
case "secure":
$helpOpenSection = 'section-security';
break;
case "step1":
$helpOpenSection = 'section-step-1';
break;
case "step2":
$helpOpenSection = 'section-step-2';
break;
case "step3":
$helpOpenSection = 'section-step-3';
break;
case "step4":
$helpOpenSection = 'section-step-4';
break;
case "help":
default:
$helpOpenSection = '';
}
$data = array_merge($_REQUEST, array(
PrmMng::PARAM_CTRL_ACTION => 'help',
Security::CTRL_TOKEN => SecureCsrf::generate('help'),
'basic' => '',
'open_section' => $helpOpenSection,
));
return SnapURL::getCurrentUrl(false, true) . '?' . http_build_query($data);
}
/**
* Help link
*
* @param string $section Help section
* @param string $linkLabel Link label
* @param bool $echo Echo or return
*
* @return string
*/
public static function helpLink($section, $linkLabel = 'Help', $echo = true)
{
ob_start();
$help_url = self::getHelpLink($section);
DUPX_U_Html::getLightBoxIframe($linkLabel, 'HELP', $help_url);
if ($echo) {
ob_end_flush();
return '';
} else {
return ob_get_clean();
}
}
/**
* Help lock link
*
* @return void
*/
public static function helpLockLink()
{
if (DUPX_ArchiveConfig::getInstance()->secure_on) {
self::helpLink('secure', '<i class="fa fa-lock fa-xs"></i>');
} else {
self::helpLink('secure', '<i class="fa fa-unlock-alt fa-xs"></i>');
}
}
/**
* Help icon link
*
* @param string $section Help section
*
* @return void
*/
public static function helpIconLink($section)
{
self::helpLink($section, '<i class="fas fa-question-circle fa-sm"></i>');
}
/**
* Get badge class attr val from status
*
* @param string $status Status
*
* @return string html class attribute
*/
public static function getBadgeClassFromCheckStatus($status)
{
switch ($status) {
case 'Pass':
return 'status-badge.pass';
case 'Fail':
return 'status-badge.fail';
case 'Warn':
return 'status-badge.warn';
default:
Log::error(sprintf("The arcCheck var has the illegal value %s in switch case", Log::v2str($status)));
return '';
}
}
}