forked from LiveCarta/LiveCartaWP
Changed source root directory
This commit is contained in:
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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'];
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user