Initial commit

This commit is contained in:
2019-11-20 07:44:43 +01:00
commit 5bf49c4a81
41188 changed files with 5459177 additions and 0 deletions

View File

@@ -0,0 +1,730 @@
<?php
/**
* 2007-2016 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to https://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2016 PrestaShop SA
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
abstract class DbCore
{
/**
* Constants used by insert() method
*/
const INSERT = 1;
const INSERT_IGNORE = 2;
const REPLACE = 3;
/**
* @var string Server (eg. localhost)
*/
protected $server;
/**
* @var string Database user (eg. root)
*/
protected $user;
/**
* @var string Database password (eg. can be empty !)
*/
protected $password;
/**
* @var string Database name
*/
protected $database;
/**
* @var bool
*/
protected $is_cache_enabled;
/**
* @var mixed Ressource link
*/
protected $link;
/**
* @var mixed SQL cached result
*/
protected $result;
/**
* @var array List of DB instance
*/
protected static $instance = array();
/**
* @var array Object instance for singleton
*/
protected static $_servers = array(
array('server' => _DB_SERVER_, 'user' => _DB_USER_, 'password' => _DB_PASSWD_, 'database' => _DB_NAME_), /* MySQL Master server */
// Add here your slave(s) server(s)
// array('server' => '192.168.0.15', 'user' => 'rep', 'password' => '123456', 'database' => 'rep'),
// array('server' => '192.168.0.3', 'user' => 'myuser', 'password' => 'mypassword', 'database' => 'mydatabase'),
);
/**
* Store last executed query
*
* @var string
*/
protected $last_query;
/**
* Last cached query
*
* @var string
*/
protected $last_cached;
/**
* Open a connection
*/
abstract public function connect();
/**
* Close a connection
*/
abstract public function disconnect();
/**
* Execute a query and get result resource
*
* @param string $sql
* @return mixed
*/
abstract protected function _query($sql);
/**
* Get number of rows in a result
*
* @param mixed $result
*/
abstract protected function _numRows($result);
/**
* Get the ID generated from the previous INSERT operation
*/
abstract public function Insert_ID();
/**
* Get number of affected rows in previous database operation
*/
abstract public function Affected_Rows();
/**
* Get next row for a query which doesn't return an array
*
* @param mixed $result
*/
abstract public function nextRow($result = false);
/**
* Get database version
*
* @return string
*/
abstract public function getVersion();
/**
* Protect string against SQL injections
*
* @param string $str
* @return string
*/
abstract public function _escape($str);
/**
* Returns the text of the error message from previous database operation
*/
abstract public function getMsgError();
/**
* Returns the number of the error from previous database operation
*/
abstract public function getNumberError();
/* do not remove, useful for some modules */
abstract public function set_db($db_name);
/**
* Get Db object instance
*
* @param bool $master Decides whether the connection to be returned by the master server or the slave server
* @return Db instance
*/
public static function getInstance($master = true)
{
static $id = 0;
$total_servers = count(self::$_servers);
if ($master || $total_servers == 1)
$id_server = 0;
else
{
$id++;
$id_server = ($total_servers > 2 && ($id % $total_servers) != 0) ? $id : 1;
}
if (!isset(self::$instance[$id_server]))
{
$class = Db::getClass();
self::$instance[$id_server] = new $class(
self::$_servers[$id_server]['server'],
self::$_servers[$id_server]['user'],
self::$_servers[$id_server]['password'],
self::$_servers[$id_server]['database']
);
}
return self::$instance[$id_server];
}
/**
* Get child layer class
*
* @return string
*/
public static function getClass()
{
if (!defined('PHP_VERSION_ID'))
{
$version = explode('.', PHP_VERSION);
define('PHP_VERSION_ID', ($version[0] * 10000 + $version[1] * 100 + $version[2]));
}
$class = 'MySQL';
if (extension_loaded('mysql') && PHP_VERSION_ID < 50500)
$class = 'MySQL';
elseif (extension_loaded('mysqli') && (PHP_VERSION_ID < 50300 || extension_loaded('mysqlnd')))
$class = 'DbMySQLi';
elseif (PHP_VERSION_ID >= 50200 && extension_loaded('pdo_mysql'))
$class = 'DbPDO';
return $class;
}
/**
* Instantiate database connection
*
* @param string $server Server address
* @param string $user User login
* @param string $password User password
* @param string $database Database name
* @param bool $connect If false, don't connect in constructor (since 1.5.0)
*/
public function __construct($server, $user, $password, $database, $connect = true)
{
$this->server = $server;
$this->user = $user;
$this->password = $password;
$this->database = $database;
$this->is_cache_enabled = (defined('_PS_CACHE_ENABLED_')) ? _PS_CACHE_ENABLED_ : false;
if (!defined('_PS_DEBUG_SQL_'))
define('_PS_DEBUG_SQL_', false);
if (!defined('_PS_MAGIC_QUOTES_GPC_'))
define('_PS_MAGIC_QUOTES_GPC_', get_magic_quotes_gpc());
if ($connect)
$this->connect();
}
/**
* Close connection to database
*/
public function __destruct()
{
if ($this->link)
$this->disconnect();
}
/**
* @deprecated 1.5.0 use insert() or update() method instead
*/
public function autoExecute($table, $data, $type, $where = '', $limit = 0, $use_cache = true, $use_null = false)
{
$type = strtoupper($type);
switch ($type)
{
case 'INSERT' :
return $this->insert($table, $data, $use_null, $use_cache, Db::INSERT, false);
case 'INSERT IGNORE' :
return $this->insert($table, $data, $use_null, $use_cache, Db::INSERT_IGNORE, false);
case 'REPLACE' :
return $this->insert($table, $data, $use_null, $use_cache, Db::REPLACE, false);
case 'UPDATE' :
return $this->update($table, $data, $where, $limit, $use_null, $use_cache, false);
default :
Tools14::displayError('Wrong argument (miss type) in Db::autoExecute()');
exit();
break;
}
}
/**
* Filter SQL query within a blacklist
*
* @param string $table Table where insert/update data
* @param string $values Data to insert/update
* @param string $type INSERT or UPDATE
* @param string $where WHERE clause, only for UPDATE (optional)
* @param int $limit LIMIT clause (optional)
* @return mixed|boolean SQL query result
*/
public function autoExecuteWithNullValues($table, $values, $type, $where = '', $limit = 0)
{
return $this->autoExecute($table, $values, $type, $where, $limit, 0, true);
}
/**
* Execute a query and get result ressource
*
* @param string $sql
* @return mixed
*/
public function query($sql)
{
if ($sql instanceof DbQuery)
$sql = $sql->build();
$this->result = $this->_query($sql);
if (_PS_DEBUG_SQL_)
$this->displayError($sql);
return $this->result;
}
/**
* Execute an INSERT query
*
* @param string $table Table name without prefix
* @param array $data Data to insert as associative array. If $data is a list of arrays, multiple insert will be done
* @param bool $null_values If we want to use NULL values instead of empty quotes
* @param bool $use_cache
* @param int $type Must be Db::INSERT or Db::INSERT_IGNORE or Db::REPLACE
* @param bool $add_prefix Add or not _DB_PREFIX_ before table name
* @return bool
*/
public function insert($table, $data, $null_values = false, $use_cache = true, $type = Db::INSERT, $add_prefix = true)
{
if (!$data && !$null_values)
return true;
if ($add_prefix)
$table = _DB_PREFIX_.$table;
if ($type == Db::INSERT)
$insert_keyword = 'INSERT';
else if ($type == Db::INSERT_IGNORE)
$insert_keyword = 'INSERT IGNORE';
else if ($type == Db::REPLACE)
$insert_keyword = 'REPLACE';
else
{
Tools14::displayError('Bad keyword, must be Db::INSERT or Db::INSERT_IGNORE or Db::REPLACE');
exit();
}
// Check if $data is a list of row
$current = current($data);
if (!is_array($current) || isset($current['type']))
$data = array($data);
$keys = array();
$values_stringified = array();
foreach ($data as $row_data)
{
$values = array();
foreach ($row_data as $key => $value)
{
if (isset($keys_stringified))
{
// Check if row array mapping are the same
if (!in_array("`$key`", $keys))
{
Tools14::displayError('Keys form $data subarray don\'t match');
exit();
}
}
else
$keys[] = "`$key`";
if (!is_array($value))
$value = array('type' => 'text', 'value' => $value);
if ($value['type'] == 'sql')
$values[] = $value['value'];
else
$values[] = $null_values && ($value['value'] === '' || is_null($value['value'])) ? 'NULL' : "'{$value['value']}'";
}
$keys_stringified = implode(', ', $keys);
$values_stringified[] = '('.implode(', ', $values).')';
}
$sql = $insert_keyword.' INTO `'.$table.'` ('.$keys_stringified.') VALUES '.implode(', ', $values_stringified);
return (bool)$this->q($sql, $use_cache);
}
/**
* @param string $table Table name without prefix
* @param array $data Data to insert as associative array. If $data is a list of arrays, multiple insert will be done
* @param string $where WHERE condition
* @param int $limit
* @param bool $null_values If we want to use NULL values instead of empty quotes
* @param bool $use_cache
* @param bool $add_prefix Add or not _DB_PREFIX_ before table name
* @return bool
*/
public function update($table, $data, $where = '', $limit = 0, $null_values = false, $use_cache = true, $add_prefix = true)
{
if (!$data)
return true;
if ($add_prefix)
$table = _DB_PREFIX_.$table;
$sql = 'UPDATE `'.$table.'` SET ';
foreach ($data as $key => $value)
{
if (!is_array($value))
$value = array('type' => 'text', 'value' => $value);
if ($value['type'] == 'sql')
$sql .= "`$key` = {$value['value']},";
else
$sql .= ($null_values && ($value['value'] === '' || is_null($value['value']))) ? "`$key` = NULL," : "`$key` = '{$value['value']}',";
}
$sql = rtrim($sql, ',');
if ($where)
$sql .= ' WHERE '.$where;
if ($limit)
$sql .= ' LIMIT '.(int)$limit;
return (bool)$this->q($sql, $use_cache);
}
/**
* Execute a DELETE query
*
* @param string $table Name of the table to delete
* @param string $where WHERE clause on query
* @param int $limit Number max of rows to delete
* @param bool $use_cache Use cache or not
* @param bool $add_prefix Add or not _DB_PREFIX_ before table name
* @return bool
*/
public function delete($table, $where = '', $limit = 0, $use_cache = true, $add_prefix = true)
{
if (_DB_PREFIX_ && !preg_match('#^'._DB_PREFIX_.'#i', $table) && $add_prefix)
$table = _DB_PREFIX_.$table;
$this->result = false;
$sql = 'DELETE FROM `'.bqSQL($table).'`'.($where ? ' WHERE '.$where : '').($limit ? ' LIMIT '.(int)$limit : '');
$res = $this->query($sql);
if ($use_cache && $this->is_cache_enabled)
Cache::getInstance()->deleteQuery($sql);
return (bool)$res;
}
/**
* Execute a query
*
* @param string $sql
* @param bool $use_cache
* @return bool
*/
public function execute($sql, $use_cache = true)
{
if ($sql instanceof DbQuery)
$sql = $sql->build();
if (trim($sql) == false)
return ($this->result = true);
$this->result = $this->query($sql);
if ($use_cache && $this->is_cache_enabled)
Cache::getInstance()->deleteQuery($sql);
return (bool)$this->result;
}
/**
* ExecuteS return the result of $sql as array
*
* @param string $sql query to execute
* @param boolean $array return an array instead of a mysql_result object (deprecated since 1.5.0, use query method instead)
* @param bool $use_cache if query has been already executed, use its result
* @return array or result object
*/
public function executeS($sql, $array = true, $use_cache = true)
{
if ($sql instanceof DbQuery)
$sql = $sql->build();
// This method must be used only with queries which display results
if (!preg_match('#^\s*\(?\s*(select|show|explain|describe|desc)\s#i', $sql))
{
if (defined('_PS_MODE_DEV_') && _PS_MODE_DEV_)
{
Tools14::displayError('Db->executeS() must be used only with select, show, explain or describe queries');
exit();
}
return $this->execute($sql, $use_cache);
}
$this->result = false;
$this->last_query = $sql;
if ($use_cache && $this->is_cache_enabled && $array && ($result = Cache::getInstance()->get(md5($sql))))
{
$this->last_cached = true;
return $result;
}
$this->result = $this->query($sql);
if (!$this->result)
return false;
$this->last_cached = false;
if (!$array)
return $this->result;
$result_array = array();
while ($row = $this->nextRow($this->result))
$result_array[] = $row;
if ($use_cache && $this->is_cache_enabled)
Cache::getInstance()->setQuery($sql, $result_array);
return $result_array;
}
/**
* getRow return an associative array containing the first row of the query
* This function automatically add "limit 1" to the query
*
* @param mixed $sql the select query (without "LIMIT 1")
* @param bool $use_cache find it in cache first
* @return array associative array of (field=>value)
*/
public function getRow($sql, $use_cache = true)
{
if ($sql instanceof DbQuery)
$sql = $sql->build();
$sql .= ' LIMIT 1';
$this->result = false;
$this->last_query = $sql;
if ($use_cache && $this->is_cache_enabled && ($result = Cache::getInstance()->get(md5($sql))))
{
$this->last_cached = true;
return $result;
}
$this->result = $this->query($sql);
if (!$this->result)
return false;
$this->last_cached = false;
$result = $this->nextRow($this->result);
if ($use_cache && $this->is_cache_enabled)
Cache::getInstance()->setQuery($sql, $result);
return $result;
}
/**
* getValue return the first item of a select query.
*
* @param mixed $sql
* @param bool $use_cache
* @return mixed
*/
public function getValue($sql, $use_cache = true)
{
if ($sql instanceof DbQuery)
$sql = $sql->build();
if (!$result = $this->getRow($sql, $use_cache))
return false;
return array_shift($result);
}
/**
* Get number of rows for last result
*
* @return int
*/
public function numRows()
{
if (!$this->last_cached && $this->result)
{
$nrows = $this->_numRows($this->result);
if ($this->is_cache_enabled)
Cache::getInstance()->set(md5($this->last_query).'_nrows', $nrows);
return $nrows;
}
else if ($this->is_cache_enabled && $this->last_cached)
return Cache::getInstance()->get(md5($this->last_query).'_nrows');
}
/**
*
* Execute a query
*
* @param string $sql
* @param bool $use_cache
* @return mixed $result
*/
protected function q($sql, $use_cache = true)
{
if ($sql instanceof DbQuery)
$sql = $sql->build();
$this->result = false;
$result = $this->query($sql);
if ($use_cache && $this->is_cache_enabled)
Cache::getInstance()->deleteQuery($sql);
return $result;
}
/**
* Display last SQL error
*
* @param bool $sql
*/
public function displayError($sql = false)
{
global $webservice_call;
$errno = $this->getNumberError();
if ($webservice_call && $errno)
{
$dbg = debug_backtrace();
WebserviceRequest::getInstance()->setError(500, '[SQL Error] '.$this->getMsgError().'. From '.(isset($dbg[3]['class']) ? $dbg[3]['class'] : '').'->'.$dbg[3]['function'].'() Query was : '.$sql, 97);
}
else if (_PS_DEBUG_SQL_ && $errno && !defined('PS_INSTALLATION_IN_PROGRESS'))
{
if ($sql)
Tools14::displayError($this->getMsgError().'<br /><br /><pre>'.$sql.'</pre>');
Tools14::displayError($this->getMsgError());
exit();
}
}
/**
* Sanitize data which will be injected into SQL query
*
* @param string $string SQL data which will be injected into SQL query
* @param boolean $html_ok Does data contain HTML code ? (optional)
* @return string Sanitized data
*/
public function escape($string, $html_ok = false)
{
if (_PS_MAGIC_QUOTES_GPC_)
$string = stripslashes($string);
if (!is_numeric($string))
{
$string = $this->_escape($string);
if (!$html_ok)
$string = strip_tags(Tools14::nl2br($string));
}
return $string;
}
/**
* Try a connection to te database
*
* @param string $server Server address
* @param string $user Login for database connection
* @param string $pwd Password for database connection
* @param string $db Database name
* @param bool $new_db_link
* @param bool $engine
* @return int
*/
public static function checkConnection($server, $user, $pwd, $db, $new_db_link = true, $engine = null, $timeout = 5)
{
return call_user_func_array(array(Db::getClass(), 'tryToConnect'), array($server, $user, $pwd, $db, $new_db_link, $engine, $timeout));
}
/**
* Try a connection to te database
*
* @param string $server Server address
* @param string $user Login for database connection
* @param string $pwd Password for database connection
* @return int
*/
public static function checkEncoding($server, $user, $pwd)
{
return call_user_func_array(array(Db::getClass(), 'tryUTF8'), array($server, $user, $pwd));
}
/**
* Try a connection to the database and check if at least one table with same prefix exists
*
* @param string $server Server address
* @param string $user Login for database connection
* @param string $pwd Password for database connection
* @param string $db Database name
* @param string $prefix Tables prefix
* @return bool
*/
public static function hasTableWithSamePrefix($server, $user, $pwd, $db, $prefix)
{
return call_user_func_array(array(Db::getClass(), 'hasTableWithSamePrefix'), array($server, $user, $pwd, $db, $prefix));
}
public static function checkCreatePrivilege($server, $user, $pwd, $db, $prefix, $engine)
{
return call_user_func_array(array(Db::getClass(), 'checkCreatePrivilege'), array($server, $user, $pwd, $db, $prefix, $engine));
}
/**
* @deprecated 1.5.0
*/
public static function s($sql, $use_cache = true)
{
return Db::getInstance()->executeS($sql, true, $use_cache);
}
/**
* @deprecated 1.5.0
*/
public static function ps($sql, $use_cache = 1)
{
$ret = Db::s($sql, $use_cache);
p($ret);
return $ret;
}
/**
* @deprecated 1.5.0
*/
public static function ds($sql, $use_cache = 1)
{
Db::s($sql, $use_cache);
die();
}
}

View File

@@ -0,0 +1,247 @@
<?php
/**
* 2007-2016 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to https://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2016 PrestaShop SA
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* @since 1.5.0
*/
class DbMySQLiCore extends Db
{
/**
* @see DbCore::connect()
*/
public function connect()
{
$socket = false;
$port = false;
if (strpos($this->server, ':') !== false)
{
list($server, $port) = explode(':', $this->server);
if (is_numeric($port) === false)
{
$socket = $port;
$port = false;
}
}
elseif (strpos($this->server, '/') !== false)
{
$socket = $this->server;
}
if ($socket)
{
$this->link = @new mysqli(null, $this->user, $this->password, $this->database, null, $socket);
}
elseif ($port)
{
$this->link = @new mysqli($server, $this->user, $this->password, $this->database, $port);
}
else
{
$this->link = @new mysqli($this->server, $this->user, $this->password, $this->database);
}
// Do not use object way for error because this work bad before PHP 5.2.9
if (mysqli_connect_error())
{
Tools14::displayError(sprintf(Tools14::displayError('Link to database cannot be established: %s'), mysqli_connect_error()));
exit();
}
// UTF-8 support
if (!$this->link->query('SET NAMES \'utf8\''))
{
Tools14::displayError(Tools14::displayError('PrestaShop Fatal error: no utf-8 support. Please check your server configuration.'));
exit();
}
return $this->link;
}
/**
* @see DbCore::disconnect()
*/
public function disconnect()
{
@$this->link->close();
}
/**
* @see DbCore::_query()
*/
protected function _query($sql)
{
return $this->link->query($sql);
}
/**
* @see DbCore::nextRow()
*/
public function nextRow($result = false)
{
if (!$result)
$result = $this->result;
if (!is_object($result))
return false;
return $result->fetch_assoc();
}
/**
* @see DbCore::_numRows()
*/
protected function _numRows($result)
{
return $result->num_rows;
}
/**
* @see DbCore::Insert_ID()
*/
public function Insert_ID()
{
return $this->link->insert_id;
}
/**
* @see DbCore::Affected_Rows()
*/
public function Affected_Rows()
{
return $this->link->affected_rows;
}
/**
* @see DbCore::getMsgError()
*/
public function getMsgError($query = false)
{
return $this->link->error;
}
/**
* @see DbCore::getNumberError()
*/
public function getNumberError()
{
return $this->link->errno;
}
/**
* @see DbCore::getVersion()
*/
public function getVersion()
{
return $this->getValue('SELECT VERSION()');
}
/**
* @see DbCore::_escape()
*/
public function _escape($str)
{
return $this->link->real_escape_string($str);
}
/**
* @see DbCore::set_db()
*/
public function set_db($db_name)
{
return $this->link->query('USE '.pSQL($db_name));
}
/**
* @see Db::hasTableWithSamePrefix()
*/
public static function hasTableWithSamePrefix($server, $user, $pwd, $db, $prefix)
{
$link = @new mysqli($server, $user, $pwd, $db);
if (mysqli_connect_error())
return false;
$sql = 'SHOW TABLES LIKE \''.$prefix.'%\'';
$result = $link->query($sql);
return (bool)$result->fetch_assoc();
}
/**
* @see Db::checkConnection()
*/
public static function tryToConnect($server, $user, $pwd, $db, $newDbLink = true, $engine = null, $timeout = 5)
{
$link = mysqli_init();
if (!$link)
return -1;
if (!$link->options(MYSQLI_OPT_CONNECT_TIMEOUT, $timeout))
return 1;
if (!$link->real_connect($server, $user, $pwd, $db))
return (mysqli_connect_errno() == 1049) ? 2 : 1;
if (strtolower($engine) == 'innodb')
{
$sql = 'SHOW VARIABLES WHERE Variable_name = \'have_innodb\'';
$result = $link->query($sql);
if (!$result)
return 4;
$row = $result->fetch_assoc();
if (!$row || strtolower($row['Value']) != 'yes')
return 4;
}
$link->close();
return 0;
}
public static function checkCreatePrivilege($server, $user, $pwd, $db, $prefix, $engine)
{
$link = @new mysqli($server, $user, $pwd, $db);
if (mysqli_connect_error())
return false;
$sql = '
CREATE TABLE `'.$prefix.'test` (
`test` tinyint(1) unsigned NOT NULL
) ENGINE=MyISAM';
$result = $link->query($sql);
if (!$result)
return $link->error;
$link->query('DROP TABLE `'.$prefix.'test`');
return true;
}
/**
* @see Db::checkEncoding()
*/
static public function tryUTF8($server, $user, $pwd)
{
$link = @new mysqli($server, $user, $pwd, $db);
$ret = $link->query("SET NAMES 'UTF8'");
$link->close();
return $ret;
}
}

View File

@@ -0,0 +1,245 @@
<?php
/**
* 2007-2016 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to https://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2016 PrestaShop SA
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* This class is currently only here for tests
*
* @since 1.5.0
*/
class DbPDOCore extends Db
{
protected static function _getPDO($host, $user, $password, $dbname, $timeout = 5)
{
$dsn = 'mysql:';
if ($dbname)
$dsn .= 'dbname='.$dbname.';';
if (preg_match('/^(.*):([0-9]+)$/', $host, $matches))
$dsn .= 'host='.$matches[1].';port='.$matches[2];
elseif (preg_match('#^.*:(/.*)$#', $host, $matches))
$dsn .= 'unix_socket='.$matches[1];
else
$dsn .= 'host='.$host;
return new PDO($dsn, $user, $password, array(PDO::ATTR_TIMEOUT => $timeout, PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true));
}
/**
* @see DbCore::connect()
*/
public function connect()
{
try {
$this->link = $this->_getPDO($this->server, $this->user, $this->password, $this->database, 5);
} catch (PDOException $e) {
die(sprintf(Tools14::displayError('Link to database cannot be established: %s'), $e->getMessage()));
exit();
}
// UTF-8 support
if (!is_object($this->link) || $this->link->exec('SET NAMES \'utf8\'') === false)
{
Tools14::displayError('PrestaShop Fatal error: no utf-8 support. Please check your server configuration.');
exit();
}
return $this->link;
}
/**
* @see DbCore::disconnect()
*/
public function disconnect()
{
unset($this->link);
}
/**
* @see DbCore::_query()
*/
protected function _query($sql)
{
return $this->link->query($sql);
}
/**
* @see DbCore::nextRow()
*/
public function nextRow($result = false)
{
if (!$result)
$result = $this->result;
if (!is_object($result))
return false;
return $result->fetch(PDO::FETCH_ASSOC);
}
/**
* @see DbCore::_numRows()
*/
protected function _numRows($result)
{
return $result->rowCount();
}
/**
* @see DbCore::Insert_ID()
*/
public function Insert_ID()
{
return $this->link->lastInsertId();
}
/**
* @see DbCore::Affected_Rows()
*/
public function Affected_Rows()
{
return $this->result->rowCount();
}
/**
* @see DbCore::getMsgError()
*/
public function getMsgError($query = false)
{
$error = $this->link->errorInfo();
return ($error[0] == '00000') ? '' : $error[2];
}
/**
* @see DbCore::getNumberError()
*/
public function getNumberError()
{
$error = $this->link->errorInfo();
return isset($error[1]) ? $error[1] : 0;
}
/**
* @see DbCore::getVersion()
*/
public function getVersion()
{
return $this->getValue('SELECT VERSION()');
}
/**
* @see DbCore::_escape()
*/
public function _escape($str)
{
$search = array("\\", "\0", "\n", "\r", "\x1a", "'", '"');
$replace = array("\\\\", "\\0", "\\n", "\\r", "\Z", "\'", '\"');
return str_replace($search, $replace, $str);
}
/**
* @see DbCore::set_db()
*/
public function set_db($db_name)
{
return $this->link->exec('USE '.pSQL($db_name));
}
/**
* @see Db::hasTableWithSamePrefix()
*/
public static function hasTableWithSamePrefix($server, $user, $pwd, $db, $prefix)
{
try {
$link = DbPDO::_getPDO($server, $user, $pwd, $db, 5);
} catch (PDOException $e) {
return false;
}
$sql = 'SHOW TABLES LIKE \''.$prefix.'%\'';
$result = $link->query($sql);
return (bool)$result->fetch();
}
public static function checkCreatePrivilege($server, $user, $pwd, $db, $prefix, $engine)
{
try {
$link = DbPDO::_getPDO($server, $user, $pwd, $db, 5);
} catch (PDOException $e) {
return false;
}
$sql = '
CREATE TABLE `'.$prefix.'test` (
`test` tinyint(1) unsigned NOT NULL
) ENGINE=MyISAM';
$result = $link->query($sql);
if (!$result)
{
$error = $link->errorInfo();
return $error[2];
}
$link->query('DROP TABLE `'.$prefix.'test`');
return true;
}
/**
* @see Db::checkConnection()
*/
public static function tryToConnect($server, $user, $pwd, $db, $newDbLink = true, $engine = null, $timeout = 5)
{
try {
$link = DbPDO::_getPDO($server, $user, $pwd, $db, $timeout);
} catch (PDOException $e) {
return ($e->getCode() == 1049) ? 2 : 1;
}
if (strtolower($engine) == 'innodb')
{
$sql = 'SHOW VARIABLES WHERE Variable_name = \'have_innodb\'';
$result = $link->query($sql);
if (!$result)
return 4;
$row = $result->fetch();
if (!$row || strtolower($row['Value']) != 'yes')
return 4;
}
unset($link);
return 0;
}
/**
* @see Db::checkEncoding()
*/
public static function tryUTF8($server, $user, $pwd)
{
try {
$link = DbPDO::_getPDO($server, $user, $pwd, false, 5);
} catch (PDOException $e) {
return false;
}
$result = $link->exec('SET NAMES \'utf8\'');
unset($link);
return ($result === false) ? false : true;
}
}

View File

@@ -0,0 +1,254 @@
<?php
/**
* 2007-2016 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to https://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2016 PrestaShop SA
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* SQL query builder
*
* @since 1.5.0
*/
class DbQueryCore
{
/**
* @var array list of data to build the query
*/
protected $query = array(
'select' => array(),
'from' => array(),
'join' => array(),
'where' => array(),
'group' => array(),
'having' => array(),
'order' => array(),
'limit' => array('offset' => 0, 'limit' => 0),
);
/**
* Add fields in query selection
*
* @param string $fields List of fields to concat to other fields
* @return DbQuery
*/
public function select($fields)
{
if (!empty($fields))
$this->query['select'][] = $fields;
return $this;
}
/**
* Set table for FROM clause
*
* @param string $table Table name
* @return DbQuery
*/
public function from($table, $alias = null)
{
if (!empty($table))
$this->query['from'][] = '`'._DB_PREFIX_.$table.'`'.($alias ? ' '.$alias : '');
return $this;
}
/**
* Add JOIN clause
* E.g. $this->join('RIGHT JOIN '._DB_PREFIX_.'product p ON ...');
*
* @param string $join Complete string
* @return DbQuery
*/
public function join($join)
{
if (!empty($join))
$this->query['join'][] = $join;
return $this;
}
/**
* Add LEFT JOIN clause
*
* @param string $table Table name (without prefix)
* @param string $alias Table alias
* @param string $on ON clause
*/
public function leftJoin($table, $alias = null, $on = null)
{
return $this->join('LEFT JOIN `'._DB_PREFIX_.bqSQL($table).'`'.($alias ? ' `'.pSQL($alias).'`' : '').($on ? ' ON '.$on : ''));
}
/**
* Add INNER JOIN clause
* E.g. $this->innerJoin('product p ON ...')
*
* @param string $table Table name (without prefix)
* @param string $alias Table alias
* @param string $on ON clause
*/
public function innerJoin($table, $alias = null, $on = null)
{
return $this->join('INNER JOIN `'._DB_PREFIX_.bqSQL($table).'`'.($alias ? ' '.pSQL($alias) : '').($on ? ' ON '.$on : ''));
}
/**
* Add LEFT OUTER JOIN clause
*
* @param string $table Table name (without prefix)
* @param string $alias Table alias
* @param string $on ON clause
*/
public function leftOuterJoin($table, $alias = null, $on = null)
{
return $this->join('LEFT OUTER JOIN `'._DB_PREFIX_.bqSQL($table).'`'.($alias ? ' '.pSQL($alias) : '').($on ? ' ON '.$on : ''));
}
/**
* Add NATURAL JOIN clause
*
* @param string $table Table name (without prefix)
* @param string $alias Table alias
*/
public function naturalJoin($table, $alias = null)
{
return $this->join('NATURAL JOIN `'._DB_PREFIX_.bqSQL($table).'`'.($alias ? ' '.pSQL($alias) : ''));
}
/**
* Add a restriction in WHERE clause (each restriction will be separated by AND statement)
*
* @param string $restriction
* @return DbQuery
*/
public function where($restriction)
{
if (!empty($restriction))
$this->query['where'][] = $restriction;
return $this;
}
/**
* Add a restriction in HAVING clause (each restriction will be separated by AND statement)
*
* @param string $restriction
* @return DbQuery
*/
public function having($restriction)
{
if (!empty($restriction))
$this->query['having'][] = $restriction;
return $this;
}
/**
* Add an ORDER B restriction
*
* @param string $fields List of fields to sort. E.g. $this->order('myField, b.mySecondField DESC')
* @return DbQuery
*/
public function orderBy($fields)
{
if (!empty($fields))
$this->query['order'][] = $fields;
return $this;
}
/**
* Add a GROUP BY restriction
*
* @param string $fields List of fields to sort. E.g. $this->group('myField, b.mySecondField DESC')
* @return DbQuery
*/
public function groupBy($fields)
{
if (!empty($fields))
$this->query['group'][] = $fields;
return $this;
}
/**
* Limit results in query
*
* @param string $fields List of fields to sort. E.g. $this->order('myField, b.mySecondField DESC')
* @return DbQuery
*/
public function limit($limit, $offset = 0)
{
$offset = (int)$offset;
if ($offset < 0)
$offset = 0;
$this->query['limit'] = array(
'offset' => $offset,
'limit' => (int)$limit,
);
return $this;
}
/**
* Generate and get the query
*
* @return string
*/
public function build()
{
$sql = 'SELECT '.((($this->query['select'])) ? implode(",\n", $this->query['select']) : '*')."\n";
if (!$this->query['from'])
die('DbQuery->build() missing from clause');
$sql .= 'FROM '.implode(', ', $this->query['from'])."\n";
if ($this->query['join'])
$sql .= implode("\n", $this->query['join'])."\n";
if ($this->query['where'])
$sql .= 'WHERE ('.implode(') AND (', $this->query['where']).")\n";
if ($this->query['group'])
$sql .= 'GROUP BY '.implode(', ', $this->query['group'])."\n";
if ($this->query['having'])
$sql .= 'HAVING ('.implode(') AND (', $this->query['having']).")\n";
if ($this->query['order'])
$sql .= 'ORDER BY '.implode(', ', $this->query['order'])."\n";
if ($this->query['limit']['limit'])
{
$limit = $this->query['limit'];
$sql .= 'LIMIT '.(($limit['offset']) ? $limit['offset'].', '.$limit['limit'] : $limit['limit']);
}
return $sql;
}
public function __toString()
{
return $this->build();
}
}

View File

@@ -0,0 +1,224 @@
<?php
/**
* 2007-2016 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to https://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2016 PrestaShop SA
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
class MySQLCore extends Db
{
/**
* @see DbCore::connect()
*/
public function connect()
{
if (!defined('_PS_MYSQL_REAL_ESCAPE_STRING_'))
define('_PS_MYSQL_REAL_ESCAPE_STRING_', function_exists('mysql_real_escape_string'));
if (!$this->link = @mysql_connect($this->server, $this->user, $this->password))
{
Tools14::displayError('Link to database cannot be established.');
exit();
}
if (!$this->set_db($this->database))
{
Tools14::displayError('The database selection cannot be made.');
exit();
}
// UTF-8 support
if (!mysql_query('SET NAMES \'utf8\'', $this->link))
Tools14::displayError('PrestaShop Fatal error: no utf-8 support. Please check your server configuration.');
return $this->link;
}
/**
* @see DbCore::disconnect()
*/
public function disconnect()
{
mysql_close($this->link);
}
/**
* @see DbCore::_query()
*/
protected function _query($sql)
{
return mysql_query($sql, $this->link);
}
/**
* @see DbCore::nextRow()
*/
public function nextRow($result = false)
{
$return = false;
if(is_resource($result) && $result)
$return = mysql_fetch_assoc($result);
elseif(is_resource($this->result) && $this->result)
$return = mysql_fetch_assoc($this->result);
return $return;
}
/**
* @see DbCore::_numRows()
*/
protected function _numRows($result)
{
return mysql_num_rows($result);
}
/**
* @see DbCore::Insert_ID()
*/
public function Insert_ID()
{
return mysql_insert_id($this->link);
}
/**
* @see DbCore::Affected_Rows()
*/
public function Affected_Rows()
{
return mysql_affected_rows($this->link);
}
/**
* @see DbCore::getMsgError()
*/
public function getMsgError($query = false)
{
return mysql_error($this->link);
}
/**
* @see DbCore::getNumberError()
*/
public function getNumberError()
{
return mysql_errno($this->link);
}
/**
* @see DbCore::getVersion()
*/
public function getVersion()
{
return mysql_get_server_info($this->link);
}
/**
* @see DbCore::_escape()
*/
public function _escape($str)
{
return _PS_MYSQL_REAL_ESCAPE_STRING_ ? mysql_real_escape_string($str, $this->link) : addslashes($str);
}
/**
* @see DbCore::set_db()
*/
public function set_db($db_name)
{
return mysql_select_db($db_name, $this->link);
}
/**
* @see Db::hasTableWithSamePrefix()
*/
public static function hasTableWithSamePrefix($server, $user, $pwd, $db, $prefix)
{
if (!$link = @mysql_connect($server, $user, $pwd, true))
return false;
if (!@mysql_select_db($db, $link))
return false;
$sql = 'SHOW TABLES LIKE \''.$prefix.'%\'';
$result = mysql_query($sql);
return (bool)@mysql_fetch_assoc($result);
}
/**
* @see Db::checkConnection()
*/
public static function tryToConnect($server, $user, $pwd, $db, $newDbLink = true, $engine = null, $timeout = 5)
{
ini_set('mysql.connect_timeout', $timeout);
if (!$link = @mysql_connect($server, $user, $pwd, $newDbLink))
return 1;
if (!@mysql_select_db($db, $link))
return 2;
if (strtolower($engine) == 'innodb')
{
$sql = 'SHOW VARIABLES WHERE Variable_name = \'have_innodb\'';
$result = mysql_query($sql);
if (!$result)
return 4;
$row = mysql_fetch_assoc($result);
if (!$row || strtolower($row['Value']) != 'yes')
return 4;
}
@mysql_close($link);
return 0;
}
public static function checkCreatePrivilege($server, $user, $pwd, $db, $prefix, $engine)
{
ini_set('mysql.connect_timeout', 5);
if (!$link = @mysql_connect($server, $user, $pwd, true))
return false;
if (!@mysql_select_db($db, $link))
return false;
$sql = '
CREATE TABLE `'.$prefix.'test` (
`test` tinyint(1) unsigned NOT NULL
) ENGINE=MyISAM';
$result = mysql_query($sql, $link);
if (!$result)
return mysql_error($link);
mysql_query('DROP TABLE `'.$prefix.'test`', $link);
return true;
}
/**
* @see Db::checkEncoding()
*/
static public function tryUTF8($server, $user, $pwd)
{
$link = @mysql_connect($server, $user, $pwd);
if (!mysql_query('SET NAMES \'utf8\'', $link))
$ret = false;
else
$ret = true;
@mysql_close($link);
return $ret;
}
}