Changed source root directory

This commit is contained in:
2026-03-05 16:30:11 +01:00
parent dc85447ee1
commit 538f85d7a2
5868 changed files with 749734 additions and 99 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,34 @@
<?php
/**
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\Chunk
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
/**
* Event iterator
*/
interface EventIterator extends Iterator
{
/**
* The callback accept 3 params
* $event , $index and $current values
*
* @param null | callable $callback
*/
public function setEventCallback($callback = null);
/**
* Execute event
*
* @param mixed $event
* @param mixed $key
* @param mixed $current
*/
public function doEvent($event, $key, $current);
}

View File

@@ -0,0 +1,43 @@
<?php
/**
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\Chunk
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
/**
*
* @author andrea
*/
interface GenericSeekableIterator extends Iterator
{
/**
*
* @param mixed $position
*
* @return bool
*/
public function gSeek($position);
/**
* return current position
*
* @return mixed
*/
public function getPosition();
/**
* Free resources in current iteration
*/
public function stopIteration();
/**
* Return iterations count
*/
public function itCount();
}

View File

@@ -0,0 +1,248 @@
<?php
/**
* Step 3 iterator
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\Chunk
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Utils\Log\Log;
require_once(DUPX_INIT . '/classes/chunk/Iterators/Interfaces/GenericSeekableIterator.php');
/**
* Description of class
*
* @author andrea
*/
class DUPX_s3_iterator implements GenericSeekableIterator
{
const STEP_START = 'start';
const STEP_CLEANUP_EXTREA = 'cleanup_extra';
const STEP_CLEANUP_PACKAGES = 'cleanup_packages';
const STEP_CLEANUP_OPTIONS = 'cleanup_trans';
const STEP_SEARCH_AND_REPLACE_INIT = 'init';
const STEP_SEARCH_AND_REPLACE = 'search_replace';
const STEP_REMOVE_MAINTENACE = 'rem_maintenance';
const STEP_CREATE_ADMIN = 'create_admin';
const STEP_CONF_UPDATE = 'config_update';
const STEP_GEN_UPD = 'gen_update';
const STEP_GEN_CLEAN = 'gen_clean';
const STEP_NOTICE_TEST = 'notice_test';
const STEP_CLEANUP_TMP_FILES = 'cleanup_tmp_files';
const STEP_SET_FILE_PERMS = 'set_files_perms';
const STEP_FINAL_REPORT_NOTICES = 'final_report';
private static $numIterations = 10;
protected $position = array(
'l0' => self::STEP_SEARCH_AND_REPLACE_INIT,
'l1' => null,
'l2' => null
);
protected $isValid = true;
protected $tablesIterator = null;
public function __construct()
{
$tables = DUPX_DB_Tables::getInstance()->getReplaceTablesNames();
$this->tablesIterator = new ArrayIterator($tables);
$this->rewind();
}
#[\ReturnTypeWillChange]
public function rewind()
{
$this->isValid = true;
$this->position = array(
'l0' => self::STEP_START,
'l1' => null,
'l2' => null
);
$this->tablesIterator->rewind();
}
#[\ReturnTypeWillChange]
public function next()
{
switch ($this->position['l0']) {
case self::STEP_START:
$this->position['l0'] = self::STEP_CLEANUP_OPTIONS;
break;
case self::STEP_CLEANUP_OPTIONS:
$this->position['l0'] = self::STEP_CLEANUP_EXTREA;
break;
case self::STEP_CLEANUP_EXTREA:
$this->position['l0'] = self::STEP_CLEANUP_PACKAGES;
break;
case self::STEP_CLEANUP_PACKAGES:
$this->position['l0'] = self::STEP_SEARCH_AND_REPLACE_INIT;
break;
case self::STEP_SEARCH_AND_REPLACE_INIT:
if ($this->getNextSearchReplacePosition(true)) {
// if search and replace is valid go to STEP_SEARCH_AND_REPLACE
$this->position['l0'] = self::STEP_SEARCH_AND_REPLACE;
} else {
// if search and replace isn't valid skip STEP_SEARCH_AND_REPLACE and go to STEP_REMOVE_MAINTENACE
$this->position['l0'] = self::STEP_REMOVE_MAINTENACE;
}
break;
case self::STEP_SEARCH_AND_REPLACE:
if (!$this->getNextSearchReplacePosition()) {
$this->position['l0'] = self::STEP_REMOVE_MAINTENACE;
}
break;
case self::STEP_REMOVE_MAINTENACE:
$this->position['l0'] = self::STEP_CONF_UPDATE;
break;
case self::STEP_CONF_UPDATE:
$this->position['l0'] = self::STEP_GEN_UPD;
break;
case self::STEP_GEN_UPD:
$this->position['l0'] = self::STEP_GEN_CLEAN;
break;
case self::STEP_GEN_CLEAN:
$this->position['l0'] = self::STEP_CREATE_ADMIN;
break;
case self::STEP_CREATE_ADMIN:
$this->position['l0'] = self::STEP_NOTICE_TEST;
break;
case self::STEP_NOTICE_TEST:
$this->position['l0'] = self::STEP_CLEANUP_TMP_FILES;
break;
case self::STEP_CLEANUP_TMP_FILES:
$this->position['l0'] = self::STEP_SET_FILE_PERMS;
break;
case self::STEP_SET_FILE_PERMS:
$this->position['l0'] = self::STEP_FINAL_REPORT_NOTICES;
break;
case self::STEP_FINAL_REPORT_NOTICES:
default:
$this->position['l0'] = null;
$this->isValid = false;
}
}
private function getNextSearchReplacePosition($init = false)
{
$valid = true;
$s3func = DUPX_S3_Funcs::getInstance();
$pages = isset($s3func->cTableParams['pages']) ? $s3func->cTableParams['pages'] : 0;
$this->position['l2'] = (int) $this->position['l2'];
$this->position['l2']++;
if ($this->position['l2'] < $pages) {
/* NEXT PAGE */
Log::info('ITERATOR INCREMENT PAGE: ' . $this->position['l2'] . ' PAGES[' . $pages . ']', 3);
$s3func->cTableParams['page'] = $this->position['l2'];
} else {
if ($init) {
DUPX_UpdateEngine::loadInit();
Log::info('ITERATOR FIRST TABLE: ' . $this->position['l2'] . ' PAGES[' . $pages . ']', 3);
$this->tablesIterator->rewind();
} else {
Log::info('ITERATOR INCREMENT TABLE: ' . $this->position['l2'] . ' PAGES[' . $pages . ']', 3);
if ($s3func->cTableParams['updated']) {
$s3func->report['updt_tables']++;
}
$this->tablesIterator->next();
}
$this->position['l1'] = $this->tablesIterator->key();
$this->position['l2'] = 0;
// search first table with rows and columns
while ($this->tablesIterator->valid()) {
Log::info('ITERATOR CHECK TABLE: ' . $this->tablesIterator->current(), 3);
// init table params if isn't initialized
if (DUPX_UpdateEngine::initTableParams($this->tablesIterator->current())) {
// table with columns and rows found
break;
}
// NEXT TABLE
$this->tablesIterator->next();
}
if ($this->tablesIterator->valid()) {
$this->position['l1'] = $this->tablesIterator->key();
$this->position['l2'] = 0;
} else {
$this->position['l1'] = null;
$this->position['l2'] = null;
$s3func->cTableParams = null;
DUPX_UpdateEngine::loadEnd();
DUPX_UpdateEngine::logStats();
DUPX_UpdateEngine::logErrors();
$valid = false;
}
}
return $valid;
}
public function gSeek($position)
{
$this->position = $position;
switch ($this->position['l0']) {
case self::STEP_SEARCH_AND_REPLACE:
$this->tablesIterator->seek($this->position['l1']);
break;
default:
}
}
public function getPosition()
{
return $this->position;
}
#[\ReturnTypeWillChange]
public function key()
{
return implode('_', $this->position);
}
#[\ReturnTypeWillChange]
public function current()
{
$result = array(
'l0' => $this->position['l0'],
'l1' => null,
'l2' => null
);
$result['l0'] = $this->position['l0'];
switch ($this->position['l0']) {
case self::STEP_SEARCH_AND_REPLACE:
$result['l1'] = $this->tablesIterator->current();
$result['l2'] = $this->position['l2'];
break;
default:
}
return $result;
}
public function stopIteration()
{
switch ($this->position['l0']) {
case self::STEP_SEARCH_AND_REPLACE:
DUPX_UpdateEngine::commitAndSave();
break;
default:
}
}
#[\ReturnTypeWillChange]
public function valid()
{
return $this->isValid;
}
public function itCount()
{
return self::$numIterations;
}
}

View File

@@ -0,0 +1,230 @@
<?php
/**
* Chunk manager step 3
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\Chunk
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Core\Deploy\Database\DbCleanup;
use Duplicator\Installer\Utils\Log\Log;
use Duplicator\Installer\Utils\Log\LogHandler;
use Duplicator\Libs\Snap\SnapJson;
require_once(DUPX_INIT . '/classes/chunk/class.chunkingmanager_file.php');
require_once(DUPX_INIT . '/classes/chunk/Iterators/class.s3.iterator.php');
/**
* Chunk manager step 3
*
* @author andrea
*/
class DUPX_chunkS3Manager extends DUPX_ChunkingManager_file
{
/**
* Exectute action for every iteration
*
* @param string $key
* @param array $current
*/
protected function action($key, $current)
{
$s3FuncsManager = DUPX_S3_Funcs::getInstance();
Log::info('CHUNK ACTION: CURRENT [' . implode('][', $current) . ']');
switch ($current['l0']) {
case DUPX_s3_iterator::STEP_START:
$s3FuncsManager->initLog();
$s3FuncsManager->initChunkLog($this->maxIteration, $this->timeOut, $this->throttling, $GLOBALS['DATABASE_PAGE_SIZE']);
break;
case DUPX_s3_iterator::STEP_CLEANUP_OPTIONS:
DbCleanup::cleanupOptions();
break;
case DUPX_s3_iterator::STEP_CLEANUP_EXTREA:
DbCleanup::cleanupExtra();
break;
case DUPX_s3_iterator::STEP_CLEANUP_PACKAGES:
DbCleanup::cleanupPackages();
break;
case DUPX_s3_iterator::STEP_SEARCH_AND_REPLACE_INIT:
break;
case DUPX_s3_iterator::STEP_SEARCH_AND_REPLACE:
DUPX_UpdateEngine::evaluateTableRows($current['l1'], $current['l2']);
DUPX_UpdateEngine::commitAndSave();
break;
case DUPX_s3_iterator::STEP_REMOVE_MAINTENACE:
$s3FuncsManager->removeMaintenanceMode();
break;
case DUPX_s3_iterator::STEP_CREATE_ADMIN:
$s3FuncsManager->createNewAdminUser();
break;
case DUPX_s3_iterator::STEP_CONF_UPDATE:
$s3FuncsManager->configFilesUpdate();
break;
case DUPX_s3_iterator::STEP_GEN_UPD:
$s3FuncsManager->generalUpdate();
break;
case DUPX_s3_iterator::STEP_GEN_CLEAN:
$s3FuncsManager->generalCleanup();
$s3FuncsManager->forceLogoutOfAllUsers();
$s3FuncsManager->duplicatorMigrationInfoSet();
break;
case DUPX_s3_iterator::STEP_NOTICE_TEST:
$s3FuncsManager->checkForIndexHtml();
$s3FuncsManager->noticeTest();
break;
case DUPX_s3_iterator::STEP_CLEANUP_TMP_FILES:
$s3FuncsManager->cleanupTmpFiles();
break;
case DUPX_s3_iterator::STEP_SET_FILE_PERMS:
$s3FuncsManager->setFilePermsission();
break;
case DUPX_s3_iterator::STEP_FINAL_REPORT_NOTICES:
$s3FuncsManager->finalReportNotices();
break;
default:
}
/**
* At each iteration save the status in case of exit with timeout
*/
$this->saveData();
}
protected function getIterator()
{
return new DUPX_s3_iterator();
}
public function getStoredDataKey()
{
return $GLOBALS["CHUNK_DATA_FILE_PATH"];
}
/**
* stop iteration without save data.
* It is already saved every iteration.
*
* @return mixed
*/
public function stop($saveData = false)
{
return parent::stop(false);
}
/**
* load data from previous step if exists adn restore _POST and GLOBALS
*
* @param string $key file name
*
* @return mixed
*/
protected function getStoredData($key)
{
if (($data = parent::getStoredData($key)) != null) {
Log::info("CHUNK LOAD DATA: POSITION " . implode(' / ', $data['position']), 2);
return $data['position'];
} else {
Log::info("CHUNK LOAD DATA: IS NULL ");
return null;
}
}
/**
* delete stored data if exists
*/
protected function deleteStoredData($key)
{
Log::info("CHUNK DELETE STORED DATA FILE:" . Log::v2str($key), 2);
return parent::deleteStoredData($key);
}
/**
* save data for next step
*/
protected function saveStoredData($key, $data)
{
// store s3 func data
$s3Funcs = DUPX_S3_Funcs::getInstance();
$s3Funcs->report['chunk'] = 1;
$s3Funcs->report['chunkPos'] = $data;
$s3Funcs->report['pass'] = 0;
$s3Funcs->report['progress_perc'] = $this->getProgressPerc();
$s3Funcs->saveData();
// managed output for timeout shutdown
LogHandler::setShutdownReturn(LogHandler::SHUTDOWN_TIMEOUT, SnapJson::jsonEncode($s3Funcs->getJsonReport()));
/**
* store position post and globals
*/
$gData = array(
'position' => $data
);
Log::info("CHUNK SAVE DATA: POSITION " . implode(' / ', $data), 2);
return parent::saveStoredData($key, $gData);
}
/**
*
* @return float progress in %
*/
public function getProgressPerc()
{
$result = 0;
$position = $this->it->getPosition();
$s3Func = DUPX_S3_Funcs::getInstance();
switch ($position['l0']) {
case DUPX_s3_iterator::STEP_SEARCH_AND_REPLACE_INIT:
$result = 5;
break;
case DUPX_s3_iterator::STEP_SEARCH_AND_REPLACE:
$lowLimit = 10;
$higthLimit = 90;
$stepDelta = $higthLimit - $lowLimit;
$tables = DUPX_DB_Tables::getInstance()->getReplaceTablesNames();
$tableDelta = $stepDelta / (count($tables) + 1);
$singePagePerc = $tableDelta / ($s3Func->cTableParams['pages'] + 1);
$result = round($lowLimit + ($tableDelta * (int) $position['l1']) + ($singePagePerc * (int) $position['l2']), 2);
break;
case DUPX_s3_iterator::STEP_REMOVE_MAINTENACE:
$result = 90;
break;
case DUPX_s3_iterator::STEP_CREATE_ADMIN:
$result = 92;
break;
case DUPX_s3_iterator::STEP_CONF_UPDATE:
$result = 93;
break;
case DUPX_s3_iterator::STEP_GEN_UPD:
$result = 94;
break;
case DUPX_s3_iterator::STEP_GEN_CLEAN:
$result = 95;
break;
case DUPX_s3_iterator::STEP_NOTICE_TEST:
$result = 96;
break;
case DUPX_s3_iterator::STEP_CLEANUP_TMP_FILES:
$result = 97;
break;
case DUPX_s3_iterator::STEP_SET_FILE_PERMS:
$result = 98;
break;
case DUPX_s3_iterator::STEP_FINAL_REPORT_NOTICES:
$result = 100;
break;
default:
}
return $result;
}
}

View File

@@ -0,0 +1,226 @@
<?php
/**
* Cunking manager
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\Chunk
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
/**
* Abstract class to split an single ajax requet in multiple requests
*/
abstract class DUPX_ChunkingManager
{
/** @var GenericSeekableIterator */
protected $it = null;
/** @var mixed */
protected $position = null;
/** @var integer max iteration before stop. If 0 have no limit */
public $maxIteration = 0;
/** @var integer timeout in milliseconds before stop exectution */
public $timeOut = 0;
/** @var integer sleep in milliseconds every iteration */
public $throttling = 0;
/** @var float */
protected $startTime = null;
/** @var integer */
protected $itCount = 0;
/**
* set params
*
* @param number $maxIteration
* @param number $timeOut
* @param number $throttling
*/
public function __construct($maxIteration = 0, $timeOut = 0, $throttling = 0)
{
$this->maxIteration = $maxIteration;
$this->timeOut = $timeOut;
$this->throttling = $throttling;
$this->it = $this->getIterator();
if (!is_subclass_of($this->it, 'GenericSeekableIterator')) {
throw new Exception('Iterator don\'t extend GenericSeekableIterator');
}
}
/**
*
* @param boolean $rewind
*
* @return boolean true if execution completed false if stopped
*/
public function start($rewind = false)
{
$this->itCount = 0;
$microThrottling = $this->throttling * 1000;
if ($rewind) {
/**
* delete store data and rewind
*/
$this->deleteStoredData($this->getStoredDataKey());
$this->it->rewind();
} elseif (( $last_position = $this->getStoredData($this->getStoredDataKey()) ) !== null) {
/**
* load last position if exist and delete it
*/
$this->deleteStoredData($this->getStoredDataKey());
$this->it->gSeek($last_position);
$this->it->next();
}
$this->startTime();
/**
* Iterate
*/
for (; $this->it->valid(); $this->it->next()) {
$this->itCount++;
/**
* excetute action for current item
*/
$this->action($this->it->key(), $this->it->current());
if ($microThrottling) {
usleep($microThrottling);
}
if ($this->maxIteration && $this->itCount >= $this->maxIteration || $this->checkTime() == false) {
$this->stop();
return false;
}
}
return true;
}
/**
* var bool $saveData is fals don't save data. Used in extended classe fot don't save data on stop.
*
* @return mixed
*/
public function stop($saveData = true)
{
if ($saveData) {
if (!$this->saveStoredData($this->getStoredDataKey(), $this->it->getPosition())) {
return null;
}
}
$position = $this->it->getPosition();
$this->it->stopIteration();
return $position;
}
protected function saveData()
{
if (!$this->saveStoredData($this->getStoredDataKey(), $this->it->getPosition())) {
return null;
}
}
/**
*
* @return mixed
*/
public function getLastPosition()
{
return $this->it->getPosition();
}
/**
*
* @return number
*/
public function getIterationsCount()
{
return $this->itCount;
}
/**
* @return void
*/
protected function startTime()
{
$this->startTime = microtime(true);
}
/**
*
* @return boolean
*/
protected function checkTime()
{
if ($this->timeOut) {
$delta = $this->getExecutionTime() * 1000;
if ($delta > $this->timeOut) {
return false;
}
}
return true;
}
/**
*
* @return number
*/
public function getExecutionTime()
{
return microtime(true) - $this->startTime;
}
/**
* Get stored data key
*/
abstract public function getStoredDataKey();
/**
* load data from previous step if exists
*/
abstract protected function getStoredData($key);
/**
* delete stored data if exists
*/
abstract protected function deleteStoredData($key);
/**
* save data for next step
*/
abstract protected function saveStoredData($key, $data);
/**
*
* @param mixed $key
* @param mixed $current
*/
abstract protected function action($key, $current);
/**
* @return GenericSeekableIterator
*/
abstract protected function getIterator();
/**
* @return int
*/
abstract public function getProgressPerc();
}

View File

@@ -0,0 +1,66 @@
<?php
/**
* Cunking manager with stored data in json file.
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\Chunk
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Libs\Snap\SnapJson;
require_once(DUPX_INIT . '/classes/chunk/class.chunkingmanager.php');
/**
* Store position on json file
*/
abstract class DUPX_ChunkingManager_file extends DUPX_ChunkingManager
{
/**
* load data from previous step if exists
*
* @param string $key file name
*
* @return mixed
*/
protected function getStoredData($key)
{
if (file_exists($key)) {
$data = file_get_contents($key);
return json_decode($data, true);
} else {
return null;
}
}
/**
* delete stored data if exists
*/
protected function deleteStoredData($key)
{
if (file_exists($key)) {
unlink($key);
}
}
/**
*
* @param string $key file path
* @param mixed $data to save in file path
*
* @return boolean|int This function returns the number of bytes that were written to the file, or FALSE on failure.
*/
protected function saveStoredData($key, $data)
{
if (($json = SnapJson::jsonEncode($data)) === false) {
throw new Exception('Json encode chunk data error');
}
return file_put_contents($key, $json);
}
}

View File

@@ -0,0 +1,64 @@
<?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
{
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));
}
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;
}
public static function scramble($string)
{
return self::encrypt(self::sk1() . self::sk2(), $string);
}
public static function unscramble($string)
{
return self::decrypt(self::sk1() . self::sk2(), $string);
}
public static function sk1()
{
return 'fdas' . self::encrypt('abx', 'v1');
}
public static function sk2()
{
return 'fres' . self::encrypt('ad3x', 'v2');
}
}

View File

@@ -0,0 +1,212 @@
<?php
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Libs\Snap\SnapJson;
class DUPX_CSRF
{
private static $packagHash = null;
private static $mainFolder = null;
/**
* Session var name prefix
*
* @var string
*/
public static $prefix = '_DUPX_CSRF';
/**
* Stores all CSRF values: Key as CSRF name and Val as CRF value
*
* @var array
*/
private static $CSRFVars = null;
public static function init($mainFolderm, $packageHash)
{
self::$mainFolder = $mainFolderm;
self::$packagHash = $packageHash;
self::$CSRFVars = null;
}
/**
* Set new CSRF
*
* @param string $key CSRF Key
* @param string $val CSRF Val
*
* @return Void
*/
public static function setKeyVal($key, $val)
{
$CSRFVars = self::getCSRFVars();
$CSRFVars[$key] = $val;
self::saveCSRFVars($CSRFVars);
self::$CSRFVars = null;
}
/**
* Get CSRF value by passing CSRF key
*
* @param string $key CSRF key
*
* @return string|boolean If CSRF value set for give n Key, It returns CRF value otherise returns false
*/
public static function getVal($key)
{
$CSRFVars = self::getCSRFVars();
if (isset($CSRFVars[$key])) {
return $CSRFVars[$key];
} else {
return false;
}
}
/**
* Generate DUPX_CSRF value for form
*
* @param string $form // Form name as session key
*
* @return string // token
*/
public static function generate($form = null)
{
$keyName = self::getKeyName($form);
$existingToken = self::getVal($keyName);
if (false !== $existingToken) {
$token = $existingToken;
} else {
$token = DUPX_CSRF::token() . DUPX_CSRF::fingerprint();
}
self::setKeyVal($keyName, $token);
return $token;
}
/**
* Check DUPX_CSRF value of form
*
* @param string $token - Token
* @param string $form - Form name as session key
*
* @return boolean
*/
public static function check($token, $form = null)
{
if (empty($form)) {
return false;
}
$keyName = self::getKeyName($form);
$CSRFVars = self::getCSRFVars();
if (isset($CSRFVars[$keyName]) && $CSRFVars[$keyName] == $token) {
// token OK
return true;
}
return false;
}
/**
* Generate token
*
* @return string
*/
protected static function token()
{
$microtime = (int) (microtime(true) * 10000);
mt_srand($microtime);
$charid = strtoupper(md5(uniqid(rand(), true)));
return substr($charid, 0, 8) . substr($charid, 8, 4) . substr($charid, 12, 4) . substr($charid, 16, 4) . substr($charid, 20, 12);
}
/**
* Returns "digital fingerprint" of user
*
* @return string - MD5 hashed data
*/
protected static function fingerprint()
{
return strtoupper(md5(implode('|', array($_SERVER['REMOTE_ADDR'], $_SERVER['HTTP_USER_AGENT']))));
}
/**
* Generate CSRF Key name
*
* @param string $form the form name for which CSRF key need to generate
*
* @return string CSRF key
*/
private static function getKeyName($form)
{
return DUPX_CSRF::$prefix . '_' . $form;
}
/**
* Get Package hash
*
* @return string Package hash
*/
private static function getPackageHash()
{
if (is_null(self::$packagHash)) {
throw new Exception('Not init CSFR CLASS');
}
return self::$packagHash;
}
/**
* Get file path where CSRF tokens are stored in JSON encoded format
*
* @return string file path where CSRF token stored
*/
public static function getFilePath()
{
if (is_null(self::$mainFolder)) {
throw new Exception('Not init CSFR CLASS');
}
$dupInstallerfolderPath = self::$mainFolder;
$packageHash = self::getPackageHash();
$fileName = 'dup-installer-csrf__' . $packageHash . '.txt';
$filePath = $dupInstallerfolderPath . '/' . $fileName;
return $filePath;
}
/**
* Get all CSRF vars in array format
*
* @return array Key as CSRF name and value as CSRF value
*/
private static function getCSRFVars()
{
if (is_null(self::$CSRFVars)) {
$filePath = self::getFilePath();
if (file_exists($filePath)) {
$contents = file_get_contents($filePath);
if (empty($contents)) {
self::$CSRFVars = array();
} else {
$CSRFobjs = json_decode($contents);
foreach ($CSRFobjs as $key => $value) {
self::$CSRFVars[$key] = $value;
}
}
} else {
self::$CSRFVars = array();
}
}
return self::$CSRFVars;
}
/**
* Stores all CSRF vars
*
* @param array $CSRFVars holds all CSRF key val
*
* @return void
*/
private static function saveCSRFVars($CSRFVars)
{
$contents = SnapJson::jsonEncode($CSRFVars);
$filePath = self::getFilePath();
file_put_contents($filePath, $contents);
}
}

View File

@@ -0,0 +1,237 @@
<?php
defined("DUPXABSPATH") or die("");
/**
* CLASS::DUPX_Http
* Http Class Utility
*/
class DUPX_HTTP
{
/**
* Do an http post request with curl or php code
*
* @param string $url A URL to post to
* @param string $params A valid key/pair combo $data = array('key1' => 'value1', 'key2' => 'value2');
* @param array $headers Optional header elements
*
* @return string or FALSE on failure.
*/
public static function post($url, $params = array(), $headers = null)
{
//PHP POST
if (!function_exists('curl_init')) {
return self::php_get_post($url, $params, $headers = null, 'POST');
}
//CURL POST
$headers_on = isset($headers) && array_count_values($headers);
$params = http_build_query($params);
$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, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, $headers_on);
if ($headers_on) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
curl_setopt($ch, CURLOPT_POST, count($params));
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
$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
*
* @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;
}
/**
* Check to see if the internet is accessible
*
* @param string $host A URL e.g without prefix "ajax.googleapis.com"
* @param string $port A valid port number
*
* @return bool
*/
public static function is_url_active($url, $port = 443, $timeout = 5)
{
//localhost will not have cpanel in most cases
if (strpos($url, 'localhost:2083') !== false) {
return false;
}
switch (true) {
case function_exists('curl_init'):
return self::is_url_active_curl($url, $port, $timeout);
break;
case function_exists('fsockopen'):
return self::is_url_active_fsockopen($url, $port, $timeout);
break;
default:
return false;
break;
}
}
/**
* Returns the host part of a URL
*
* @param string $url A valid URL
*
* @return string
*/
public static function parse_host($url)
{
$url = parse_url(trim($url));
if ($url == false) {
return null;
}
return trim($url['host'] ? $url['host'] : array_shift(explode('/', $url['path'], 2)));
}
/**
* Return the current page URL
*
* @param bool $withQuery Return the URL with its string
*
* @return string
*/
public static function get_page_url($withQuery = true)
{
$protocol = (!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off')
|| (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) === 'https')
|| (!empty($_SERVER['HTTP_FRONT_END_HTTPS']) && strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) !== 'off')
|| (isset($_SERVER['SERVER_PORT']) && intval($_SERVER['SERVER_PORT']) === 443) ? 'https' : 'http';
$uri = $protocol . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
return $withQuery ? $uri : str_replace('?' . $_SERVER['QUERY_STRING'], '', $uri);
}
//PHP POST or GET requets
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, $php_errormsg");
}
$response = @stream_get_contents($fp);
if ($response === false) {
throw new Exception("Problem reading data from $full_url, $php_errormsg");
}
return $response;
}
//Check URL with fsockopen/
private static function is_url_active_fsockopen($url, $port = 443, $timeout = 5)
{
try {
$host = parse_url($url, PHP_URL_HOST);
$host = DUPX_U::is_ssl() ? "ssl://{$host}" : $host;
$errno = 0;
$message = 'Error with fsockopen';
$connection = @fsockopen($host, $port, $code, $message, $timeout);
if (!is_resource($connection)) {
return false;
}
@fclose($connection);
return true;
} catch (Exception $e) {
return false;
}
}
//Check URL with curl
private static function is_url_active_curl($url, $port = 443, $timeout = 5)
{
try {
$result = false;
$url = filter_var($url, FILTER_VALIDATE_URL);
$handle = curl_init($url);
/* Set curl parameter */
curl_setopt_array($handle, array(
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_NOBODY => true,
CURLOPT_HEADER => false,
CURLOPT_RETURNTRANSFER => false,
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_TIMEOUT => $timeout,
CURLOPT_PORT => $port
));
$response = curl_exec($handle);
$httpCode = curl_getinfo($handle, CURLINFO_EFFECTIVE_URL); // Try to get the last url
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE); // Get http status from last url
/* Check for 200 (file is found). */
if ($httpCode == 200) {
$result = true;
}
curl_close($handle);
return $result;
} catch (Exception $e) {
return false;
}
}
}

View File

@@ -0,0 +1,689 @@
<?php
defined("DUPXABSPATH") or die("");
use Duplicator\Installer\Utils\Log\Log;
use Duplicator\Installer\Core\Params\Descriptors\ParamDescConfigs;
use Duplicator\Installer\Core\Params\PrmMng;
use Duplicator\Libs\Snap\SnapIO;
class DUPX_InstallerState
{
/**
* modes
*/
const MODE_UNKNOWN = -1;
const MODE_STD_INSTALL = 0;
const MODE_OVR_INSTALL = 1;
/**
* install types
*/
const INSTALL_NOT_SET = -2;
const INSTALL_SINGLE_SITE = -1;
const INSTALL_SINGLE_SITE_ON_SUBDOMAIN = 4;
const INSTALL_SINGLE_SITE_ON_SUBFOLDER = 5;
const INSTALL_RBACKUP_SINGLE_SITE = 8;
const LOGIC_MODE_IMPORT = 'IMPORT';
const LOGIC_MODE_RECOVERY = 'RECOVERY';
const LOGIC_MODE_CLASSIC = 'CLASSIC';
const LOGIC_MODE_OVERWRITE = 'OVERWRITE';
const LOGIC_MODE_BRIDGE = 'BRIDGE';
const LOGIC_MODE_RESTORE_BACKUP = 'RESTORE_BACKUP';
/**
* min versions
*/
const SUBSITE_IMPORT_WP_MIN_VERSION = '4.6';
/**
*
* @var int
*/
protected $mode = self::MODE_UNKNOWN;
/**
*
* @var string
*/
protected $ovr_wp_content_dir = '';
/**
*
* @var self
*/
private static $instance = null;
/**
*
* @return self
*/
public static function getInstance()
{
if (is_null(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct()
{
}
/**
* return installer mode
*
* @return int
*/
public function getMode()
{
return PrmMng::getInstance()->getValue(PrmMng::PARAM_INSTALLER_MODE);
}
/**
* check current installer mode
*
* @param bool $onlyIfUnknown // check se state only if is unknow state
* @param bool $saveParams // if true update params
*
* @return boolean
*/
public function checkState($onlyIfUnknown = true, $saveParams = true)
{
$paramsManager = PrmMng::getInstance();
if ($onlyIfUnknown && $paramsManager->getValue(PrmMng::PARAM_INSTALLER_MODE) !== self::MODE_UNKNOWN) {
return true;
}
$isOverwrite = false;
$nManager = DUPX_NOTICE_MANAGER::getInstance();
try {
if (self::isImportFromBackendMode()) {
$overwriteData = $this->getOverwriteDataFromParams();
} else {
$overwriteData = $this->getOverwriteDataFromWpConfig();
}
if (!empty($overwriteData)) {
if (!DUPX_DB::testConnection($overwriteData['dbhost'], $overwriteData['dbuser'], $overwriteData['dbpass'], $overwriteData['dbname'])) {
throw new Exception('wp-config.php exists but database data connection isn\'t valid. Continuing with standard install');
}
$isOverwrite = true;
if (!self::isImportFromBackendMode()) {
//Add additional overwrite data for standard installs
$overwriteData['adminUsers'] = $this->getAdminUsersOnOverwriteDatabase($overwriteData);
$overwriteData['wpVersion'] = $this->getWordPressVersionOverwrite();
$this->updateOverwriteDataFromDb($overwriteData);
}
}
} catch (Exception $e) {
Log::logException($e);
$longMsg = "Exception message: " . $e->getMessage() . "\n\n";
$nManager->addNextStepNotice(array(
'shortMsg' => 'wp-config.php exists but isn\'t valid. Continue on standard install.',
'level' => DUPX_NOTICE_ITEM::SOFT_WARNING,
'longMsg' => $longMsg,
'longMsgMode' => DUPX_NOTICE_ITEM::MSG_MODE_PRE
));
$nManager->saveNotices();
} catch (Error $e) {
Log::logException($e);
$longMsg = "Exception message: " . $e->getMessage() . "\n\n";
$nManager->addNextStepNotice(array(
'shortMsg' => 'wp-config.php exists but isn\'t valid. Continue on standard install.',
'level' => DUPX_NOTICE_ITEM::SOFT_WARNING,
'longMsg' => $longMsg,
'longMsgMode' => DUPX_NOTICE_ITEM::MSG_MODE_PRE
));
$nManager->saveNotices();
}
if ($isOverwrite) {
$paramsManager->setValue(PrmMng::PARAM_INSTALLER_MODE, self::MODE_OVR_INSTALL);
$paramsManager->setValue(PrmMng::PARAM_OVERWRITE_SITE_DATA, $overwriteData);
} else {
$paramsManager->setValue(PrmMng::PARAM_INSTALLER_MODE, self::MODE_STD_INSTALL);
}
if ($saveParams) {
return $this->save();
} else {
return true;
}
}
/**
*
* @param int $type
*
* @return string
*/
public static function installTypeToString($type = null)
{
if (is_null($type)) {
$type = self::getInstType();
}
switch ($type) {
case self::INSTALL_SINGLE_SITE:
return 'single site';
case self::INSTALL_SINGLE_SITE_ON_SUBDOMAIN:
return 'single site on subdomain multisite';
case self::INSTALL_SINGLE_SITE_ON_SUBFOLDER:
return 'single site on subfolder multisite';
case self::INSTALL_RBACKUP_SINGLE_SITE:
return 'restore single site';
case self::INSTALL_NOT_SET:
return 'NOT SET';
default:
throw new Exception('Invalid installer mode');
}
}
public static function overwriteDataDefault()
{
return array(
'dupVersion' => '0',
'wpVersion' => '0',
'dbhost' => '',
'dbname' => '',
'dbuser' => '',
'dbpass' => '',
'table_prefix' => '',
'restUrl' => '',
'restNonce' => '',
'restAuthUser' => '',
'restAuthPassword' => '',
'ustatIdentifier' => '',
'isMultisite' => false,
'subdomain' => false,
'subsites' => array(),
'nextSubsiteIdAI' => -1,
'adminUsers' => array(),
'paths' => array(),
'urls' => array()
);
}
protected function getOverwriteDataFromParams()
{
$overwriteData = PrmMng::getInstance()->getValue(PrmMng::PARAM_OVERWRITE_SITE_DATA);
if (empty($overwriteData)) {
return false;
}
if (!isset($overwriteData['dbhost']) || !isset($overwriteData['dbname']) || !isset($overwriteData['dbuser']) || !isset($overwriteData['dbpass'])) {
return false;
}
return array_merge(self::overwriteDataDefault(), $overwriteData);
}
protected function getOverwriteDataFromWpConfig()
{
if (($wpConfigPath = DUPX_ServerConfig::getWpConfigLocalStoredPath()) === false) {
$wpConfigPath = DUPX_WPConfig::getWpConfigPath();
if (!file_exists($wpConfigPath)) {
$wpConfigPath = DUPX_WPConfig::getWpConfigDeafultPath();
}
}
$overwriteData = false;
Log::info('CHECK STATE INSTALLER WP CONFIG PATH: ' . Log::v2str($wpConfigPath), Log::LV_DETAILED);
if (!file_exists($wpConfigPath)) {
return $overwriteData;
}
$nManager = DUPX_NOTICE_MANAGER::getInstance();
try {
if (DUPX_WPConfig::getLocalConfigTransformer() === false) {
throw new Exception('wp-config.php exist but isn\'t valid. continue on standard install');
}
$overwriteData = array_merge(
self::overwriteDataDefault(),
array(
'dbhost' => DUPX_WPConfig::getValueFromLocalWpConfig('DB_HOST'),
'dbname' => DUPX_WPConfig::getValueFromLocalWpConfig('DB_NAME'),
'dbuser' => DUPX_WPConfig::getValueFromLocalWpConfig('DB_USER'),
'dbpass' => DUPX_WPConfig::getValueFromLocalWpConfig('DB_PASSWORD'),
'table_prefix' => DUPX_WPConfig::getValueFromLocalWpConfig('table_prefix', 'variable')
)
);
if (DUPX_WPConfig::getValueFromLocalWpConfig('MULTISITE', 'constant', false)) {
$overwriteData['isMultisite'] = true;
$overwriteData['subdomain'] = DUPX_WPConfig::getValueFromLocalWpConfig('SUBDOMAIN_INSTALL', 'constant', false);
}
} catch (Exception $e) {
$overwriteData = false;
Log::logException($e);
$longMsg = "Exception message: " . $e->getMessage() . "\n\n";
$nManager->addNextStepNotice(array(
'shortMsg' => 'wp-config.php exists but isn\'t valid. Continue on standard install.',
'level' => DUPX_NOTICE_ITEM::SOFT_WARNING,
'longMsg' => $longMsg,
'longMsgMode' => DUPX_NOTICE_ITEM::MSG_MODE_PRE
));
$nManager->saveNotices();
} catch (Error $e) {
$overwriteData = false;
Log::logException($e);
$longMsg = "Exception message: " . $e->getMessage() . "\n\n";
$nManager->addNextStepNotice(array(
'shortMsg' => 'wp-config.php exists but isn\'t valid. Continue on standard install.',
'level' => DUPX_NOTICE_ITEM::SOFT_WARNING,
'longMsg' => $longMsg,
'longMsgMode' => DUPX_NOTICE_ITEM::MSG_MODE_PRE
));
$nManager->saveNotices();
}
return $overwriteData;
}
/**
*
* @return bool
*/
public static function isRestoreBackup($type = null)
{
return self::isInstType(
array(
self::INSTALL_RBACKUP_SINGLE_SITE
),
$type
);
}
/**
*
* @return bool
*/
public static function isImportFromBackendMode()
{
$template = PrmMng::getInstance()->getValue(PrmMng::PARAM_TEMPLATE);
return ($template === DUPX_Template::TEMPLATE_IMPORT_BASE ||
$template === DUPX_Template::TEMPLATE_IMPORT_ADVANCED);
}
/**
*
* @return bool
*/
public static function isClassicInstall()
{
return (!self::isImportFromBackendMode());
}
/**
*
* @param int|array $type
*
* @return bool
*/
public static function instTypeAvaiable($type)
{
$acceptList = ParamDescConfigs::getInstallTypesAcceptValues();
$typesToCheck = is_array($type) ? $type : array($type);
$typesAvaliables = array_intersect($acceptList, $typesToCheck);
return (count($typesAvaliables) > 0);
}
/**
* this function in case of an error returns an empty array but never generates exceptions
*
* @param string $overwriteData
*
* @return array
*/
protected function getAdminUsersOnOverwriteDatabase($overwriteData)
{
$adminUsers = array();
try {
$dbFuncs = DUPX_DB_Functions::getInstance();
if (!$dbFuncs->dbConnection($overwriteData)) {
Log::info('GET USERS ON CURRENT DATABASE FAILED. Can\'t connect');
return $adminUsers;
}
$usersTables = array(
$dbFuncs->getUserTableName($overwriteData['table_prefix']),
$dbFuncs->getUserMetaTableName($overwriteData['table_prefix'])
);
if (!$dbFuncs->tablesExist($usersTables)) {
Log::info('GET USERS ON CURRENT DATABASE FAILED. Users tables doesn\'t exist, continue with orverwrite installation but with option keep users disabled' . "\n");
$dbFuncs->closeDbConnection();
return $adminUsers;
}
if (($adminUsers = $dbFuncs->getAdminUsers($overwriteData['table_prefix'])) === false) {
Log::info('GET USERS ON CURRENT DATABASE FAILED. OVERWRITE DB USERS NOT FOUND');
$dbFuncs->closeDbConnection();
return $adminUsers;
}
$dbFuncs->closeDbConnection();
} catch (Exception $e) {
Log::logException($e, Log::LV_DEFAULT, 'GET ADMIN USER EXECPTION BUT CONTINUE');
} catch (Error $e) {
Log::logException($e, Log::LV_DEFAULT, 'GET ADMIN USER EXECPTION BUT CONTINUE');
}
return $adminUsers;
}
/**
* Returns the WP version from the ./wp-includes/version.php file if it exists, otherwise '0'
*
* @return string WP version
*/
protected function getWordPressVersionOverwrite()
{
$wp_version = '0';
try {
$versionFilePath = PrmMng::getInstance()->getValue(PrmMng::PARAM_PATH_WP_CORE_NEW) . "/wp-includes/version.php";
if (!file_exists($versionFilePath) || !is_readable($versionFilePath)) {
Log::info("WordPress Version file does not exist or is not readable at path: {$versionFilePath}");
return $wp_version;
}
include($versionFilePath);
return $wp_version;
} catch (Exception $e) {
Log::logException($e, Log::LV_DEFAULT, 'EXCEPTION GETTING WORDPRESS VERSION, BUT CONTINUE');
} catch (Error $e) {
Log::logException($e, Log::LV_DEFAULT, 'ERROR GETTING WORDPRESS VERSION, BUT CONTINUE');
}
return $wp_version;
}
/**
* Returns the Duplicator Pro version if it exists, otherwise '0'
*
* @param array<string, mixed> $overwriteData Overwrite data
*
* @return bool True on success, false on failure
*/
protected function updateOverwriteDataFromDb(&$overwriteData)
{
try {
$dbFuncs = null;
$dbFuncs = DUPX_DB_Functions::getInstance();
if (!$dbFuncs->dbConnection($overwriteData)) {
throw new Exception('GET DUPLICATOR VERSION ON CURRENT DATABASE FAILED. Can\'t connect');
}
$optionsTable = DUPX_DB_Functions::getOptionsTableName($overwriteData['table_prefix']);
if (!$dbFuncs->tablesExist($optionsTable)) {
throw new Exception("GET DUPLICATOR VERSION ON CURRENT DATABASE FAILED. Options tables doesn't exist.\n");
}
$duplicatorProVersion = $dbFuncs->getDuplicatorVersion($overwriteData['table_prefix']);
$overwriteData['dupVersion'] = (empty($duplicatorProVersion) ? '0' : $duplicatorProVersion);
$overwriteData['ustatIdentifier'] = $dbFuncs->getUstatIdentifier($overwriteData['table_prefix']);
} catch (Exception $e) {
if ($dbFuncs instanceof DUPX_DB_Functions) {
$dbFuncs->closeDbConnection();
}
Log::logException($e, Log::LV_DEFAULT, 'GET DUPLICATOR VERSION EXECPTION BUT CONTINUE');
return false;
} catch (Error $e) {
if ($dbFuncs instanceof DUPX_DB_Functions) {
$dbFuncs->closeDbConnection();
}
Log::logException($e, Log::LV_DEFAULT, 'GET DUPLICATOR VERSION ERROR BUT CONTINUE');
return false;
}
if ($dbFuncs instanceof DUPX_DB_Functions) {
$dbFuncs->closeDbConnection();
}
return true;
}
/**
* getHtmlModeHeader
*
* @return string
*/
public function getHtmlModeHeader()
{
$php_enforced_txt = ($GLOBALS['DUPX_ENFORCE_PHP_INI']) ? '<i style="color:red"><br/>*PHP ini enforced*</i>' : '';
$db_only_txt = (DUPX_ArchiveConfig::getInstance()->exportOnlyDB) ? ' - Database Only' : '';
$db_only_txt = $db_only_txt . $php_enforced_txt;
switch ($this->getMode()) {
case self::MODE_OVR_INSTALL:
$label = 'Overwrite Install';
$class = 'dupx-overwrite mode_overwrite';
break;
case self::MODE_STD_INSTALL:
$label = 'Standard Install';
$class = 'dupx-overwrite mode_standard';
break;
case self::MODE_UNKNOWN:
default:
$label = 'Unknown';
$class = 'mode_unknown';
break;
}
if (strlen($db_only_txt)) {
return "<span class='{$class}'>{$label} {$db_only_txt}</span>";
} else {
return "<span class='{$class}'>{$label}</span>";
}
}
/**
* reset current mode
*
* @param boolean $saveParams
*
* @return boolean
*/
public function resetState($saveParams = true)
{
$paramsManager = PrmMng::getInstance();
$paramsManager->setValue(PrmMng::PARAM_INSTALLER_MODE, self::MODE_UNKNOWN);
if ($saveParams) {
return $this->save();
} else {
return true;
}
}
/**
* save current installer state
*
* @return bool
*/
public function save()
{
return PrmMng::getInstance()->save();
}
/**
* Return stru if is overwrite install
*
* @return boolean
*/
public static function isOverwrite()
{
return (PrmMng::getInstance()->getValue(PrmMng::PARAM_INSTALLER_MODE) === self::MODE_OVR_INSTALL);
}
/**
* this function returns true if both the URL and path old and new path are identical
*
* @return bool
*/
public static function isInstallerCreatedInThisLocation()
{
$paramsManager = PrmMng::getInstance();
$urlNew = null;
$pathNew = null;
if (DUPX_InstallerState::isImportFromBackendMode()) {
$overwriteData = $paramsManager->getValue(PrmMng::PARAM_OVERWRITE_SITE_DATA);
if (isset($overwriteData['urls']['home']) && isset($overwriteData['paths']['home'])) {
$urlNew = $overwriteData['urls']['home'];
$pathNew = $overwriteData['paths']['home'];
}
}
if (is_null($urlNew) || is_null($pathNew)) {
$pathNew = $paramsManager->getValue(PrmMng::PARAM_PATH_NEW);
$urlNew = $paramsManager->getValue(PrmMng::PARAM_URL_NEW);
}
return self::urlAndPathAreSameOfArchive($urlNew, $pathNew);
}
/**
* isSameLocationOfArtiche
*
* @param string $urlNew
* @param string $pathNew
*
* @return bool
*/
public static function urlAndPathAreSameOfArchive($urlNew, $pathNew)
{
$archiveConfig = \DUPX_ArchiveConfig::getInstance();
$urlOld = rtrim($archiveConfig->getRealValue('homeUrl'), '/');
$paths = $archiveConfig->getRealValue('archivePaths');
$pathOld = $paths->home;
$paths = $archiveConfig->getRealValue('originalPaths');
$pathOldOrig = $paths->home;
$urlNew = SnapIO::untrailingslashit($urlNew);
$urlOld = SnapIO::untrailingslashit($urlOld);
$pathNew = SnapIO::untrailingslashit($pathNew);
$pathOld = SnapIO::untrailingslashit($pathOld);
$pathOldOrig = SnapIO::untrailingslashit($pathOldOrig);
return (($pathNew === $pathOld || $pathNew === $pathOldOrig) && $urlNew === $urlOld);
}
/**
* get migration data to store in wp-options
*
* @return array
*/
public static function getMigrationData()
{
$sec = DUPX_Security::getInstance();
$paramsManager = PrmMng::getInstance();
$ac = DUPX_ArchiveConfig::getInstance();
$overwriteData = $paramsManager->getValue(PrmMng::PARAM_OVERWRITE_SITE_DATA);
return array(
'plugin' => 'dup-lite',
'installerVersion' => DUPX_VERSION,
'installType' => $paramsManager->getValue(PrmMng::PARAM_INST_TYPE),
'logicModes' => self::getLogicModes(),
'template' => PrmMng::getInstance()->getValue(PrmMng::PARAM_TEMPLATE),
'restoreBackupMode' => self::isRestoreBackup(),
'recoveryMode' => false,
'archivePath' => $sec->getArchivePath(),
'packageHash' => DUPX_Package::getPackageHash(),
'installerPath' => $sec->getBootFilePath(),
'installerBootLog' => $sec->getBootLogFile(),
'installerLog' => Log::getLogFilePath(),
'dupInstallerPath' => DUPX_INIT,
'origFileFolderPath' => DUPX_Orig_File_Manager::getInstance()->getMainFolder(),
'safeMode' => $paramsManager->getValue(PrmMng::PARAM_SAFE_MODE),
'cleanInstallerFiles' => $paramsManager->getValue(PrmMng::PARAM_AUTO_CLEAN_INSTALLER_FILES),
'licenseType' => $ac->license_type,
'phpVersion' => $ac->version_php,
'archiveType' => $ac->isZipArchive() ? 'zip' : 'dup',
'siteSize' => $ac->fileInfo->size,
'siteNumFiles' => ($ac->fileInfo->dirCount + $ac->fileInfo->fileCount),
'siteDbSize' => $ac->dbInfo->tablesSizeOnDisk,
'siteDBNumTables' => $ac->dbInfo->tablesFinalCount,
'components' => $ac->components,
'ustatIdentifier' => $overwriteData['ustatIdentifier'],
'time' => time()
);
}
/**
*
* @return string
*/
public static function getAdminLogin()
{
$paramsManager = PrmMng::getInstance();
$archiveConfig = \DUPX_ArchiveConfig::getInstance();
$adminUrl = rtrim($paramsManager->getValue(PrmMng::PARAM_SITE_URL), "/");
$sourceAdminUrl = rtrim($archiveConfig->getRealValue("siteUrl"), "/");
$sourceLoginUrl = $archiveConfig->getRealValue("loginUrl");
$relLoginUrl = substr($sourceLoginUrl, strlen($sourceAdminUrl));
$loginUrl = $adminUrl . $relLoginUrl;
return $loginUrl;
}
/**
*
* @return int
*/
public static function getInstType()
{
return PrmMng::getInstance()->getValue(PrmMng::PARAM_INST_TYPE);
}
/**
* @param int|array $type list of types to check
* @param int $typeToCheck if is null get param install time or check this
*
* @return bool
*/
public static function isInstType($type, $typeToCheck = null)
{
$currentType = is_null($typeToCheck) ? self::getInstType() : $typeToCheck;
if (is_array($type)) {
return in_array($currentType, $type);
} else {
return $currentType === $type;
}
}
/**
* Get install logic modes
*
* @return string[]
*/
public static function getLogicModes()
{
$modes = array();
if (self::isImportFromBackendMode()) {
$modes[] = self::LOGIC_MODE_IMPORT;
}
if (self::isClassicInstall()) {
$modes[] = self::LOGIC_MODE_CLASSIC;
}
if (self::isOverwrite()) {
$modes[] = self::LOGIC_MODE_OVERWRITE;
}
if (self::isRestoreBackup()) {
$modes[] = self::LOGIC_MODE_RESTORE_BACKUP;
}
return $modes;
}
}

View File

@@ -0,0 +1,245 @@
<?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\Bootstrap;
/**
* Package related functions
*/
final class DUPX_Package
{
/**
*
* @staticvar bool|string $packageHash
* @return bool|string false if fail
* @throws Exception
*/
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;
}
/**
*
* @staticvar string $fileHash
* @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', DUPX_Security::getInstance()->getArchivePath());
}
return $fileHash;
}
/**
*
* @staticvar string $archivePath
* @return bool|string false if fail
* @throws Exception
*/
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
* @throws Exception
*/
public static function getWpconfigArkPath()
{
return DUPX_Orig_File_Manager::getInstance()->getEntryStoredPath(DUPX_ServerConfig::CONFIG_ORIG_FILE_WPCONFIG_ID);
}
/**
*
* @return string
* @throws Exception
*/
public static function getManualExtractFile()
{
return DUPX_INIT . '/dup-manual-extract__' . self::getPackageHash();
}
/**
*
* @staticvar type $path
* @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';
}
/**
*
* @staticvar string $path
* @return string
*/
public static function getSqlFilePath()
{
static $path = null;
if (is_null($path)) {
$path = DUPX_INIT . '/dup-database__' . self::getPackageHash() . '.sql';
}
return $path;
}
/**
*
* @staticvar string $dirsPath
* @return string
*/
public static function getDirsListPath()
{
static $path = null;
if (is_null($path)) {
$path = DUPX_INIT . '/dup-scanned-dirs__' . self::getPackageHash() . '.txt';
}
return $path;
}
/**
*
* @staticvar string $dirsPath
* @return string
*/
public static function getFilesListPath()
{
static $path = null;
if (is_null($path)) {
$path = DUPX_INIT . '/dup-scanned-files__' . self::getPackageHash() . '.txt';
}
return $path;
}
/**
*
* @staticvar string $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
*
* @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
*
* @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,233 @@
<?php
#
# Portable PHP password hashing framework.
#
# Version 0.5 / genuine.
#
# Written by Solar Designer <solar at openwall.com> in 2004-2006 and placed in
# the public domain. Revised in subsequent years, still public domain.
#
# There's absolutely no warranty.
#
# The homepage URL for this framework is:
#
# http://www.openwall.com/phpass/
#
# Please be sure to update the Version line if you edit this file in any way.
# It is suggested that you leave the main version number intact, but indicate
# your project name (after the slash) and add your own revision information.
#
# Please do not change the "private" password hashing method implemented in
# here, thereby making your hashes incompatible. However, if you must, please
# change the hash type identifier (the "$P$") to something different.
#
# Obviously, since this code is in the public domain, the above are not
# requirements (there can be none), but merely suggestions.
#
class DUPX_PasswordHash
{
public $itoa64;
public $iteration_count_log2;
public $portable_hashes;
public $random_state;
public function __construct($iteration_count_log2, $portable_hashes)
{
$this->itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
if ($iteration_count_log2 < 4 || $iteration_count_log2 > 31) {
$iteration_count_log2 = 8;
}
$this->iteration_count_log2 = $iteration_count_log2;
$this->portable_hashes = $portable_hashes;
$this->random_state = microtime();
if (function_exists('getmypid')) {
$this->random_state .= getmypid();
}
}
public function PasswordHash($iteration_count_log2, $portable_hashes)
{
self::__construct($iteration_count_log2, $portable_hashes);
}
public function get_random_bytes($count)
{
$output = '';
if (
@is_readable('/dev/urandom') &&
($fh = @fopen('/dev/urandom', 'rb'))
) {
$output = fread($fh, $count);
fclose($fh);
}
if (strlen($output) < $count) {
$output = '';
for ($i = 0; $i < $count; $i += 16) {
$this->random_state =
md5(microtime() . $this->random_state);
$output .= md5($this->random_state, true);
}
$output = substr($output, 0, $count);
}
return $output;
}
public function encode64($input, $count)
{
$output = '';
$i = 0;
do {
$value = ord($input[$i++]);
$output .= $this->itoa64[$value & 0x3f];
if ($i < $count) {
$value |= ord($input[$i]) << 8;
}
$output .= $this->itoa64[($value >> 6) & 0x3f];
if ($i++ >= $count) {
break;
}
if ($i < $count) {
$value |= ord($input[$i]) << 16;
}
$output .= $this->itoa64[($value >> 12) & 0x3f];
if ($i++ >= $count) {
break;
}
$output .= $this->itoa64[($value >> 18) & 0x3f];
} while ($i < $count);
return $output;
}
public function gensalt_private($input)
{
$output = '$P$';
$output .= $this->itoa64[min($this->iteration_count_log2 +
((PHP_VERSION >= '5') ? 5 : 3), 30)];
$output .= $this->encode64($input, 6);
return $output;
}
public function crypt_private($password, $setting)
{
$output = '*0';
if (substr($setting, 0, 2) === $output) {
$output = '*1';
}
$id = substr($setting, 0, 3);
# We use "$P$", phpBB3 uses "$H$" for the same thing
if ($id !== '$P$' && $id !== '$H$') {
return $output;
}
$count_log2 = strpos($this->itoa64, $setting[3]);
if ($count_log2 < 7 || $count_log2 > 30) {
return $output;
}
$count = 1 << $count_log2;
$salt = substr($setting, 4, 8);
if (strlen($salt) !== 8) {
return $output;
}
# We were kind of forced to use MD5 here since it's the only
# cryptographic primitive that was available in all versions
# of PHP in use. To implement our own low-level crypto in PHP
# would have resulted in much worse performance and
# consequently in lower iteration counts and hashes that are
# quicker to crack (by non-PHP code).
$hash = md5($salt . $password, true);
do {
$hash = md5($hash . $password, true);
} while (--$count);
$output = substr($setting, 0, 12);
$output .= $this->encode64($hash, 16);
return $output;
}
public function gensalt_blowfish($input)
{
# This one needs to use a different order of characters and a
# different encoding scheme from the one in encode64() above.
# We care because the last character in our encoded string will
# only represent 2 bits. While two known implementations of
# bcrypt will happily accept and correct a salt string which
# has the 4 unused bits set to non-zero, we do not want to take
# chances and we also do not want to waste an additional byte
# of entropy.
$itoa64 = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$output = '$2a$';
$output .= chr(ord('0') + $this->iteration_count_log2 / 10);
$output .= chr(ord('0') + $this->iteration_count_log2 % 10);
$output .= '$';
$i = 0;
do {
$c1 = ord($input[$i++]);
$output .= $itoa64[$c1 >> 2];
$c1 = ($c1 & 0x03) << 4;
if ($i >= 16) {
$output .= $itoa64[$c1];
break;
}
$c2 = ord($input[$i++]);
$c1 |= $c2 >> 4;
$output .= $itoa64[$c1];
$c1 = ($c2 & 0x0f) << 2;
$c2 = ord($input[$i++]);
$c1 |= $c2 >> 6;
$output .= $itoa64[$c1];
$output .= $itoa64[$c2 & 0x3f];
} while (1);
return $output;
}
public function HashPassword($password)
{
$random = '';
if (CRYPT_BLOWFISH === 1 && !$this->portable_hashes) {
$random = $this->get_random_bytes(16);
$hash =
crypt($password, $this->gensalt_blowfish($random));
if (strlen($hash) === 60) {
return $hash;
}
}
if (strlen($random) < 6) {
$random = $this->get_random_bytes(6);
}
$hash =
$this->crypt_private(
$password,
$this->gensalt_private($random)
);
if (strlen($hash) === 34) {
return $hash;
}
# Returning '*' on error is safe here, but would _not_ be safe
# in a crypt(3)-like function used _both_ for generating new
# hashes and for validating passwords against existing hashes.
return '*';
}
public function CheckPassword($password, $stored_hash)
{
// IMPORTANT - PHP 5.2 may bomb out at the crypt call
$hash = $this->crypt_private($password, $stored_hash);
if ($hash[0] === '*') {
$hash = crypt($password, $stored_hash);
}
# This is not constant-time. In order to keep the code simple,
# for timing safety we currently rely on the salts being
# unpredictable, which they are at least in the non-fallback
# cases (that is, when we use /dev/urandom and bcrypt).
return $hash === $stored_hash;
}
}

View File

@@ -0,0 +1,160 @@
<?php
defined("DUPXABSPATH") or die("");
use Duplicator\Installer\Core\Params\PrmMng;
use Duplicator\Libs\Snap\SnapIO;
use Duplicator\Libs\Snap\SnapWP;
/**
* DUPX_cPanel
* Wrapper Class for cPanel API */
class DUPX_Server
{
/**
* A list of the core WordPress directories
*/
public static $wpCoreDirsList = array(
'wp-admin',
'wp-includes'
);
public static function phpSafeModeOn()
{
if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
// safe_mode has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0.
return false;
} else {
return filter_var(
ini_get('safe_mode'),
FILTER_VALIDATE_BOOLEAN,
array(
'options' => array(
'default' => false
)
)
);
}
}
/**
* Check given path prefixed with path array
*
* @param string $checkPath Path to check
* @param array $pathsArr check against
*
* @return boolean
*/
private static function isPathPrefixedWithArrayPath($checkPath, $pathsArr)
{
foreach ($pathsArr as $path) {
if (0 === strpos($checkPath, $path)) {
return true;
}
}
return false;
}
/**
* Can this server process in shell_exec mode
*
* @return bool
*/
public static function is_shell_exec_available()
{
if (array_intersect(array('shell_exec', 'escapeshellarg', 'escapeshellcmd', 'extension_loaded'), array_map('trim', explode(',', @ini_get('disable_functions'))))) {
return false;
}
//Suhosin: http://www.hardened-php.net/suhosin/
//Will cause PHP to silently fail.
if (extension_loaded('suhosin')) {
return false;
}
if (! function_exists('shell_exec')) {
return false;
}
// Can we issue a simple echo command?
if (!@shell_exec('echo duplicator')) {
return false;
}
return true;
}
/**
* 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 (self::is_shell_exec_available()) {
if (shell_exec('hash unzip 2>&1') == null) {
$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,782 @@
<?php
/**
* Class used to control values about the package meta data
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\ArchiveConfig
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Utils\Log\Log;
use Duplicator\Installer\Core\Params\PrmMng;
use Duplicator\Libs\Snap\SnapIO;
use Duplicator\Libs\Snap\SnapURL;
use Duplicator\Libs\Snap\SnapDB;
use Duplicator\Libs\Snap\SnapString;
use Duplicator\Libs\WpConfig\WPConfigTransformer;
/**
* singleton class
*/
class DUPX_ArchiveConfig
{
const NOTICE_ID_PARAM_EMPTY = 'param_empty_to_validate';
// READ-ONLY: COMPARE VALUES
public $dup_type;
public $created;
public $version_dup;
public $version_wp;
public $version_db;
public $version_php;
public $version_os;
public $packInfo;
public $fileInfo;
public $dbInfo;
public $wpInfo;
/** @var int<-1,max> */
public $defaultStorageId = -1;
/** @var string[] */
public $components = array();
// GENERAL
public $secure_on;
public $secure_pass;
public $installer_base_name = '';
public $installer_backup_name = '';
public $package_name;
public $package_hash;
public $package_notes;
public $wp_tableprefix;
public $blogname;
public $blogNameSafe;
public $exportOnlyDB;
//ADV OPTS
public $opts_delete;
//MULTISITE
public $mu_mode;
public $mu_generation;
/** @var mixed[] */
public $subsites = array();
public $main_site_id = 1;
public $mu_is_filtered;
public $mu_siteadmins = array();
//LICENSING
/** @var int<0, max> */
public $license_limit = 0;
/** @var int ENUM LICENSE TYPE */
public $license_type = 0;
//PARAMS
public $overwriteInstallerParams = array();
/** @var ?string */
public $dbhost = null;
/** @var ?string */
public $dbname = null;
/** @var ?string */
public $dbuser = null;
/** @var object */
public $brand = null;
/** @var ?string */
public $cpnl_host;
/** @var ?string */
public $cpnl_user;
/** @var ?string */
public $cpnl_pass;
/** @var ?string */
public $cpnl_enable;
/** @var self */
private static $instance = null;
/**
* Get instance
*
* @return self
*/
public static function getInstance()
{
if (is_null(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
/**
* Singleton class constructor
*/
protected function __construct()
{
$config_filepath = DUPX_Package::getPackageArchivePath();
if (!file_exists($config_filepath)) {
throw new Exception("Archive file $config_filepath doesn't exist");
}
if (($file_contents = file_get_contents($config_filepath)) === false) {
throw new Exception("Can\'t read Archive file $config_filepath");
}
if (($data = json_decode($file_contents)) === null) {
throw new Exception("Can\'t decode archive json");
}
foreach ($data as $key => $value) {
$this->{$key} = $value;
}
//Instance Updates:
$this->blogNameSafe = preg_replace("/[^A-Za-z0-9?!]/", '', $this->blogname);
}
/**
*
* @return bool
*/
public function isZipArchive()
{
$extension = strtolower(pathinfo($this->package_name, PATHINFO_EXTENSION));
return ($extension == 'zip');
}
/**
*
* @param string $define
*
* @return bool // return true if define value exists
*/
public function defineValueExists($define)
{
return isset($this->wpInfo->configs->defines->{$define});
}
public function getUsersLists()
{
$result = array();
foreach ($this->wpInfo->adminUsers as $user) {
$result[$user->ID] = $user->user_login;
}
return $result;
}
/**
*
* @param string $define
* @param array $default
*
* @return array
*/
public function getDefineArrayValue($define, $default = array(
'value' => false,
'inWpConfig' => false
))
{
$defines = $this->wpInfo->configs->defines;
if (isset($defines->{$define})) {
return (array) $defines->{$define};
} else {
return $default;
}
}
/**
* return define value from archive or default value if don't exists
*
* @param string $define
* @param mixed $default
*
* @return mixed
*/
public function getDefineValue($define, $default = false)
{
$defines = $this->wpInfo->configs->defines;
if (isset($defines->{$define})) {
return $defines->{$define}->value;
} else {
return $default;
}
}
/**
* return define value from archive or default value if don't exists in wp-config
*
* @param string $define
* @param mixed $default
*
* @return mixed
*/
public function getWpConfigDefineValue($define, $default = false)
{
$defines = $this->wpInfo->configs->defines;
if (isset($defines->{$define}) && $defines->{$define}->inWpConfig) {
return $defines->{$define}->value;
} else {
return $default;
}
}
public function inWpConfigDefine($define)
{
$defines = $this->wpInfo->configs->defines;
if (isset($defines->{$define})) {
return $defines->{$define}->inWpConfig;
} else {
return false;
}
}
/**
*
* @param string $key
*
* @return boolean
*/
public function realValueExists($key)
{
return isset($this->wpInfo->configs->realValues->{$key});
}
/**
* return read value from archive if exists of default if don't exists
*
* @param string $key
* @param mixed $default
*
* @return mixed
*/
public function getRealValue($key, $default = false)
{
$values = $this->wpInfo->configs->realValues;
if (isset($values->{$key})) {
return $values->{$key};
} else {
return $default;
}
}
/**
* in hours
*
* @return int
*/
public function getPackageLife()
{
$packageTime = strtotime($this->created);
$currentTime = strtotime('now');
return ceil(($currentTime - $packageTime) / 60 / 60);
}
/**
*
* @return int
*/
public function totalArchiveItemsCount()
{
return $this->fileInfo->dirCount + $this->fileInfo->fileCount;
}
public function setNewPathsAndUrlParamsByMainNew()
{
self::manageEmptyPathAndUrl(PrmMng::PARAM_PATH_WP_CORE_NEW, PrmMng::PARAM_SITE_URL);
self::manageEmptyPathAndUrl(PrmMng::PARAM_PATH_CONTENT_NEW, PrmMng::PARAM_URL_CONTENT_NEW);
self::manageEmptyPathAndUrl(PrmMng::PARAM_PATH_UPLOADS_NEW, PrmMng::PARAM_URL_UPLOADS_NEW);
self::manageEmptyPathAndUrl(PrmMng::PARAM_PATH_PLUGINS_NEW, PrmMng::PARAM_URL_PLUGINS_NEW);
self::manageEmptyPathAndUrl(PrmMng::PARAM_PATH_MUPLUGINS_NEW, PrmMng::PARAM_URL_MUPLUGINS_NEW);
$paramsManager = PrmMng::getInstance();
$noticeManager = DUPX_NOTICE_MANAGER::getInstance();
$noticeManager->addNextStepNotice(array(
'shortMsg' => '',
'level' => DUPX_NOTICE_ITEM::NOTICE,
'longMsg' => '<span class="green">If desired, you can change the default values in "Advanced install" &gt; "Other options"</span>.',
'longMsgMode' => DUPX_NOTICE_ITEM::MSG_MODE_HTML
), DUPX_NOTICE_MANAGER::ADD_UNIQUE_APPEND_IF_EXISTS, self::NOTICE_ID_PARAM_EMPTY);
$paramsManager->save();
$noticeManager->saveNotices();
}
protected static function manageEmptyPathAndUrl($pathKey, $urlKey)
{
$paramsManager = PrmMng::getInstance();
$validPath = (strlen($paramsManager->getValue($pathKey)) > 0);
$validUrl = (strlen($paramsManager->getValue($urlKey)) > 0);
if ($validPath && $validUrl) {
return true;
}
$paramsManager->setValue($pathKey, self::getDefaultPathUrlValueFromParamKey($pathKey));
$paramsManager->setValue($urlKey, self::getDefaultPathUrlValueFromParamKey($urlKey));
$noticeManager = DUPX_NOTICE_MANAGER::getInstance();
$msg = '<b>' . $paramsManager->getLabel($pathKey) . ' and/or ' . $paramsManager->getLabel($urlKey) . '</b> can\'t be generated automatically so they are set to their default value.' . "<br>\n";
$msg .= $paramsManager->getLabel($pathKey) . ': ' . $paramsManager->getValue($pathKey) . "<br>\n";
$msg .= $paramsManager->getLabel($urlKey) . ': ' . $paramsManager->getValue($urlKey) . "<br>\n";
$noticeManager->addNextStepNotice(array(
'shortMsg' => 'URLs and/or PATHs set automatically to their default value.',
'level' => DUPX_NOTICE_ITEM::NOTICE,
'longMsg' => $msg . "<br>\n",
'longMsgMode' => DUPX_NOTICE_ITEM::MSG_MODE_HTML
), DUPX_NOTICE_MANAGER::ADD_UNIQUE_APPEND, self::NOTICE_ID_PARAM_EMPTY);
}
public static function getDefaultPathUrlValueFromParamKey($paramKey)
{
$paramsManager = PrmMng::getInstance();
switch ($paramKey) {
case PrmMng::PARAM_SITE_URL:
return $paramsManager->getValue(PrmMng::PARAM_URL_NEW);
case PrmMng::PARAM_URL_CONTENT_NEW:
return $paramsManager->getValue(PrmMng::PARAM_URL_NEW) . '/wp-content';
case PrmMng::PARAM_URL_UPLOADS_NEW:
return $paramsManager->getValue(PrmMng::PARAM_URL_CONTENT_NEW) . '/uploads';
case PrmMng::PARAM_URL_PLUGINS_NEW:
return $paramsManager->getValue(PrmMng::PARAM_URL_CONTENT_NEW) . '/plugins';
case PrmMng::PARAM_URL_MUPLUGINS_NEW:
return $paramsManager->getValue(PrmMng::PARAM_URL_CONTENT_NEW) . '/mu-plugins';
case PrmMng::PARAM_PATH_WP_CORE_NEW:
return $paramsManager->getValue(PrmMng::PARAM_PATH_NEW);
case PrmMng::PARAM_PATH_CONTENT_NEW:
return $paramsManager->getValue(PrmMng::PARAM_PATH_NEW) . '/wp-content';
case PrmMng::PARAM_PATH_UPLOADS_NEW:
return $paramsManager->getValue(PrmMng::PARAM_PATH_CONTENT_NEW) . '/uploads';
case PrmMng::PARAM_PATH_PLUGINS_NEW:
return $paramsManager->getValue(PrmMng::PARAM_PATH_CONTENT_NEW) . '/plugins';
case PrmMng::PARAM_PATH_MUPLUGINS_NEW:
return $paramsManager->getValue(PrmMng::PARAM_PATH_CONTENT_NEW) . '/mu-plugins';
default:
throw new Exception('Invalid URL or PATH param');
}
}
/**
*
* @param string $oldMain
* @param string $newMain
* @param string $subOld
*
* @return boolean|string return false if cant generate new sub string
*/
public static function getNewSubString($oldMain, $newMain, $subOld)
{
if (($relativePath = SnapIO::getRelativePath($subOld, $oldMain)) === false) {
return false;
}
return $newMain . '/' . $relativePath;
}
/**
*
* @param string $oldMain
* @param string $newMain
* @param string $subOld
*
* @return boolean|string return false if cant generate new sub string
*/
public static function getNewSubUrl($oldMain, $newMain, $subOld)
{
$parsedOldMain = SnapURL::parseUrl($oldMain);
$parsedNewMain = SnapURL::parseUrl($newMain);
$parsedSubOld = SnapURL::parseUrl($subOld);
$parsedSubNew = $parsedSubOld;
$parsedSubNew['scheme'] = $parsedNewMain['scheme'];
$parsedSubNew['port'] = $parsedNewMain['port'];
if ($parsedOldMain['host'] !== $parsedSubOld['host']) {
return false;
}
$parsedSubNew['host'] = $parsedNewMain['host'];
if (($newPath = self::getNewSubString($parsedOldMain['path'], $parsedNewMain['path'], $parsedSubOld['path'])) === false) {
return false;
}
$parsedSubNew['path'] = $newPath;
return SnapURL::buildUrl($parsedSubNew);
}
/**
* Returns case insensitive duplicate tables from source site
*
* @return array<string[]>
*/
public function getDuplicateTableNames()
{
$tableList = (array) $this->dbInfo->tablesList;
$allTables = array_keys($tableList);
$duplicates = SnapString::getCaseInsesitiveDuplicates($allTables);
return $duplicates;
}
/**
* Returns list of redundant duplicates
*
* @return string[]
*/
public function getRedundantDuplicateTableNames()
{
$duplicateTables = $this->getDuplicateTableNames();
$prefix = DUPX_ArchiveConfig::getInstance()->wp_tableprefix;
$redundantTables = array();
foreach ($duplicateTables as $tables) {
$redundantTables = array_merge($redundantTables, SnapDB::getRedundantDuplicateTables($prefix, $tables));
}
return $redundantTables;
}
/**
*
* @return bool
*/
public function isTablesCaseSensitive()
{
return $this->dbInfo->isTablesUpperCase;
}
public function isTablePrefixChanged()
{
return $this->wp_tableprefix != PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_TABLE_PREFIX);
}
public function getTableWithNewPrefix($table)
{
$search = '/^' . preg_quote($this->wp_tableprefix, '/') . '(.*)/';
$replace = PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_TABLE_PREFIX) . '$1';
return preg_replace($search, $replace, $table, 1);
}
public function getOldUrlScheme()
{
static $oldScheme = null;
if (is_null($oldScheme)) {
$siteUrl = $this->getRealValue('siteUrl');
$oldScheme = parse_url($siteUrl, PHP_URL_SCHEME);
if ($oldScheme === false) {
$oldScheme = 'http';
}
}
return $oldScheme;
}
/**
* get relative path in archive of wordpress main paths
*
* @param string $pathKey (abs,home,plugins ...)
*
* @return string
*/
public function getRelativePathsInArchive($pathKey = null)
{
static $realtviePaths = null;
if (is_null($realtviePaths)) {
$realtviePaths = (array) $this->getRealValue('archivePaths');
foreach ($realtviePaths as $key => $path) {
$realtviePaths[$key] = SnapIO::getRelativePath($path, $this->wpInfo->targetRoot);
}
}
if (!empty($pathKey)) {
if (array_key_exists($pathKey, $realtviePaths)) {
return $realtviePaths[$pathKey];
} else {
return false;
}
} else {
return $realtviePaths;
}
}
/**
*
* @param string $path
* @param string|string[] $pathKeys
*
* @return boolean
*/
public function isChildOfArchivePath($path, $pathKeys = array())
{
if (is_scalar($pathKeys)) {
$pathKeys = array($pathKeys);
}
$mainPaths = $this->getRelativePathsInArchive();
foreach ($pathKeys as $key) {
if (!isset($mainPaths[$key])) {
continue;
}
if (strlen($mainPaths[$key]) == 0) {
return true;
}
if (strpos($path, $mainPaths[$key]) === 0) {
return true;
}
}
return false;
}
/**
*
* @staticvar string|bool $relativePath return false if PARAM_PATH_MUPLUGINS_NEW isn't a sub path of PARAM_PATH_NEW
* @return string
*/
public function getRelativeMuPlugins()
{
static $relativePath = null;
if (is_null($relativePath)) {
$relativePath = SnapIO::getRelativePath(
PrmMng::getInstance()->getValue(PrmMng::PARAM_PATH_MUPLUGINS_NEW),
PrmMng::getInstance()->getValue(PrmMng::PARAM_PATH_NEW)
);
}
return $relativePath;
}
/**
* return the mapping paths from relative path of archive zip and target folder
* if exist only one entry return the target folter string
*
* @param bool $reset // if true recalculater path mappintg
*
* @return string|array
*/
public function getPathsMapping($reset = false)
{
static $pathsMapping = null;
if (is_null($pathsMapping) || $reset) {
$paramsManager = PrmMng::getInstance();
$pathsMapping = array();
$targeRootPath = $this->wpInfo->targetRoot;
$paths = (array) $this->getRealValue('archivePaths');
foreach ($paths as $key => $path) {
if (($relativePath = SnapIO::getRelativePath($path, $targeRootPath)) !== false) {
$paths[$key] = $relativePath;
}
}
$pathsMapping[$paths['home']] = $paramsManager->getValue(PrmMng::PARAM_PATH_NEW);
if ($paths['home'] !== $paths['abs']) {
$pathsMapping[$paths['abs']] = $paramsManager->getValue(PrmMng::PARAM_PATH_WP_CORE_NEW);
}
$pathsMapping[$paths['wpcontent']] = $paramsManager->getValue(PrmMng::PARAM_PATH_CONTENT_NEW);
$pathsMapping[$paths['plugins']] = $paramsManager->getValue(PrmMng::PARAM_PATH_PLUGINS_NEW);
$pathsMapping[$paths['muplugins']] = $paramsManager->getValue(PrmMng::PARAM_PATH_MUPLUGINS_NEW);
switch (DUPX_InstallerState::getInstType()) {
case DUPX_InstallerState::INSTALL_SINGLE_SITE:
case DUPX_InstallerState::INSTALL_RBACKUP_SINGLE_SITE:
$pathsMapping[$paths['uploads']] = $paramsManager->getValue(PrmMng::PARAM_PATH_UPLOADS_NEW);
break;
case DUPX_InstallerState::INSTALL_SINGLE_SITE_ON_SUBDOMAIN:
case DUPX_InstallerState::INSTALL_SINGLE_SITE_ON_SUBFOLDER:
throw new Exception('Mode not avaiable');
case DUPX_InstallerState::INSTALL_NOT_SET:
throw new Exception('Cannot change setup with current installation type [' . DUPX_InstallerState::getInstType() . ']');
default:
throw new Exception('Unknown mode');
}
// remove all empty values for safe,
// This should never happen, but if it does, there is a risk that the installer will remove all the files in the server root.
$pathsMapping = array_filter($pathsMapping, function ($value) {
return strlen($value) > 0;
});
$pathsMapping = SnapIO::sortBySubfoldersCount($pathsMapping, true, false, true);
$unsetKeys = array();
foreach (array_reverse($pathsMapping) as $oldPathA => $newPathA) {
foreach ($pathsMapping as $oldPathB => $newPathB) {
if ($oldPathA == $oldPathB) {
continue;
}
if (
($relativePathOld = SnapIO::getRelativePath($oldPathA, $oldPathB)) === false ||
($relativePathNew = SnapIO::getRelativePath($newPathA, $newPathB)) === false
) {
continue;
}
if ($relativePathOld == $relativePathNew) {
$unsetKeys[] = $oldPathA;
break;
}
}
}
foreach (array_unique($unsetKeys) as $unsetKey) {
unset($pathsMapping[$unsetKey]);
}
$tempArray = $pathsMapping;
$pathsMapping = array();
foreach ($tempArray as $key => $val) {
$pathsMapping['/' . $key] = $val;
}
switch (count($pathsMapping)) {
case 0:
throw new Exception('Paths archive mapping is inconsistent');
break;
case 1:
$pathsMapping = reset($pathsMapping);
break;
default:
}
Log::info("--------------------------------------");
Log::info('PATHS MAPPING : ' . Log::v2str($pathsMapping));
Log::info("--------------------------------------");
}
return $pathsMapping;
}
/**
* get absolute target path from archive relative path
*
* @param string $pathInArchive
*
* @return string
*/
public function destFileFromArchiveName($pathInArchive)
{
$pathsMapping = $this->getPathsMapping();
if (is_string($pathsMapping)) {
return $pathsMapping . '/' . ltrim($pathInArchive, '\\/');
}
if (strlen($pathInArchive) === 0) {
$pathInArchive = '/';
} elseif ($pathInArchive[0] != '/') {
$pathInArchive = '/' . $pathInArchive;
}
foreach ($pathsMapping as $archiveMainPath => $newMainPath) {
if (($relative = SnapIO::getRelativePath($pathInArchive, $archiveMainPath)) !== false) {
return $newMainPath . '/' . $relative;
}
}
// if don't find corrispondance in mapping get the path new as default (this should never happen)
return PrmMng::getInstance()->getValue(PrmMng::PARAM_PATH_NEW) . '/' . ltrim($pathInArchive, '\\/');
}
/**
*
* @return string[]
*/
public function invalidCharsets()
{
return array_diff($this->dbInfo->charSetList, DUPX_DB_Functions::getInstance()->getCharsetsList());
}
/**
*
* @return string[]
*/
public function invalidCollations()
{
return array_diff($this->dbInfo->collationList, DUPX_DB_Functions::getInstance()->getCollationsList());
}
/**
*
* @return string[] list of MySQL engines in source site not supported by the current database
* @throws Exception
*/
public function invalidEngines()
{
return array_diff($this->dbInfo->engineList, DUPX_DB_Functions::getInstance()->getSupportedEngineList());
}
/**
*
* @param WPConfigTransformer $confTrans
* @param string $defineKey
* @param string $paramKey
*/
public static function updateWpConfigByParam(WPConfigTransformer $confTrans, $defineKey, $paramKey)
{
$paramsManager = PrmMng::getInstance();
$wpConfVal = $paramsManager->getValue($paramKey);
return self::updateWpConfigByValue($confTrans, $defineKey, $wpConfVal);
}
/**
*
* @param WPConfigTransformer $confTrans
* @param string $defineKey
* @param mixed $wpConfVal
*/
/**
* Update wp conf
*
* @param WPConfigTransformer $confTrans
* @param string $defineKey
* @param array $wpConfVal
* @param mixed $customValue if is not null custom value overwrite value
*
* @return void
*/
public static function updateWpConfigByValue(WPConfigTransformer $confTrans, $defineKey, $wpConfVal, $customValue = null)
{
if ($wpConfVal['inWpConfig']) {
$stringVal = '';
if ($customValue !== null) {
$stringVal = $customValue;
$updParam = array('raw' => true, 'normalize' => true);
} else {
switch (gettype($wpConfVal['value'])) {
case "boolean":
$stringVal = $wpConfVal['value'] ? 'true' : 'false';
$updParam = array('raw' => true, 'normalize' => true);
break;
case "integer":
case "double":
$stringVal = (string) $wpConfVal['value'];
$updParam = array('raw' => true, 'normalize' => true);
break;
case "string":
$stringVal = $wpConfVal['value'];
$updParam = array('raw' => false, 'normalize' => true);
break;
case "NULL":
$stringVal = 'null';
$updParam = array('raw' => true, 'normalize' => true);
break;
case "array":
case "object":
case "resource":
case "resource (closed)":
case "unknown type":
default:
$stringVal = '';
$updParam = array('raw' => true, 'normalize' => true);
break;
}
}
Log::info('WP CONFIG UPDATE ' . $defineKey . ' ' . Log::v2str($stringVal));
$confTrans->update('constant', $defineKey, $stringVal, $updParam);
} else {
if ($confTrans->exists('constant', $defineKey)) {
Log::info('WP CONFIG REMOVE ' . $defineKey);
$confTrans->remove('constant', $defineKey);
}
}
}
}

View File

@@ -0,0 +1,471 @@
<?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\ServerConfig
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Utils\Log\Log;
use Duplicator\Installer\Core\Params\PrmMng;
use Duplicator\Libs\Snap\SnapIO;
class DUPX_ServerConfig
{
const INSTALLER_HOST_ENTITY_PREFIX = 'installer_host_';
const CONFIG_ORIG_FILE_USERINI_ID = 'userini';
const CONFIG_ORIG_FILE_HTACCESS_ID = 'htaccess';
const CONFIG_ORIG_FILE_WPCONFIG_ID = 'wpconfig';
const CONFIG_ORIG_FILE_PHPINI_ID = 'phpini';
const CONFIG_ORIG_FILE_WEBCONFIG_ID = 'webconfig';
const CONFIG_ORIG_FILE_USERINI_ID_OVERWRITE_SITE = 'installer_host_userini';
const CONFIG_ORIG_FILE_HTACCESS_ID_OVERWRITE_SITE = 'installer_host_htaccess';
const CONFIG_ORIG_FILE_WPCONFIG_ID_OVERWRITE_SITE = 'installer_host_wpconfig';
const CONFIG_ORIG_FILE_PHPINI_ID_OVERWRITE_SITE = 'installer_host_phpini';
const CONFIG_ORIG_FILE_WEBCONFIG_ID_OVERWRITE_SITE = 'installer_host_webconfig';
/**
* Common timestamp of all members of this class
*
* @staticvar type $time
* @return type
*/
public static function getFixedTimestamp()
{
static $time = null;
if (is_null($time)) {
$time = date("ymdHis");
}
return $time;
}
/**
* Creates a copy of the original server config file and resets the original to blank
*
* @param string $rootPath The root path to the location of the server config files
*
* @return null
* @throws Exception
*/
public static function reset($rootPath)
{
$rootPath = SnapIO::trailingslashit($rootPath);
$paramsManager = PrmMng::getInstance();
Log::info("\n*** RESET CONFIG FILES IN CURRENT HOSTING >>> START");
switch ($paramsManager->getValue(PrmMng::PARAM_WP_CONFIG)) {
case 'modify':
case 'new':
if (self::runReset($rootPath . 'wp-config.php', self::CONFIG_ORIG_FILE_WPCONFIG_ID) === false) {
$paramsManager->setValue(PrmMng::PARAM_WP_CONFIG, 'nothing');
}
break;
case 'nothing':
break;
}
switch ($paramsManager->getValue(PrmMng::PARAM_HTACCESS_CONFIG)) {
case 'new':
case 'original':
if (self::runReset($rootPath . '.htaccess', self::CONFIG_ORIG_FILE_HTACCESS_ID) === false) {
$paramsManager->setValue(PrmMng::PARAM_HTACCESS_CONFIG, 'nothing');
}
break;
case 'nothing':
break;
}
switch ($paramsManager->getValue(PrmMng::PARAM_OTHER_CONFIG)) {
case 'new':
case 'original':
if (self::runReset($rootPath . 'web.config', self::CONFIG_ORIG_FILE_WEBCONFIG_ID) === false) {
$paramsManager->setValue(PrmMng::PARAM_OTHER_CONFIG, 'nothing');
}
if (self::runReset($rootPath . '.user.ini', self::CONFIG_ORIG_FILE_USERINI_ID) === false) {
$paramsManager->setValue(PrmMng::PARAM_OTHER_CONFIG, 'nothing');
}
if (self::runReset($rootPath . 'php.ini', self::CONFIG_ORIG_FILE_PHPINI_ID) === false) {
$paramsManager->setValue(PrmMng::PARAM_OTHER_CONFIG, 'nothing');
}
break;
case 'nothing':
break;
}
$paramsManager->save();
Log::info("\n*** RESET CONFIG FILES IN CURRENT HOSTING >>> END");
}
public static function setFiles($rootPath)
{
$paramsManager = PrmMng::getInstance();
$origFiles = DUPX_Orig_File_Manager::getInstance();
Log::info("SET CONFIG FILES");
$entryKey = self::CONFIG_ORIG_FILE_WPCONFIG_ID;
switch ($paramsManager->getValue(PrmMng::PARAM_WP_CONFIG)) {
case 'new':
if (SnapIO::copy(DUPX_Package::getWpconfigSamplePath(), DUPX_WPConfig::getWpConfigPath()) === false) {
DUPX_NOTICE_MANAGER::getInstance()->addFinalReportNotice(array(
'shortMsg' => 'Can\' reset wp-config to wp-config-sample',
'level' => DUPX_NOTICE_ITEM::CRITICAL,
'longMsgMode' => DUPX_NOTICE_ITEM::MSG_MODE_DEFAULT,
'longMsg' => 'Target file entry ' . Log::v2str(DUPX_WPConfig::getWpConfigPath()),
'sections' => 'general'
));
} else {
Log::info("Copy wp-config-sample.php to target:" . DUPX_WPConfig::getWpConfigPath());
}
break;
case 'modify':
if (SnapIO::copy($origFiles->getEntryStoredPath($entryKey), DUPX_WPConfig::getWpConfigPath()) === false) {
DUPX_NOTICE_MANAGER::getInstance()->addFinalReportNotice(array(
'shortMsg' => 'Can\' restore oirg file entry ' . $entryKey,
'level' => DUPX_NOTICE_ITEM::CRITICAL,
'longMsgMode' => DUPX_NOTICE_ITEM::MSG_MODE_DEFAULT,
'longMsg' => 'Target file entry ' . Log::v2str(DUPX_WPConfig::getWpConfigPath()),
'sections' => 'general'
));
} else {
Log::info("Retained original entry " . $entryKey . " target:" . DUPX_WPConfig::getWpConfigPath());
}
break;
case 'nothing':
break;
}
$entryKey = self::CONFIG_ORIG_FILE_HTACCESS_ID;
switch ($paramsManager->getValue(PrmMng::PARAM_HTACCESS_CONFIG)) {
case 'new':
$targetHtaccess = self::getHtaccessTargetPath();
if (SnapIO::touch($targetHtaccess) === false) {
DUPX_NOTICE_MANAGER::getInstance()->addFinalReportNotice(array(
'shortMsg' => 'Can\'t create new htaccess file',
'level' => DUPX_NOTICE_ITEM::CRITICAL,
'longMsgMode' => DUPX_NOTICE_ITEM::MSG_MODE_DEFAULT,
'longMsg' => 'Target file entry ' . $targetHtaccess,
'sections' => 'general'
));
} else {
Log::info("New htaccess file created:" . $targetHtaccess);
}
break;
case 'original':
if (($storedHtaccess = $origFiles->getEntryStoredPath($entryKey)) === false) {
Log::info("Retained original entry. htaccess doesn\'t exist in original site");
break;
}
$targetHtaccess = self::getHtaccessTargetPath();
if (SnapIO::copy($storedHtaccess, $targetHtaccess) === false) {
DUPX_NOTICE_MANAGER::getInstance()->addFinalReportNotice(array(
'shortMsg' => 'Can\' restore oirg file entry ' . $entryKey,
'level' => DUPX_NOTICE_ITEM::HARD_WARNING,
'longMsgMode' => DUPX_NOTICE_ITEM::MSG_MODE_DEFAULT,
'longMsg' => 'Target file entry ' . Log::v2str($targetHtaccess),
'sections' => 'general'
));
} else {
Log::info("Retained original entry " . $entryKey . " target:" . $targetHtaccess);
}
break;
case 'nothing':
break;
}
switch ($paramsManager->getValue(PrmMng::PARAM_OTHER_CONFIG)) {
case 'new':
if ($origFiles->getEntry(self::CONFIG_ORIG_FILE_WEBCONFIG_ID_OVERWRITE_SITE)) {
//IIS: This is reset because on some instances of IIS having old values cause issues
//Recommended fix for users who want it because errors are triggered is to have
//them check the box for ignoring the web.config files on step 1 of installer
$xml_contents = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
$xml_contents .= "<!-- Reset by Duplicator Installer. Original can be found in the original_files_ folder-->\n";
$xml_contents .= "<configuration></configuration>\n";
if (file_put_contents($rootPath . "/web.config", $xml_contents) === false) {
Log::info('RESET: can\'t create a new empty web.config');
}
}
break;
case 'original':
$entries = array(
self::CONFIG_ORIG_FILE_USERINI_ID,
self::CONFIG_ORIG_FILE_WEBCONFIG_ID,
self::CONFIG_ORIG_FILE_PHPINI_ID
);
foreach ($entries as $entryKey) {
if ($origFiles->getEntry($entryKey) !== false) {
if (SnapIO::copy($origFiles->getEntryStoredPath($entryKey), $origFiles->getEntryTargetPath($entryKey, false)) === false) {
DUPX_NOTICE_MANAGER::getInstance()->addFinalReportNotice(array(
'shortMsg' => 'Notice: Cannot restore original file entry ' . $entryKey,
'level' => DUPX_NOTICE_ITEM::HARD_WARNING,
'longMsgMode' => DUPX_NOTICE_ITEM::MSG_MODE_DEFAULT,
'longMsg' => 'Target file entry ' . Log::v2str($origFiles->getEntryTargetPath($entryKey, false)),
'sections' => 'general'
));
} else {
Log::info("Retained original entry " . $entryKey . " target:" . $origFiles->getEntryTargetPath($entryKey, false));
}
}
}
break;
case 'nothing':
break;
}
DUPX_NOTICE_MANAGER::getInstance()->saveNotices();
}
public static function getHtaccessTargetPath()
{
if (($targetEnty = DUPX_Orig_File_Manager::getInstance()->getEntryTargetPath(self::CONFIG_ORIG_FILE_HTACCESS_ID, false)) !== false) {
return $targetEnty;
} else {
return PrmMng::getInstance()->getValue(PrmMng::PARAM_PATH_NEW) . '/.htaccess';
}
}
/**
* Moves the configuration file to the dup_installer/original_files_[hash] folder
*
* @param string $filePath file path to store
* @param string $storedName if not false rename
*
* @return bool Returns true if the file was backed-up and reset or there was no file to reset
*/
private static function runReset($filePath, $storedName)
{
$fileName = basename($filePath);
try {
if (file_exists($filePath)) {
if (!SnapIO::chmod($filePath, 'u+rw') || !is_readable($filePath) || !is_writable($filePath)) {
throw new Exception("RESET CONFIG FILES: permissions error on file config path " . $filePath);
}
$origFiles = DUPX_Orig_File_Manager::getInstance();
$filePath = SnapIO::safePathUntrailingslashit($filePath);
Log::info("RESET CONFIG FILES: I'M GOING TO MOVE CONFIG FILE " . Log::v2str($fileName) . " IN ORIGINAL FOLDER");
if (
$origFiles->addEntry(
self::INSTALLER_HOST_ENTITY_PREFIX . $storedName,
$filePath,
DUPX_Orig_File_Manager::MODE_MOVE,
self::INSTALLER_HOST_ENTITY_PREFIX . $storedName
)
) {
Log::info("\tCONFIG FILE HAS BEEN RESET");
} else {
throw new Exception("cannot store file " . Log::v2str($fileName) . " in orginal file folder");
}
} else {
Log::info("RESET CONFIG FILES: " . Log::v2str($fileName) . " does not exist, no need for reset", Log::LV_DETAILED);
}
} catch (Exception $e) {
Log::logException($e, Log::LV_DEFAULT, 'RESET CONFIG FILES ERROR: ');
DUPX_NOTICE_MANAGER::getInstance()->addBothNextAndFinalReportNotice(array(
'shortMsg' => 'Can\'t reset config file ' . Log::v2str($fileName) . ' so it will not be modified.',
'level' => DUPX_NOTICE_ITEM::HARD_WARNING,
'longMsgMode' => DUPX_NOTICE_ITEM::MSG_MODE_DEFAULT,
'longMsg' => 'Message: ' . $e->getMessage(),
'sections' => 'general'
));
return false;
} catch (Error $e) {
Log::logException($e, Log::LV_DEFAULT, 'RESET CONFIG FILES ERROR: ');
DUPX_NOTICE_MANAGER::getInstance()->addBothNextAndFinalReportNotice(array(
'shortMsg' => 'Can\'t reset config file ' . Log::v2str($fileName) . ' so it will not be modified.',
'level' => DUPX_NOTICE_ITEM::HARD_WARNING,
'longMsgMode' => DUPX_NOTICE_ITEM::MSG_MODE_DEFAULT,
'longMsg' => 'Message: ' . $e->getMessage(),
'sections' => 'general'
));
return false;
}
return true;
}
/**
*
* @return boolean|string false if loca config don't exists or path of store local config
*/
public static function getWpConfigLocalStoredPath()
{
$origFiles = DUPX_Orig_File_Manager::getInstance();
$entry = self::CONFIG_ORIG_FILE_WPCONFIG_ID_OVERWRITE_SITE;
if ($origFiles->getEntry($entry)) {
return $origFiles->getEntryStoredPath($entry);
} else {
return false;
}
}
/**
* Get AddHandler line from existing WP .htaccess file
*
* @return string
* @throws Exception
*/
private static function getOldHtaccessAddhandlerLine()
{
$origFiles = DUPX_Orig_File_Manager::getInstance();
$backupHtaccessPath = $origFiles->getEntryStoredPath(self::CONFIG_ORIG_FILE_HTACCESS_ID_OVERWRITE_SITE);
Log::info("Installer Host Htaccess path: " . $backupHtaccessPath, Log::LV_DEBUG);
if ($backupHtaccessPath !== false && file_exists($backupHtaccessPath)) {
$htaccessContent = file_get_contents($backupHtaccessPath);
if (!empty($htaccessContent)) {
// match and trim non commented line "AddHandler application/x-httpd-XXXX .php" case insenstive
$re = '/^[\s\t]*[^#]?[\s\t]*(AddHandler[\s\t]+.+\.php[ \t]?.*?)[\s\t]*$/mi';
$matches = array();
if (preg_match($re, $htaccessContent, $matches)) {
return "\n" . $matches[1];
}
}
}
return '';
}
/**
* Sets up the web config file based on the inputs from the installer forms.
*
* @param int $mu_mode Is this site a specific multi-site mode
* @param object $dbh The database connection handle for this request
* @param string $path The path to the config file
*
* @return null
*/
public static function setup($dbh, $path)
{
Log::info("\nWEB SERVER CONFIGURATION FILE UPDATED:");
$paramsManager = PrmMng::getInstance();
$htAccessPath = "{$path}/.htaccess";
$mu_generation = DUPX_ArchiveConfig::getInstance()->mu_generation;
// SKIP HTACCESS
$skipHtaccessConfigVals = array('nothing', 'original');
if (in_array($paramsManager->getValue(PrmMng::PARAM_HTACCESS_CONFIG), $skipHtaccessConfigVals)) {
if (!DUPX_InstallerState::isRestoreBackup()) {
// on restore packup mode no warning needed
$longMsg = 'Retaining the original .htaccess file from the old site or not creating a new one may cause issues with the initial setup '
. 'of this site. If you encounter any issues, validate the contents of the .htaccess file or reinstall the site again using the '
. 'Step 1 Options Advanced Configuration Files Apache .htaccess Create New option. If your site works as expected this '
. 'message can be ignored.';
DUPX_NOTICE_MANAGER::getInstance()->addFinalReportNotice(array(
'shortMsg' => 'Notice: A new .htaccess file was not created',
'level' => DUPX_NOTICE_ITEM::NOTICE,
'longMsgMode' => DUPX_NOTICE_ITEM::MSG_MODE_DEFAULT,
'longMsg' => $longMsg,
'sections' => 'general'
));
}
return;
}
$timestamp = date("Y-m-d H:i:s");
$post_url_new = $paramsManager->getValue(PrmMng::PARAM_URL_NEW);
$newdata = parse_url($post_url_new);
$newpath = DUPX_U::addSlash(isset($newdata['path']) ? $newdata['path'] : "");
$update_msg = "# This file was updated by Duplicator on {$timestamp}.\n";
$update_msg .= "# See the original_files_ folder for the original source_site_htaccess file.";
$update_msg .= self::getOldHtaccessAddhandlerLine();
switch (DUPX_InstallerState::getInstType()) {
case DUPX_InstallerState::INSTALL_SINGLE_SITE:
case DUPX_InstallerState::INSTALL_RBACKUP_SINGLE_SITE:
$tmp_htaccess = self::htAcccessNoMultisite($update_msg, $newpath, $dbh);
Log::info("- Preparing .htaccess file with basic setup.");
break;
case DUPX_InstallerState::INSTALL_SINGLE_SITE_ON_SUBDOMAIN:
case DUPX_InstallerState::INSTALL_SINGLE_SITE_ON_SUBFOLDER:
case DUPX_InstallerState::INSTALL_NOT_SET:
throw new Exception('Cannot change setup with current installation type [' . DUPX_InstallerState::getInstType() . ']');
default:
throw new Exception('Unknown mode');
}
if (file_exists($htAccessPath) && SnapIO::chmod($htAccessPath, 'u+rw') === false) {
Log::info("WARNING: Unable to update htaccess file permessition.");
DUPX_NOTICE_MANAGER::getInstance()->addFinalReportNotice(array(
'shortMsg' => 'Notice: Unable to update new .htaccess file',
'level' => DUPX_NOTICE_ITEM::CRITICAL,
'longMsgMode' => DUPX_NOTICE_ITEM::MSG_MODE_DEFAULT,
'longMsg' => 'Unable to update the .htaccess file! Please check the permission on the root directory and make sure the .htaccess exists.',
'sections' => 'general'
));
} elseif (file_put_contents($htAccessPath, $tmp_htaccess) === false) {
Log::info("WARNING: Unable to update the .htaccess file! Please check the permission on the root directory and make sure the .htaccess exists.");
DUPX_NOTICE_MANAGER::getInstance()->addFinalReportNotice(array(
'shortMsg' => 'Noitice: Unable to update new .htaccess file',
'level' => DUPX_NOTICE_ITEM::CRITICAL,
'longMsgMode' => DUPX_NOTICE_ITEM::MSG_MODE_DEFAULT,
'longMsg' => 'Unable to update the .htaccess file! Please check the permission on the root directory and make sure the .htaccess exists.',
'sections' => 'general'
));
} else {
DUP_Extraction::setPermsFromParams($htAccessPath);
Log::info("HTACCESS FILE - Successfully updated the .htaccess file setting.");
}
}
private static function htAcccessNoMultisite($update_msg, $newpath, $dbh)
{
$result = '';
// no multisite
$empty_htaccess = false;
$optonsTable = mysqli_real_escape_string($dbh, DUPX_DB_Functions::getOptionsTableName());
$query_result = DUPX_DB::mysqli_query($dbh, "SELECT option_value FROM `" . $optonsTable . "` WHERE option_name = 'permalink_structure' ");
if ($query_result) {
$row = @mysqli_fetch_array($query_result);
if ($row != null) {
$permalink_structure = trim($row[0]);
$empty_htaccess = empty($permalink_structure);
}
}
if ($empty_htaccess) {
Log::info('NO PERMALINK STRUCTURE FOUND: set htaccess without directives');
$result = <<<EMPTYHTACCESS
{$update_msg}
# BEGIN WordPress
# The directives (lines) between `BEGIN WordPress` and `END WordPress` are
# dynamically generated, and should only be modified via WordPress filters.
# Any changes to the directives between these markers will be overwritten.
# END WordPress
EMPTYHTACCESS;
} else {
$result = <<<HTACCESS
{$update_msg}
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase {$newpath}
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . {$newpath}index.php [L]
</IfModule>
# END WordPress
HTACCESS;
}
return $result;
}
}

View File

@@ -0,0 +1,97 @@
<?php
/**
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX
*/
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 null|bool $present
* @return bool
*/
public static function isConfArkPresent()
{
static $present = null;
if (is_null($present)) {
$present = file_exists(DUPX_Package::getWpconfigArkPath());
}
return $present;
}
/**
*
* @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 shellExecUnzipEnable()
{
static $enable = null;
if (is_null($enable)) {
$enable = DUPX_Server::get_unzip_filepath() != null;
}
return $enable;
}
/**
*
* @return bool
*/
public static function classZipArchiveEnable()
{
return class_exists('ZipArchive');
}
/**
*
* @staticvar bool $exists
* @return bool
*/
public static function archiveExists()
{
static $exists = null;
if (is_null($exists)) {
$exists = file_exists(DUPX_Security::getInstance()->getArchivePath());
}
return $exists;
}
/**
*
* @staticvar bool $arcSize
* @return bool
*/
public static function archiveSize()
{
static $arcSize = null;
if (is_null($arcSize)) {
$archivePath = DUPX_Security::getInstance()->getArchivePath();
$arcSize = file_exists($archivePath) ? (int) @filesize($archivePath) : 0;
}
return $arcSize;
}
}

View File

@@ -0,0 +1,92 @@
<?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\Params\PrmMng;
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 = DUPX_Orig_File_Manager::getInstance()->getEntryTargetPath(DUPX_ServerConfig::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";
}
}
/**
*
* @staticvar boolean|WPConfigTransformer $confTransformer
*
* @return boolean|WPConfigTransformer
*/
public static function getLocalConfigTransformer()
{
static $confTransformer = null;
if (is_null($confTransformer)) {
try {
if (($wpConfigPath = DUPX_ServerConfig::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
* @param string $type // constant | variable
* @param mixed $default
*
* @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;
}
}
}

View File

@@ -0,0 +1,195 @@
<?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\Installer\Utils\InstallerLinkManager;
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 URL_SUBSCRIBE = 'https://duplicator.com/?lite_email_signup=1';
const MIN_NEW_PASSWORD_LEN = 6;
const BACKUP_RENAME_PREFIX = 'dp___bk_';
const UPSELL_DEFAULT_DISCOUNT = 50; // Default discount for upsell
/**
* Init method used to auto initialize the global params
* This function init all params before read from request
*
* @return null
*/
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;
//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'] = extension_loaded('suhosin') ? '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
$helpUrl = InstallerLinkManager::getDocUrl('how-to-handle-various-install-scenarios', 'install', 'additional help');
$additional_msg = ' for additional details ';
$additional_msg .= '<a href="' . $helpUrl . '" 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");
self::initErrDefines();
}
protected static function initErrDefines()
{
define('ERR_CONFIG_FOUND', 'A wp-config.php already exists in this location. ' .
'This error prevents users from accidentally overwriting a WordPress site or trying to install on top of an existing one. ' .
'When the archive file is extracted it can overwrite existing items if they have the same name. ' .
'If you have already manually extracted the installer then choose #1 other-wise consider these options: ' .
'<ol><li>Click &gt; Try Again &gt; Options &gt; choose "Manual Archive Extraction".</li>' .
'<li>Delete the wp-config.php file and try again.</li>' .
'<li>Empty the root directory except for the package and installer and try again.</li></ol>');
define('ERR_ZIPNOTFOUND', 'The packaged zip file was not found or has become unreadable. ' .
'Be sure the zip package is in the same directory as the installer file. ' .
'If you are trying to reinstall a package you can copy the package from the source site, ' .
' back up to your root which is the same location as your installer file.');
define('ERR_SHELLEXEC_ZIPOPEN', 'Failed to extract the archive using shell_exec unzip');
define(
'ERR_ZIPOPEN',
'Failed to open the zip archive file. Please be sure the archive is completely downloaded before running the installer. ' .
'Try to extract the archive manually to make sure the file is not corrupted.'
);
define(
'ERR_ZIPEXTRACTION',
'Errors extracting the zip file. Portions or part of the zip archive did not extract correctly.' .
' Try to extract the archive manually with a client side program like unzip/win-zip/winrar to make sure the file is not corrupted.' .
' If the file extracts correctly then there is an invalid file or directory that PHP is unable to extract.' .
'This can happen if you are moving from one operating system to another where certain naming ' .
'conventions work on one environment and not another. <br/><br/> Workarounds: <br/> 1. ' .
'Create a new package and be sure to exclude any directories that have name checks or files in them.' .
'This warning will be displayed on the scan results under "Name Checks". <br/> 2. Manually extract the zip file with a client side program.' .
'Then under options in step 1 of the installer select the "Manual Archive Extraction" option and perform the install.'
);
define(
'ERR_ZIPMANUAL',
'When choosing "Manual Archive Extraction", the contents of the package must already be extracted for the process to continue.' .
'Please manually extract the package into the current directory before continuing in manual extraction mode.'
);
define(
'ERR_MAKELOG',
'PHP is having issues writing to the log file <b>' . DUPX_INIT . '\dup-installer-log__[HASH].txt .</b>' .
'In order for the Duplicator to proceed to validate your owner/group and permission settings for PHP on this path. ' .
'Try temporarily setting you permissions to 777 to see if the issue gets resolved. ' .
'If you are on a shared hosting environment please contact your hosting company and tell ' .
'them you are getting errors writing files to the path above when using PHP.'
);
define(
'ERR_ZIPARCHIVE',
'In order to extract the archive.zip file, the PHP ZipArchive module must be installed.' .
'Please read the FAQ for more details. You can still install this package but you will need to select the ' .
'"Manual Archive Extraction" options found under Options. ' .
'Please read the online user guide for details in performing a manual archive extraction.'
);
define(
'ERR_MYSQLI_SUPPORT',
'In order to complete an install the mysqli extension for PHP is required.' .
'If you are on a hosted server please contact your host and request that mysqli be enabled.' .
' For more information visit: http://php.net/manual/en/mysqli.installation.php'
);
define(
'ERR_DBCONNECT',
'DATABASE CONNECTION FAILED!<br/>'
);
define(
'ERR_DBCONNECT_CREATE',
'DATABASE CREATION FAILURE!<br/> Unable to create database "%s". ' .
'Check to make sure the user has "Create" privileges. ' .
'Some hosts will restrict the creation of a database only through the cpanel. ' .
'Try creating the database manually to proceed with the installation. ' .
'If the database already exists select the action "Connect and Remove All Data" which will remove all existing tables.'
);
define('ERR_DROP_TABLE_TRYCLEAN', 'TABLE CLEAN FAILURE'
. 'Unable to remove TABLE "%s" from database "%s".<br/>'
. 'Please remove all tables from this database and try the installation again. '
. 'If no tables show in the database, then Drop the database and re-create it.<br/>'
. 'ERROR MESSAGE: %s');
define('ERR_DROP_PROCEDURE_TRYCLEAN', 'PROCEDURE CLEAN FAILURE. '
. 'Please remove all procedures from this database and try the installation again. '
. 'If no procedures show in the database, then Drop the database and re-create it.<br/>'
. 'ERROR MESSAGE: %s <br/><br/>');
define('ERR_DROP_FUNCTION_TRYCLEAN', 'FUNCTION CLEAN FAILURE. '
. 'Please remove all functions from this database and try the installation again. '
. 'If no functions show in the database, then Drop the database and re-create it.<br/>'
. 'ERROR MESSAGE: %s <br/><br/>');
define('ERR_DROP_VIEW_TRYCLEAN', 'VIEW CLEAN FAILURE. '
. 'Please remove all views from this database and try the installation again. '
. 'If no views show in the database, then Drop the database and re-create it.<br/>'
. 'ERROR MESSAGE: %s <br/><br/>');
define(
'ERR_DBCREATE',
'The database "%s" does not exist.<br/> Change the action to create in order ' .
'to "Create New Database" to create the database. ' .
'Some hosting providers do not allow database creation except through their control panels. ' .
' In this case, you will need to log in to your hosting providers control panel and create the database manually. ' .
'Please contact your hosting provider for further details on how to create the database.'
);
define(
'ERR_DBEMPTY',
'The database "%s" already exists and has "%s" tables. ' .
' When using the "Create New Database" action the database should not exist. ' .
' Select the action "Connect and Remove All Data" or "Connect and Backup Any Existing Data" ' .
'to remove or backup the existing tables or choose a database name that does not already exist. ' .
'Some hosting providers do not allow table removal or renaming from scripts. ' .
'In this case, you will need to log in to your hosting providers\' control panel and remove or rename the tables manually. ' .
' Please contact your hosting provider for further details. Always backup all your data before proceeding!'
);
define('ERR_CPNL_API', 'The cPanel API had the following issues when trying to communicate on this host: <br/> %s');
}
}

View File

@@ -0,0 +1,361 @@
<?php
/**
* Security class
*
* 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\Utils\Log\Log;
use Duplicator\Installer\Core\Bootstrap;
use Duplicator\Installer\Core\Params\PrmMng;
use Duplicator\Installer\Core\Params\Items\ParamItem;
use Duplicator\Libs\Snap\SnapIO;
use Duplicator\Libs\Snap\SnapUtil;
/**
* singleton class
*
* In this class all installer security checks are performed. If the security checks are not passed, an exception is thrown and the installer is stopped.
* This happens before anything else so the class must work without the initialization of all global duplicator variables.
*/
class DUPX_Security
{
const CTRL_TOKEN = 'ctrl_csrf_token';
const ROUTER_TOKEN = 'router_csrf_token';
const SECURITY_NONE = 'none';
const SECURITY_PASSWORD = 'pwd';
const SECURITY_ARCHIVE = 'archive';
/**
*
* @var self
*/
private static $instance = null;
/**
* archive path read from csrf file
*
* @var string
*/
private $archivePath = null;
/**
* installer name read from csrf file
*
* @var string
*/
private $bootloader = null;
/**
* installer url path read from csrf file
*
* @var string
*/
private $bootUrl = null;
/**
* boot log file full path read from csrf file
*
* @var string
*/
private $bootFilePath = null;
/**
* boot log file full path read from csrf file
*
* @var string
*/
private $bootLogFile = null;
/**
* package hash read from csrf file
*
* @var string
*/
private $packageHash = null;
/**
* public package hash read from csrf file
*
* @var string
*/
private $secondaryPackageHash = null;
/**
*
* @return self
*/
public static function getInstance()
{
if (is_null(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct()
{
DUPX_CSRF::init(DUPX_INIT, Bootstrap::getPackageHash());
if (!file_exists(DUPX_CSRF::getFilePath())) {
throw new Exception("CSRF FILE NOT FOUND\n"
. "Please, check webroot file permsission and dup-installer folder permission");
}
$this->bootloader = DUPX_CSRF::getVal('bootloader');
$this->bootUrl = DUPX_CSRF::getVal('booturl');
$this->bootLogFile = SnapIO::safePath(DUPX_CSRF::getVal('bootLogFile'));
$this->bootFilePath = SnapIO::safePath(DUPX_CSRF::getVal('installerOrigPath'));
$this->archivePath = SnapIO::safePath(DUPX_CSRF::getVal('archive'));
$this->packageHash = DUPX_CSRF::getVal('package_hash');
$this->secondaryPackageHash = DUPX_CSRF::getVal('secondaryHash');
}
/**
* archive path read from intaller.php passed by DUPX_CSFR
*
* @return string
*/
public function getArchivePath()
{
return $this->archivePath;
}
/**
* installer full path read from intaller.php passed by DUPX_CSFR
*
* @return string
*/
public function getBootFilePath()
{
return $this->bootFilePath;
}
/**
* boot log file full path read from intaller.php passed by DUPX_CSFR
*
* @return string
*/
public function getBootLogFile()
{
return $this->bootLogFile;
}
/**
* bootloader path read from intaller.php passed by DUPX_CSFR
*
* @return string
*/
public function getBootloader()
{
return $this->bootloader;
}
/**
* bootloader path read from intaller.php passed by DUPX_CSFR
*
* @return string
*/
public function getBootUrl()
{
return $this->bootUrl;
}
/**
* package hash read from intaller.php passed by DUPX_CSFR
*
* @return string
*/
public function getPackageHash()
{
return $this->packageHash;
}
/**
* package public hash read from intaller.php passed by DUPX_CSFR
*
* @return string
*/
public function getSecondaryPackageHash()
{
return $this->secondaryPackageHash;
}
/**
*
* @return boolean
* @throws Exception // if fail throw exception of return true
*/
public function check()
{
try {
// check if current package hash is equal at bootloader package hash
if ($this->packageHash !== Bootstrap::getPackageHash()) {
throw new Exception('Incorrect hash package');
}
// checks if the version of the package descriptor is consistent with the version of the files.
if (DUPX_ArchiveConfig::getInstance()->version_dup !== DUPX_VERSION) {
throw new Exception('The version of the archive is different from the version of the PHP scripts');
}
$token_tested = false;
// @todo connect with global debug
$debug = false;
$action = null;
if (DUPX_Ctrl_ajax::isAjax($action) == true) {
if (($token = self::getTokenFromInput(DUPX_Ctrl_ajax::TOKEN_NAME)) === false) {
$msg = 'Security issue' . ($debug ? ' LINE: ' . __LINE__ . ' TOKEN: ' . $token . ' KEY NAME: ' . DUPX_Ctrl_ajax::TOKEN_NAME : '');
throw new Exception($msg);
}
if (!DUPX_CSRF::check(self::getTokenFromInput(DUPX_Ctrl_ajax::TOKEN_NAME), DUPX_Ctrl_ajax::getTokenKeyByAction($action))) {
$msg = 'Security issue' . ($debug ? ' LINE: ' . __LINE__ . ' TOKEN: ' . $token . ' KEY NAME: ' . DUPX_Ctrl_ajax::getTokenKeyByAction($action) . ' KEY VALUE ' . DUPX_Ctrl_ajax::getTokenKeyByAction($action) : '');
throw new Exception($msg);
}
$token_tested = true;
} elseif (($token = self::getTokenFromInput(self::CTRL_TOKEN)) !== false) {
if (!isset($_REQUEST[PrmMng::PARAM_CTRL_ACTION])) {
$msg = 'Security issue' . ($debug ? ' LINE: ' . __LINE__ . ' TOKEN: ' . $token . ' KEY NAME: ' . PrmMng::PARAM_CTRL_ACTION : '');
throw new Exception($msg);
}
if (!DUPX_CSRF::check($token, $_REQUEST[PrmMng::PARAM_CTRL_ACTION])) {
$msg = 'Security issue' . ($debug ? ' LINE: ' . __LINE__ . ' TOKEN: ' . $token . ' KEY NAME: ' . PrmMng::PARAM_CTRL_ACTION . ' KEY VALUE ' . $_REQUEST[PrmMng::PARAM_CTRL_ACTION] : '');
throw new Exception($msg);
}
$token_tested = true;
}
if (($token = self::getTokenFromInput(self::ROUTER_TOKEN)) !== false) {
if (!isset($_REQUEST[PrmMng::PARAM_ROUTER_ACTION])) {
$msg = 'Security issue' . ($debug ? ' LINE: ' . __LINE__ . ' TOKEN: ' . $token . ' KEY NAME: ' . PrmMng::PARAM_ROUTER_ACTION : '');
throw new Exception($msg);
}
if (!DUPX_CSRF::check($token, $_REQUEST[PrmMng::PARAM_ROUTER_ACTION])) {
$msg = 'Security issue' . ($debug ? ' LINE: ' . __LINE__ . ' TOKEN: ' . $token . ' KEY NAME: ' . PrmMng::PARAM_ROUTER_ACTION . ' KEY VALUE ' . $_REQUEST[PrmMng::PARAM_ROUTER_ACTION] : '');
throw new Exception($msg);
}
$token_tested = true;
}
// At least one token must always and in any case be tested
if (!$token_tested) {
throw new Exception('Security Check Validation - No Token Found');
}
} catch (Exception $e) {
if (function_exists('error_clear_last')) {
/**
* comment error_clear_last if you want see te exception html on shutdown
*/
error_clear_last(); // phpcs:ignore PHPCompatibility.FunctionUse.NewFunctions.error_clear_lastFound
}
Log::logException($e, Log::LV_DEFAULT, 'SECURITY CHECK: ');
dupxTplRender('page-security-error', array(
'message' => $e->getMessage()
));
die();
}
return true;
}
/**
* get sanitized token frominput
*
* @param string $tokenName
*
* @return string
*/
protected static function getTokenFromInput($tokenName)
{
return SnapUtil::filterInputDefaultSanitizeString(SnapUtil::INPUT_REQUEST, $tokenName, false);
}
/**
* Get security tipe (NONE, PASSWORD, ARCHIVE)
*
* @return string enum type
*/
public function getSecurityType()
{
if (PrmMng::getInstance()->getValue(PrmMng::PARAM_SECURE_OK) == true) {
return self::SECURITY_NONE;
}
$archiveConfig = DUPX_ArchiveConfig::getInstance();
if ($archiveConfig->secure_on) {
return self::SECURITY_PASSWORD;
}
if (
DUPX_InstallerState::isOverwrite() &&
basename($this->bootFilePath) == 'installer.php' &&
!in_array($_SERVER['REMOTE_ADDR'], self::getSecurityAddrWhitelist())
) {
return self::SECURITY_ARCHIVE;
}
return self::SECURITY_NONE;
}
/**
* Get IPs white list for remote requests
*
* @return string[]
*/
private static function getSecurityAddrWhitelist()
{
// uncomment this to test security archive on localhost
// return array();
// -------
return array(
'127.0.0.1',
'::1'
);
}
/**
* return true if security check is passed
*
* @return bool
*/
public function securityCheck()
{
$paramsManager = PrmMng::getInstance();
$archiveConfig = DUPX_ArchiveConfig::getInstance();
$result = false;
switch ($this->getSecurityType()) {
case self::SECURITY_NONE:
$result = true;
break;
case self::SECURITY_PASSWORD:
$paramsManager->setValueFromInput(PrmMng::PARAM_SECURE_PASS);
$pass_hasher = new DUPX_PasswordHash(8, false);
$base64Pass = base64_encode($paramsManager->getValue(PrmMng::PARAM_SECURE_PASS));
$result = $pass_hasher->CheckPassword($base64Pass, $archiveConfig->secure_pass);
break;
case self::SECURITY_ARCHIVE:
$paramsManager->setValueFromInput(PrmMng::PARAM_SECURE_ARCHIVE_HASH);
$result = (strcmp(basename($this->archivePath), $paramsManager->getValue(PrmMng::PARAM_SECURE_ARCHIVE_HASH)) == 0);
break;
default:
throw new Exception('Security type not valid ' . $this->getSecurityType());
break;
}
$paramsManager->setValue(PrmMng::PARAM_SECURE_OK, $result);
$paramsManager->save();
return $result;
}
}

View File

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

View File

@@ -0,0 +1,797 @@
<?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\Core\Params\Descriptors\ParamDescDatabase;
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
{
/**
*
* @var self
*/
protected static $instance = null;
/** @var \mysqli connection */
private $dbh = null;
/** @var float */
protected $timeStart = 0;
/**
* current data connection
*
* @var array connection
*/
private $dataConnection = null;
/**
* list of supported engine types
*
* @var array
*/
private $engineData = null;
/**
* supported charset and collation data
*
* @var array
*/
private $charsetData = null;
/**
* default charset in dwtabase connection
*
* @var string
*/
private $defaultCharset = null;
/** @var int */
private $rename_tbl_log = 0;
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|null $customConnection
*
* @return mysqli|null
*/
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
* @param string $dbuser
* @param string $dbpass
* @param string $dbname
*
* @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") &&
// phpcs:ignore PHPCompatibility.Constants.NewConstants.mysqli_client_ssl_dont_verify_server_certFound
($dbh = DUPX_DB::connect($dbhost, $dbuser, $dbpass, $dbname, MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT)) != false
) {
// phpcs:ignore PHPCompatibility.Constants.NewConstants.mysqli_client_ssl_dont_verify_server_certFound
$dbflag = MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT;
$wpConfigFalgsVal['inWpConfig'] = true;
// phpcs:ignore PHPCompatibility.Constants.NewConstants.mysqli_client_ssl_dont_verify_server_certFound
$wpConfigFalgsVal['value'] = array(MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT);
} 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
*/
public function closeDbConnection()
{
if (!is_null($this->dbh)) {
mysqli_close($this->dbh);
$this->dbh = null;
$this->dataConnection = null;
$this->charsetData = null;
$this->defaultCharset = null;
}
}
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
*
* @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;
}
/**
* @return array list of supported MySQL engine data\
*/
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 array list of supported MySQL engine names
*/
public function getSupportedEngineList()
{
return array_map(function ($engine) {
return $engine["name"];
}, $this->getEngineData());
}
/**
* @return string the default MySQL engine of the database
*/
public function getDefaultEngine()
{
foreach ($this->engineData as $engine) {
if ($engine["isDefault"]) {
return $engine["name"];
}
}
return $this->engineData[0]["name"];
}
/**
*
* @return array
*/
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);
}
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());
}
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;
}
/**
*
* @param null|string $prefix
*
* @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
*
* @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
*
* @return string
*/
public static function getUserTableName($prefix = null)
{
if (is_null($prefix)) {
$prefix = PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_TABLE_PREFIX);
}
return $prefix . 'users';
}
/**
*
* @param null|string $prefix
*
* @return string
*/
public static function getUserMetaTableName($prefix = null)
{
if (is_null($prefix)) {
$prefix = PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_TABLE_PREFIX);
}
return $prefix . 'usermeta';
}
/**
*
* @param null|string $prefix
*
* @return string
*/
public static function getPackagesTableName($prefix = null)
{
if (is_null($prefix)) {
$prefix = PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_TABLE_PREFIX);
}
return $prefix . 'duplicator_packages';
}
/**
*
* @param string $userLogin
*
* @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);
}
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|array $tables
*/
public function tablesExist($tables)
{
$this->dbConnection();
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
* @param string $pattern regex search string
* @param string $replacement regex replace string
*
* @return array [
* [
* 'old' => string
* 'new' => string
* ]
* ]
*/
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($nSuffix, 10, 36);
$newName = substr($newName, 0, -strlen($suffix)) . $suffix;
$nSuffix++;
}
$newNames[$index] = $newName;
$result[] = array(
'old' => $oldName,
'new' => $newName
);
}
return $result;
}
/**
*
* @param type $newPrefix
* @param type $options
*/
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']) . '"';
}
if (($tablesList = DUPX_DB::queryColumnToArray($this->dbh, 'SHOW TABLES FROM `' . $escapedDbName . '`' . $where)) === false) {
Log::error('SQL ERROR:' . mysqli_error($this->dbh));
}
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 string $tableNamePatten
*
* @return array
*/
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 string $tableNamePatten
*
* @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;
}
public function copyTable($existing_name, $new_name, $delete_if_conflict = false)
{
$this->dbConnection();
return DUPX_DB::copyTable($this->dbh, $existing_name, $new_name, $delete_if_conflict);
}
public function renameTable($existing_name, $new_name, $delete_if_conflict = false)
{
$this->dbConnection();
return DUPX_DB::renameTable($this->dbh, $existing_name, $new_name, $delete_if_conflict);
}
public function dropTable($name)
{
$this->dbConnection();
return DUPX_DB::dropTable($this->dbh, $name);
}
/**
*
* @param string $prefix
*
* @return boolean
*/
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[] = $row;
}
return $result;
}
/**
* Returns the Duplicator version if it exists, otherwise false
*
* @param $prefix
*
* @return false|string Duplicator version
*/
public function getDuplicatorVersion($prefix)
{
$optionsTable = self::getOptionsTableName($prefix);
$sql = "SELECT `option_value` FROM `{$optionsTable}` WHERE `option_name` = 'duplicator_version_plugin'";
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_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
* @param null|string $prefix
*
* @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,696 @@
<?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, false);
}
}
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/
*
* @param string $host The DB_HOST setting to parse
*
* @return array|bool 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
*/
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
*/
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 array 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 Supported collation
*/
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 array 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 array 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 obj|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);
}
/**
* Select database if exists
*
* @param mysqli|obj $dbh
* @param string $dbname
*
* @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 array A list of all table names
*/
public static function getTables($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 string 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 obj $dbh A valid database link handle
* @param string $sql The sql to run
*
* @return array 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 array 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 null
*/
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 . '`');
}
/**
* 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 string $delete_if_conflict Delete the table name if there is a conflict
*
* @return null
*/
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 string $delete_if_conflict Delete the table name if there is a conflict
*
* @return null
*/
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
*/
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
* @param string $sql
* @param int $logFailLevel // Write in the log only if the log level is equal to or greater than level
*
* @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;
}
/**
*
* @param mysqli_result|bool $result
*/
public static function query_log_callback(\mysqli $link, $result, $query, $logFailLevel = Log::LV_DEFAULT)
{
if ($result === false) {
if (Log::isLevel($logFailLevel)) {
$callers = debug_backtrace();
$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();
$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,273 @@
<?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\Params\Descriptors\ParamDescUsers;
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
{
protected $originalName = '';
protected $tableWithoutPrefix = '';
protected $rows = 0;
protected $size = 0;
protected $havePrefix = false;
protected $subsiteId = -1;
protected $subsitePrefix = '';
/**
*
* @param string $name
* @param int $rows
* @param int $size
*/
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;
}
$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.
*
* @return string
*/
public function getNameWithoutPrefix($includeSubsiteId = false)
{
return (($includeSubsiteId && $this->subsiteId > 1) ? $this->subsiteId . '_' : '') . $this->tableWithoutPrefix;
}
/**
*
* @param array $diffData
*
* @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 (DUPX_InstallerState::getInstType()) {
case DUPX_InstallerState::INSTALL_SINGLE_SITE:
case DUPX_InstallerState::INSTALL_RBACKUP_SINGLE_SITE:
return $paramsManager->getValue(PrmMng::PARAM_DB_TABLE_PREFIX) . $this->getNameWithoutPrefix(true);
case DUPX_InstallerState::INSTALL_SINGLE_SITE_ON_SUBDOMAIN:
case DUPX_InstallerState::INSTALL_SINGLE_SITE_ON_SUBFOLDER:
throw new Exception('Mode not avaiable');
case DUPX_InstallerState::INSTALL_NOT_SET:
throw new Exception('Cannot change setup with current installation type [' . DUPX_InstallerState::getInstType() . ']');
default:
throw new Exception('Unknown mode');
}
}
/**
*
* @return int
*/
public function getRows()
{
return $this->rows;
}
/**
*
* @param type $formatted
*
* @return int|string
*/
public function getSize($formatted = false)
{
return $formatted ? DUPX_U::readableByteSize($this->size) : $this->size;
}
/**
*
* @return int // if -1 isn't a subsite sable
*/
public function getSubsisteId()
{
return $this->subsiteId;
}
/**
*
* @return boolean
*/
public function canBeExctracted()
{
return true;
}
/**
* If false the current table create query is skipped
*
* @return boolran
*/
public function createTable()
{
if ($this->usersTablesCreateCheck() === false) {
return false;
}
return true;
}
/**
* Check if create users table
*
* @return boolran
*/
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('users', 'usermeta')));
}
/**
* 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,329 @@
<?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;
}
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;
}
/**
* 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;
}
/**
* 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;
}
/**
*
* @param type $table
*
* @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];
}
/**
*
* @return array
*/
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();
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
*/
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,250 @@
<?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\Params\PrmMng;
use Duplicator\Installer\Core\Params\Items\ParamForm;
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();
/**
* active custom hosting in current server
*
* @var string[]
*/
private $activeHostings = 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()) {
$this->activeHostings[] = $cHost->getIdentifier();
$cHost->init();
}
}
$this->initialized = true;
return true;
}
/**
* return the lisst of current custom active hostings
*
* @return DUPX_Host_interface[]
*/
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
*
* @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 type $identifier
*
* @return boolean|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
*
* @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, DUPX_Plugins_Manager::getInstance()->getDropInsPaths())) {
return true;
} else {
return false;
}
}
/**
*
* @return bool
* @throws Exception
*/
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);
$paramsManager->setValue(PrmMng::PARAM_DB_ACTION, 'empty');
if (DUPX_InstallerState::getInstance()->getMode() === DUPX_InstallerState::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_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,72 @@
<?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
*/
public function setCustomParams()
{
$paramsManager = PrmMng::getInstance();
$paramsManager->setValue(PrmMng::PARAM_ARCHIVE_ENGINE_SKIP_WP_FILES, DUP_Extraction::FILTER_SKIP_WP_CORE);
}
}

View File

@@ -0,0 +1,73 @@
<?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
*/
public function setCustomParams()
{
PrmMng::getInstance()->setValue(PrmMng::PARAM_IGNORE_PLUGINS, array(
'gd-system-plugin.php',
'object-cache.php'
));
}
}

View File

@@ -0,0 +1,71 @@
<?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
*/
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,70 @@
<?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
*/
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/
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
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
*/
public function setCustomParams()
{
}
}

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\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
*/
public function setCustomParams()
{
$paramsManager = PrmMng::getInstance();
$paramsManager->setValue(PrmMng::PARAM_ARCHIVE_ENGINE_SKIP_WP_FILES, DUP_Extraction::FILTER_SKIP_WP_CORE);
$paramsManager->setValue(PrmMng::PARAM_USERS_MODE, ParamDescUsers::USER_MODE_IMPORT_USERS);
}
}

View File

@@ -0,0 +1,157 @@
<?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;
/**
* 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()
{
// check only mu plugin file exists
$file = PrmMng::getInstance()->getValue(PrmMng::PARAM_PATH_MUPLUGINS_NEW) . '/wpengine-security-auditor.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 'WP Engine';
}
/**
* this function is called if current hosting is this
*/
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,50 @@
<?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
*/
public function setCustomParams();
}

View File

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

View File

@@ -0,0 +1,91 @@
<?php
/**
* plugin custom actions
*
* 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_Plugin_custom_actions
{
const BY_DEFAULT_AUTO = 'auto';
const BY_DEFAULT_DISABLED = 'disabled';
const BY_DEFAULT_ENABLED = 'enabled';
/** @var string */
protected $slug = null;
/** @var bool|callable */
protected $byDefaultStatus = self::BY_DEFAULT_AUTO;
/** @var bool|callable */
protected $enableAfterLogin = false;
/** @var string */
protected $byDefaultMessage = '';
/**
* Class constructor
*
* @param string $slug plugin slug
* @param string|callable $byDefaultStatus set plugin status
* @param bool|callable $enableAfterLogin enable plugin after login
* @param string|callable $byDefaultMessage message if status change
*/
public function __construct(
$slug,
$byDefaultStatus = self::BY_DEFAULT_AUTO,
$enableAfterLogin = false,
$byDefaultMessage = ''
) {
$this->slug = $slug;
$this->byDefaultStatus = $byDefaultStatus;
$this->enableAfterLogin = $enableAfterLogin;
$this->byDefaultMessage = $byDefaultMessage;
}
/**
* Return by defualt status
*
* @return string by default enum
*/
public function byDefaultStatus()
{
if (is_callable($this->byDefaultStatus)) {
return call_user_func($this->byDefaultStatus, $this);
} else {
return $this->byDefaultStatus;
}
}
/**
* return true if plugin must be enabled after login
*
* @return boolean
*/
public function isEnableAfterLogin()
{
if (is_callable($this->enableAfterLogin)) {
return call_user_func($this->enableAfterLogin, $this);
} else {
return $this->enableAfterLogin;
}
}
/**
* By default message
*
* @return string
*/
public function byDefaultMessage()
{
if (is_callable($this->byDefaultMessage)) {
return call_user_func($this->byDefaultMessage, $this);
} else {
return $this->byDefaultMessage;
}
}
}

View File

@@ -0,0 +1,561 @@
<?php
/**
* plugin 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\Utils\Log\Log;
use Duplicator\Installer\Core\Params\PrmMng;
use Duplicator\Libs\Snap\SnapUtil;
/**
* Plugin Item
*/
class DUPX_Plugin_item
{
const STATUS_ACTIVE = 'active';
const STATUS_INACTIVE = 'inactive';
const STATUS_NETWORK_ACTIVE = 'network-active';
const STATUS_DROP_INS = 'drop-ins';
const STATUS_MUST_USE = 'must-use';
/**
*
* @var string
*/
private $data = array(
'slug' => null,
'name' => '',
'version' => '',
'pluginURI' => '',
'author' => '',
'authorURI' => '',
'description' => '',
'title' => '',
'networkActive' => false,
'active' => false,
'mustUse' => false,
'dropIns' => false,
'deactivateAction' => false,
'deactivateMessage' => null,
'activateAction' => false
);
/**
*
* @param array $data
*
* @throws Exception
*/
public function __construct($data)
{
if (!is_array($data) || !isset($data['slug'])) {
throw new Exception('invalud input data');
}
$this->data = array_merge($this->data, $data);
if (empty($this->data['name'])) {
$this->data['name'] = $this->data['slug'];
}
if (empty($this->data['title'])) {
$this->data['title'] = $this->data['name'];
}
}
/**
*
* @param int $subsite // if -1 it checks that at least one site exists in which it is active in the netowrk
*
* @return boolean
*/
public function isActive($subsite = -1)
{
if ($this->data['active'] === true) {
return true;
} elseif ($subsite === -1 && !empty($this->data['active'])) {
return true;
} elseif ($this->data['active'] === true || (is_array($this->data['active']) && in_array($subsite, $this->data['active']))) {
return true;
} else {
return false;
}
}
/**
*
* @return boolean
*/
public function isNetworkActive()
{
return $this->data['networkActive'];
}
/**
*
* @return boolean
*/
public function isMustUse()
{
return $this->data['mustUse'];
}
/**
*
* @return boolean
*/
public function isDropIns()
{
return $this->data['dropIns'];
}
/**
* is true if all active status are false
*
* @param int $subsite // if -1 it checks that at least one site exists in which it is active in the netowrk
*
* @return boolean
*/
public function isInactive($subsite = -1)
{
return !$this->isActive($subsite) && !$this->isNetworkActive() && !$this->isMustUse() && !$this->isDropIns();
}
/**
* return true if isn't networkActive or must-use or drop-ins
*
* @return boolean
*/
public function isNetworkInactive()
{
return !$this->isNetworkActive() && !$this->isMustUse() && !$this->isDropIns();
}
public function isIgnore()
{
return in_array($this->data['slug'], PrmMng::getInstance()->getValue(PrmMng::PARAM_IGNORE_PLUGINS));
}
public function isForceDisabled()
{
return in_array($this->data['slug'], PrmMng::getInstance()->getValue(PrmMng::PARAM_FORCE_DIABLE_PLUGINS));
}
/**
* set activate action true if the plugin is active or if deactivateAction is enabled
*
* @return bool // return activateAction
*/
/**
* set activate action true if the plugin is active or if deactivateAction is enabled
*
* @param int $subsite // current subsite id
* @param bool $networkCheck // if true check only on network or check by subsite id
* @param bool $forceActivation // if true skip all pluginstati check and set activation action
*
* @return bool // return activateAction
*/
public function setActivationAction($subsite = -1, $networkCheck = false, $forceActivation = false)
{
if ($this->isIgnore()) {
return true;
}
if ($forceActivation) {
Log::info('PLUGINS [' . __FUNCTION__ . ']: set forced activation action ' . Log::v2str($this->slug), Log::LV_DEBUG);
return ($this->data['activateAction'] = true);
}
$activate = false;
if ($networkCheck) {
if ($this->isNetworkInactive()) {
$activate = true;
}
} else {
if ($this->isInactive($subsite) || ($subsite > -1 && $this->isNetworkActive())) {
$activate = true;
}
}
if ($activate || $this->data['deactivateAction']) {
Log::info('PLUGINS [' . __FUNCTION__ . ']: set activation action ' . Log::v2str($this->slug), Log::LV_DEBUG);
$this->data['activateAction'] = true;
}
return $this->data['activateAction'];
}
/**
* set deactivation action if the plugin isn't inactive
*
* @param string $shortMsg
* @param string $longMsg
* @param boolean $networkCheck // if true check if is active only on network
*
* @return boolean // return deactivaeAction status
*/
public function setDeactivateAction($subsite = -1, $shortMsg = null, $longMsg = null, $networkCheck = false)
{
if ($this->isIgnore()) {
return true;
}
$deactivate = false;
if ($networkCheck) {
if (!$this->isNetworkInactive()) {
$deactivate = true;
}
} else {
if (!$this->isInactive($subsite)) {
$deactivate = true;
}
}
if ($deactivate) {
Log::info('PLUGINS [' . __FUNCTION__ . ']: set deactivate action ' . Log::v2str($this->slug), Log::LV_DEBUG);
$this->data['deactivateAction'] = true;
if (!empty($shortMsg)) {
$this->data['deactivateMessage'] = array(
'shortMsg' => $shortMsg,
'longMsg' => $longMsg
);
}
}
return $this->data['deactivateAction'];
}
public function getPluginArchivePath()
{
$archiveConfig = DUPX_ArchiveConfig::getInstance();
if ($this->isMustUse()) {
$mainDir = $archiveConfig->getRelativePathsInArchive('muplugins');
} elseif ($this->isDropIns()) {
$mainDir = $archiveConfig->getRelativePathsInArchive('wpcontent');
} else {
$mainDir = $archiveConfig->getRelativePathsInArchive('plugins');
}
return $mainDir . '/' . $this->slug;
}
public function getPluginPath()
{
$paramManager = PrmMng::getInstance();
$mainDir = false;
if ($this->isMustUse()) {
$mainDir = $paramManager->getValue(PrmMng::PARAM_PATH_MUPLUGINS_NEW);
} elseif ($this->isDropIns()) {
$mainDir = $paramManager->getValue(PrmMng::PARAM_PATH_CONTENT_NEW);
} else {
$mainDir = $paramManager->getValue(PrmMng::PARAM_PATH_PLUGINS_NEW);
}
if ($mainDir === false) {
return false;
}
$dirNameRelative = dirname($this->slug);
$relativePath = false;
if (empty($dirNameRelative) || $dirNameRelative == '.') {
$relativePath = $this->slug;
} else {
$relativePath = $dirNameRelative;
}
$result = $mainDir . '/' . $relativePath;
if (!file_exists($result)) {
return false;
} else {
return $result;
}
}
/**
* @return mixed
*/
public function deactivate()
{
if (!$this->deactivateAction) {
return false;
}
Log::info('[PLUGINS MANAGER] deactivate ' . Log::v2str($this->slug), Log::LV_DETAILED);
$deactivated = false;
$origFileManager = DUPX_Orig_File_Manager::getInstance();
if ($this->isMustUse() || $this->isDropIns()) {
if (($pluginPath = $this->getPluginPath()) == false) {
Log::info('PLUGINS: can\'t remove plugin ' . $this->slug . ' because it doesn\'t exists');
} else {
$origFileManager->addEntry($this->slug, $pluginPath, DUPX_Orig_File_Manager::MODE_MOVE);
$deactivated = true;
}
} else {
// for other type of plugins do nothing. They are not activated because they are missing in the table list of plugins
$deactivated = true;
}
if ($deactivated) {
if (is_null($this->data['deactivateMessage'])) {
DUPX_NOTICE_MANAGER::getInstance()->addFinalReportNotice(array(
'shortMsg' => $this->name . ' has been deactivated',
'level' => DUPX_NOTICE_ITEM::NOTICE,
'sections' => 'plugins'
));
} else {
DUPX_NOTICE_MANAGER::getInstance()->addFinalReportNotice(array(
'shortMsg' => $this->data['deactivateMessage']['shortMsg'],
'level' => DUPX_NOTICE_ITEM::SOFT_WARNING,
'longMsg' => $this->data['deactivateMessage']['longMsg'],
'longMsgMode' => DUPX_NOTICE_ITEM::MSG_MODE_HTML,
'sections' => 'plugins'
));
}
} else {
DUPX_NOTICE_MANAGER::getInstance()->addFinalReportNotice(array(
'shortMsg' => 'Can\'t deactivate the plugin ' . $this->name,
'level' => DUPX_NOTICE_ITEM::SOFT_WARNING,
'longMsg' => 'Folder of the plugin not found',
'sections' => 'plugins'
));
}
// prevent multiple decativation action
$this->deactivateAction = false;
return true;
}
/**
*
* @param int $subsiteId
*
* @return string
*/
public function getOrgiStatus($subsiteId)
{
if ($this->isMustUse()) {
return self::STATUS_MUST_USE;
} elseif ($this->isDropIns()) {
return self::STATUS_DROP_INS;
} elseif ($this->isNetworkActive()) {
return self::STATUS_NETWORK_ACTIVE;
} elseif ($this->isActive($subsiteId)) {
return self::STATUS_ACTIVE;
} else {
return self::STATUS_INACTIVE;
}
}
/**
*
* @param string $status
*
* @return string
*/
public static function getStatusLabel($status)
{
switch ($status) {
case self::STATUS_MUST_USE:
return 'must-use';
case self::STATUS_DROP_INS:
return 'drop-in';
case self::STATUS_NETWORK_ACTIVE:
return 'network active';
case self::STATUS_ACTIVE:
return 'active';
case self::STATUS_INACTIVE:
return 'inactive';
default:
throw new Exception('Invalid status');
}
}
/**
* Uninstall a single plugin.
*
* Calls the uninstall hook, if it is available.
*
* @param string $plugin Path to the main plugin file from plugins directory.
*
* @return true True if a plugin's uninstall.php file has been found and included.
*/
public function uninstall()
{
$nManager = DUPX_NOTICE_MANAGER::getInstance();
try {
DUPX_RemoveRedundantData::loadWP();
// UNINSTALL PLUGIN IF IS ACTIVE
$level = error_reporting(E_CORE_ERROR | E_CORE_WARNING | E_COMPILE_ERROR | E_ERROR | E_WARNING | E_PARSE | E_USER_ERROR | E_USER_WARNING | E_RECOVERABLE_ERROR);
if (SnapUtil::isIniValChangeable('display_errors')) {
@ini_set('display_errors', 0);
}
Log::info("UNINSTALL PLUGIN " . Log::v2str($this->data['slug']), Log::LV_DEBUG);
$pluginFile = plugin_basename($this->data['slug']);
$uninstallable_plugins = (array) get_option('uninstall_plugins');
/**
* Fires in uninstall_plugin() immediately before the plugin is uninstalled.
*
* @param string $plugin Path to the main plugin file from plugins directory.
* @param array $uninstallable_plugins Uninstallable plugins.
*/
do_action('pre_uninstall_plugin', $this->data['slug'], $uninstallable_plugins);
if (file_exists(WP_PLUGIN_DIR . '/' . dirname($pluginFile) . '/uninstall.php')) {
if (isset($uninstallable_plugins[$pluginFile])) {
unset($uninstallable_plugins[$pluginFile]);
update_option('uninstall_plugins', $uninstallable_plugins);
}
unset($uninstallable_plugins);
if (defined('WP_UNINSTALL_PLUGIN')) {
$already_defined_uninstall_const = true;
} else {
define('WP_UNINSTALL_PLUGIN', $pluginFile);
$already_defined_uninstall_const = false;
}
wp_register_plugin_realpath(WP_PLUGIN_DIR . '/' . $pluginFile);
if ($already_defined_uninstall_const) {
$uninstall_file_content = file_get_contents(WP_PLUGIN_DIR . '/' . dirname($pluginFile) . '/uninstall.php');
/*
$regexProhibited = array(
'dirname[\t\s]*\([\t\s]*WP_UNINSTALL_PLUGIN[\t\s]*\)',
'WP_UNINSTALL_PLUGIN[\t\s]*\!?=',
'\!?=[\t\s]*WP_UNINSTALL_PLUGIN',
'current_user_can'
); */
$prohibited_codes = array(
'dirname( WP_UNINSTALL_PLUGIN )',
'dirname(WP_UNINSTALL_PLUGIN )',
'dirname( WP_UNINSTALL_PLUGIN)',
'dirname(WP_UNINSTALL_PLUGIN)',
'WP_UNINSTALL_PLUGIN =',
'WP_UNINSTALL_PLUGIN !=',
'WP_UNINSTALL_PLUGIN=',
'WP_UNINSTALL_PLUGIN!=',
'= WP_UNINSTALL_PLUGIN',
'!= WP_UNINSTALL_PLUGIN',
'=WP_UNINSTALL_PLUGIN=',
'!=WP_UNINSTALL_PLUGIN',
'current_user_can',
);
foreach ($prohibited_codes as $prohibited_code) {
if (false !== stripos($uninstall_file_content, $prohibited_code)) {
Log::info("Can't include uninstall.php file of the " . $this->data['slug'] . " because prohibited code found");
return false;
}
}
}
include(WP_PLUGIN_DIR . '/' . dirname($pluginFile) . '/uninstall.php');
} elseif (isset($uninstallable_plugins[$pluginFile])) {
$callable = $uninstallable_plugins[$pluginFile];
unset($uninstallable_plugins[$pluginFile]);
update_option('uninstall_plugins', $uninstallable_plugins);
unset($uninstallable_plugins);
wp_register_plugin_realpath(WP_PLUGIN_DIR . '/' . $pluginFile);
include_once(WP_PLUGIN_DIR . '/' . $pluginFile);
add_action("uninstall_{$pluginFile}", $callable);
/**
* Fires in uninstall_plugin() once the plugin has been uninstalled.
*
* The action concatenates the 'uninstall_' prefix with the basename of the
* plugin passed to uninstall_plugin() to create a dynamically-named action.
*
* @since 2.7.0
*/
do_action("uninstall_{$pluginFile}");
// Extra
// Extra
} else {
// The plugin was never activated so no need to call uninstallation hook
}
// store plugin in original file folder
$origFileManager = DUPX_Orig_File_Manager::getInstance();
if (($pluginPath = $this->getPluginPath()) == false) {
Log::info('PLUGINS: can\'t remove plugin ' . $this->slug . ' because doesn\'t exist');
} else {
$origFileManager->addEntry($this->slug, $pluginPath, DUPX_Orig_File_Manager::MODE_MOVE);
}
} catch (Exception $e) {
$errorMsg = "**ERROR** The Inactive plugin " . $this->name . " can't be deleted";
$longMsg = 'Please delete the plugin ' . $this->name . ' (' . $this->slug . ') manually' . PHP_EOL .
'Exception message: ' . $e->getMessage() . PHP_EOL .
'Trace: ' . $e->getTraceAsString();
Log::info($errorMsg);
$nManager->addFinalReportNotice(array(
'shortMsg' => $errorMsg,
'level' => DUPX_NOTICE_ITEM::HARD_WARNING,
'longMsg' => $longMsg,
'longMsgMode' => DUPX_NOTICE_ITEM::MSG_MODE_PRE,
'sections' => 'plugins'
));
return false;
} catch (Error $e) {
$errorMsg = "**ERROR** The Inactive plugin " . $this->name . " can't be deleted";
$longMsg = 'Please delete the plugin ' . $this->name . ' (' . $this->slug . ') manually' . PHP_EOL .
'Exception message: ' . $e->getMessage() . PHP_EOL .
'Trace: ' . $e->getTraceAsString();
Log::info($errorMsg);
$nManager->addFinalReportNotice(array(
'shortMsg' => $errorMsg,
'level' => DUPX_NOTICE_ITEM::HARD_WARNING,
'longMsg' => $longMsg,
'longMsgMode' => DUPX_NOTICE_ITEM::MSG_MODE_PRE,
'sections' => 'plugins'
));
return false;
}
error_reporting($level);
return true;
}
/**
*
* @param string $key
*
* @return mixed
*/
public function __get($key)
{
if (!isset($this->data[$key])) {
throw new Exception('prop ' . $key . ' doesn\'t exist');
}
return $this->data[$key];
}
/**
*
* @param string $key
* @param mixed $value
*
* @return mixed
*/
public function __set($key, $value)
{
if (!isset($this->data[$key])) {
throw new Exception('prop ' . $key . ' doesn\'t exist');
}
if ($key === 'slug') {
throw new Exception('can\'t modify slug prop');
}
return ($this->data[$key] = $value);
}
/**
*
* @param string $key
*
* @return boolean
*/
public function __isset($key)
{
return isset($this->data[$key]);
}
}

View File

@@ -0,0 +1,496 @@
<?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;
require_once(DUPX_INIT . '/classes/plugins/class.plugin.item.php');
require_once(DUPX_INIT . '/classes/plugins/class.plugin.custom.actions.php');
require_once(DUPX_INIT . '/classes/utilities/class.u.remove.redundant.data.php');
/**
* Original installer files manager
* singleton class
*/
final class DUPX_Plugins_Manager
{
const SLUG_WOO_ADMIN = 'woocommerce-admin/woocommerce-admin.php';
const SLUG_SIMPLE_SSL = 'really-simple-ssl/rlrsssl-really-simple-ssl.php';
const SLUG_ONE_CLICK_SSL = 'one-click-ssl/ssl.php';
const SLUG_WP_FORCE_SSL = 'wp-force-ssl/wp-force-ssl.php';
const SLUG_RECAPTCHA = 'simple-google-recaptcha/simple-google-recaptcha.php';
const SLUG_WPBAKERY_PAGE_BUILDER = 'js_composer/js_composer.php';
const SLUG_DUPLICATOR_PRO = 'duplicator-pro/duplicator-pro.php';
const SLUG_DUPLICATOR_LITE = 'duplicator/duplicator.php';
const SLUG_DUPLICATOR_TESTER = 'duplicator-tester-plugin/duplicator-tester.php';
const SLUG_POPUP_MAKER = 'popup-maker/popup-maker.php';
const SLUG_JETPACK = 'jetpack/jetpack.php';
const SLUG_WP_ROCKET = 'wp-rocket/wp-rocket.php';
const SLUG_BETTER_WP_SECURITY = 'better-wp-security/better-wp-security.php';
const SLUG_HTTPS_REDIRECTION = 'https-redirection/https-redirection.php';
const SLUG_LOGIN_NOCAPTCHA = 'login-recaptcha/login-nocaptcha.php';
const SLUG_GOOGLE_CAPTCHA = 'google-captcha/google-captcha.php';
const SLUG_ADVANCED_CAPTCHA = 'advanced-google-recaptcha/advanced-google-recaptcha.php';
const OPTION_ACTIVATE_PLUGINS = 'duplicator_activate_plugins_after_installation';
/**
*
* @var self
*/
private static $instance = null;
/**
*
* @var DUPX_Plugin_item[]
*/
private $plugins = array();
/**
*
* @var DUPX_Plugin_item[]
*/
private $unistallList = array();
/**
*
* @var DUPX_Plugin_custom_actions[]
*/
private $customPluginsActions = array();
/**
*
* @return self
*/
public static function getInstance()
{
if (is_null(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct()
{
foreach (DUPX_ArchiveConfig::getInstance()->wpInfo->plugins as $pluginInfo) {
$this->plugins[$pluginInfo->slug] = new DUPX_Plugin_item((array) $pluginInfo);
}
$this->setCustomPluginsActions();
Log::info('CONSTRUCT PLUGINS OBJECTS: ' . Log::v2str($this->plugins), Log::LV_HARD_DEBUG);
}
private function setCustomPluginsActions()
{
$default = DUPX_Plugin_custom_actions::BY_DEFAULT_ENABLED;
$afterLogin = true;
$longMsg = '';
$this->customPluginsActions[self::SLUG_DUPLICATOR_LITE] = new DUPX_Plugin_custom_actions(
self::SLUG_DUPLICATOR_LITE,
$default,
$afterLogin,
$longMsg
);
$this->customPluginsActions[self::SLUG_DUPLICATOR_TESTER] = new DUPX_Plugin_custom_actions(
self::SLUG_DUPLICATOR_TESTER,
$default,
$afterLogin,
$longMsg
);
$this->customPluginsActions[self::SLUG_DUPLICATOR_PRO] = new DUPX_Plugin_custom_actions(
self::SLUG_DUPLICATOR_PRO,
DUPX_Plugin_custom_actions::BY_DEFAULT_DISABLED,
false,
'Duplicator PRO has been deactivated because in the new versions it is not possible to ' .
'have Duplicator PRO active at the same time as PRO.'
);
$longMsg = "This plugin is deactivated by default automatically. "
. "<strong>You must reactivate from the WordPress admin panel after completing the installation</strong> "
. "or from the plugins tab."
. " Your site's frontend will render properly after reactivating the plugin.";
$this->customPluginsActions[self::SLUG_WPBAKERY_PAGE_BUILDER] = new DUPX_Plugin_custom_actions(
self::SLUG_WPBAKERY_PAGE_BUILDER,
DUPX_Plugin_custom_actions::BY_DEFAULT_DISABLED,
true,
$longMsg
);
$this->customPluginsActions[self::SLUG_JETPACK] = new DUPX_Plugin_custom_actions(
self::SLUG_JETPACK,
DUPX_Plugin_custom_actions::BY_DEFAULT_DISABLED,
true,
$longMsg
);
$longMsg = "This plugin is deactivated by default automatically due to issues that one may encounter when migrating. "
. "<strong>You must reactivate from the WordPress admin panel after completing the installation</strong> "
. "or from the plugins tab."
. " Your site's frontend will render properly after reactivating the plugin.";
$this->customPluginsActions[self::SLUG_POPUP_MAKER] = new DUPX_Plugin_custom_actions(
self::SLUG_POPUP_MAKER,
DUPX_Plugin_custom_actions::BY_DEFAULT_DISABLED,
true,
$longMsg
);
$this->customPluginsActions[self::SLUG_WP_ROCKET] = new DUPX_Plugin_custom_actions(
self::SLUG_WP_ROCKET,
DUPX_Plugin_custom_actions::BY_DEFAULT_DISABLED,
true,
$longMsg
);
$longMsg = "This plugin is deactivated by default automatically due to issues that one may encounter when migrating. "
. "<strong>You must reactivate from the WordPress admin panel after completing the installation</strong> "
. "or from the plugins tab.";
$this->customPluginsActions[self::SLUG_WOO_ADMIN] = new DUPX_Plugin_custom_actions(
self::SLUG_WOO_ADMIN,
DUPX_Plugin_custom_actions::BY_DEFAULT_DISABLED,
true,
$longMsg
);
$this->customPluginsActions[self::SLUG_BETTER_WP_SECURITY] = new DUPX_Plugin_custom_actions(
self::SLUG_BETTER_WP_SECURITY,
DUPX_Plugin_custom_actions::BY_DEFAULT_DISABLED,
true,
$longMsg
);
}
/**
*
* @return DUPX_Plugin_item[]
*/
public function getPlugins()
{
return $this->plugins;
}
/**
*
* @staticvar string[] $dropInsPaths
* @return string[]
*/
public function getDropInsPaths()
{
static $dropInsPaths = null;
if (is_null($dropInsPaths)) {
$dropInsPaths = array();
foreach ($this->plugins as $plugin) {
if ($plugin->isDropIns()) {
$dropInsPaths[] = $plugin->getPluginArchivePath();
}
}
Log::info('DROP INS PATHS: ' . Log::v2str($dropInsPaths));
}
return $dropInsPaths;
}
public function pluginExistsInArchive($slug)
{
return array_key_exists($slug, $this->plugins);
}
/**
* This function performs status checks on plugins and disables those that must disable creating user messages
*/
public function preViewChecks()
{
$noticeManager = DUPX_NOTICE_MANAGER::getInstance();
$paramsManager = PrmMng::getInstance();
if (DUPX_InstallerState::isRestoreBackup()) {
return;
}
$activePlugins = $paramsManager->getValue(PrmMng::PARAM_PLUGINS);
$saveParams = false;
foreach ($this->customPluginsActions as $slug => $customPlugin) {
if (!isset($this->plugins[$slug])) {
continue;
}
switch ($customPlugin->byDefaultStatus()) {
case DUPX_Plugin_custom_actions::BY_DEFAULT_DISABLED:
if (($delKey = array_search($slug, $activePlugins)) !== false) {
$saveParams = true;
unset($activePlugins[$delKey]);
$noticeManager->addNextStepNotice(array(
'shortMsg' => 'Plugin ' . $this->plugins[$slug]->name . ' disabled by default',
'level' => DUPX_NOTICE_ITEM::NOTICE,
'longMsg' => $customPlugin->byDefaultMessage(),
'longMsgMode' => DUPX_NOTICE_ITEM::MSG_MODE_HTML,
'sections' => 'plugins'
), DUPX_NOTICE_MANAGER::ADD_UNIQUE, 'custom_plugin_action' . $slug);
}
break;
case DUPX_Plugin_custom_actions::BY_DEFAULT_ENABLED:
if (!in_array($slug, $activePlugins)) {
$saveParams = true;
$activePlugins[] = $slug;
$noticeManager->addNextStepNotice(array(
'shortMsg' => 'Plugin ' . $this->plugins[$slug]->name . ' enabled by default',
'level' => DUPX_NOTICE_ITEM::NOTICE,
'longMsg' => $customPlugin->byDefaultMessage(),
'longMsgMode' => DUPX_NOTICE_ITEM::MSG_MODE_HTML,
'sections' => 'plugins'
), DUPX_NOTICE_MANAGER::ADD_UNIQUE, 'custom_plugin_action' . $slug);
}
break;
case DUPX_Plugin_custom_actions::BY_DEFAULT_AUTO:
default:
break;
}
}
if ($saveParams) {
$paramsManager->setValue(PrmMng::PARAM_PLUGINS, $activePlugins);
$paramsManager->save();
$noticeManager->saveNotices();
}
}
public function getStatusCounts($subsiteId = -1)
{
$result = array(
DUPX_Plugin_item::STATUS_MUST_USE => 0,
DUPX_Plugin_item::STATUS_DROP_INS => 0,
DUPX_Plugin_item::STATUS_NETWORK_ACTIVE => 0,
DUPX_Plugin_item::STATUS_ACTIVE => 0,
DUPX_Plugin_item::STATUS_INACTIVE => 0
);
foreach ($this->plugins as $plugin) {
$result[$plugin->getOrgiStatus($subsiteId)]++;
}
return $result;
}
public function getDefaultActivePluginsList($subsiteId = -1)
{
$result = array();
foreach ($this->plugins as $plugin) {
if (!$plugin->isInactive($subsiteId)) {
$result[] = $plugin->slug;
}
}
return $result;
}
/**
* return alla plugins slugs list
*
* @return string[]
*/
public function getAllPluginsSlugs()
{
return array_keys($this->plugins);
}
public function setActions($plugins, $subsiteId = -1)
{
Log::info('FUNCTION [' . __FUNCTION__ . ']: plugins ' . Log::v2str($plugins), Log::LV_DEBUG);
foreach ($this->plugins as $slug => $plugin) {
$deactivate = false;
if ($plugin->isForceDisabled()) {
$deactivate = true;
} else {
if (!$this->plugins[$slug]->isInactive($subsiteId) && !in_array($slug, $plugins)) {
$deactivate = true;
}
}
if ($deactivate) {
$this->plugins[$slug]->setDeactivateAction($subsiteId, null, null, false);
}
}
foreach ($plugins as $slug) {
if (isset($this->plugins[$slug])) {
$this->plugins[$slug]->setActivationAction($subsiteId, false);
}
}
$this->setAutoActions($subsiteId);
DUPX_NOTICE_MANAGER::getInstance()->saveNotices();
}
public function executeActions($dbh, $subsiteId = -1)
{
$activePluginsList = array();
$activateOnLoginPluginsList = array();
$this->unistallList = array();
$escapedTablePrefix = mysqli_real_escape_string($dbh, PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_TABLE_PREFIX));
$noticeManager = DUPX_NOTICE_MANAGER::getInstance();
Log::info('PLUGINS OBJECTS: ' . Log::v2str($this->plugins), Log::LV_HARD_DEBUG);
foreach ($this->plugins as $plugin) {
$deactivated = false;
if ($plugin->deactivateAction) {
$plugin->deactivate();
// can't remove deactivate after login
$deactivated = true;
} else {
if ($plugin->isActive($subsiteId)) {
$activePluginsList[] = $plugin->slug;
}
}
if ($plugin->activateAction) {
$activateOnLoginPluginsList[] = $plugin->slug;
$noticeManager->addFinalReportNotice(array(
'shortMsg' => 'Activate ' . $plugin->name . ' after you login.',
'level' => DUPX_NOTICE_ITEM::NOTICE,
'sections' => 'plugins'
));
}
}
// force duplicator lite activation
if (!array_key_exists(self::SLUG_DUPLICATOR_LITE, $activePluginsList)) {
$activePluginsList[] = self::SLUG_DUPLICATOR_LITE;
}
// force duplicator tester activation if exists
if ($this->pluginExistsInArchive(self::SLUG_DUPLICATOR_TESTER) && !array_key_exists(self::SLUG_DUPLICATOR_TESTER, $activePluginsList)) {
$activePluginsList[] = self::SLUG_DUPLICATOR_TESTER;
}
Log::info('Active plugins: ' . Log::v2str($activePluginsList), Log::LV_DEBUG);
$value = mysqli_real_escape_string($dbh, @serialize($activePluginsList));
$optionTable = mysqli_real_escape_string($dbh, DUPX_DB_Functions::getOptionsTableName());
$query = "UPDATE `" . $optionTable . "` SET option_value = '" . $value . "' WHERE option_name = 'active_plugins' ";
if (!DUPX_DB::mysqli_query($dbh, $query)) {
$noticeManager->addFinalReportNotice(array(
'shortMsg' => 'QUERY ERROR: MySQL',
'level' => DUPX_NOTICE_ITEM::HARD_WARNING,
'longMsg' => "Error description: " . mysqli_error($dbh),
'longMsgMode' => DUPX_NOTICE_ITEM::MSG_MODE_DEFAULT,
'sections' => 'database'
));
throw new Exception("Database error description: " . mysqli_error($dbh));
}
$value = mysqli_real_escape_string($dbh, @serialize($activateOnLoginPluginsList));
$optionTable = mysqli_real_escape_string($dbh, DUPX_DB_Functions::getOptionsTableName());
$query = "INSERT INTO `" . $optionTable . "` (option_name, option_value) VALUES('" . self::OPTION_ACTIVATE_PLUGINS . "','" . $value . "') ON DUPLICATE KEY UPDATE option_name=\"" . self::OPTION_ACTIVATE_PLUGINS . "\"";
if (!DUPX_DB::mysqli_query($dbh, $query)) {
$noticeManager->addFinalReportNotice(array(
'shortMsg' => 'QUERY ERROR: MySQL',
'level' => DUPX_NOTICE_ITEM::HARD_WARNING,
'longMsg' => "Error description: " . mysqli_error($dbh),
'longMsgMode' => DUPX_NOTICE_ITEM::MSG_MODE_DEFAULT,
'sections' => 'database'
));
throw new Exception("Database error description: " . mysqli_error($dbh));
}
return true;
}
/**
* remove inactive plugins
* this method must calle after wp-config set
*/
public function unistallInactivePlugins()
{
Log::info('FUNCTION [' . __FUNCTION__ . ']: unistall inactive plugins');
foreach ($this->unistallList as $plugin) {
if ($plugin->uninstall()) {
Log::info("UNINSTALL PLUGIN " . Log::v2str($plugin->slug) . ' DONE');
} else {
Log::info("UNINSTALL PLUGIN " . Log::v2str($plugin->slug) . ' FAILED');
}
}
}
/**
* Set automatic actions for plugins
*
* @return void
*/
public function setAutoActions($subsiteId = -1)
{
$paramManager = PrmMng::getInstance();
$casesToHandle = array(
array(
'slugs' => array(
self::SLUG_SIMPLE_SSL,
self::SLUG_WP_FORCE_SSL,
self::SLUG_HTTPS_REDIRECTION,
self::SLUG_ONE_CLICK_SSL
),
'longMsg' => "The plugin '%name%' has been deactivated because you are migrating from SSL (HTTPS) to Non-SSL (HTTP).<br>" .
"If it was not deactivated, you would not be able to login.",
'info' => '%name% [as Non-SSL installation] will be deactivated',
'condition' => !DUPX_U::is_ssl()
),
array(
'slugs' => array(
self::SLUG_RECAPTCHA,
self::SLUG_LOGIN_NOCAPTCHA,
self::SLUG_GOOGLE_CAPTCHA,
self::SLUG_ADVANCED_CAPTCHA
),
'longMsg' => "The plugin '%name%' has been deactivated because reCaptcha requires a site key which is bound to the site's address." .
"Your package site's address and installed site's address don't match. " .
"You can reactivate it after finishing with the installation.<br>" .
"<strong>Please do not forget to change the reCaptcha site key after activating it.</strong>",
'info' => '%name% [as package creation site URL and the installation site URL are different] will be deactivated',
'condition' => $paramManager->getValue(PrmMng::PARAM_SITE_URL_OLD) != $paramManager->getValue(PrmMng::PARAM_SITE_URL),
),
);
foreach ($casesToHandle as $case) {
foreach ($case['slugs'] as $slug) {
if (isset($this->plugins[$slug]) && $this->plugins[$slug]->isActive($subsiteId) && $case['condition']) {
$info = str_replace('%name%', $this->plugins[$slug]->name, $case['info']);
$longMsg = str_replace('%name%', $this->plugins[$slug]->name, $case['longMsg']);
Log::info($info, Log::LV_DEBUG);
$this->plugins[$slug]->setDeactivateAction($subsiteId, $info, $longMsg);
}
}
}
foreach ($this->customPluginsActions as $slug => $customPlugin) {
if (!isset($this->plugins[$slug])) {
continue;
}
if (!$this->plugins[$slug]->isInactive($subsiteId) && $customPlugin->isEnableAfterLogin()) {
$this->plugins[$slug]->setActivationAction($subsiteId);
}
}
}
private function __clone()
{
}
}

View File

@@ -0,0 +1,42 @@
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
class DUPX_REST_AUTH implements Requests_Auth
{
protected $nonce = null;
protected $basicAuthUser = "";
protected $basicAuthPassword = "";
public function __construct($nonce, $basicAuthUser = "", $basicAuthPassword = "")
{
$this->nonce = $nonce;
$this->basicAuthUser = $basicAuthUser;
$this->basicAuthPassword = $basicAuthPassword;
}
public function register(Requests_Hooks &$hooks)
{
if (strlen($this->basicAuthUser) > 0) {
$basicAuth = new Requests_Auth_Basic(array(
$this->basicAuthUser,
$this->basicAuthPassword
));
$basicAuth->register($hooks);
}
$hooks->register('requests.before_request', array($this, 'before_request'));
}
public function before_request(&$url, &$headers, &$data, &$type, &$options)
{
$data['_wpnonce'] = $this->nonce;
foreach ($_COOKIE as $key => $val) {
$options['cookies'][$key] = $val;
}
}
}

View File

@@ -0,0 +1,148 @@
<?php
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Libs\Snap\SnapIO;
use Duplicator\Installer\Utils\Log\Log;
use Duplicator\Installer\Core\Params\PrmMng;
class DUPX_REST
{
const DUPLICATOR_NAMESPACE = 'duplicator/v1/';
/**
*
* @var string
*/
private $nonce = false;
/**
*
* @var string
*/
private $basicAuthUser = "";
/**
*
* @var string
*/
private $basicAuthPassword = "";
/**
*
* @var string
*/
private $url = false;
/**
*
* @var self
*/
private static $instance = null;
/**
*
* @return self
*/
public static function getInstance()
{
if (is_null(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct()
{
$paramsManager = PrmMng::getInstance();
$overwriteData = $paramsManager->getValue(PrmMng::PARAM_OVERWRITE_SITE_DATA);
if (is_array($overwriteData)) {
if (
isset($overwriteData['restUrl']) &&
strlen($overwriteData['restUrl']) > 0 &&
isset($overwriteData['restNonce']) &&
strlen($overwriteData['restNonce']) > 0
) {
$this->url = SnapIO::untrailingslashit($overwriteData['restUrl']);
$this->nonce = $overwriteData['restNonce'];
}
if (strlen($overwriteData['restAuthUser']) > 0) {
$this->basicAuthUser = $overwriteData['restAuthUser'];
$this->basicAuthPassword = $overwriteData['restAuthPassword'];
}
}
}
public function checkRest($reset = false, &$errorMessage = "")
{
static $success = null;
if (is_null($success) || $reset) {
try {
$success = true;
if ($this->nonce === false) {
throw new Exception("Nonce is not set.");
}
if (strlen($testUrl = $this->getRestUrl('versions')) === 0) {
throw new Exception("Couldn't get REST API backed URL to do tests. REST API URL was empty.");
}
$response = Requests::get($testUrl, array(), $this->getRequestAuthOptions());
if ($response->success == false) {
Log::info(Log::v2str($response));
throw new Exception("REST API request on $testUrl failed");
}
if (($result = json_decode($response->body, true)) === null) {
throw new Exception("Can't decode json.");
}
if (!isset($result["dup"])) {
throw new Exception("Did not receive the expected result.");
}
} catch (Exception $ex) {
$success = false;
$errorMessage = $ex->getMessage();
Log::info("FAILED REST API CHECK. MESSAGE: " . $ex->getMessage());
}
}
return $success;
}
public function getVersions()
{
$response = Requests::get($this->getRestUrl('versions'), array(), $this->getRequestAuthOptions());
if (!$response->success) {
return false;
}
if (($result = json_decode($response->body)) === null) {
return false;
}
return $result;
}
/**
* Return request auth options
*
* @return array
*/
private function getRequestAuthOptions()
{
return array(
'auth' => new DUPX_REST_AUTH($this->nonce, $this->basicAuthUser, $this->basicAuthPassword),
'verify' => false,
'verifyname' => false
);
}
private function getRestUrl($subPath = '')
{
return $this->url ? $this->url . '/' . self::DUPLICATOR_NAMESPACE . $subPath : '';
}
}

View File

@@ -0,0 +1,63 @@
<?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\Core\Bootstrap;
use Duplicator\Installer\Core\Params\PrmMng;
use Duplicator\Libs\Snap\SnapOrigFileManager;
/**
* Original installer files manager
*
* This class saves a file or folder in the original files folder and saves the original location persistant.
* By entry we mean a file or a folder but not the files contained within it.
* In this way it is possible, for example, to move an entire plugin to restore it later.
*
* singleton class
*/
final class DUPX_Orig_File_Manager extends SnapOrigFileManager
{
/**
*
* @var DUPX_Orig_File_Manager
*/
private static $instance = null;
/**
*
* @return DUPX_Orig_File_Manager
*/
public static function getInstance()
{
if (is_null(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
/**
* This class should be singleton, but unfortunately it is not possible to change the constructor in private with versions prior to PHP 7.2.
*/
public function __construct()
{
//Init Original File Manager
$packageHash = Bootstrap::getPackageHash();
$root = PrmMng::getInstance()->getValue(PrmMng::PARAM_PATH_NEW);
parent::__construct($root, DUPX_INIT, $packageHash);
}
private function __clone()
{
}
}

View File

@@ -0,0 +1,33 @@
<?php
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
use Duplicator\Installer\Utils\Log\Log;
use Duplicator\Installer\Core\Params\PrmMng;
class DUPX_RemoveRedundantData
{
public static function loadWP()
{
static $loaded = null;
if (is_null($loaded)) {
$wp_root_dir = PrmMng::getInstance()->getValue(PrmMng::PARAM_PATH_WP_CORE_NEW);
require_once($wp_root_dir . '/wp-load.php');
if (!class_exists('WP_Privacy_Policy_Content')) {
require_once($wp_root_dir . '/wp-admin/includes/misc.php');
}
if (!function_exists('request_filesystem_credentials')) {
require_once($wp_root_dir . '/wp-admin/includes/file.php');
}
if (!function_exists('get_plugins')) {
require_once $wp_root_dir . '/wp-admin/includes/plugin.php';
}
if (!function_exists('delete_theme')) {
require_once $wp_root_dir . '/wp-admin/includes/theme.php';
}
$GLOBALS['wpdb']->show_errors(false);
$loaded = true;
}
return $loaded;
}
}

View File

@@ -0,0 +1,724 @@
<?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\Installer\Utils\Log\Log;
use Duplicator\Libs\Snap\SnapIO;
use Duplicator\Libs\Snap\SnapJson;
/**
* Search and replace manager
* singleton class
*/
final class DUPX_S_R_MANAGER
{
const GLOBAL_SCOPE_KEY = '___!GLOBAL!___!SCOPE!___';
/**
*
* @var DUPX_S_R_MANAGER
*/
private static $instance = null;
/**
* full list items not sorted
*
* @var DUPX_S_R_ITEM[]
*/
private $items = array();
/**
* items sorted by priority and scope
* [
* 10 => [
* '___!GLOBAL!___!SCOPE!___' => [
* DUPX_S_R_ITEM
* DUPX_S_R_ITEM
* DUPX_S_R_ITEM
* ],
* 'scope_one' => [
* DUPX_S_R_ITEM
* DUPX_S_R_ITEM
* ]
* ],
* 20 => [
* .
* .
* .
* ]
* ]
*
* @var array
*/
private $prorityScopeItems = array();
/**
*
* @return DUPX_S_R_MANAGER
*/
public static function getInstance()
{
if (is_null(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct()
{
}
/**
*
* @return array
*/
public function getArrayData()
{
$data = array();
foreach ($this->items as $item) {
$data[] = $item->toArray();
}
return $data;
}
/**
*
* @param array $data
*/
public function setFromArrayData($data)
{
foreach ($data as $itemArray) {
$new_item = DUPX_S_R_ITEM::getItemFromArray($itemArray);
$this->setNewItem($new_item);
}
}
/**
*
* @param string $search
* @param string $replace
* @param string $type // item type DUPX_S_R_ITEM::[TYPE_STRING|TYPE_URL|TYPE_URL_NORMALIZE_DOMAIN|TYPE_PATH]
* @param int $prority // lower first
* @param bool|string|string[] $scope // true = global scope | false = never | string signle scope | string[] scope list
*
* @return boolean|DUPX_S_R_ITEM // false if fail or new DUPX_S_R_ITEM
*/
public function addItem($search, $replace, $type = DUPX_S_R_ITEM::TYPE_STRING, $prority = 10, $scope = true)
{
$search = (string) $search;
$replace = (string) $replace;
if (strlen($search) == 0 || $search === $replace) {
return false;
}
if (is_bool($scope)) {
$scope = $scope ? self::GLOBAL_SCOPE_KEY : '';
}
if (is_array($scope)) {
$scopeStr = implode(',', $scope);
$scopeStr = (strlen($scopeStr) > 50 ? substr($scopeStr, 0, 50) . "..." : $scopeStr);
} else {
$scopeStr = 'ALL';
}
Log::info(
"SEARCH ITEM[T:" . str_pad($type, 5) . "|P:" . str_pad($prority, 2) . "]" .
" SEARCH: " . $search .
" REPLACE: " . $replace . " [SCOPE: " . $scopeStr . "]"
);
$new_item = new DUPX_S_R_ITEM($search, $replace, $type, $prority, $scope);
return $this->setNewItem($new_item);
}
/**
*
* @param DUPX_S_R_ITEM $new_item
*
* @return boolean|DUPX_S_R_ITEM // false if fail or new DUPX_S_R_ITEM
*/
private function setNewItem($new_item)
{
$this->items[$new_item->getId()] = $new_item;
// create priority array
if (!isset($this->prorityScopeItems[$new_item->prority])) {
$this->prorityScopeItems[$new_item->prority] = array();
// sort by priority
ksort($this->prorityScopeItems);
}
// create scope list
foreach ($new_item->scope as $scope) {
if (!isset($this->prorityScopeItems[$new_item->prority][$scope])) {
$this->prorityScopeItems[$new_item->prority][$scope] = array();
}
$this->prorityScopeItems[$new_item->prority][$scope][] = $new_item;
}
return $new_item;
}
/**
* get all search and reaple items by scpoe
*
* @param null|string $scope if scope is empty get only global scope
*
* @return DUPX_S_R_ITEM[]
*/
private function getSearchReplaceItems($scope = null, $globalScope = true)
{
$items_list = array();
foreach ($this->prorityScopeItems as $priority => $priority_list) {
// get scope list
if (!empty($scope) && isset($priority_list[$scope])) {
foreach ($priority_list[$scope] as $item) {
$items_list[] = $item;
}
}
// get global scope
if ($globalScope && isset($priority_list[self::GLOBAL_SCOPE_KEY])) {
foreach ($priority_list[self::GLOBAL_SCOPE_KEY] as $item) {
$items_list[] = $item;
}
}
}
return $items_list;
}
/**
* get replace list by scope
* result
* [
* ['search' => ...,'replace' => ...]
* ['search' => ...,'replace' => ...]
* ]
*
* @param null|string $scope if scope is empty get only global scope
* @param bool $unique_search If true it eliminates the double searches leaving the one with lower priority.
*
* @return array
*/
public function getSearchReplaceList($scope = null, $unique_search = true, $globalScope = true)
{
Log::info('-- SEARCH LIST -- SCOPE: ' . Log::v2str($scope), Log::LV_DEBUG);
$items_list = $this->getSearchReplaceItems($scope, $globalScope);
if (Log::isLevel(Log::LV_HARD_DEBUG)) {
Log::info('-- SEARCH LIST ITEMS --' . "\n" . print_r($items_list, true), Log::LV_HARD_DEBUG);
}
if ($unique_search) {
$items_list = self::uniqueSearchListItem($items_list);
if (Log::isLevel(Log::LV_HARD_DEBUG)) {
Log::info('-- UNIQUE LIST ITEMS --' . "\n" . print_r($items_list, true), Log::LV_HARD_DEBUG);
}
}
Log::info('--- BASE STRINGS ---');
foreach ($items_list as $index => $item) {
Log::info(
'SEARCH[' . str_pad($item->type, 5, ' ', STR_PAD_RIGHT) . ']' . str_pad($index + 1, 3, ' ', STR_PAD_LEFT) . ":" .
str_pad(Log::v2str($item->search) . " ", 50, '=', STR_PAD_RIGHT) .
"=> " .
Log::v2str($item->replace)
);
}
$result = array();
foreach ($items_list as $item) {
$result = array_merge($result, $item->getPairsSearchReplace());
}
// remove empty search strings
$result = array_filter($result, function ($val) {
if (!empty($val['search'])) {
return true;
} else {
Log::info('Empty search string remove, replace: ' . Log::v2str($val['replace']), Log::LV_DETAILED);
return false;
}
});
if (Log::isLevel(Log::LV_DEBUG)) {
Log::info('--- REXEXES ---');
foreach ($result as $index => $c_sr) {
Log::info(
'SEARCH' . str_pad($index + 1, 3, ' ', STR_PAD_LEFT) . ":" .
str_pad(Log::v2str($c_sr['search']) . " ", 50, '=', STR_PAD_RIGHT) .
"=> " .
Log::v2str($c_sr['replace'])
);
}
}
return $result;
}
/**
* remove duplicated search strings.
* Leave the object at lower priority
*
* @param DUPX_S_R_ITEM[] $list
*
* @return boolean|DUPX_S_R_ITEM[]
*/
private static function uniqueSearchListItem($list)
{
$search_strings = array();
$result = array();
if (!is_array($list)) {
return false;
}
foreach ($list as $item) {
if (!in_array($item->search, $search_strings)) {
$result[] = $item;
$search_strings[] = $item->search;
}
}
return $result;
}
private function __clone()
{
}
}
/**
* search and replace item use in manager to creat the search and replace list.
*/
class DUPX_S_R_ITEM
{
const PATH_SEPARATOR_REGEX_NORMAL = '[\/\\\\]';
const PATH_SEPARATOR_REGEX_JSON = '(?:\\\\\/|\\\\\\\\)';
const PATH_END_REGEX_MATCH_NORMAL = '([\/\\\\"\'\n\r]|$)';
const PATH_END_REGEX_MATCH_JSON = '(\\\\\/|\\\\\\\\|["\'\n\r]|$)';
const URL_END_REGEX_MATCH_NORMAL = '([\/?"\'\n\r]|$)';
const URL_END_REGEX_MATCH_JSON = '(\\\\\/|[?"\'\n\r]|$)';
const URL_END_REGEX_MATCH_URLENCODE = '(%2F|%3F|["\'\n\r]|$)';
private static $uniqueIdCount = 0;
const TYPE_STRING = 'str';
const TYPE_URL = 'url';
const TYPE_URL_NORMALIZE_DOMAIN = 'urlnd';
const TYPE_PATH = 'path';
/**
*
* @var int
*/
private $id = 0;
/**
*
* @var int prority lower first
*/
public $prority = 10;
/**
*
* @var string[] scope list
*/
public $scope = array();
/**
*
* @var string type of string
*/
public $type = self::TYPE_STRING;
/**
*
* @var string search string
*/
public $search = '';
/**
*
* @var string replace string
*/
public $replace = '';
/**
*
* @param string $search
* @param string $replace
* @param string $type
* @param int $prority
* @param string|string[] $scope if empty never used
*/
public function __construct($search, $replace, $type = DUPX_S_R_ITEM::TYPE_STRING, $prority = 10, $scope = array())
{
if (!is_array($scope)) {
$this->scope = empty($scope) ? array() : array((string) $scope);
} else {
$this->scope = $scope;
}
$this->prority = (int) $prority;
switch ($type) {
case DUPX_S_R_ITEM::TYPE_URL:
case DUPX_S_R_ITEM::TYPE_URL_NORMALIZE_DOMAIN:
$this->search = rtrim($search, '/');
$this->replace = rtrim($replace, '/');
break;
case DUPX_S_R_ITEM::TYPE_PATH:
$this->search = SnapIO::safePathUntrailingslashit($search);
$this->replace = SnapIO::safePathUntrailingslashit($replace);
break;
case DUPX_S_R_ITEM::TYPE_STRING:
default:
$this->search = (string) $search;
$this->replace = (string) $replace;
break;
}
$this->type = $type;
$this->id = self::$uniqueIdCount;
self::$uniqueIdCount++;
}
public function toArray()
{
return array(
'id' => $this->id,
'prority' => $this->prority,
'scope' => $this->scope,
'type' => $this->type,
'search' => $this->search,
'replace' => $this->replace
);
}
public static function getItemFromArray($array)
{
$result = new self($array['search'], $array['replace'], $array['type'], $array['prority'], $array['scope']);
return $result;
}
/**
* return search an replace string
*
* result
* [
* ['search' => ...,'replace' => ...]
* ['search' => ...,'replace' => ...]
* ]
*
* @return array
*/
public function getPairsSearchReplace()
{
switch ($this->type) {
case self::TYPE_URL:
return self::searchReplaceUrl($this->search, $this->replace);
case self::TYPE_URL_NORMALIZE_DOMAIN:
return self::searchReplaceUrl($this->search, $this->replace, true, true);
case self::TYPE_PATH:
return self::searchReplacePath($this->search, $this->replace);
case self::TYPE_STRING:
default:
return self::searchReplaceWithEncodings($this->search, $this->replace);
}
}
/**
* Get search and replace strings with encodings
* prevents unnecessary substitution like when search and reaplace are the same.
*
* result
* [
* ['search' => ...,'replace' => ...]
* ['search' => ...,'replace' => ...]
* ]
*
* @param string $search
* @param string $replace
* @param bool $json add json encode string
* @param bool $urlencode add urlencode string
*
* @return array pairs search and replace
*/
public static function searchReplaceWithEncodings($search, $replace, $json = true, $urlencode = true)
{
$result = array();
if ($search != $replace) {
$result[] = array(
'search' => '/' . preg_quote($search, '/') . '/m',
'replace' => addcslashes($replace, '\\$')
);
} else {
return array();
}
// JSON ENCODE
if ($json) {
$search_json = SnapJson::getJsonWithoutQuotes($search);
$replace_json = SnapJson::getJsonWithoutQuotes($replace);
if ($search != $search_json && $search_json != $replace_json) {
$result[] = array(
'search' => '/' . preg_quote($search_json, '/') . '/m',
'replace' => addcslashes($replace_json, '\\$')
);
}
}
// URL ENCODE
if ($urlencode) {
$search_urlencode = urlencode($search);
$replace_urlencode = urlencode($replace);
if ($search != $search_urlencode && $search_urlencode != $replace_urlencode) {
$result[] = array(
'search' => '/' . preg_quote($search_urlencode, '/') . '/m',
'replace' => addcslashes($replace_urlencode, '\\$')
);
}
}
return $result;
}
/**
* Add replace strings to substitute old url to new url
* 1) no protocol old url to no protocol new url (es. //www.hold.url => //www.new.url)
* 2) wrong protocol new url to right protocol new url (es. http://www.new.url => https://www.new.url)
*
* result
* [
* ['search' => ...,'replace' => ...]
* ['search' => ...,'replace' => ...]
* ]
*
* @param string $search_url
* @param string $replace_url
* @param bool $force_new_protocol if true force http or https protocol (work only if replace url have http or https scheme)
*
* @return array
*/
public static function searchReplaceUrl($search_url, $replace_url, $force_new_protocol = true, $normalizeWww = false)
{
$result = array();
if (($parse_search_url = parse_url($search_url)) !== false && isset($parse_search_url['scheme'])) {
$search_url_raw = substr($search_url, strlen($parse_search_url['scheme']) + 1);
} else {
$search_url_raw = $search_url;
}
$search_url_raw = trim($search_url_raw, '/');
if (($parse_replace_url = parse_url($replace_url)) !== false && isset($parse_replace_url['scheme'])) {
$replace_url_raw = substr($replace_url, strlen($parse_replace_url['scheme']) + 1);
} else {
$replace_url_raw = $replace_url;
}
$replace_url_raw = trim($replace_url_raw, '/');
// (?<!https:|http:)\/\/(?:www\.|)aaaa\.it([?\/'"]|$)
if ($normalizeWww && self::domainCanNormalized($search_url)) {
if (self::isWww($search_url_raw)) {
$baseSearchUrl = substr($search_url_raw, strlen('www.'));
} else {
$baseSearchUrl = $search_url_raw;
}
$regExSearchUrlNormal = '\/\/(?:www\.)?' . preg_quote($baseSearchUrl, '/');
$regExSearchUrlJson = '\\\\\/\\\\\/(?:www\.)?' . preg_quote(SnapJson::getJsonWithoutQuotes($baseSearchUrl), '/');
$regExSearchUrlEncode = '%2F%2F(?:www\.)?' . preg_quote(urlencode($baseSearchUrl), '/');
//'/https?:\/\/(?:www\.|)aaaa\.it(?<end>[?\/\'"]|$)/m'
//$searchRawRegEx = '/(?<!https:|http:)\/\/(?:www\.|)'.preg_quote($baseSearchUrl, '/').'([?\/\'"]|$)/m';
} else {
$regExSearchUrlNormal = '\/\/' . preg_quote($search_url_raw, '/');
$regExSearchUrlJson = '\\\\\/\\\\\/' . preg_quote(SnapJson::getJsonWithoutQuotes($search_url_raw), '/');
$regExSearchUrlEncode = '%2F%2F' . preg_quote(urlencode($search_url_raw), '/');
}
// NORMALIZE source protocol
if ($force_new_protocol && $parse_replace_url !== false && isset($parse_replace_url['scheme'])) {
$result[] = array(
'search' => '/(?<!https:|http:)' . $regExSearchUrlNormal . self::URL_END_REGEX_MATCH_NORMAL . '/m',
'replace' => addcslashes('//' . $replace_url_raw, '\\$') . '$1'
);
$result[] = array(
'search' => '/https?:' . $regExSearchUrlNormal . self::URL_END_REGEX_MATCH_NORMAL . '/m',
'replace' => addcslashes($replace_url, '\\$') . '$1'
);
$result[] = array(
'search' => '/(?<!https:|http:)' . $regExSearchUrlJson . self::URL_END_REGEX_MATCH_JSON . '/m',
'replace' => addcslashes(SnapJson::getJsonWithoutQuotes('//' . $replace_url_raw), '\\$') . '$1'
);
$result[] = array(
'search' => '/https?:' . $regExSearchUrlJson . self::URL_END_REGEX_MATCH_JSON . '/m',
'replace' => addcslashes(SnapJson::getJsonWithoutQuotes($replace_url), '\\$') . '$1'
);
$result[] = array(
'search' => '/(?<!https%3A|http%3A)' . $regExSearchUrlEncode . self::URL_END_REGEX_MATCH_URLENCODE . '/m',
'replace' => addcslashes(urlencode('//' . $replace_url_raw), '\\$') . '$1'
);
$result[] = array(
'search' => '/https?%3A' . $regExSearchUrlEncode . self::URL_END_REGEX_MATCH_URLENCODE . '/m',
'replace' => addcslashes(urlencode($replace_url), '\\$') . '$1'
);
} else {
$result[] = array(
'search' => '/' . $regExSearchUrlNormal . self::URL_END_REGEX_MATCH_NORMAL . '/m',
'replace' => addcslashes('//' . $replace_url_raw, '\\$') . '$1'
);
$result[] = array(
'search' => '/' . $regExSearchUrlJson . self::URL_END_REGEX_MATCH_JSON . '/m',
'replace' => addcslashes(SnapJson::getJsonWithoutQuotes('//' . $replace_url_raw), '\\$') . '$1'
);
$result[] = array(
'search' => '/' . $regExSearchUrlEncode . self::URL_END_REGEX_MATCH_URLENCODE . '/m',
'replace' => addcslashes(urlencode('//' . $replace_url_raw), '\\$') . '$1'
);
}
return $result;
}
/**
* result
* [
* ['search' => ...,'replace' => ...]
* ['search' => ...,'replace' => ...]
* ]
*
* @param string $search_path
* @param string $replace_path
*
* @return array
*/
public static function searchReplacePath($search_path, $replace_path)
{
$result = array();
if ($search_path == $replace_path) {
return $result;
}
$explodeSearch = explode('/', $search_path);
$normaSearchArray = array_map(function ($val) {
return preg_quote(SnapJson::getJsonWithoutQuotes($val), '/');
}, $explodeSearch);
$normalPathSearch = '/' . implode(self::PATH_SEPARATOR_REGEX_NORMAL, $normaSearchArray) . self::PATH_END_REGEX_MATCH_NORMAL . '/m';
$result[] = array('search' => $normalPathSearch, 'replace' => addcslashes($replace_path, '\\$') . '$1');
$jsonSearchArray = array_map(function ($val) {
return preg_quote(SnapJson::getJsonWithoutQuotes($val), '/');
}, $explodeSearch);
$jsonPathSearch = '/' . implode(self::PATH_SEPARATOR_REGEX_JSON, $jsonSearchArray) . self::PATH_END_REGEX_MATCH_JSON . '/m';
$result[] = array('search' => $jsonPathSearch, 'replace' => addcslashes(SnapJson::getJsonWithoutQuotes($replace_path), '\\$') . '$1');
return $result;
}
/**
* get unique item id
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* @param $url string The URL whichs domain you want to get
*
* @return string The domain part of the given URL
* www.myurl.co.uk => myurl.co.uk
* www.google.com => google.com
* my.test.myurl.co.uk => myurl.co.uk
* www.myurl.localweb => myurl.localweb
*/
public static function getDomain($url)
{
$pieces = parse_url($url);
$domain = isset($pieces['host']) ? $pieces['host'] : '';
$regs = null;
if (strpos($domain, ".") !== false) {
if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $domain, $regs)) {
return $regs['domain'];
} else {
$exDomain = explode('.', $domain);
return implode('.', array_slice($exDomain, -2, 2));
}
} else {
return $domain;
}
}
public static function domainCanNormalized($url)
{
$pieces = parse_url($url);
if (!isset($pieces['host'])) {
return false;
}
if (strpos($pieces['host'], ".") === false) {
return false;
}
$dLevels = explode('.', $pieces['host']);
if ($dLevels[0] == 'www') {
return true;
}
switch (count($dLevels)) {
case 1:
return false;
case 2:
return true;
case 3:
if (preg_match('/(?P<domain>[a-z0-9][a-z0-9\-]{1,63}\.[a-z\.]{2,6})$/i', $pieces['host'], $regs)) {
return $regs['domain'] == $pieces['host'];
}
return false;
default:
return false;
}
}
public static function isWww($url)
{
$pieces = parse_url($url);
if (!isset($pieces['host'])) {
return false;
} else {
return strpos($pieces['host'], 'www.') === 0;
}
}
}

View File

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

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
* @param string $mainFolder
* @param null|DUPX_TemplateItem $parentName
*/
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 $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
*
* @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,127 @@
<?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');
final class DUPX_Template
{
const TEMPLATE_ADVANCED = 'default';
const TEMPLATE_BASE = 'base';
const TEMPLATE_IMPORT_BASE = 'import-base';
const TEMPLATE_IMPORT_ADVANCED = 'import-advanced';
/** @var DUPX_Template */
private static $instance = null;
/** @var DUPX_TemplateItem[] */
private $templates = array();
/** @var string */
private $currentTemplate = null;
/**
*
* @return DUPX_Template
*/
public static function getInstance()
{
if (is_null(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct()
{
// ADD DEFAULT TEMPLATE
$this->addTemplate(DUPX_Template::TEMPLATE_ADVANCED, DUPX_INIT . '/templates/default');
$this->setTemplate(DUPX_Template::TEMPLATE_ADVANCED);
}
/**
*
* @param string $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;
}
/**
*
* @param string $name
* @param string $mainFolder
* @param string $parentName
*
* @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;
}
/**
*
* @param string $fileTpl // template file is a relative path from root template folder
* @param array $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);
}
private function __clone()
{
}
}
/**
*
* @param string $fileTpl // template file is a relative path from root template folder
* @param array $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,226 @@
<?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;
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;
protected $category = '';
protected $testResult = null;
public function __construct($category = '')
{
$this->category = $category;
}
/**
*
* @param bool $reset
*
* @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;
}
abstract protected function runTest();
public function display()
{
if ($this->testResult === self::LV_SKIP) {
return false;
} else {
return true;
}
}
public function getCategory()
{
return $this->category;
}
public function getTitle()
{
return 'Test class ' . get_called_class();
}
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>';
}
}
public function getBadgeClass()
{
return self::resultLevelToBadgeClass($this->test(false));
}
public function getUniqueSelector()
{
return strtolower(str_replace("_", "-", get_called_class()));
}
public function resultString()
{
return self::resultLevelToString($this->test(false));
}
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';
}
}
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,778 @@
<?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\Installer\Core\Params\PrmMng;
use Duplicator\Libs\Snap\SnapOS;
class DUPX_Validation_database_service
{
/**
*
* @var self
*/
private static $instance = null;
/**
*
* @var mysqli
*/
private $dbh = null;
/**
*
* @var bool
*/
private $skipOtherTests = false;
/**
*
* @var bool
*/
private $dbCreated = false;
/**
*
* @return self
*/
public static function getInstance()
{
if (is_null(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct()
{
}
/**
*
* @return mysqli <p>Returns an object which represents the connection to a MySQL Server.</p>
*/
public function getDbConnection()
{
if (is_null($this->dbh)) {
$paramsManager = PrmMng::getInstance();
$this->dbh = DUPX_DB_Functions::getInstance()->dbConnection(array(
'dbhost' => $paramsManager->getValue(PrmMng::PARAM_DB_HOST),
'dbuser' => $paramsManager->getValue(PrmMng::PARAM_DB_USER),
'dbpass' => $paramsManager->getValue(PrmMng::PARAM_DB_PASS),
'dbname' => null
));
if (empty($this->dbh)) {
DUPX_DB_Functions::getInstance()->closeDbConnection();
$this->dbh = false;
}
}
return $this->dbh;
}
/**
* close db connection if is open
*/
public function closeDbConnection()
{
if (!is_null($this->dbh)) {
mysqli_close($this->dbh);
$this->dbh = null;
}
}
public function setSkipOtherTests($skip = true)
{
$this->skipOtherTests = (bool) $skip;
}
public function skipDatabaseTests()
{
return $this->skipOtherTests;
}
public function databaseExists(&$errorMessage = null)
{
try {
$result = true;
if (!$this->getDbConnection()) {
throw new Exception('Database not connected');
}
$paramsManager = PrmMng::getInstance();
if (mysqli_select_db($this->dbh, $paramsManager->getValue(PrmMng::PARAM_DB_NAME)) !== true) {
$errorMessage = mysqli_error($this->dbh);
$result = false;
}
} catch (Exception $e) {
$errorMessage = $e->getMessage();
Log::logException($e, Log::LV_DEFAULT, 'DATABASE SELECT EXCEPTION: ');
$result = false;
} catch (Error $e) {
$errorMessage = $e->getMessage();
Log::logException($e, Log::LV_DEFAULT, 'DATABASE SELECT EXCEPTION: ');
$result = false;
}
return $result;
}
public function createDatabase(&$errorMessage = null)
{
if ($this->dbCreated) {
return true;
}
try {
$result = true;
if (!$this->getDbConnection()) {
throw new Exception('Database not connected');
}
$dbName = PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_NAME);
switch (PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_VIEW_MODE)) {
case 'basic':
case 'cpnl':
$query = 'CREATE DATABASE `' . mysqli_real_escape_string($this->dbh, $dbName) . '`';
if (DUPX_DB::mysqli_query($this->dbh, $query) === false) {
$errorMessage = mysqli_error($this->dbh);
$result = false;
}
if ($result && $this->databaseExists() === false) {
$errorMessage = 'Can\'t select database after creation';
$result = false;
}
break;
default:
$result = false;
$errorMessage = 'Invalid db view mode';
break;
}
} catch (Exception $e) {
$errorMessage = $e->getMessage();
Log::logException($e, Log::LV_DEFAULT, 'DATABASE CREATE EXCEPTION: ');
$result = false;
} catch (Error $e) {
$errorMessage = $e->getMessage();
Log::logException($e, Log::LV_DEFAULT, 'DATABASE CREATE EXCEPTION: ');
$result = false;
}
if ($result) {
$this->dbCreated = true;
return true;
} else {
return false;
}
}
public function isDatabaseCreated()
{
return $this->dbCreated;
}
public function cleanUpDatabase(&$errorMessage = null)
{
if (!$this->dbCreated) {
return true;
}
$result = true;
try {
$dbName = PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_NAME);
switch (PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_VIEW_MODE)) {
case 'basic':
case 'cpnl':
//DELETE DB
if (DUPX_DB::mysqli_query($this->dbh, "DROP DATABASE IF EXISTS `" . mysqli_real_escape_string($this->dbh, $dbName) . "`") === false) {
$errorMessage = mysqli_error($this->dbh);
$result = false;
}
break;
default:
$errorMessage = 'Invalid db view mode';
$result = false;
break;
}
} catch (Exception $e) {
$errorMessage = $e->getMessage();
Log::logException($e, Log::LV_DEFAULT, 'DATABASE CLEANUP EXCEPTION: ');
$result = false;
} catch (Error $e) {
$errorMessage = $e->getMessage();
Log::logException($e, Log::LV_DEFAULT, 'DATABASE CLEANUP EXCEPTION: ');
$result = false;
}
if ($result) {
$this->dbCreated = false;
}
return $result;
}
public function getDatabases()
{
if (!$this->getDbConnection()) {
return array();
}
switch (PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_VIEW_MODE)) {
case 'basic':
case 'cpnl':
$dbUser = PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_USER);
$host_user = substr_replace($dbUser, '', strpos($dbUser, '_'));
break;
default:
return array();
}
return DUPX_DB::getDatabases($this->dbh, $host_user);
}
/**
* Get list of tables that are affect by the DB action
*
* @param string|null $dbAction Adb action, if null get param db action
*
* @return string[]
*/
public function getDBActionAffectedTables($dbAction = null)
{
if ($dbAction === null) {
$dbAction = PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_ACTION);
}
$affectedTables = array();
$excludeTables = DUPX_DB_Functions::getExcludedTables();
$escapedDbName = mysqli_real_escape_string($this->dbh, PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_NAME));
$allTables = DUPX_DB::queryColumnToArray($this->dbh, 'SHOW TABLES FROM `' . $escapedDbName . '`');
switch ($dbAction) {
case DUPX_DBInstall::DBACTION_EMPTY:
case DUPX_DBInstall::DBACTION_RENAME:
$affectedTables = array_diff($allTables, $excludeTables);
break;
case DUPX_DBInstall::DBACTION_REMOVE_ONLY_TABLES:
$affectedTables = array_intersect(
DUPX_DB_Tables::getInstance()->getNewTablesNames(),
array_diff($allTables, $excludeTables)
);
break;
default:
break;
}
return $affectedTables;
}
/**
* Get number of tables that are affect by the DB action
*
* @param string|null $dbAction Adb action, if null get param db action
*
* @return int
*/
public function getDBActionAffectedTablesCount($dbAction = null)
{
$isCreateNewDatabase = PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_ACTION) == DUPX_DBInstall::DBACTION_CREATE;
return ($isCreateNewDatabase) ? 0 : count($this->getDBActionAffectedTables($dbAction));
}
public function checkDbVisibility(&$errorMessage = null)
{
$result = true;
try {
if (!$this->getDbConnection()) {
throw new Exception('Database not connected');
}
switch (PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_VIEW_MODE)) {
case 'basic':
case 'cpnl':
$result = $this->databaseExists($errorMessage);
break;
default:
$errorMessage = 'Invalid db view mode';
$result = false;
break;
}
} catch (Exception $e) {
$errorMessage = $e->getMessage();
Log::logException($e, Log::LV_DEFAULT, 'DATABASE CHECK VISIBILITY EXCEPTION: ');
$result = false;
} catch (Error $e) {
$errorMessage = $e->getMessage();
Log::logException($e, Log::LV_DEFAULT, 'DATABASE CHECK VISIBILITY EXCEPTION: ');
$result = false;
}
return $result;
}
/**
* This is validation test for "Prefix too long". Checks if there are
* any new table names longer than 64 characters.
*
* @param string &$errorMessage // Will be filled with error message in case when validation test fails
*
* @return bool // Returns true if validation test passes, false otherwise
*/
public function checkDbPrefixTooLong(&$errorMessage = null)
{
$result = true;
$numOfTooLongNewTableNames = count($this->getTooLongNewTableNames());
if ($numOfTooLongNewTableNames > 0) {
$errorMessage = "Length of $numOfTooLongNewTableNames table names exceeds limit of 64 after adding prefix.";
$result = false;
}
return $result;
}
/**
* Returns list of new table names whose length is bigger than 64 limit
*
* @return array
*/
public function getTooLongNewTableNames()
{
$tooLongNewTableNames = array();
$newTableNames = array();
$newTableNames = DUPX_DB_Tables::getInstance()->getNewTablesNames();
for ($i = 0; $i < count($newTableNames); $i++) {
if (strlen($newTableNames[$i]) > 64) {
$tooLongNewTableNames[] = $newTableNames[$i];
}
}
return $tooLongNewTableNames;
}
public function dbTablesCount(&$errorMessage = null)
{
$result = true;
try {
if (!$this->getDbConnection()) {
throw new Exception('Database not connected');
}
$dbName = PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_NAME);
$result = DUPX_DB::countTables($this->dbh, $dbName);
} catch (Exception $e) {
$errorMessage = $e->getMessage();
Log::logException($e, Log::LV_DEFAULT, 'DATABASE TABLES COUNT EXCEPTION: ');
$result = false;
} catch (Error $e) {
$errorMessage = $e->getMessage();
Log::logException($e, Log::LV_DEFAULT, 'DATABASE TABLES COUNT EXCEPTION: ');
$result = false;
}
return $result;
}
/**
*
* @param array $perms
* @param array $errorMessages
*
* @return int // test result level
*/
public function dbCheckUserPerms(&$perms = array(), &$errorMessages = array())
{
$perms = array(
'create' => DUPX_Validation_abstract_item::LV_SKIP,
'insert' => DUPX_Validation_abstract_item::LV_SKIP,
'select' => DUPX_Validation_abstract_item::LV_SKIP,
'update' => DUPX_Validation_abstract_item::LV_SKIP,
'delete' => DUPX_Validation_abstract_item::LV_SKIP,
'drop' => DUPX_Validation_abstract_item::LV_SKIP,
'view' => DUPX_Validation_abstract_item::LV_SKIP,
'proc' => DUPX_Validation_abstract_item::LV_SKIP,
'func' => DUPX_Validation_abstract_item::LV_SKIP,
'trigger' => DUPX_Validation_abstract_item::LV_SKIP
);
$errorMessages = array();
try {
if (!$this->getDbConnection()) {
throw new Exception('Database not connected');
}
$dbName = PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_NAME);
if (mysqli_select_db($this->dbh, $dbName) === false) {
throw new Exception('Can\'t select database ' . $dbName);
}
$tmpTable = '__dpro_temp_' . rand(1000, 9999) . '_' . date("ymdHis");
$tmpTableEscaped = '`' . mysqli_real_escape_string($this->dbh, $tmpTable) . '`';
if (
$this->isQueryWorking("CREATE TABLE " . $tmpTableEscaped . " ("
. "`id` int(11) NOT NULL AUTO_INCREMENT, "
. "`text` text NOT NULL, "
. "PRIMARY KEY (`id`))", $errorMessages)
) {
$perms['create'] = DUPX_Validation_abstract_item::LV_PASS;
} else {
$perms['create'] = DUPX_Validation_abstract_item::LV_FAIL;
}
if ($perms['create']) {
if ($this->isQueryWorking("INSERT INTO " . $tmpTableEscaped . " (`text`) VALUES ('TEXT-1')", $errorMessages)) {
$perms['insert'] = DUPX_Validation_abstract_item::LV_PASS;
} else {
$perms['insert'] = DUPX_Validation_abstract_item::LV_FAIL;
}
if ($this->isQueryWorking("SELECT COUNT(*) FROM " . $tmpTableEscaped, $errorMessages)) {
$perms['select'] = DUPX_Validation_abstract_item::LV_PASS;
} else {
$perms['select'] = DUPX_Validation_abstract_item::LV_FAIL;
}
if ($this->isQueryWorking("UPDATE " . $tmpTableEscaped . " SET text = 'TEXT-2' WHERE text = 'TEXT-1'", $errorMessages)) {
$perms['update'] = DUPX_Validation_abstract_item::LV_PASS;
} else {
$perms['update'] = DUPX_Validation_abstract_item::LV_FAIL;
}
if ($this->isQueryWorking("DELETE FROM " . $tmpTableEscaped . " WHERE text = 'TEXT-2'", $errorMessages)) {
$perms['delete'] = DUPX_Validation_abstract_item::LV_PASS;
} else {
$perms['delete'] = DUPX_Validation_abstract_item::LV_FAIL;
}
if ($this->isQueryWorking("DROP TABLE IF EXISTS " . $tmpTableEscaped . ";", $errorMessages)) {
$perms['drop'] = DUPX_Validation_abstract_item::LV_PASS;
} else {
$perms['drop'] = DUPX_Validation_abstract_item::LV_FAIL;
}
}
if ($this->dbHasViews()) {
if ($this->dbCheckGrants(array("CREATE VIEW"), $errorMessages)) {
$perms['view'] = DUPX_Validation_abstract_item::LV_PASS;
} else {
$perms['view'] = DUPX_Validation_abstract_item::LV_HARD_WARNING;
}
}
if ($this->dbHasProcedures()) {
if ($this->dbCheckGrants(array("CREATE ROUTINE", "ALTER ROUTINE"), $errorMessages)) {
$perms['proc'] = DUPX_Validation_abstract_item::LV_PASS;
} else {
$perms['proc'] = DUPX_Validation_abstract_item::LV_HARD_WARNING;
}
}
if ($this->dbHasFunctions()) {
if ($this->dbCheckGrants(array("CREATE ROUTINE", "ALTER ROUTINE"), $errorMessages)) {
$perms['func'] = DUPX_Validation_abstract_item::LV_PASS;
} else {
$perms['func'] = DUPX_Validation_abstract_item::LV_HARD_WARNING;
}
}
if ($this->dbHasTriggers()) {
if ($this->dbCheckGrants(array("TRIGGER"), $errorMessages)) {
$perms['trigger'] = DUPX_Validation_abstract_item::LV_PASS;
} else {
$perms['trigger'] = DUPX_Validation_abstract_item::LV_SOFT_WARNING;
}
}
} catch (Exception $e) {
$errorMessages[] = $e->getMessage();
Log::logException($e, Log::LV_DEFAULT, 'DATABASE CHECK USER PERMS EXCEPTION: ');
} catch (Error $e) {
$errorMessages[] = $e->getMessage();
Log::logException($e, Log::LV_DEFAULT, 'DATABASE CHECK USER PERMS EXCEPTION: ');
}
return min($perms);
}
/**
*
* @param string $query The SQL query
* @param array $errorMessages Optionally you can capture the errors in this array
*
* @return boolean returns true if running the query did not fail
*/
public function isQueryWorking($query, &$errorMessages = array())
{
$result = true;
try {
if (DUPX_DB::mysqli_query($this->dbh, $query) === false) {
$currentError = mysqli_error($this->dbh);
$result = false;
}
} catch (Exception $e) {
$currentError = $e->getMessage();
Log::logException($e, Log::LV_DEFAULT, 'TESTING QUERY: ');
$result = false;
} catch (Error $e) {
$currentError = $e->getMessage();
Log::logException($e, Log::LV_DEFAULT, 'TESTING QUERY: ');
$result = false;
}
if ($result === false) {
$errorMessages[] = $currentError;
}
return $result;
}
/**
*
* @param array $grants // list of grants to check
* @param array $errorMessages
*
* @return boolean
*/
public function dbCheckGrants($grants, &$errorMessages = array())
{
try {
if (($queryResult = DUPX_DB::mysqli_query($this->dbh, "SHOW GRANTS")) === false) {
$errorMessages[] = mysqli_error($this->dbh);
return false;
}
$dbName = PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_NAME);
$regex = '/^GRANT\s+(?!USAGE)(.+)\s+ON\s+(\*|`.*?`)\..*$/';
$matches = null;
$matchFound = false;
while ($row = mysqli_fetch_array($queryResult)) {
if (!preg_match($regex, $row[0], $matches)) {
continue;
}
if (
$matches['2'] === '*' ||
$matches['2'] === $dbName ||
$matches['2'] === addcslashes($dbName, '_%')
) {
Log::info('SHOW GRANTS CURRENT DB: ' . $row[0], Log::LV_DEBUG);
$matchFound = true;
break;
}
//The GRANT queries can have wildcarsds in them which we have to take into account.
//Turn wildcards into regex expressions and try matching the expression against the DB name.
$dbNameRegex = preg_replace('/(?<!\\\\)%/', '.*', $matches['2']); // unescaped % becomes .*
$dbNameRegex = preg_replace('/(?<!\\\\)_/', '.', $dbNameRegex); // unescaped _ becomes .
if (preg_match($dbNameRegex, $dbName) === 1) {
Log::info('Grant matched via Wildcard: ' . $dbNameRegex, Log::LV_DEBUG);
Log::info('SHOW GRANTS CURRENT DB: ' . $row[0], Log::LV_DEBUG);
$matchFound = true;
break;
}
}
if (!$matchFound) {
Log::info('GRANTS LINE OF CURRENT DB NOT FOUND');
return false;
}
if ($matches['1'] === 'ALL PRIVILEGES') {
return true;
}
$userPrivileges = preg_split('/\s*,\s*/', $matches['1']);
if (($notGrants = array_diff($grants, $userPrivileges))) {
$message = "The mysql user does not have the '" . implode(', ', $notGrants) . "' permission.";
Log::info('NO GRANTS: ' . $message);
$errorMessages[] = $message;
return false;
} else {
return true;
}
} catch (Exception $e) {
$errorMessages[] = $e->getMessage();
Log::logException($e, Log::LV_DEFAULT, 'DATABASE CHECK PERM EXCEPTION: ');
return false;
}
return false;
}
public function dbHasProcedures()
{
if (DUPX_ArchiveConfig::getInstance()->dbInfo->procCount > 0) {
Log::info("SOURCE SITE DB HAD PROCEDURES", Log::LV_DEBUG);
return true;
}
if (($result = DUPX_DB::mysqli_query($this->dbh, "SHOW PROCEDURE STATUS"))) {
if (mysqli_num_rows($result) > 0) {
Log::info("INSTALL SITE HAS PROCEDURES", Log::LV_DEBUG);
return true;
}
}
return false;
}
public function dbHasFunctions()
{
if (DUPX_ArchiveConfig::getInstance()->dbInfo->funcCount > 0) {
Log::info("SOURCE SITE DB HAD FUNCTIONS", Log::LV_DEBUG);
return true;
}
if (($result = DUPX_DB::mysqli_query($this->dbh, "SHOW FUNCTION STATUS"))) {
if (mysqli_num_rows($result) > 0) {
Log::info("INSTALL SITE HAS FUNCTIONS", Log::LV_DEBUG);
return true;
}
}
return false;
}
public function dbHasTriggers()
{
if (($result = DUPX_DB::mysqli_query($this->dbh, "SHOW TRIGGERS"))) {
if (mysqli_num_rows($result) > 0) {
Log::info("INSTALL SITE HAS TRIGGERS", Log::LV_DEBUG);
return true;
}
}
return false;
}
public function dbHasViews()
{
if (DUPX_ArchiveConfig::getInstance()->dbInfo->viewCount > 0) {
Log::info("SOURCE SITE DB HAD VIEWS", Log::LV_DEBUG);
return true;
}
if (($result = DUPX_DB::mysqli_query($this->dbh, "SHOW FULL TABLES WHERE Table_Type = 'VIEW'"))) {
if (mysqli_num_rows($result) > 0) {
Log::info("INSTALL SITE HAS VIEWS", Log::LV_DEBUG);
return true;
}
}
return false;
}
public function dbGtidModeEnabled(&$errorMessage = array())
{
try {
$gtidModeEnabled = false;
if (($result = DUPX_DB::mysqli_query($this->dbh, 'SELECT @@GLOBAL.GTID_MODE', Log::LV_DEBUG)) === false) {
if (Log::isLevel(Log::LV_DEBUG)) {
// It is normal for this query to generate an error when the GTID is not active. So normally it is better not to worry users with managed error messages.
$errorMessage = mysqli_error($this->dbh);
}
} else {
if (($row = mysqli_fetch_array($result, MYSQLI_NUM)) !== false) {
if (strcasecmp($row[0], 'on') === 0) {
$gtidModeEnabled = true;
}
}
}
$result = $gtidModeEnabled;
} catch (Exception $e) {
$errorMessage = $e->getMessage();
Log::logException($e, Log::LV_DEFAULT, 'DATABASE CHECK CHARSET EXCEPTION: ');
$result = false;
} catch (Error $e) {
$errorMessage = $e->getMessage();
Log::logException($e, Log::LV_DEFAULT, 'DATABASE CHECK CHARSET EXCEPTION: ');
$result = false;
}
return $result;
}
/**
*
* @param string $errorMessage
*
* @return int // -1 fail
*/
public function caseSensitiveTablesValue(&$errorMessage = array())
{
try {
if (!$this->getDbConnection()) {
throw new Exception('Database not connected');
}
if (($lowerCaseTableNames = DUPX_DB::getVariable($this->dbh, 'lower_case_table_names')) === null) {
if (SnapOS::isWindows()) {
$lowerCaseTableNames = 1;
} elseif (SnapOS::isOSX()) {
$lowerCaseTableNames = 2;
} else {
$lowerCaseTableNames = 0;
}
}
$result = $lowerCaseTableNames;
} catch (Exception $e) {
$errorMessage = $e->getMessage();
Log::logException($e, Log::LV_DEFAULT, 'DATABASE CHECK CHARSET EXCEPTION: ');
$result = -1;
} catch (Error $e) {
$errorMessage = $e->getMessage();
Log::logException($e, Log::LV_DEFAULT, 'DATABASE CHECK CHARSET EXCEPTION: ');
$result = -1;
}
return (int) $result;
}
/**
* @return array|false
*/
public function getUserResources()
{
try {
$host = PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_HOST);
$user = PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_USER);
$query = "SELECT max_questions, max_updates, max_connections FROM mysql.user WHERE user = '{$user}' AND host = '{$host}'";
if (($result = DUPX_DB::mysqli_query($this->dbh, $query, Log::LV_DEFAULT)) != false && $result->num_rows > 0) {
return $result->fetch_assoc();
}
} catch (Exception $e) {
Log::logException($e, Log::LV_DEFAULT, 'DATABASE CHECK USER RESOURCE EXCEPTION: ');
} catch (Error $e) {
Log::logException($e, Log::LV_DEFAULT, 'DATABASE CHECK USER RESOURCE ERROR: ');
}
return false;
}
private function __clone()
{
}
}

View File

@@ -0,0 +1,296 @@
<?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.package.size.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.tokenizer.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.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.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.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');
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 = 1; // DUPX_Validation_abstract_item::LV_HARD_WARNING, can't assign directly in php 5.3
/**
*
* @var self
*/
private static $instance = null;
/**
*
* @var DUPX_Validation_abstract_item[]
*/
private $tests = array();
/**
*
* @var array
*/
private $extraData = array();
/**
*
* @return self
*/
public static function getInstance()
{
if (is_null(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
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_package_size(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_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);
/* 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_tokenizer(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_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);
}
/**
*
* @return boolean
*/
public static function isValidated()
{
$paramsManager = PrmMng::getInstance();
return $paramsManager->getValue(PrmMng::PARAM_VALIDATION_LEVEL) >= self::MIN_LEVEL_VALID;
}
/**
*
* @return boolean
*/
public static function isFirstValidationOnLoad()
{
return (
Bootstrap::isInit() &&
PrmMng::getInstance()->getValue(PrmMng::PARAM_VALIDATION_ACTION_ON_START) === DUPX_Validation_manager::ACTION_ON_START_AUTO
);
}
/**
*
* @return boolean
*/
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;
}
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
);
}
protected function runTests()
{
$this->extraData = array();
foreach ($this->tests as $test) {
$test->test(true);
}
}
protected function getValidationHtmlResult()
{
return dupxTplRender('parts/validation/validation-result', array(
'validationManager' => $this
), false);
}
/**
*
* @param string $key
* @param mixed $value
*/
public function addExtraData($key, $value)
{
$this->extraData[$key] = $value;
}
public function getTestsCategory($category)
{
$result = array();
foreach ($this->tests as $test) {
if ($test->getCategory() === $category) {
$result[] = $test;
}
}
return $result;
}
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;
}
public function getCagegoryBadge($category)
{
return DUPX_Validation_abstract_item::resultLevelToBadgeClass($this->getCagegoryResult($category));
}
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,96 @@
<?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\Descriptors\ParamDescUsers;
use Duplicator\Installer\Core\Params\PrmMng;
use Duplicator\Installer\Utils\Log\Log;
class DUPX_Validation_test_db_affected_tables extends DUPX_Validation_abstract_item
{
const MAX_DISPLAY_TABLE_COUNT = 1000;
private $affectedTableCount = 0;
private $affectedTables = array();
private $message = "";
private $isNewSubSite = false;
/**
* @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 listed below:";
} else {
$this->message = "{$partialText} tables flagged for <b>back-up and rename</b> are listed below:";
}
if ($this->affectedTableCount > 0) {
return self::LV_SOFT_WARNING;
}
return self::LV_PASS;
}
/**
* @return string
*/
public function getTitle()
{
return 'Tables Flagged for Removal or Backup';
}
/**
* @return void
*/
protected function passContent()
{
return dupxTplRender('parts/validation/database-tests/db-affected-tables', array(
'isOk' => true,
'isNewSubSite' => $this->isNewSubSite
), false);
}
/**
* @return void
*/
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 = array();
/** @var string[] */
protected $redundantTables = array();
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,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;
use Duplicator\Installer\Core\Params\PrmMng;
class DUPX_Validation_test_db_cleanup extends DUPX_Validation_abstract_item
{
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' => false,
'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' => false,
'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' => false,
'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' => false,
'dbname' => PrmMng::getInstance()->getValue(PrmMng::PARAM_DB_NAME)
), false);
}
}

View File

@@ -0,0 +1,52 @@
<?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
{
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,66 @@
<?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
{
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,68 @@
<?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;
protected $errorMessage = '';
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,
'minNumTables' > self::MIN_TABLES_NUM,
'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,
'minNumTables' > self::MIN_TABLES_NUM,
'errorMessage' => $this->errorMessage
), false);
}
}

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
*/
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
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) {
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 WordPress 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,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;
use Duplicator\Installer\Core\Params\PrmMng;
class DUPX_Validation_test_db_prefix_too_long extends DUPX_Validation_abstract_item
{
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,48 @@
<?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,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;
class DUPX_Validation_test_db_supported_charset extends DUPX_Validation_abstract_item
{
protected $errorMessage = '';
protected $charsetsList = array();
protected $collationsList = array();
protected $invalidCharsets = array();
protected $invalidCollations = array();
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,83 @@
<?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
{
protected $errorMessage = '';
protected $charsetOk = true;
protected $collateOk = true;
protected $sourceCharset = null;
protected $sourceCollate = null;
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;
}
}
public function getTitle()
{
return 'Character Set and Collation Support';
}
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);
}
protected function swarnContent()
{
return $this->failContent();
}
protected function passContent()
{
return $this->failContent();
}
}

View File

@@ -0,0 +1,66 @@
<?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
{
protected $errorMessage = '';
protected $invalidEngines = array();
protected $defaultEngine = "";
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();
if (empty($this->invalidEngines)) {
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 '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
), false);
}
protected function hwarnContent()
{
return $this->failContent();
}
protected function passContent()
{
return $this->failContent();
}
}

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_triggers extends DUPX_Validation_abstract_item
{
protected $triggers = array();
protected function runTest()
{
if (DUPX_Validation_database_service::getInstance()->skipDatabaseTests()) {
return self::LV_SKIP;
}
$this->triggers = (array)DUPX_ArchiveConfig::getInstance()->dbInfo->triggerList;
if (count($this->triggers) > 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' => $this->triggers,
), false);
}
protected function swarnContent()
{
return dupxTplRender('parts/validation/database-tests/db-triggers', array(
'isOk' => false,
'triggers' => $this->triggers,
), 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_user_perms extends DUPX_Validation_abstract_item
{
protected $perms = array();
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';
}
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);
}
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);
}
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);
}
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,61 @@
<?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
{
private $userResources = array();
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;
}
public function getTitle()
{
return 'Privileges: User Resources';
}
protected function passContent()
{
return dupxTplRender('parts/validation/database-tests/db-user-resources', array(
'isOk' => !$this->userHasRestrictedResource,
'userResources' => $this->userResources,
), false);
}
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,85 @@
<?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
{
protected $sourceDBVersion = null;
protected $hostDBVersion = null;
protected $hostDBEngine = null;
protected $sourceDBEngine = null;
protected $dbsOfSameType = true;
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;
}
public function getTitle()
{
return 'Database Version';
}
protected function failContent()
{
return dupxTplRender('parts/validation/database-tests/db-version', array(
'isOk' => false,
'hostDBVersion' => $this->hostDBVersion,
), false);
}
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);
}
protected function passContent()
{
return dupxTplRender('parts/validation/database-tests/db-version', array(
'isOk' => true,
'hostDBVersion' => $this->hostDBVersion,
), 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\Params\PrmMng;
class DUPX_Validation_test_db_visibility extends DUPX_Validation_abstract_item
{
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;
}
}
public function getTitle()
{
return 'Privileges: User Visibility';
}
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);
}
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_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,51 @@
<?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::isConfArkPresent()) {
if (DUPX_Conf_Utils::archiveExists()) {
return self::LV_PASS;
} else {
return self::LV_SOFT_WARNING;
}
} else {
return self::LV_FAIL;
}
}
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()->exportOnlyDB) {
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,66 @@
<?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\Installer\Models\ScanInfo;
use Duplicator\Libs\Snap\SnapIO;
class DUPX_Validation_test_disk_space extends DUPX_Validation_abstract_item
{
private $freeSpace = 0;
private $archiveSize = 0;
private $extractedSize = 0;
protected function runTest()
{
if (!function_exists('disk_free_space')) {
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 = @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,120 @@
<?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\Models\ScanInfo;
class DUPX_Validation_test_importable extends DUPX_Validation_abstract_item
{
/** @var string */
protected $failMessage = '';
/**
* Run test
*
* @return int test status enum
*/
protected function runTest()
{
if (DUPX_InstallerState::isClassicInstall()) {
return self::LV_SKIP;
}
$archiveConf = DUPX_ArchiveConfig::getInstance();
$coreFoldersCheck = false;
$subsitesCheck = false;
$globalTablesCheck = false;
switch (DUPX_InstallerState::getInstType()) {
case DUPX_InstallerState::INSTALL_SINGLE_SITE:
case DUPX_InstallerState::INSTALL_RBACKUP_SINGLE_SITE:
$coreFoldersCheck = true;
$globalTablesCheck = true;
break;
case DUPX_InstallerState::INSTALL_SINGLE_SITE_ON_SUBDOMAIN:
case DUPX_InstallerState::INSTALL_SINGLE_SITE_ON_SUBFOLDER:
$globalTablesCheck = true;
break;
case DUPX_InstallerState::INSTALL_NOT_SET:
default:
throw new Exception('Unknown mode');
}
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->failMessage = 'The package does not have any importable subsite.';
return self::LV_FAIL;
}
}
if ($coreFoldersCheck) {
if (ScanInfo::getInstance()->hasFilteredCoreFolders()) {
$this->failMessage = 'The package is missing WordPress core folder(s)! ' .
'It must include wp-admin, wp-content, wp-includes, uploads, plugins, and themes folders.';
return self::LV_FAIL;
}
}
if ($globalTablesCheck) {
if ($archiveConf->dbInfo->tablesBaseCount != $archiveConf->dbInfo->tablesFinalCount) {
$this->failMessage = 'The package is missing some of the site tables.';
return self::LV_FAIL;
}
}
return self::LV_PASS;
}
/**
* Get test title
*
* @return string
*/
public function getTitle()
{
return 'Package is Importable';
}
/**
* Render fail content
*
* @return void
*/
protected function failContent()
{
return dupxTplRender(
'parts/validation/tests/importable-package',
array(
'testResult' => $this->testResult,
'failMessage' => $this->failMessage
),
false
);
}
protected function passContent()
{
return $this->failContent();
}
}

View File

@@ -0,0 +1,61 @@
<?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\Params\PrmMng;
use Duplicator\Libs\Snap\SnapUtil;
class DUPX_Validation_test_importer_version extends DUPX_Validation_abstract_item
{
/**
*
* @return int
*/
protected function runTest()
{
if (!DUPX_InstallerState::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,136 @@
<?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_iswritable_configs extends DUPX_Validation_abstract_item
{
/**
*
* @var bool[]
*/
protected $configsCheck = array(
'wpconfig' => false,
'htaccess' => false,
'other' => false
);
/**
*
* @var string[]
*/
protected $notWritableConfigsList = array();
/**
*
* @var string
*/
protected function runTest()
{
$this->configsCheck = self::configsWritableChecks();
foreach ($this->configsCheck as $check) {
if ($check === false) {
if (
DUPX_InstallerState::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
*/
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,192 @@
<?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;
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 array */
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_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 (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_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,77 @@
<?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_managed_supported extends DUPX_Validation_abstract_item
{
private $managed = false;
private $failMessage = '';
protected function runTest()
{
if (!($this->managed = DUPX_Custom_Host_Manager::getInstance()->isManaged())) {
return self::LV_SKIP;
}
if (DUPX_InstallerState::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,51 @@
<?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,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\Libs\Snap\SnapUtil;
class DUPX_Validation_test_memory_limit extends DUPX_Validation_abstract_item
{
const MIN_MEMORY_LIMIT = '256M';
private $memoryLimit = false;
protected function runTest()
{
if (($this->memoryLimit = @ini_get('memory_limit')) === false || empty($this->memoryLimit)) {
return self::LV_SKIP;
}
$this->memoryLimit = is_numeric($this->memoryLimit) ? DUPX_U::readableByteSize($this->memoryLimit) : $this->memoryLimit;
if (SnapUtil::convertToBytes($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' => $this->memoryLimit,
'minMemoryLimit' => self::MIN_MEMORY_LIMIT,
'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,71 @@
<?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\SnapIO;
class DUPX_Validation_test_open_basedir extends DUPX_Validation_abstract_item
{
private $openBaseDirEnabled = false;
private $pathsOutsideOpenBaseDir = array();
protected function runTest()
{
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,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_owrinstall extends DUPX_Validation_abstract_item
{
protected function runTest()
{
if (
DUPX_InstallerState::getInstance()->getMode() !== DUPX_InstallerState::MODE_OVR_INSTALL ||
DUPX_InstallerState::isImportFromBackendMode()
) {
return self::LV_SKIP;
}
if (DUPX_InstallerState::getInstance()->getMode() === DUPX_InstallerState::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,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_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;
}
}
protected function getPackageDays()
{
return 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,51 @@
<?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_size extends DUPX_Validation_abstract_item
{
const PACKAGE_SIZE_BEFORE_WARNING_MB = 500;
private $packageSize = 0;
protected function runTest()
{
$this->packageSize = DUPX_Conf_Utils::archiveSize();
if ($this->packageSize <= self::PACKAGE_SIZE_BEFORE_WARNING_MB * 1024 * 1024) {
return self::LV_GOOD;
} else {
return self::LV_SOFT_WARNING;
}
}
public function getTitle()
{
return 'Package Size';
}
protected function swarnContent()
{
return dupxTplRender('parts/validation/tests/package-size', array(
'packageSize' => DUPX_U::readableByteSize($this->packageSize),
'maxPackageSize' => self::PACKAGE_SIZE_BEFORE_WARNING_MB
), false);
}
protected function goodContent()
{
return dupxTplRender('parts/validation/tests/package-size', array(
'packageSize' => DUPX_U::readableByteSize($this->packageSize),
'maxPackageSize' => self::PACKAGE_SIZE_BEFORE_WARNING_MB
), false);
}
}

View File

@@ -0,0 +1,75 @@
<?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
{
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,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;
class DUPX_Validation_test_php_version extends DUPX_Validation_abstract_item
{
protected function runTest()
{
$archiveConfig = DUPX_ArchiveConfig::getInstance();
if ($archiveConfig->exportOnlyDB) {
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 (DUPX_InstallerState::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,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;
use Duplicator\Installer\Core\Params\PrmMng;
class DUPX_Validation_test_recovery extends DUPX_Validation_abstract_item
{
protected $importSiteInfo = array();
protected $recoveryPage = false;
protected $importPage = false;
protected $recoveryIsOutToDate = false;
protected $recoveryPackageLife = -1;
protected function runTest()
{
$paramsManager = PrmMng::getInstance();
if (!DUPX_InstallerState::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 'Recovery Point';
}
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,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_replace_paths extends DUPX_Validation_abstract_item
{
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,75 @@
<?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\Params\PrmMng;
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
class DUPX_Validation_test_rest_api extends DUPX_Validation_abstract_item
{
protected $errorMessage = '';
protected $restUrl = '';
protected function runTest()
{
if (true) {
// REST API for future feathures
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 (DUPX_REST::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,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;
class DUPX_Validation_test_timeout extends DUPX_Validation_abstract_item
{
const MAX_TIME_SIZE = 314572800; //300MB
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,48 @@
<?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_tokenizer extends DUPX_Validation_abstract_item
{
protected function runTest()
{
if (function_exists('token_get_all')) {
return self::LV_PASS;
} else {
PrmMng::getInstance()->setValue(PrmMng::PARAM_WP_CONFIG, 'nothing');
PrmMng::getInstance()->save();
return self::LV_HARD_WARNING;
}
}
public function getTitle()
{
return 'PHP Tokenizer';
}
protected function hwarnContent()
{
return dupxTplRender('parts/validation/tests/tokenizer', array(
'isOk' => false
), false);
}
protected function passContent()
{
return dupxTplRender('parts/validation/tests/tokenizer', array(
'isOk' => true
), false);
}
}

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;
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
{
private $wordFencePath = "";
protected function runTest()
{
return $this->parentHasWordfence() ? self::LV_HARD_WARNING : self::LV_GOOD;
}
public function getTitle()
{
return 'Wordfence';
}
protected function swarnContent()
{
return dupxTplRender('parts/validation/tests/wordfence/wordfence-detected', array(
'wordFencePath' => $this->wordFencePath
), false);
}
protected function hwarnContent()
{
return dupxTplRender('parts/validation/tests/wordfence/wordfence-detected', array(
'wordFencePath' => $this->wordFencePath
), false);
}
protected function goodContent()
{
return dupxTplRender('parts/validation/tests/wordfence/wordfence-not-detected', array(), false);
}
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;
}
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,596 @@
<?php
/**
* Various html elements
*
* Standard: PSR-2
*
* @link http://www.php-fig.org/psr/psr-2 Full Documentation
*
* @package SC\DUPX\U
*/
use Duplicator\Installer\Utils\InstallerLinkManager;
defined('ABSPATH') || defined('DUPXABSPATH') || exit;
/**
* HTML Utils
*/
class DUPX_U_Html
{
protected static $uniqueId = 0;
/**
* initialize css for html elements
*/
public static function css()
{
self::lightBoxCss();
self::inputPasswordToggleCss();
self::checkboxSwitchCss();
}
/**
* initialize js for html elements
*/
public static function js()
{
self::lightBoxJs();
self::inputPasswordToggleJs();
}
private static function getUniqueId()
{
self::$uniqueId++;
return 'dup-html-id-' . self::$uniqueId . '-' . str_replace('.', '-', 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 $attrs
*
* @return string
*/
public static function arrayAttrToHtml($attrs)
{
$sttrsStr = array();
foreach ($attrs as $key => $val) {
$sttrsStr[] = $key . '="' . DUPX_U::esc_attr($val) . '"';
}
return implode(' ', $sttrsStr);
}
public static function getHeaderMain($htmlTitle)
{
?>
<div id="header-main-wrapper" >
<div class="dupx-modes">
<?php echo DUPX_InstallerState::getInstance()->getHtmlModeHeader(); ?>
</div>
<div class="dupx-logfile-link">
<?php DUPX_View_Funcs::installerLogLink(); ?>
</div>
<div class="hdr-main">
<?php echo $htmlTitle; ?>
</div>
</div>
<?php
}
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();
} else {
return ob_get_clean();
}
}
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);
}
protected static function lightBoxCss()
{
?>
<style>
.dup-ligthbox-link {
text-decoration: underline;
cursor: pointer;
}
.dub-ligthbox-content {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background-color: #FFFFFF;
background-color: rgba(255,255,255,0.95);
z-index: 999999;
overflow: hidden;
}
.dub-ligthbox-content.close {
width: 0;
height: 0;
}
.dub-ligthbox-content.open {
width: 100vw;
height: 100vh;
}
.dub-ligthbox-content > .wrapper {
width: 100vw;
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 {
height: 100%;
}
.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
}
protected static function lightBoxJs()
{
?>
<script>
$(document).ready(function ()
{
var currentLightboxOpen = null;
var toggleLightbox = function (target) {
if (target.hasClass('close')) {
target.animate({
height: "100vh",
width: "100vw"
}, 500, 'linear', function () {
$(this).removeClass('close').addClass('open').trigger('dup-lightbox-open');
currentLightboxOpen = target;
});
} else {
target.animate({
height: "0",
width: "0"
}, 500, 'linear', function () {
$(this).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]').click(function (event) {
event.stopPropagation();
var target = $('#' + $(this).data('dup-ligthbox'));
toggleLightbox(target);
});
$('.dub-ligthbox-content .toggle-auto-update').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').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
* @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
*
* @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>
<div class="more-faq-link">
<?php $url = InstallerLinkManager::getCategoryUrl(InstallerLinkManager::TROUBLESHOOTING_CAT, 'install', 'Technical FAQs'); ?>
Please search the <a href="<?php echo DUPX_U::esc_attr($url); ?>" target="_blank">Online Technical FAQs</a>
for solutions to these issues.
</div>
<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();
}
}
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
}
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
}
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
}
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
}
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,105 @@
<?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\Utils\Log\Log;
use Duplicator\Installer\Core\Params\PrmMng;
/**
* View functions
*/
class DUPX_View_Funcs
{
public static function installerLogLink($echo = true)
{
return DUPX_U_Html::getLightBoxIframe('installer-log.txt', 'installer-log.txt', Log::getLogFileUrl(), true, true, $echo);
}
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 = '';
}
return '?' . http_build_query(array(
PrmMng::PARAM_CTRL_ACTION => 'help',
DUPX_Security::CTRL_TOKEN => DUPX_CSRF::generate('help'),
'basic' => '',
'open_section' => $helpOpenSection
));
}
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();
} else {
return ob_get_clean();
}
}
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>');
}
}
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
*
* @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)));
}
}
}