From 766a38dcd7ecb8760b0e3d8737a0766938f9f3a7 Mon Sep 17 00:00:00 2001 From: rMalie Date: Wed, 20 Jul 2011 16:10:12 +0000 Subject: [PATCH] // Add config/alias.php file + refactoring of DB / MySQL classes --- admin-dev/tabs/AdminCustomerThreads.php | 4 +- admin-dev/tabs/AdminOrders.php | 6 +- admin-dev/tabs/AdminProducts.php | 2 +- classes/Db.php | 608 +++++++++++++++--------- classes/Manufacturer.php | 46 +- classes/MySQL.php | 245 +++------- classes/OrderReturn.php | 2 +- classes/Shop.php | 4 +- classes/Tools.php | 12 +- config/config.inc.php | 18 +- config/defines.inc.php | 2 - controllers/CategoryController.php | 2 +- controllers/ContactController.php | 2 +- install-dev/php/utf8.php | 1 - install-dev/xml/checkShopInfos.php | 1 - install-dev/xml/createDB.php | 3 - modules/bankwire/bankwire.php | 4 +- modules/blocklink/blocklink.php | 2 +- modules/cheque/cheque.php | 4 +- 19 files changed, 494 insertions(+), 474 deletions(-) diff --git a/admin-dev/tabs/AdminCustomerThreads.php b/admin-dev/tabs/AdminCustomerThreads.php index 14f7bc6c4..5f06b5756 100644 --- a/admin-dev/tabs/AdminCustomerThreads.php +++ b/admin-dev/tabs/AdminCustomerThreads.php @@ -156,7 +156,7 @@ class AdminCustomerThreads extends AdminTab $cm = new CustomerMessage(); $cm->id_employee = (int)$context->employee->id; $cm->id_customer_thread = $ct->id; - $cm->message = Tools::htmlentitiesutf8(nl2br2(Tools::getValue('reply_message'))); + $cm->message = Tools::htmlentitiesutf8(Tools::nl2br(Tools::getValue('reply_message'))); $cm->ip_address = ip2long($_SERVER['REMOTE_ADDR']); if (isset($_FILES) AND !empty($_FILES['joinFile']['name']) AND $_FILES['joinFile']['error'] != 0) $this->_errors[] = Tools::displayError('An error occurred with the file upload.'); @@ -170,7 +170,7 @@ class AdminCustomerThreads extends AdminTab $fileAttachment['mime'] = $_FILES['joinFile']['type']; } $params = array( - '{reply}' => nl2br2(Tools::getValue('reply_message')), + '{reply}' => Tools::nl2br(Tools::getValue('reply_message')), '{link}' => Tools::url($context->link->getPageLink('contact', true), 'id_customer_thread='.(int)($ct->id).'&token='.$ct->token), ); Mail::Send($ct->id_lang, 'reply_msg', Mail::l('An answer to your message is available'), $params, Tools::getValue('msg_email'), NULL, NULL, NULL, $fileAttachment); diff --git a/admin-dev/tabs/AdminOrders.php b/admin-dev/tabs/AdminOrders.php index bbe6b24b2..0c8d2b35e 100644 --- a/admin-dev/tabs/AdminOrders.php +++ b/admin-dev/tabs/AdminOrders.php @@ -181,7 +181,7 @@ class AdminOrders extends AdminTab $order = new Order((int)($message->id_order)); if (Validate::isLoadedObject($order)) { - $varsTpl = array('{lastname}' => $customer->lastname, '{firstname}' => $customer->firstname, '{id_order}' => $message->id_order, '{message}' => (Configuration::get('PS_MAIL_TYPE') == 2 ? $message->message : nl2br2($message->message))); + $varsTpl = array('{lastname}' => $customer->lastname, '{firstname}' => $customer->firstname, '{id_order}' => $message->id_order, '{message}' => (Configuration::get('PS_MAIL_TYPE') == 2 ? $message->message : Tools::nl2br($message->message))); if (@Mail::Send((int)($order->id_lang), 'order_merchant_comment', Mail::l('New message regarding your order'), $varsTpl, $customer->email, $customer->firstname.' '.$customer->lastname)) Tools::redirectAdmin(self::$currentIndex.'&id_order='.$id_order.'&vieworder&conf=11'.'&token='.$this->token); } @@ -682,7 +682,7 @@ class AdminOrders extends AdminTab '.($order->gift ? '
- '.(!empty($order->gift_message) ? '
'.$this->l('Message:').'
'.nl2br2($order->gift_message).'
' : '') : '').' + '.(!empty($order->gift_message) ? '
'.$this->l('Message:').'
'.Tools::nl2br($order->gift_message).'
' : '') : '').'
'; @@ -901,7 +901,7 @@ class AdminOrders extends AdminTab echo $this->l('At').' '.Tools::displayDate($message['date_add'], $context->language->id, true); echo ' '.$this->l('from').' '.(($message['elastname']) ? ($message['efirstname'].' '.$message['elastname']) : ($message['cfirstname'].' '.$message['clastname'])).''; echo ((int)($message['private']) == 1 ? ''.$this->l('Private:').'' : ''); - echo '

'.nl2br2($message['message']).'

'; + echo '

'.Tools::nl2br($message['message']).'

'; echo ''; echo '
'; } diff --git a/admin-dev/tabs/AdminProducts.php b/admin-dev/tabs/AdminProducts.php index 1f7bbc05b..94b5ff7dd 100644 --- a/admin-dev/tabs/AdminProducts.php +++ b/admin-dev/tabs/AdminProducts.php @@ -2151,7 +2151,7 @@ class AdminProducts extends AdminTab $preview_url = ''; if (isset($obj->id)) { - $preview_url = ($link->getProductLink($this->getFieldValue($obj, 'id'), $this->getFieldValue($obj, 'link_rewrite', $this->_defaultFormLanguage), Category::getLinkRewrite($this->getFieldValue($obj, 'id_category_default'), $context->language->id))); + $preview_url = ($context->link->getProductLink($this->getFieldValue($obj, 'id'), $this->getFieldValue($obj, 'link_rewrite', $this->_defaultFormLanguage), Category::getLinkRewrite($this->getFieldValue($obj, 'id_category_default'), $context->language->id))); if (!$obj->active) { $admin_dir = dirname($_SERVER['PHP_SELF']); diff --git a/classes/Db.php b/classes/Db.php index 0c0c9a6a4..337994329 100644 --- a/classes/Db.php +++ b/classes/Db.php @@ -27,7 +27,6 @@ if (file_exists(dirname(__FILE__).'/../config/settings.inc.php')) include_once(dirname(__FILE__).'/../config/settings.inc.php'); -//include_once(dirname(__FILE__).'/../classes/MySQL.php'); abstract class DbCore { @@ -52,162 +51,42 @@ abstract class DbCore /** @var mixed SQL cached result */ protected $_result; - /** @var mixed ? */ - protected static $_db; - - /** @var mixed Object instance for singleton */ + /** @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'), - */ + 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'), ); protected $_lastQuery; protected $_lastCached; - protected static $_idServer; - - /** - * Get Db object instance (Singleton) - * - * @param boolean $master Decides wether the connection to be returned by the master server or the slave server - * @return Db instance - */ - public static function getInstance($master = 1) - { - if ($master OR ($nServers = sizeof(self::$_servers)) == 1) - $idServer = 0; - else - $idServer = ($nServers > 2 AND ($id = ++self::$_idServer % (int)$nServers) !== 0) ? $id : 1; - - if(!isset(self::$_instance[$idServer])) - self::$_instance[(int)($idServer)] = new MySQL(self::$_servers[(int)($idServer)]['server'], self::$_servers[(int)($idServer)]['user'], self::$_servers[(int)($idServer)]['password'], self::$_servers[(int)($idServer)]['database']); - - return self::$_instance[(int)($idServer)]; - } - - public function getRessource() { return $this->_link;} - - public function __destruct() - { - $this->disconnect(); - } - - /** - * Build a Db object - */ - public function __construct($server, $user, $password, $database) - { - $this->_server = $server; - $this->_user = $user; - $this->_password = $password; - $this->_type = _DB_TYPE_; - $this->_database = $database; - - $this->connect(); - } - - /** - * 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 string $limit LIMIT clause (optional) - * @return mixed|boolean SQL query result - */ - public function autoExecute($table, $values, $type, $where = false, $limit = false, $use_cache = 1) - { - if (!sizeof($values)) - return true; - - if (strtoupper($type) == 'INSERT') - { - $query = 'INSERT INTO `'.$table.'` ('; - foreach ($values AS $key => $value) - $query .= '`'.$key.'`,'; - $query = rtrim($query, ',').') VALUES ('; - foreach ($values AS $key => $value) - $query .= '\''.$value.'\','; - $query = rtrim($query, ',').')'; - if ($limit) - $query .= ' LIMIT '.(int)($limit); - return $this->q($query, $use_cache); - } - elseif (strtoupper($type) == 'UPDATE') - { - $query = 'UPDATE `'.$table.'` SET '; - foreach ($values AS $key => $value) - $query .= '`'.$key.'` = \''.$value.'\','; - $query = rtrim($query, ','); - if ($where) - $query .= ' WHERE '.$where; - if ($limit) - $query .= ' LIMIT '.(int)($limit); - return $this->q($query, $use_cache); - } - - return false; - } - - - /** - * 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 string $limit LIMIT clause (optional) - * @return mixed|boolean SQL query result - */ - public function autoExecuteWithNullValues($table, $values, $type, $where = false, $limit = false) - { - if (!sizeof($values)) - return true; - - if (strtoupper($type) == 'INSERT') - { - $query = 'INSERT INTO `'.$table.'` ('; - foreach ($values AS $key => $value) - $query .= '`'.$key.'`,'; - $query = rtrim($query, ',').') VALUES ('; - foreach ($values AS $key => $value) - $query .= (($value === '' OR $value === NULL) ? 'NULL' : '\''.$value.'\'').','; - $query = rtrim($query, ',').')'; - if ($limit) - $query .= ' LIMIT '.(int)($limit); - return $this->q($query); - } - elseif (strtoupper($type) == 'UPDATE') - { - $query = 'UPDATE `'.$table.'` SET '; - foreach ($values AS $key => $value) - $query .= '`'.$key.'` = '.(($value === '' OR $value === NULL) ? 'NULL' : '\''.$value.'\'').','; - $query = rtrim($query, ','); - if ($where) - $query .= ' WHERE '.$where; - if ($limit) - $query .= ' LIMIT '.(int)($limit); - return $this->q($query); - } - - return false; - } - - /********************************************************* - * ABSTRACT METHODS - *********************************************************/ - /** * Open a connection */ abstract public function connect(); + + /** + * Close a connection + */ + abstract public function disconnect(); + + /** + * Execute a query and get result ressource + * + * @param string $sql + * @return mixed + */ + abstract protected function _query($sql); + + /** + * Get number of rows in a result + */ + abstract protected function _numRows($result); /** * Get the ID generated from the previous INSERT operation @@ -220,25 +99,6 @@ abstract class DbCore abstract public function Affected_Rows(); /** - * Gets the number of rows in a result - */ - abstract public function NumRows(); - - /** - * Delete - */ - abstract public function delete ($table, $where = false, $limit = false, $use_cache = 1); - /** - * Fetches a row from a result set - */ - abstract public function Execute ($query, $use_cache = 1); - - /** - * Fetches an array containing all of the rows from a result set - */ - abstract public function ExecuteS($query, $array = true, $use_cache = 1); - - /* * Get next row for a query which doesn't return an array */ abstract public function nextRow($result = false); @@ -256,7 +116,352 @@ abstract class DbCore * @param string $str * @return string */ - abstract public function escape($str); + 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); + + /** + * Try a connection + */ + abstract static public function tryToConnect($server, $user, $pwd, $db); + + /** + * Try to change UTF8 + */ + abstract static public function tryUTF8($server, $user, $pwd); + + /** + * Get Db object instance + * + * @param boolean $master Decides wether the connection to be returned by the master server or the slave server + * @return Db instance + */ + public static function getInstance($master = 1) + { + static $id = 0; + + $nServers = sizeof(self::$_servers); + if ($master || $nServers == 1) + $idServer = 0; + else + { + $id++; + $idServer = ($nServers > 2 && ($id % $nServers) != 0) ? $id : 1; + } + + if (!isset(self::$_instance[$idServer])) + self::$_instance[$idServer] = new MySQL(self::$_servers[$idServer]['server'], self::$_servers[$idServer]['user'], self::$_servers[$idServer]['password'], self::$_servers[$idServer]['database']); + + return self::$_instance[$idServer]; + } + + /** + * Instantiate database connection + * + * @param string $server Server address + * @param string $user User login + * @param string $password User password + * @param string $database Database name + */ + public function __construct($server, $user, $password, $database) + { + $this->_server = $server; + $this->_user = $user; + $this->_password = $password; + $this->_type = _DB_TYPE_; + $this->_database = $database; + + if (!defined('_PS_DEBUG_SQL_')) + define('_PS_DEBUG_SQL_', false); + + $this->connect(); + } + + /** + * Close connection to database + */ + public function __destruct() + { + $this->disconnect(); + } + + /** + * 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 string $limit LIMIT clause (optional) + * @param bool $useNull If true, replace empty strings and NULL by a NULL value + * @return mixed|boolean SQL query result + */ + public function autoExecute($table, $data, $type, $where = false, $limit = false, $use_cache = 1, $useNull = false) + { + if (!$data) + return true; + + if (strtoupper($type) == 'INSERT') + { + $keys = $values = array(); + foreach ($data AS $key => $value) + { + $keys[] = "`$key`"; + $values[] = ($useNull && ($value === '' || is_null($value))) ? 'NULL' : "'$value'"; + } + + $sql = 'INSERT INTO `'.$table.'` ('.implode(', ', $keys).') VALUES ('.implode(', ', $values).')'; + if ($limit) + $sql .= ' LIMIT '.(int)$limit; + return $this->q($sql, $use_cache); + } + else if (strtoupper($type) == 'UPDATE') + { + $sql = 'UPDATE `'.$table.'` SET '; + foreach ($data AS $key => $value) + $sql .= ($useNull && ($value === '' || is_null($value))) ? "`$key` = NULL" : "`$key` = '$value',"; + $sql = rtrim($sql, ','); + if ($where) + $sql .= ' WHERE '.$where; + if ($limit) + $sql .= ' LIMIT '.(int)$limit; + return $this->q($sql, $use_cache); + } + else + die('Wrong argument (miss type) in Db::autoExecute()'); + + return false; + } + + /** + * 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 string $limit LIMIT clause (optional) + * @return mixed|boolean SQL query result + */ + public function autoExecuteWithNullValues($table, $values, $type, $where = false, $limit = false) + { + 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) + { + $result = $this->_query($sql); + if (_PS_DEBUG_SQL_) + $this->displayError($sql); + return $result; + } + + /** + * Execute a DELETE query + * + * @param unknown_type $table Name of the table to delete + * @param unknown_type $where WHERE clause on query + * @param unknown_type $limit Number max of rows to delete + * @param unknown_type $use_cache Use cache or not + * @return bool + */ + public function delete($table, $where = false, $limit = false, $use_cache = 1) + { + $this->_result = false; + $res = $this->query('DELETE FROM `'.pSQL($table).'`'.($where ? ' WHERE '.$where : '').($limit ? ' LIMIT '.(int)$limit : '')); + if ($use_cache AND _PS_CACHE_ENABLED_) + Cache::getInstance()->deleteQuery($sql); + return $res; + } + + /** + * Execute a query + * + * @param string $sql + * @param bool $use_cache + * @return mixed + */ + public function Execute($sql, $use_cache = 1) + { + $this->_result = $this->query($sql); + if ($use_cache AND _PS_CACHE_ENABLED_) + Cache::getInstance()->deleteQuery($sql); + return $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 + * @param int $use_cache if query has been already executed, use its result + * @return array or result object + */ + public function ExecuteS($sql, $array = true, $use_cache = 1) + { + $this->_result = false; + $this->_lastQuery = $sql; + if ($use_cache AND _PS_CACHE_ENABLED_ && $array AND ($result = Cache::getInstance()->get(md5($sql)))) + { + $this->_lastCached = true; + return $result; + } + + $this->_result = $this->query($sql); + if (!$this->_result) + return false; + + $this->_lastCached = false; + if (!$array) + return $this->_result; + + $resultArray = array(); + while ($row = $this->nextRow($this->_result)) + $resultArray[] = $row; + + if ($use_cache AND _PS_CACHE_ENABLED_) + Cache::getInstance()->setQuery($sql, $resultArray); + return $resultArray; + } + + /** + * 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 int $use_cache find it in cache first + * @return array associative array of (field=>value) + */ + public function getRow($sql, $use_cache = 1) + { + $sql .= ' LIMIT 1'; + $this->_result = false; + $this->_lastQuery = $sql; + if ($use_cache && _PS_CACHE_ENABLED_ && ($result = Cache::getInstance()->get(md5($sql)))) + { + $this->_lastCached = true; + return $result; + } + + $this->_result = $this->query($sql); + if (!$this->_result) + return false; + + $this->_lastCached = false; + $result = $this->nextRow($this->_result); + if ($use_cache AND _PS_CACHE_ENABLED_) + Cache::getInstance()->setQuery($sql, $result); + return $result; + } + + /** + * getValue return the first item of a select query. + * + * @param mixed $sql + * @param int $use_cache + * @return void + */ + public function getValue($sql, $use_cache = 1) + { + 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->_lastCached && $this->_result) + { + $nrows = $this->_numRows($this->_result); + if (_PS_CACHE_ENABLED_) + Cache::getInstance()->setNumRows(md5($this->_lastQuery), $nrows); + return $nrows; + } + else if (_PS_CACHE_ENABLED_ AND $this->_lastCached) + return Cache::getInstance()->getNumRows(md5($this->_lastQuery)); + } + + /** + * + * Execute a query + * + * @param string $sql + * @param bool $use_cache + */ + protected function q($sql, $use_cache = 1) + { + global $webservice_call; + + $this->_result = false; + $result = $this->query($sql); + $this->_lastQuery = $sql; + if ($use_cache AND _PS_CACHE_ENABLED_) + Cache::getInstance()->deleteQuery($sql); + return $result; + } + + /** + * Display last SQL error + * + * @param unknown_type $sql + */ + public function displayError($sql = false) + { + global $webservice_call; + + $errno = $this->getNumberError(); + if ($webservice_call && $errno) + WebserviceRequest::getInstance()->setError(500, '[SQL Error] '.$this->getMsgError().'. Query was : '.$sql, 97); + elseif (_PS_DEBUG_SQL_ AND $errno AND !defined('PS_INSTALLATION_IN_PROGRESS')) + { + if ($sql) + die(Tools::displayError($this->getMsgError().'

'.$sql.'
')); + die(Tools::displayError($this->getMsgError())); + } + } + + /** + * Sanitize data which will be injected into SQL query + * + * @param string $string SQL data which will be injected into SQL query + * @param boolean $htmlOK Does data contain HTML code ? (optional) + * @return string Sanitized data + */ + public function escape($string, $htmlOK) + { + if (_PS_MAGIC_QUOTES_GPC_) + $string = stripslashes($string); + if (!is_numeric($string)) + { + $string = $this->_escape($string); + if (!$htmlOK) + $string = strip_tags(Tools::nl2br($string)); + } + + return $string; + } /** * Alias of Db::getInstance()->ExecuteS @@ -264,80 +469,21 @@ abstract class DbCore * @acces string query The query to execute * @return array Array of line returned by MySQL */ - static public function s($query, $use_cache = 1) + static public function s($sql, $use_cache = 1) { - return Db::getInstance()->ExecuteS($query, true, $use_cache); + return Db::getInstance()->ExecuteS($sql, true, $use_cache); } - static public function ps($query, $use_cache = 1) + static public function ps($sql, $use_cache = 1) { - $ret = Db::s($query, $use_cache); + $ret = Db::s($sql, $use_cache); p($ret); return $ret; } - static public function ds($query, $use_cache = 1) + static public function ds($sql, $use_cache = 1) { - Db::s($query, $use_cache); + Db::s($sql, $use_cache); die(); } - - /** - * getRow return an associative array containing the first row of the query - * This function automatically add "limit 1" to the query - * - * @param mixed $query the select query (without "LIMIT 1") - * @param int $use_cache find it in cache first - * @return array associative array of (field=>value) - */ - abstract public function getRow($query, $use_cache = 1); - - /** - * getValue return the first item of a select query. - * - * @param mixed $query - * @param int $use_cache - * @return void - */ - abstract public function getValue($query, $use_cache = 1); - - /** - * Returns the text of the error message from previous database operation - */ - abstract public function getMsgError(); -} - -/** - * Sanitize data which will be injected into SQL query - * - * @param string $string SQL data which will be injected into SQL query - * @param boolean $htmlOK Does data contain HTML code ? (optional) - * @return string Sanitized data - */ -function pSQL($string, $htmlOK = false) -{ - if (_PS_MAGIC_QUOTES_GPC_) - $string = stripslashes($string); - if (!is_numeric($string)) - { - $link = Db::getInstance()->getRessource(); - $string = _PS_MYSQL_REAL_ESCAPE_STRING_ ? Db::getInstance()->escape($string, $link) : addslashes($string); - if (!$htmlOK) - $string = strip_tags(nl2br2($string)); - } - - return $string; -} - -/** - * Convert \n and \r\n and \r to
- * - * @param string $string String to transform - * @return string New string - */ -function nl2br2($string) -{ - return str_replace(array("\r\n", "\r", "\n"), '
', $string); -} - - +} \ No newline at end of file diff --git a/classes/Manufacturer.php b/classes/Manufacturer.php index 6d4912734..60daa9817 100644 --- a/classes/Manufacturer.php +++ b/classes/Manufacturer.php @@ -293,6 +293,7 @@ class ManufacturerCore extends ObjectModel $sql = ' SELECT p.`id_product` FROM `'._DB_PREFIX_.'product` p + '.$context->shop->sqlAsso('product', 'p', true).' WHERE p.id_manufacturer = '.(int)($id_manufacturer) .($active ? ' AND p.`active` = 1' : '').' AND p.`id_product` IN ( @@ -304,29 +305,30 @@ class ManufacturerCore extends ObjectModel $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql); return (int)(sizeof($result)); } - $sql = ' - SELECT p.*, pa.`id_product_attribute`, pl.`description`, pl.`description_short`, pl.`link_rewrite`, pl.`meta_description`, pl.`meta_keywords`, pl.`meta_title`, pl.`name`, i.`id_image`, il.`legend`, m.`name` AS manufacturer_name, tl.`name` AS tax_name, t.`rate`, DATEDIFF(p.`date_add`, DATE_SUB(NOW(), INTERVAL '.(Validate::isUnsignedInt(Configuration::get('PS_NB_DAYS_NEW_PRODUCT')) ? Configuration::get('PS_NB_DAYS_NEW_PRODUCT') : 20).' DAY)) > 0 AS new, + + $sql = 'SELECT p.*, pa.`id_product_attribute`, pl.`description`, pl.`description_short`, pl.`link_rewrite`, pl.`meta_description`, pl.`meta_keywords`, pl.`meta_title`, pl.`name`, i.`id_image`, il.`legend`, m.`name` AS manufacturer_name, tl.`name` AS tax_name, t.`rate`, DATEDIFF(p.`date_add`, DATE_SUB(NOW(), INTERVAL '.(Validate::isUnsignedInt(Configuration::get('PS_NB_DAYS_NEW_PRODUCT')) ? Configuration::get('PS_NB_DAYS_NEW_PRODUCT') : 20).' DAY)) > 0 AS new, (p.`price` * ((100 + (t.`rate`))/100)) AS orderprice - FROM `'._DB_PREFIX_.'product` p - LEFT JOIN `'._DB_PREFIX_.'product_attribute` pa ON (p.`id_product` = pa.`id_product` AND default_on = 1) - LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = '.(int)($id_lang).') - LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1) - LEFT JOIN `'._DB_PREFIX_.'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = '.(int)($id_lang).') - LEFT JOIN `'._DB_PREFIX_.'tax_rule` tr ON (p.`id_tax_rules_group` = tr.`id_tax_rules_group` - AND tr.`id_country` = '.(int)$context->country->id.' - AND tr.`id_state` = 0) - LEFT JOIN `'._DB_PREFIX_.'tax` t ON (t.`id_tax` = tr.`id_tax`) - LEFT JOIN `'._DB_PREFIX_.'tax_lang` tl ON (t.`id_tax` = tl.`id_tax` AND tl.`id_lang` = '.(int)($id_lang).') - LEFT JOIN `'._DB_PREFIX_.'manufacturer` m ON m.`id_manufacturer` = p.`id_manufacturer` - WHERE p.`id_manufacturer` = '.(int)($id_manufacturer).($active ? ' AND p.`active` = 1' : '').' - AND p.`id_product` IN ( - SELECT cp.`id_product` - FROM `'._DB_PREFIX_.'category_group` cg - LEFT JOIN `'._DB_PREFIX_.'category_product` cp ON (cp.`id_category` = cg.`id_category`) - WHERE cg.`id_group` '.$sqlGroups.' - ) - ORDER BY '.(($orderBy == 'id_product') ? 'p.' : '').'`'.pSQL($orderBy).'` '.pSQL($orderWay).' - LIMIT '.(((int)($p) - 1) * (int)($n)).','.(int)($n); + FROM `'._DB_PREFIX_.'product` p + '.$context->shop->sqlAsso('product', 'p', true).' + LEFT JOIN `'._DB_PREFIX_.'product_attribute` pa ON (p.`id_product` = pa.`id_product` AND default_on = 1) + LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = '.(int)$id_lang.$context->shop->sqlLang('pl').') + LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1) + LEFT JOIN `'._DB_PREFIX_.'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = '.(int)$id_lang.') + LEFT JOIN `'._DB_PREFIX_.'tax_rule` tr ON (p.`id_tax_rules_group` = tr.`id_tax_rules_group` + AND tr.`id_country` = '.(int)$context->country->id.' + AND tr.`id_state` = 0) + LEFT JOIN `'._DB_PREFIX_.'tax` t ON (t.`id_tax` = tr.`id_tax`) + LEFT JOIN `'._DB_PREFIX_.'tax_lang` tl ON (t.`id_tax` = tl.`id_tax` AND tl.`id_lang` = '.(int)$id_lang.') + LEFT JOIN `'._DB_PREFIX_.'manufacturer` m ON m.`id_manufacturer` = p.`id_manufacturer` + WHERE p.`id_manufacturer` = '.(int)($id_manufacturer).($active ? ' AND p.`active` = 1' : '').' + AND p.`id_product` IN ( + SELECT cp.`id_product` + FROM `'._DB_PREFIX_.'category_group` cg + LEFT JOIN `'._DB_PREFIX_.'category_product` cp ON (cp.`id_category` = cg.`id_category`) + WHERE cg.`id_group` '.$sqlGroups.' + ) + ORDER BY '.(($orderBy == 'id_product') ? 'p.' : '').'`'.pSQL($orderBy).'` '.pSQL($orderWay).' + LIMIT '.(((int)$p - 1) * (int)$n).','.(int)$n; $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql); if (!$result) return false; diff --git a/classes/MySQL.php b/classes/MySQL.php index 2b68d6bc4..ac3b6e9eb 100644 --- a/classes/MySQL.php +++ b/classes/MySQL.php @@ -27,30 +27,30 @@ class MySQLCore extends Db { + /** + * @see DbCore::connect() + */ public function connect() { - if (!defined('_PS_DEBUG_SQL_')) - define('_PS_DEBUG_SQL_', false); - if ($this->_link = mysql_connect($this->_server, $this->_user, $this->_password)) - { - if(!$this->set_db($this->_database)) - die(Tools::displayError('The database selection cannot be made.')); - } - else + 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)) die(Tools::displayError('Link to database cannot be established.')); - /* UTF-8 support */ + + if (!$this->set_db($this->_database)) + die(Tools::displayError('The database selection cannot be made.')); + + // UTF-8 support if (!mysql_query('SET NAMES \'utf8\'', $this->_link)) die(Tools::displayError('PrestaShop Fatal error: no utf-8 support. Please check your server configuration.')); - // removed SET GLOBAL SQL_MODE : we can't do that (see PSCFI-1548) + return $this->_link; } - /* do not remove, useful for some modules */ - public function set_db($db_name) - { - return mysql_select_db($db_name, $this->_link); - } - + /** + * @see DbCore::disconnect() + */ public function disconnect() { if ($this->_link) @@ -58,193 +58,60 @@ class MySQLCore extends Db $this->_link = false; } - public function getRow($query, $use_cache = 1) - { - $query .= ' LIMIT 1'; - $this->_result = false; - $this->_lastQuery = $query; - if($use_cache AND _PS_CACHE_ENABLED_) - if ($result = Cache::getInstance()->get(md5($query))) - { - $this->_lastCached = true; - return $result; - } - if ($this->_link) - if ($this->_result = mysql_query($query, $this->_link)) - { - $this->_lastCached = false; - if (_PS_DEBUG_SQL_) - $this->displayMySQLError($query); - $result = mysql_fetch_assoc($this->_result); - if ($use_cache = 1 AND _PS_CACHE_ENABLED_) - Cache::getInstance()->setQuery($query, $result); - return $result; - } - if (_PS_DEBUG_SQL_) - $this->displayMySQLError($query); - return false; - } - - public function getValue($query, $use_cache = 1) - { - if (!$result = $this->getRow($query, $use_cache)) - return false; - return array_shift($result); - } - - public function Execute($query, $use_cache = 1) - { - $this->_result = false; - if ($this->_link) - { - $this->_result = mysql_query($query, $this->_link); - if (_PS_DEBUG_SQL_) - $this->displayMySQLError($query); - if ($use_cache AND _PS_CACHE_ENABLED_) - Cache::getInstance()->deleteQuery($query); - return $this->_result; - } - if (_PS_DEBUG_SQL_) - $this->displayMySQLError($query); - return false; - } - /** - * ExecuteS return the result of $query as array, - * or as mysqli_result if $array set to false - * - * @param string $query query to execute - * @param boolean $array return an array instead of a mysql_result object - * @param int $use_cache if query has been already executed, use its result - * @return array or result object + * @see DbCore::_query() */ - public function ExecuteS($query, $array = true, $use_cache = 1) + protected function _query($sql) { - $this->_result = false; - $this->_lastQuery = $query; - if ($use_cache AND _PS_CACHE_ENABLED_) - if ($array AND ($result = Cache::getInstance()->get(md5($query)))) - { - $this->_lastCached = true; - return $result; - } - if ($this->_link && $this->_result = mysql_query($query, $this->_link)) - { - $this->_lastCached = false; - if (_PS_DEBUG_SQL_) - $this->displayMySQLError($query); - if (!$array) - return $this->_result; - $resultArray = array(); - // Only SELECT queries and a few others return a valid resource usable with mysql_fetch_assoc - if ($this->_result !== true) - while ($row = mysql_fetch_assoc($this->_result)) - $resultArray[] = $row; - if ($use_cache AND _PS_CACHE_ENABLED_) - Cache::getInstance()->setQuery($query, $resultArray); - return $resultArray; - } - if (_PS_DEBUG_SQL_) - $this->displayMySQLError($query); - return false; + return mysql_query($sql, $this->_link); } + /** + * @see DbCore::nextRow() + */ public function nextRow($result = false) { return mysql_fetch_assoc($result ? $result : $this->_result); } - public function delete($table, $where = false, $limit = false, $use_cache = 1) + /** + * @see DbCore::_numRows() + */ + protected function _numRows($result) { - $this->_result = false; - if ($this->_link) - { - $query = 'DELETE FROM `'.pSQL($table).'`'.($where ? ' WHERE '.$where : '').($limit ? ' LIMIT '.(int)($limit) : ''); - $res = mysql_query($query, $this->_link); - if ($use_cache AND _PS_CACHE_ENABLED_) - Cache::getInstance()->deleteQuery($query); - return $res; - } - - return false; - } - - public function NumRows() - { - if (!$this->_lastCached AND $this->_link AND $this->_result) - { - $nrows = mysql_num_rows($this->_result); - if (_PS_CACHE_ENABLED_) - Cache::getInstance()->setNumRows(md5($this->_lastQuery), $nrows); - return $nrows; - } - elseif (_PS_CACHE_ENABLED_ AND $this->_lastCached) - { - return Cache::getInstance()->getNumRows(md5($this->_lastQuery)); - } + return mysql_num_rows($result); } + /** + * @see DbCore::Insert_ID() + */ public function Insert_ID() { - if ($this->_link) - return mysql_insert_id($this->_link); - return false; - } - - public function Affected_Rows() - { - if ($this->_link) - return mysql_affected_rows($this->_link); - return false; - } - - protected function q($query, $use_cache = 1) - { - global $webservice_call; - $this->_result = false; - if ($this->_link) - { - $result = mysql_query($query, $this->_link); - $this->_lastQuery = $query; - if ($webservice_call) - $this->displayMySQLError($query); - if ($use_cache AND _PS_CACHE_ENABLED_) - Cache::getInstance()->deleteQuery($query); - return $result; - } - return false; + mysql_insert_id($this->_link); } /** - * Returns the text of the error message from previous MySQL operation - * - * @return string error + * @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(); + return mysql_error($this->_link); } + /** + * @see DbCore::getNumberError() + */ public function getNumberError() { - return mysql_errno(); - } - - public function displayMySQLError($query = false) - { - global $webservice_call; - if ($webservice_call && mysql_errno()) - { - WebserviceRequest::getInstance()->setError(500, '[SQL Error] '.mysql_error().'. Query was : '.$query, 97); - } - elseif (_PS_DEBUG_SQL_ AND mysql_errno() AND !defined('PS_INSTALLATION_IN_PROGRESS')) - { - if ($query) - { - die(Tools::displayError(mysql_error().'

'.$query.'
')); - } - die(Tools::displayError((mysql_error()))); - } + return mysql_errno($this->_link); } /** @@ -252,17 +119,28 @@ class MySQLCore extends Db */ public function getVersion() { - return mysql_get_server_info(); + return mysql_get_server_info($this->_link); } /** - * @see DbCore::escape() + * @see DbCore::_escape() */ - public function escape($str) + public function _escape($str) { - return mysql_real_escape_string($str, $this->_link); + 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 DbCore::tryToConnect() + */ static public function tryToConnect($server, $user, $pwd, $db) { if (!$link = @mysql_connect($server, $user, $pwd)) @@ -273,6 +151,9 @@ class MySQLCore extends Db return 0; } + /** + * @see DbCore::tryUTF8() + */ static public function tryUTF8($server, $user, $pwd) { $link = @mysql_connect($server, $user, $pwd); diff --git a/classes/OrderReturn.php b/classes/OrderReturn.php index 13a2a116c..27978700c 100644 --- a/classes/OrderReturn.php +++ b/classes/OrderReturn.php @@ -65,7 +65,7 @@ class OrderReturnCore extends ObjectModel $fields['state'] = pSQL($this->state); $fields['date_add'] = pSQL($this->date_add); $fields['date_upd'] = pSQL($this->date_upd); - $fields['question'] = pSQL(nl2br2($this->question), true); + $fields['question'] = pSQL(Tools::nl2br($this->question), true); return $fields; } diff --git a/classes/Shop.php b/classes/Shop.php index 01a1c9b4d..1d4720fd8 100644 --- a/classes/Shop.php +++ b/classes/Shop.php @@ -185,7 +185,7 @@ class ShopCore extends ObjectModel AND s.active = 1 AND s.deleted = 0'; if (!$id_shop = $db->getValue($sql)) - $id_shop = Configuration::get('PS_SHOP_DEFAULT'); + $id_shop = (int)Db::getInstance()->getValue('SELECT value FROM '._DB_PREFIX_.'configuration WHERE name = \'PS_SHOP_DEFAULT\''); } // Get instance of found shop @@ -496,6 +496,8 @@ class ShopCore extends ObjectModel } else { + if (!isset($context->shop)) + return ($type == 'shop' || $type == 'group') ? '' : array('', ''); $shopID = (int)$context->shop->id_shop; $shopGroupID = (int)$context->shop->id_group_shop; } diff --git a/classes/Tools.php b/classes/Tools.php index e880ace7c..54b549a7c 100644 --- a/classes/Tools.php +++ b/classes/Tools.php @@ -2094,7 +2094,17 @@ FileETag INode MTime Size public static function url($begin, $end) { return $begin.((strpos($begin, '?') !== false) ? '&' : '?').$end; - + } + + /** + * Convert \n and \r\n and \r to
+ * + * @param string $string String to transform + * @return string New string + */ + public static function nl2br($str) + { + return str_replace(array("\r\n", "\r", "\n"), '
', $str); } } diff --git a/config/config.inc.php b/config/config.inc.php index 9c8a437b8..bbd6e20eb 100644 --- a/config/config.inc.php +++ b/config/config.inc.php @@ -75,23 +75,9 @@ require_once(dirname(__FILE__).'/autoload.php'); if (!defined('_PS_MAGIC_QUOTES_GPC_')) define('_PS_MAGIC_QUOTES_GPC_', get_magic_quotes_gpc()); -if (!defined('_PS_MYSQL_REAL_ESCAPE_STRING_')) - define('_PS_MYSQL_REAL_ESCAPE_STRING_', function_exists('mysql_real_escape_string')); -/* aliases */ -function p($var) { - return (Tools::p($var)); -} -function d($var) { - Tools::d($var); -} - -function ppp($var) { - return (Tools::p($var)); -} -function ddd($var) { - Tools::d($var); -} +// Include some alias functions +include_once(dirname(__FILE__).'/alias.php'); /* Set the current Shop */ Context::getContext()->shop = Shop::initialize(); diff --git a/config/defines.inc.php b/config/defines.inc.php index bccb52b3e..6e40afaf7 100755 --- a/config/defines.inc.php +++ b/config/defines.inc.php @@ -101,8 +101,6 @@ define('_PS_TRANS_PATTERN_', '(.*[^\\\\])'); define('_PS_MIN_TIME_GENERATE_PASSWD_', '360'); if (!defined('_PS_MAGIC_QUOTES_GPC_')) define('_PS_MAGIC_QUOTES_GPC_', get_magic_quotes_gpc()); -if (!defined('_PS_MYSQL_REAL_ESCAPE_STRING_')) - define('_PS_MYSQL_REAL_ESCAPE_STRING_', function_exists('mysql_real_escape_string')); define('_CAN_LOAD_FILES_', 1); diff --git a/controllers/CategoryController.php b/controllers/CategoryController.php index 1c85eac95..14c695a04 100644 --- a/controllers/CategoryController.php +++ b/controllers/CategoryController.php @@ -121,7 +121,7 @@ class CategoryControllerCore extends FrontController $this->smarty->assign('largeSceneImageType', isset($largeSceneImageType) ? $largeSceneImageType : NULL); } - $this->category->description = nl2br2($this->category->description); + $this->category->description = Tools::nl2br($this->category->description); $subCategories = $this->category->getSubCategories((int)(self::$cookie->id_lang)); $this->smarty->assign('category', $this->category); diff --git a/controllers/ContactController.php b/controllers/ContactController.php index 7646bac69..39a26c64a 100644 --- a/controllers/ContactController.php +++ b/controllers/ContactController.php @@ -86,7 +86,7 @@ class ContactControllerCore extends FrontController $message = Tools::htmlentitiesUTF8(Tools::getValue('message')); if (!($from = trim(Tools::getValue('from'))) OR !Validate::isEmail($from)) $this->errors[] = Tools::displayError('Invalid e-mail address'); - elseif (!($message = nl2br2($message))) + elseif (!($message = Tools::nl2br($message))) $this->errors[] = Tools::displayError('Message cannot be blank'); elseif (!Validate::isCleanHtml($message)) $this->errors[] = Tools::displayError('Invalid message'); diff --git a/install-dev/php/utf8.php b/install-dev/php/utf8.php index 060dd61af..759bdd348 100644 --- a/install-dev/php/utf8.php +++ b/install-dev/php/utf8.php @@ -25,7 +25,6 @@ * International Registered Trademark & Property of PrestaShop SA */ define('_PS_MAGIC_QUOTES_GPC_', get_magic_quotes_gpc()); -define('_PS_MYSQL_REAL_ESCAPE_STRING_', function_exists('mysql_real_escape_string')); function latin1_database_to_utf8() { diff --git a/install-dev/xml/checkShopInfos.php b/install-dev/xml/checkShopInfos.php index 531545cff..c125e7296 100644 --- a/install-dev/xml/checkShopInfos.php +++ b/install-dev/xml/checkShopInfos.php @@ -29,7 +29,6 @@ if (function_exists('date_default_timezone_set')) date_default_timezone_set('Europe/Paris'); define('_PS_MAGIC_QUOTES_GPC_', get_magic_quotes_gpc()); -define('_PS_MYSQL_REAL_ESCAPE_STRING_', function_exists('mysql_real_escape_string')); include(INSTALL_PATH.'/classes/AddConfToFile.php'); include(INSTALL_PATH.'/../classes/Validate.php'); diff --git a/install-dev/xml/createDB.php b/install-dev/xml/createDB.php index 40335f846..d29673028 100644 --- a/install-dev/xml/createDB.php +++ b/install-dev/xml/createDB.php @@ -28,9 +28,6 @@ if (!defined('_PS_MAGIC_QUOTES_GPC_')) define('_PS_MAGIC_QUOTES_GPC_', get_magic_quotes_gpc()); -if (!defined('_PS_MYSQL_REAL_ESCAPE_STRING_')) - define('_PS_MYSQL_REAL_ESCAPE_STRING_', function_exists('mysql_real_escape_string')); - if (function_exists('date_default_timezone_set')) date_default_timezone_set('Europe/Paris'); diff --git a/modules/bankwire/bankwire.php b/modules/bankwire/bankwire.php index 0374a8919..0fa4a3b61 100644 --- a/modules/bankwire/bankwire.php +++ b/modules/bankwire/bankwire.php @@ -209,8 +209,8 @@ class BankWire extends PaymentModule if ($state == _PS_OS_BANKWIRE_ OR $state == _PS_OS_OUTOFSTOCK_) $context->smarty->assign(array( 'total_to_pay' => Tools::displayPrice($params['total_to_pay'], $params['currencyObj'], false), - 'bankwireDetails' => nl2br2($this->details), - 'bankwireAddress' => nl2br2($this->address), + 'bankwireDetails' => Tools::nl2br($this->details), + 'bankwireAddress' => Tools::nl2br($this->address), 'bankwireOwner' => $this->owner, 'status' => 'ok', 'id_order' => $params['objOrder']->id diff --git a/modules/blocklink/blocklink.php b/modules/blocklink/blocklink.php index cb121a08d..0dcca9fa4 100644 --- a/modules/blocklink/blocklink.php +++ b/modules/blocklink/blocklink.php @@ -127,7 +127,7 @@ class BlockLink extends Module public function addLink() { /* Url registration */ - if (!Db::getInstance()->Execute('INSERT INTO '._DB_PREFIX_.'blocklink VALUES (NULL, \''.pSQL($_POST['url']).'\', '.((isset($_POST['newWindow']) AND $_POST['newWindow']) == 'on' ? 1 : 0).')') OR !$lastId = mysql_insert_id()) + if (!Db::getInstance()->Execute('INSERT INTO '._DB_PREFIX_.'blocklink VALUES (NULL, \''.pSQL($_POST['url']).'\', '.((isset($_POST['newWindow']) AND $_POST['newWindow']) == 'on' ? 1 : 0).')') OR !$lastId = Db::getInstance()->Insert_ID()) return false; /* Multilingual text */ $languages = Language::getLanguages(); diff --git a/modules/cheque/cheque.php b/modules/cheque/cheque.php index 9e15387af..985886d10 100644 --- a/modules/cheque/cheque.php +++ b/modules/cheque/cheque.php @@ -164,7 +164,7 @@ class Cheque extends PaymentModule 'total' => $cart->getOrderTotal(true, Cart::BOTH), 'isoCode' => $context->language->iso_code, 'chequeName' => $this->chequeName, - 'chequeAddress' => nl2br2($this->address), + 'chequeAddress' => Tools::nl2br($this->address), 'this_path' => $this->_path, 'this_path_ssl' => Tools::getShopDomainSsl(true, true).__PS_BASE_URI__.'modules/'.$this->name.'/' )); @@ -198,7 +198,7 @@ class Cheque extends PaymentModule $context->smarty->assign(array( 'total_to_pay' => Tools::displayPrice($params['total_to_pay'], $params['currencyObj'], false), 'chequeName' => $this->chequeName, - 'chequeAddress' => nl2br2($this->address), + 'chequeAddress' => Tools::nl2br($this->address), 'status' => 'ok', 'id_order' => $params['objOrder']->id ));