Один драйвер MySQLi (Избавляемся от неиспользуемых драйверов БД)

17:33 9.01.2021
По просьбе участника сообщества, пытаюсь вспомнить все правки, что я провел, для избавления всех неиспользуемых драйверов Базы Данных. Сразу скажу, что я не вспомнил всех правок, поэтому будем добивать тему до полной победу.

Одна из самых важных правок, что я сделал, это заменил содержимое файла: "include/library/phpfox/database/database.class.php". Полный код файла (Для PHP 5.4 и выше | Версия PHPFOX 3.9.0):
<?php
phpfox::getLibClass('phpfox.database.dba');

class phpfox_database extends phpfox_database_dba
{
	public    $slaveServer;     // IP | Хост сервера
	protected $master  = null;  // Ресурс сервера MySQL
	protected $slave   = null;  // Ресурс подчиненного сервера MySQL
	protected $isSlave = false; // Проверка подключенных серверов

	public function __construct()
	{
		$this->connect(
		    phpfox::getParam(['db', 'host']), 
		    phpfox::getParam(['db', 'user']), 
			phpfox::getParam(['db', 'pass']), 
			phpfox::getParam(['db', 'name'])
		);
	}	

	public function connect($host, $user, $pass, $name, $port = false, $persistent = false)
	{
		if ($port)
		{
			$host = $host . ':' . $port;
		}

		$this->master = new mysqli($host, $user, $pass, $port, $persistent);
		$this->master->set_charset('utf8');

		# Unable to connect to master
		if ($this->master->connect_errno)
		{
			# Cannot connect to the database
			return phpfox_error::set('Cannot connect to the database: ' . $this->sqlerror());
		}

		# Check if we have any slave servers
		if (phpfox::getParam(['db', 'slave']))
		{
			# Get the slave array
			$ss = phpfox::getParam(['db', 'slave_servers']);

			# Get a random slave to use if there is more then one slave
			$iSlave = (count($ss) > 1 ? rand(0, (count($ss) - 1)) : 0);

			if (PHPFOX_DEBUG)
			{
				$this->slaveServer = $ss[$iSlave][0];
			}

			# Connect to slave
			$this->slave = $this->_connect(
			    $ss[$iSlave][0],
				$ss[$iSlave][1],
				$ss[$iSlave][2],
				$ss[$iSlave][3],
				$ss[$iSlave][4]
			);

			# Check if we were able to connect to the slave
			if ($this->slave)
			{
				if (!$this->master->select_db($name))
				{
					$this->slave = null;
				}
			}	
		}

		# If unable to connect to a slave or if no slave is called lets copy the master 
		if (!$this->slave)
		{
			$this->slave =& $this->master;
		}	

		# Attempt to connect to master table
		if (!$this->master->select_db($name))
		{
			return phpfox_error::set('Cannot connect to the database: ' . $this->sqlerror());
		}

		return true;
	}

	# Returns the MySQL version
	public function getVersion()
	{
		return $this->master->get_server_info();	
	}

	# Returns MySQL server information. Here we only identify that it is MySQL and the version being used.
	public function getServerInfo()
	{
		return 'MySQL ' . $this->getVersion();
	}	

    // Performs sql query with error reporting and logging.
	public function query($sql, &$link = '')
    {
		if (empty($link))
		{
			$link = $this->master;	
		}

    	(PHPFOX_DEBUG ? phpfox_debug::start('sql') : '');

    	$res = $link->query($sql); 	

        if (empty($res))
        {
        	phpfox_error::trigger('Query Error: ' . $this->sqlerror(), (PHPFOX_DEBUG ? E_USER_ERROR : E_USER_WARNING));
        }        

        (PHPFOX_DEBUG ? phpfox_debug::end('sql', [
		        'sql'   => $sql, 
				'slave' => $this->isSlave, 
				'rows'  => (is_bool($res) ? '-' : $res->num_rows)
			]) : ''
		);

        $this->isSlave = false;        

        return $res;
    }  

    # Prepares string to store in db (performs  addslashes())
    public function escape($param)
    {
        if (is_array($param))
        {
            return array_map(array(&$this, 'escape'), $param);
		}

        if (get_magic_quotes_gpc())
        {
            $param = stripslashes($param);
        }

        $param = $this->master->real_escape_string($param);

        return $param;
    }   

    # Returns row id from last executed query
    public function getLastId()
    {
        return $this->master->insert_id;
    }

    # Frees the MySQL results
    public function freeResult()
	{
		if (is_resource($this->rQuery))
		{
			$this->rQuery->free_result();
		}
	}

	# Returns the affected rows
	public function affectedRows()
	{
		return $this->master->affected_rows;
	}

	# MySQL has special search functions, so we try to use that here
	public function search($sType, $mFields, $sSearch)
	{
		switch ($sType)
		{
			case 'full':
				return "AND MATCH(" . implode(',', $mFields) . ") AGAINST ('+" . $this->escape($sSearch) . "' IN BOOLEAN MODE)";
			break;

			case 'like%':
				$sql = '';
				foreach ($mFields as $sField)
				{
					$sql .= "OR ". $sField . " LIKE '%" . $this->escape($sSearch) . "%' ";	
				}

				return 'AND (' . trim(ltrim(trim($sql), 'OR')) . ')';
			break;
		}		
	}

	# During development you may need to check how your queries are being executed and how long they are taking. This
	# routine uses MySQL's EXPLAIN to return useful information.
	public function sqlReport($query)
	{	
		$html = '';
		$explainQuery = $query;
		if (preg_match('/UPDATE ([a-z0-9_]+).*?WHERE(.*)/s', $query, $m))
		{
			$explainQuery = 'SELECT * FROM ' . $m[1] . ' WHERE ' . $m[2];
		}
		else if (preg_match('/DELETE FROM ([a-z0-9_]+).*?WHERE(.*)/s', $query, $m))
		{
			$explainQuery = 'SELECT * FROM ' . $m[1] . ' WHERE ' . $m[2];
		}

		$explainQuery = trim($explainQuery);
		if (preg_match('/SELECT/', $explainQuery))
		{
			$bTable = false;
			if ($result = $this->master->query("EXPLAIN $explainQuery"))
			{
				while ($aRow = $result->fetch_assoc())
				{					
					list ($bTable, $sData) = phpfox_debug::addRow($bTable, $aRow);
					$html .= $sData;
				}
			}

			$result->free_result();

			if ($bTable)
			{
				$html .= '</table>';
			}
		}

		return $html;
	}

	# Check if a field in the database is set to null
	public function isNull($sField)
	{
		return $sField . ' IS NULL';
	}

	# Check if a field in the database is set not null
	public function isNotNull($sField)
	{
		return $sField . ' IS NOT NULL';
	}	
	
	# Adds an index to a table
	public function addIndex($sTable, $sField)
	{
		$sql = 'ALTER TABLE ' . $sTable . ' ADD INDEX (' . $sField . ')';

		return $this->query($sql);
	}

	# Adds fields to a database table
	public function addField($aParams)
	{
		$sql = 'ALTER TABLE ' . $aParams['table'] . ' ADD ' . $aParams['field'] . ' ' . $aParams['type'] . '';
		if (isset($aParams['attribute']))
		{
			$sql .= ' ' . $aParams['attribute'] . ' ';
		}

		if (isset($aParams['null']))
		{
			$sql .= ' ' . ($aParams['null'] ? 'NULL' : 'NOT NULL') . ' ';
		}

		if (isset($aParams['default']))
		{
			$sql .= ' ' . $aParams['default'] . ' ';
		}

		return $this->query($sql);
	}

	# Drops a specific field from a table
	public function dropField($sTable, $sField)
	{
		return $this->query('ALTER TABLE ' . $sTable . ' DROP ' . $sField. '');
	}

	# Checks if a field already exists or not
	public function isField($sTable, $sField)
	{
		$aRows = $this->getRows("SHOW COLUMNS FROM {$sTable}");
		foreach ($aRows as $aRow)
		{
			if (strtolower($aRow['Field']) == strtolower($sField))
			{
				return true;
			}
		}

		return false;
	}

	# Checks if a field already exists or not.
	public function isIndex($sTable, $sField)
	{
		$aRows = $this->getRows("SHOW INDEX FROM {$sTable}");
		foreach ($aRows as $aRow)
		{
			if (strtolower($aRow['Key_name']) == strtolower($sField))
			{
				return true;
			}
		}

		return false;
	}

	# Returns the status of the table
	public function getTableStatus()
	{
		return $this->_getRows('SHOW TABLE STATUS', true, $this->master);
	}

	# Checks if a database table exists
	public function tableExists($sTable)
	{
		$aTables = $this->getTableStatus();
		foreach ($aTables as $aTable)
		{
			if ($aTable['Name'] == $sTable)
			{
				return true;
			}
		}

		return false;
	}

	# Optimizes a table
	public function optimizeTable($sTable)
	{
		return $this->query('OPTIMIZE TABLE ' . $this->escape($sTable));
	}

	# Repairs a table
	public function repairTable($sTable)
	{
		return $this->query('REPAIR TABLE ' . $this->escape($sTable));
	}	

	# Checks if we can backup the database or not. This depends on the server itself
	# We currently only support unix based servers
	public function canBackup()
	{
		return ((function_exists('exec') and $checkDump = str_replace('mysqldump:', '', exec('whereis mysqldump')) and !empty($checkDump)) ? true : false);
	}
	
    # Бэкап
	public function backup($sPath)
	{
		if (!is_dir($sPath))
		{
			return phpfox_error::set(phpfox::getPhrase('admincp.the_path_you_provided_is_not_a_valid_directory'));
		}

		if (!phpfox::getLib('file')->isWritable($sPath, true))
		{
			return phpfox_error::set(phpfox::getPhrase('admincp.the_path_you_provided_is_not_a_valid_directory'));
		}

		$sPath = rtrim($sPath, PHPFOX_DS) . PHPFOX_DS;
		$sFileName = uniqid() . '.sql';
		$sZipName = 'sql-backup-' . date('Y-d-m', PHPFOX_TIME) . '-' . uniqid() . '.tar.gz';

		shell_exec('mysqldump --skip-add-locks --disable-keys --skip-comments -h' . phpfox::getParam(['db', 'host']) . ' -u' . phpfox::getParam(['db', 'user']) . ' -p' . phpfox::getParam(['db', 'pass']) . ' ' . phpfox::getParam(['db', 'name']) . ' > ' . $sPath . $sFileName . '');
		chdir($sPath);
		shell_exec('tar -czf ' . $sZipName . ' ' . $sFileName . '');
		chdir(PHPFOX_DIR);
		unlink($sPath . $sFileName);

		return $sPath . $sZipName;
	}

    # Close the SQL connection
    public function close()
    {
        return $this->master->close();
    }	

	protected function _getRow($sql, $assoc, &$link)
    {
        $data = $this->query($sql, $link);
        if ($data)
		{
            $assoc = ($assoc ? MYSQLI_ASSOC : MYSQLI_NUM);
            $res   = $data->fetch_array($assoc);
		}

        return !empty($res) ? $res : [];
    } 

    protected function _getRows($sql, $assoc = true, $link)
    {
        $rows = [];		
        $this->rQuery = $this->query($sql, $link);
		if (!empty($this->rQuery))
		{
            $assoc = ($assoc ? MYSQLI_ASSOC : MYSQLI_NUM);		
            while ($row = $this->rQuery->fetch_array($assoc))
            {
                $rows[] = $row;
            }
		}

        return $rows;
    }

	private function sqlerror()
	{
		return $this->master->error;
	}	

	public function &getInstance()
	{
		return $this;
	}
}

Папку: "include/library/phpfox/database/drivers" я удалил, она больше не нужна.

После замены кода, возможно появятся ошибки (Включите отладчик), если будут ошибки, пишите их сюда.

Пожалуйста, если будите, пользоваться моими правками, напишите, как приживается код?