[+] Classes: add DbQuery class in order to build queries (usefull when working with chunks of queries)

git-svn-id: http://dev.prestashop.com/svn/v1/branches/1.5.x@8668 b9a71923-0436-4b27-9f14-aed3839534dd
This commit is contained in:
rMalie
2011-09-20 16:14:19 +00:00
parent 92cc465a3c
commit 95233f9df5
13 changed files with 260 additions and 217 deletions
+10 -6
View File
@@ -76,10 +76,6 @@
'Customization' => 'override/classes/Customization.php',
'DateRangeCore' => 'classes/DateRange.php',
'DateRange' => 'override/classes/DateRange.php',
'DbCore' => 'classes/Db.php',
'Db' => 'override/classes/Db.php',
'DbMySQLiCore' => 'classes/DbMySQLi.php',
'DbMySQLi' => 'override/classes/DbMySQLi.php',
'DeliveryCore' => 'classes/Delivery.php',
'Delivery' => 'override/classes/Delivery.php',
'DiscountCore' => 'classes/Discount.php',
@@ -146,8 +142,6 @@
'ModuleGrid' => 'override/classes/ModuleGrid.php',
'ModuleGridEngineCore' => 'classes/ModuleGridEngine.php',
'ModuleGridEngine' => 'override/classes/ModuleGridEngine.php',
'MySQLCore' => 'classes/MySQL.php',
'MySQL' => 'override/classes/MySQL.php',
'NotificationCore' => 'classes/Notification.php',
'Notification' => 'override/classes/Notification.php',
'ObjectModelCore' => 'classes/ObjectModel.php',
@@ -252,6 +246,16 @@
'WebserviceSpecificManagementSearch' => 'override/classes/WebserviceSpecificManagementSearch.php',
'ZoneCore' => 'classes/Zone.php',
'Zone' => 'override/classes/Zone.php',
'DbCore' => 'classes/db/Db.php',
'Db' => 'override/classes/db/Db.php',
'DbMySQLiCore' => 'classes/db/DbMySQLi.php',
'DbMySQLi' => 'override/classes/db/DbMySQLi.php',
'DbPDOCore' => 'classes/db/DbPDO.php',
'DbPDO' => 'override/classes/db/DbPDO.php',
'DbQueryCore' => 'classes/db/DbQuery.php',
'DbQuery' => 'override/classes/db/DbQuery.php',
'MySQLCore' => 'classes/db/MySQL.php',
'MySQL' => 'override/classes/db/MySQL.php',
'GroupShopCore' => 'classes/shop/GroupShop.php',
'GroupShop' => 'override/classes/shop/GroupShop.php',
'ShopCore' => 'classes/shop/Shop.php',
+45 -38
View File
@@ -366,61 +366,68 @@ class CartCore extends ObjectModel
$id_country = Context::getContext()->country->id;
// Build query
$sql = array();
$sql = new DbQuery();
// Build SELECT
$sql['select'] = 'SELECT cp.`id_product_attribute`, cp.`id_product`, cp.`quantity` AS cart_quantity, cp.id_shop, pl.`name`,
pl.`description_short`, pl.`available_now`, pl.`available_later`, p.`id_product`, p.`id_category_default`, p.`id_supplier`, p.`id_manufacturer`, p.`on_sale`, p.`ecotax`, p.`additional_shipping_cost`, p.`available_for_order`,
p.`price`, p.`weight`, p.`width`, p.`height`, p.`depth`, p.`out_of_stock`, p.`active`, p.`date_add`, p.`date_upd`,
t.`id_tax`, tl.`name` AS tax, t.`rate`, stock.quantity, pl.`link_rewrite`, cl.`link_rewrite` AS category, CONCAT(cp.`id_product`, cp.`id_product_attribute`) AS unique_id';
$sql->select('cp.`id_product_attribute`, cp.`id_product`, cp.`quantity` AS cart_quantity, cp.id_shop, pl.`name`')
->select('pl.`description_short`, pl.`available_now`, pl.`available_later`, p.`id_product`, p.`id_category_default`, p.`id_supplier`, p.`id_manufacturer`')
->select('p.`on_sale`, p.`ecotax`, p.`additional_shipping_cost`, p.`available_for_order`, p.`price`, p.`weight`, p.`width`, p.`height`, p.`depth`, p.`out_of_stock`')
->select('p.`active`, p.`date_add`, p.`date_upd`, t.`id_tax`, tl.`name` AS tax, t.`rate`, stock.quantity, pl.`link_rewrite`, cl.`link_rewrite` AS category')
->select('CONCAT(cp.`id_product`, cp.`id_product_attribute`) AS unique_id');
// Build FROM
$sql['from'] = 'FROM `'._DB_PREFIX_.'cart_product` cp';
$sql->from(_DB_PREFIX_.'cart_product cp');
// Build JOIN
$sql['join'] = 'LEFT JOIN `'._DB_PREFIX_.'product` p ON p.`id_product` = cp.`id_product`
LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = '.(int)$this->id_lang.Context::getContext()->shop->sqlLang('pl').')
LEFT JOIN `'._DB_PREFIX_.'tax_rule` tr ON (p.`id_tax_rules_group` = tr.`id_tax_rules_group`
AND tr.`id_country` = '.(int)$id_country.'
AND tr.`id_state` = 0
AND tr.`zipcode_from` = 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)$this->id_lang.')
LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON (p.`id_category_default` = cl.`id_category` AND cl.`id_lang` = '.(int)$this->id_lang.Context::getContext()->shop->sqlLang('cl').')
'.Product::sqlStock('cp', 'cp');
$sql->leftJoin(_DB_PREFIX_.'product p', 'p.`id_product` = cp.`id_product`')
->leftJoin(_DB_PREFIX_.'product_lang pl', 'p.`id_product` = pl.`id_product` AND pl.`id_lang` = '.(int)$this->id_lang.Context::getContext()->shop->sqlLang('pl'))
->leftJoin(_DB_PREFIX_.'tax_rule tr', 'p.`id_tax_rules_group` = tr.`id_tax_rules_group`
AND tr.`id_country` = '.(int)$id_country.'
AND tr.`id_state` = 0
AND tr.`zipcode_from` = 0')
->leftJoin(_DB_PREFIX_.'tax t', 't.`id_tax` = tr.`id_tax`')
->leftJoin(_DB_PREFIX_.'tax_lang tl', 't.`id_tax` = tl.`id_tax` AND tl.`id_lang` = '.(int)$this->id_lang)
->leftJoin(_DB_PREFIX_.'category_lang cl', 'p.`id_category_default` = cl.`id_category` AND cl.`id_lang` = '.(int)$this->id_lang.Context::getContext()->shop->sqlLang('cl'));
// @todo test if everything is ok, then refactorise call of this method
Product::sqlStock('cp', 'cp', false, null, $sql);
// Build WHERE clauses
$sql['where'] = '
WHERE cp.`id_cart` = '.(int)$this->id.'
'.($id_product ? ' AND cp.`id_product` = '.(int)$id_product : '').'
AND p.`id_product` IS NOT NULL';
$sql->where('cp.`id_cart` = '.(int)$this->id);
if ($id_product)
$sql->where('cp.`id_product` = '.(int)$id_product);
$sql->where('p.`id_product` IS NOT NULL');
// Build GROUP BY
$sql['groupby'] = 'GROUP BY unique_id';
$sql->group('unique_id');
// Build ORDER BY
$sql['orderby'] = 'ORDER BY cp.date_add ASC';
$sql->order('cp.date_add ASC');
if (Customization::isFeatureActive())
{
$sql['select'] .= ', cu.`id_customization`, cu.`quantity` AS customization_quantity';
$sql['join'] .= 'LEFT JOIN `'._DB_PREFIX_.'customization` cu ON (p.`id_product` = cu.`id_product`)';
$sql->select('cu.`id_customization`, cu.`quantity` AS customization_quantity');
$sql->leftJoin(_DB_PREFIX_.'customization` cu ON (p.`id_product` = cu.`id_product`)');
}
if (Combination::isFeatureActive())
{
$sql['select'] .= ', pa.`price` AS price_attribute, pa.`ecotax` AS ecotax_attr,
IF (IFNULL(pa.`reference`, \'\') = \'\', p.`reference`, pa.`reference`) AS reference,
IF (IFNULL(pa.`supplier_reference`, \'\') = \'\', p.`supplier_reference`, pa.`supplier_reference`) AS supplier_reference,
(p.`weight`+ pa.`weight`) weight_attribute,
IF (IFNULL(pa.`ean13`, \'\') = \'\', p.`ean13`, pa.`ean13`) AS ean13, IF (IFNULL(pa.`upc`, \'\') = \'\', p.`upc`, pa.`upc`) AS upc,
pai.`id_image` as pai_id_image, IFNULL(pa.`minimal_quantity`, p.`minimal_quantity`) as minimal_quantity, pa.`ecotax` AS ecotax_attr';
$sql['join'] .= '
LEFT JOIN `'._DB_PREFIX_.'product_attribute` pa ON (pa.`id_product_attribute` = cp.`id_product_attribute`)
LEFT JOIN `'._DB_PREFIX_.'product_attribute_image` pai ON (pai.`id_product_attribute` = pa.`id_product_attribute`)
';
$sql->select('pa.`price` AS price_attribute, pa.`ecotax` AS ecotax_attr')
->select('IF (IFNULL(pa.`reference`, \'\') = \'\', p.`reference`, pa.`reference`) AS reference')
->select('IF (IFNULL(pa.`supplier_reference`, \'\') = \'\', p.`supplier_reference`, pa.`supplier_reference`) AS supplier_reference')
->select('(p.`weight`+ pa.`weight`) weight_attribute')
->select('IF (IFNULL(pa.`ean13`, \'\') = \'\', p.`ean13`, pa.`ean13`) AS ean13, IF (IFNULL(pa.`upc`, \'\') = \'\', p.`upc`, pa.`upc`) AS upc')
->select('pai.`id_image` as pai_id_image, IFNULL(pa.`minimal_quantity`, p.`minimal_quantity`) as minimal_quantity, pa.`ecotax` AS ecotax_attr');
$sql->leftJoin(_DB_PREFIX_.'product_attribute pa', 'pa.`id_product_attribute` = cp.`id_product_attribute`')
->leftJoin(_DB_PREFIX_.'product_attribute_image pai', 'pai.`id_product_attribute` = pa.`id_product_attribute`');
}
else
$sql['select'] .= ', p.`reference` AS reference, p.`supplier_reference` AS supplier_reference,
p.`ean13`, p.`upc` AS upc, p.`minimal_quantity` AS minimal_quantity';
$sql->select('p.`reference` AS reference, p.`supplier_reference` AS supplier_reference, p.`ean13`, p.`upc` AS upc, p.`minimal_quantity` AS minimal_quantity');
$result = Db::getInstance()->ExecuteS($sql);
$result = Db::getInstance()->ExecuteS(Tools::buildQuery($sql));
// Reset the cache before the following return, or else an empty cart will add dozens of queries
$productsIds = array();
$paIds = array();
foreach ($result as $row)
+29 -10
View File
@@ -2056,22 +2056,41 @@ class ProductCore extends ObjectModel
* @param Context $context
* @return string
*/
public static function sqlStock($productAlias, $productAttribute = 0, $innerJoin = false, Shop $shop = null)
public static function sqlStock($productAlias, $productAttribute = 0, $innerJoin = false, Shop $shop = null, DbQuery $sql = null)
{
if (!$shop)
$shop = Context::getContext()->shop;
$sql = (($innerJoin) ? ' INNER ' : ' LEFT ').'JOIN '._DB_PREFIX_.'stock stock ON stock.id_product = '.pSQL($productAlias).'.id_product';
if (!is_null($productAttribute))
if ($sql)
{
if (!Combination::isFeatureActive())
$sql .= ' AND stock.id_product_attribute = 0';
else if (is_numeric($productAttribute))
$sql .= ' AND stock.id_product_attribute = '.$productAttribute;
else if (is_string($productAttribute))
$sql .= ' AND stock.id_product_attribute = IFNULL('.pSQL($productAttribute).'.id_product_attribute, 0)';
// @todo remove this code when query builder is accepted or removed
$method = ($innerJoin) ? 'innerJoin' : 'leftJoin';
$sql->$method(_DB_PREFIX_.'stock stock', 'stock.id_product = '.pSQL($productAlias).'.id_product');
if (!is_null($productAttribute))
{
if (!Combination::isFeatureActive())
$sql->where('stock.id_product_attribute = 0');
else if (is_numeric($productAttribute))
$sql->where('stock.id_product_attribute = '.$productAttribute);
else if (is_string($productAttribute))
$sql->where('stock.id_product_attribute = IFNULL('.pSQL($productAttribute).'.id_product_attribute, 0)');
}
$sql->where(ltrim($shop->sqlRestriction(Shop::SHARE_STOCK, 'stock'), ' AND '));
}
else
{
$sql = (($innerJoin) ? ' INNER ' : ' LEFT ').'JOIN '._DB_PREFIX_.'stock stock ON stock.id_product = '.pSQL($productAlias).'.id_product';
if (!is_null($productAttribute))
{
if (!Combination::isFeatureActive())
$sql .= ' AND stock.id_product_attribute = 0';
else if (is_numeric($productAttribute))
$sql .= ' AND stock.id_product_attribute = '.$productAttribute;
else if (is_string($productAttribute))
$sql .= ' AND stock.id_product_attribute = IFNULL('.pSQL($productAttribute).'.id_product_attribute, 0)';
}
$sql .= $shop->sqlRestriction(Shop::SHARE_STOCK, 'stock') . ' ';
}
$sql .= $shop->sqlRestriction(Shop::SHARE_STOCK, 'stock') . ' ';
return $sql;
}
+79 -74
View File
@@ -70,7 +70,7 @@ class ToolsCore
}
$explode = explode('?', $url);
// don't use ssl if url is home page
// don't use ssl if url is home page
// used when logout for example
$useSSL = !empty($url);
$url = $link->getPageLink($explode[0], $useSSL);
@@ -216,7 +216,7 @@ class ToolsCore
}
return $_SERVER['REMOTE_ADDR'];
}
/**
* Check if the current page use SSL connection on not
*
@@ -229,10 +229,10 @@ class ToolsCore
// $_SERVER['SSL'] exists only in some specific configuration
if (isset($_SERVER['SSL']))
return ($_SERVER['SSL'] == 1 || strtolower($_SERVER['SSL']) == 'on');
return false;
}
/**
* Get the current url prefix protocol (https/http)
*
@@ -669,7 +669,7 @@ class ToolsCore
$row['meta_title'] = $row['meta_title'].(!empty($page_number) ? ' ('.$page_number.')' : '').' - '.Configuration::get('PS_SHOP_NAME');
else
$row['meta_title'] = $row['name'].(!empty($page_number) ? ' ('.$page_number.')' : '').' - '.Configuration::get('PS_SHOP_NAME');
return self::completeMetaTags($row, $row['name']);
}
}
@@ -725,7 +725,7 @@ class ToolsCore
return self::completeMetaTags($row, $row['meta_title']);
}
}
/* CMS category specifics meta tags */
elseif ($id_cms = self::getValue('id_cms_category'))
{
@@ -927,11 +927,11 @@ class ToolsCore
{
return self::str2url($str);
}
/**
* Return a friendly url made from the provided string
* If the mbstring library is available, the output is the same as the js function of the same name
*
*
* @param string $str
* @return string
*/
@@ -1281,7 +1281,7 @@ class ToolsCore
'/\\s*(<script\\b[^>]*?>)([\\s\\S]*?)(<\\/script>)\\s*/i'
,array('Tools', 'packJSinHTMLpregCallback')
,$html_content);
// If the string is too big preg_replace return an error
// In this case, we don't compress the content
if( preg_last_error() == PREG_BACKTRACK_LIMIT_ERROR ) {
@@ -1354,9 +1354,9 @@ class ToolsCore
public static function replaceByAbsoluteURL($matches)
{
global $current_css_file;
$protocol_link = self::getCurrentUrlProtocolPrefix();
if (array_key_exists(1, $matches))
{
$tmp = dirname($current_css_file).'/'.$matches[1];
@@ -1378,7 +1378,7 @@ class ToolsCore
$context = Context::getContext();
$context->controller->addJs($js_uri);
}
/**
* addCSS allows you to add stylesheet at any time.
*
@@ -1477,10 +1477,10 @@ class ToolsCore
return $css_files;
}
/**
* Combine Compress and Cache (ccc) JS calls
*
*
* @param array js_files
* @return array processed js_files
*/
@@ -1498,17 +1498,17 @@ class ToolsCore
foreach ($js_files as $filename)
{
$expr = explode(':', $filename);
if ($expr[0] == 'http')
$js_external_files[] = $filename;
else
$js_external_files[] = $filename;
else
{
$infos = array();
$infos['uri'] = $filename;
$url_data = parse_url($filename);
$infos['path'] =_PS_ROOT_DIR_.self::str_replace_once(__PS_BASE_URI__, '/', $url_data['path']);
$js_files_infos[] = $infos;
$js_files_date = max(
file_exists($infos['path']) ? filemtime($infos['path']) : 0,
$js_files_date
@@ -1565,7 +1565,7 @@ class ToolsCore
else
self::$_cache_nb_media_servers = 3;
}
if (self::$_cache_nb_media_servers AND ($id_media_server = (abs(crc32($filename)) % self::$_cache_nb_media_servers + 1)))
return constant('_MEDIA_SERVER_'.$id_media_server.'_');
return self::getHttpHost();
@@ -1597,7 +1597,7 @@ class ToolsCore
if (!$write_fd = @fopen($path, 'w'))
return false;
fwrite($write_fd, trim($specific_before)."\n\n");
$domains = array();
foreach (ShopUrl::getShopUrls() as $shop_url)
{
@@ -1621,7 +1621,7 @@ class ToolsCore
// Disable multiviews ?
if ($disable_multiviews)
fwrite($write_fd, "\n# Disable Multiviews\nOptions -Multiviews\n\n");
fwrite($write_fd, "RewriteEngine on\n\n");
foreach ($domains as $domain => $list_uri)
foreach ($list_uri as $uri)
@@ -1711,8 +1711,8 @@ FileETag INode MTime Size
/**
* jsonDecode convert json string to php array / object
*
* @param string $json
*
* @param string $json
* @param boolean $assoc (since 1.4.2.4) if true, convert to associativ array
* @return array
*/
@@ -1725,12 +1725,12 @@ FileETag INode MTime Size
include_once(_PS_TOOL_DIR_.'json/json.php');
$pearJson = new Services_JSON(($assoc) ? SERVICES_JSON_LOOSE_TYPE : 0);
return $pearJson->decode($json);
}
}
}
}
/**
* Convert an array to json string
*
*
* @param array $data
* @return string json
*/
@@ -1743,21 +1743,26 @@ FileETag INode MTime Size
include_once(_PS_TOOL_DIR_.'json/json.php');
$pearJson = new Services_JSON();
return $pearJson->encode($data);
}
}
}
}
/**
* Display a warning message indicating that the method is deprecated
*/
public static function displayAsDeprecated()
public static function displayAsDeprecated($message = null)
{
if (_PS_DISPLAY_COMPATIBILITY_WARNING_)
{
$backtrace = debug_backtrace();
$callee = next($backtrace);
trigger_error('Function <strong>'.$callee['function'].'()</strong> is deprecated in <strong>'.$callee['file'].'</strong> on line <strong>'.$callee['line'].'</strong><br />', E_USER_WARNING);
$message = self::displayError('The function').' '.$callee['function'].' ('.self::displayError('Line').' '.$callee['line'].') '.self::displayError('is deprecated and will be removed in the next major version.');
if ($message)
trigger_error($message, E_USER_WARNING);
else
{
trigger_error('Function <strong>'.$callee['function'].'()</strong> is deprecated in <strong>'.$callee['file'].'</strong> on line <strong>'.$callee['line'].'</strong><br />', E_USER_WARNING);
$message = self::displayError('The function').' '.$callee['function'].' ('.self::displayError('Line').' '.$callee['line'].') '.self::displayError('is deprecated and will be removed in the next major version.');
}
Logger::addLog($message, 3, $callee['class']);
}
@@ -1771,7 +1776,7 @@ FileETag INode MTime Size
$backtrace = debug_backtrace();
$callee = next($backtrace);
$error = 'Parameter <strong>'.$parameter.'</strong> in function <strong>'.$callee['function'].'()</strong> is deprecated in <strong>'.$callee['file'].'</strong> on line <strong>'.$callee['Line'].'</strong><br />';
$message = self::displayError('The parameter').' '.$parameter.' '.self::displayError(' in function ').' '.$callee['function'].' ('.self::displayError('Line').' '.$callee['Line'].') '.self::displayError('is deprecated and will be removed in the next major version.');
$message = self::displayError('The parameter').' '.$parameter.' '.self::displayError(' in function ').' '.$callee['function'].' ('.self::displayError('Line').' '.$callee['Line'].') '.self::displayError('is deprecated and will be removed in the next major version.');
self::throwDeprecated($error, $message, $callee['class']);
}
@@ -1814,7 +1819,7 @@ FileETag INode MTime Size
{
if (!$context)
$context = Context::getContext();
if (isset(self::$_forceCompile))
$context->smarty->force_compile = (int)(self::$_forceCompile);
if (isset(self::$_caching))
@@ -1834,7 +1839,7 @@ FileETag INode MTime Size
$s = str_replace($char, '\\'.$char, $s);
return $s;
}
public static function str_replace_once($needle , $replace, $haystack)
{
$pos = strpos($haystack, $needle);
@@ -1842,8 +1847,8 @@ FileETag INode MTime Size
return $haystack;
return substr_replace($haystack, $replace, $pos, strlen($needle));
}
/**
* Function property_exists does not exist in PHP < 5.1
*
@@ -1855,12 +1860,12 @@ FileETag INode MTime Size
{
if (function_exists('property_exists'))
return property_exists($class, $property);
if (is_object($class))
$vars = get_object_vars($class);
else
$vars = get_class_vars($class);
return array_key_exists($property, $vars);
}
@@ -1871,7 +1876,7 @@ FileETag INode MTime Size
public static function checkPhpVersion()
{
$version = null;
if(defined('PHP_VERSION'))
$version = PHP_VERSION;
else
@@ -1883,7 +1888,7 @@ FileETag INode MTime Size
return $version;
}
/**
* @desc try to open a zip file in order to check if it's valid
* @return bool success
@@ -1898,11 +1903,11 @@ FileETag INode MTime Size
else
{
require_once(dirname(__FILE__).'/../tools/pclzip/pclzip.lib.php');
$zip = new PclZip($fromFile);
return ($zip->privCheckFormat() === true);
$zip = new PclZip($fromFile);
return ($zip->privCheckFormat() === true);
}
}
/**
* @desc extract a zip file to the given directory
* @return bool success
@@ -1921,7 +1926,7 @@ FileETag INode MTime Size
else
{
require_once(dirname(__FILE__).'/../tools/pclzip/pclzip.lib.php');
$zip = new PclZip($fromFile);
$zip = new PclZip($fromFile);
$list = $zip->extract(PCLZIP_OPT_PATH, $toDir);
foreach ($list as $extractedFile)
if ($extractedFile['status'] != 'ok')
@@ -1929,10 +1934,10 @@ FileETag INode MTime Size
return true;
}
}
/**
* Get products order field name for queries.
*
*
* @param string $type by|way
* @param string $value If no index given, use default order from admin -> pref -> products
*/
@@ -1952,7 +1957,7 @@ FileETag INode MTime Size
elseif ($value == 'position' || empty($value))
$orderByPrefix = 'cp.';
}
$value = (is_null($value) || $value === false || $value === '') ? (int)Configuration::get('PS_PRODUCTS_ORDER_BY') : $value;
$list = array(0 => 'name', 1 => 'price', 2 => 'date_add', 3 => 'date_upd', 4 => 'position', 5 => 'manufacturer_name', 6 => 'quantity');
return $orderByPrefix.((isset($list[$value])) ? $list[$value] : ((in_array($value, $list)) ? $value : 'position'));
@@ -1997,7 +2002,7 @@ FileETag INode MTime Size
return $qty;
}
}
public static function display404Error()
{
header('HTTP/1.1 404 Not Found');
@@ -2005,10 +2010,10 @@ FileETag INode MTime Size
include(dirname(__FILE__).'/../404.php');
die;
}
/**
* Concat $begin and $end, add ? or & between strings
*
*
* @since 1.5.0
* @param string $begin
* @param string $end
@@ -2018,10 +2023,10 @@ FileETag INode MTime Size
{
return $begin.((strpos($begin, '?') !== false) ? '&' : '?').$end;
}
/**
* Display error and dies or silently log the error.
*
*
* @param string $msg
* @param bool $die
* @return success of logging
@@ -2043,48 +2048,48 @@ FileETag INode MTime Size
{
return str_replace(array("\r\n", "\r", "\n"), '<br />', $str);
}
/**
* Clear cache for Smarty
*
*
* @param objet $smarty
*/
public static function clearCache($smarty)
{
$smarty->clearAllCache();
}
/**
* getMemoryLimit allow to get the memory limit in octet
*
*
* @since 1.4.5.0
* @return int the memory limit value in octet
* @return int the memory limit value in octet
*/
public static function getMemoryLimit()
{
$memory_limit = @ini_get('memory_limit');
if (preg_match('/[0-9]+k/i', $memory_limit))
return 1024 * (int)$memory_limit;
if (preg_match('/[0-9]+m/i', $memory_limit))
return 1024 * 1024 * (int)$memory_limit;
if (preg_match('/[0-9]+g/i', $memory_limit))
return 1024 * 1024 * 1024 * (int)$memory_limit;
return $memory_limit;
}
/**
*
* @return bool true if the server use 64bit arch
*
* @return bool true if the server use 64bit arch
*/
public static function isX86_64arch()
{
return (PHP_INT_MAX == '9223372036854775807');
}
/**
* @param array SQL query in array
* @return string SQL query
@@ -2093,34 +2098,34 @@ FileETag INode MTime Size
{
if (!isset($sql['select']))
$sql['select'] = 'SELECT *';
$req = $sql['select']."\n";
$req .= $sql['from']."\n";
if (isset($sql['join']))
$req .= $sql['join']."\n";
if (isset($sql['where']))
$req .= $sql['where']."\n";
if (isset($sql['groupby']))
$req .= $sql['groupby']."\n";
if (isset($sql['having']))
$req .= $sql['having']."\n";
if (isset($sql['orderby']))
$req .= $sql['orderby']."\n";
if (isset($sql['limit']))
$req .= $sql['limit']."\n";
return $req;
}
/**
* Get max file upload size considering server settings and optional max value
*
*
* @param int $max_size optional max file size
* @return int max file size in bytes
*/
+50 -44
View File
@@ -1,6 +1,6 @@
<?php
/*
* 2007-2011 PrestaShop
* 2007-2011 PrestaShop
*
* NOTICE OF LICENSE
*
@@ -52,7 +52,7 @@ abstract class DbCore
protected static $_instance = array();
/** @var array Object instance for singleton */
protected static $_servers = array(
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'),
@@ -61,36 +61,36 @@ abstract class DbCore
/**
* Store last executed query
*
*
* @var string
*/
protected $_lastQuery;
/**
* Last cached query
*
*
* @var string
*/
protected $_lastCached;
/**
* 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
*/
@@ -107,17 +107,17 @@ abstract class DbCore
abstract public function Affected_Rows();
/**
* Get next row for a query which doesn't return an array
* Get next row for a query which doesn't return an array
*/
abstract public function nextRow($result = false);
/**
* Get database version
*
*
* @return string
*/
abstract public function getVersion();
/**
* Protect string against SQL injections
*
@@ -130,12 +130,12 @@ abstract class DbCore
* 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);
@@ -163,13 +163,13 @@ abstract class DbCore
$class = Db::getClass();
self::$_instance[$idServer] = new $class(self::$_servers[$idServer]['server'], self::$_servers[$idServer]['user'], self::$_servers[$idServer]['password'], self::$_servers[$idServer]['database']);
}
return self::$_instance[$idServer];
}
/**
* Get child layer class
*
*
* @return string
*/
public static function getClass()
@@ -182,7 +182,7 @@ abstract class DbCore
/**
* Instantiate database connection
*
*
* @param string $server Server address
* @param string $user User login
* @param string $password User password
@@ -196,14 +196,14 @@ abstract class DbCore
$this->_password = $password;
$this->_type = _DB_TYPE_;
$this->_database = $database;
if (!defined('_PS_DEBUG_SQL_'))
define('_PS_DEBUG_SQL_', false);
if ($connect)
$this->connect();
}
/**
* Close connection to database
*/
@@ -257,7 +257,7 @@ abstract class DbCore
}
else
die('Wrong argument (miss type) in Db::autoExecute()');
return false;
}
@@ -278,18 +278,19 @@ abstract class DbCore
/**
* Execute a query and get result ressource
*
*
* @param string $sql
* @return mixed
*/
public function query($sql)
{
$sql = (string)$sql;
$result = $this->_query($sql);
if (_PS_DEBUG_SQL_)
$this->displayError($sql);
return $result;
}
/**
* Execute a DELETE query
*
@@ -308,7 +309,7 @@ abstract class DbCore
Cache::getInstance()->deleteQuery($sql);
return $res;
}
/**
* Execute a query
*
@@ -318,22 +319,24 @@ abstract class DbCore
*/
public function Execute($sql, $use_cache = 1)
{
$sql = (string)$sql;
$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
* @return array or result object
*/
public function ExecuteS($sql, $array = true, $use_cache = 1)
{
$sql = (string)$sql;
$this->_result = false;
$this->_lastQuery = $sql;
if ($use_cache AND _PS_CACHE_ENABLED_ && $array AND ($result = Cache::getInstance()->get(md5($sql))))
@@ -354,7 +357,7 @@ abstract class DbCore
while ($row = $this->nextRow($this->_result))
$resultArray[] = $row;
if ($use_cache AND _PS_CACHE_ENABLED_)
if ($use_cache AND _PS_CACHE_ENABLED_)
Cache::getInstance()->setQuery($sql, $resultArray);
return $resultArray;
}
@@ -362,13 +365,14 @@ abstract class DbCore
/**
* 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 = (string)$sql;
$sql .= ' LIMIT 1';
$this->_result = false;
$this->_lastQuery = $sql;
@@ -391,21 +395,22 @@ abstract class DbCore
/**
* getValue return the first item of a select query.
*
* @param mixed $sql
* @param int $use_cache
*
* @param mixed $sql
* @param int $use_cache
* @return void
*/
public function getValue($sql, $use_cache = 1)
{
$sql = (string)$sql;
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()
@@ -420,11 +425,11 @@ abstract class DbCore
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
*/
@@ -432,6 +437,7 @@ abstract class DbCore
{
global $webservice_call;
$sql = (string)$sql;
$this->_result = false;
$result = $this->query($sql);
if ($use_cache AND _PS_CACHE_ENABLED_)
@@ -458,7 +464,7 @@ abstract class DbCore
die(Tools::displayError($this->getMsgError()));
}
}
/**
* Sanitize data which will be injected into SQL query
*
@@ -476,13 +482,13 @@ abstract class DbCore
if (!$htmlOK)
$string = strip_tags(Tools::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
@@ -497,7 +503,7 @@ abstract class DbCore
/**
* 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
@@ -518,14 +524,14 @@ abstract class DbCore
{
return Db::getInstance()->ExecuteS($sql, true, $use_cache);
}
static public function ps($sql, $use_cache = 1)
{
$ret = Db::s($sql, $use_cache);
p($ret);
return $ret;
}
static public function ds($sql, $use_cache = 1)
{
Db::s($sql, $use_cache);
@@ -1,6 +1,6 @@
<?php
/*
* 2007-2011 PrestaShop
* 2007-2011 PrestaShop
*
* NOTICE OF LICENSE
*
@@ -25,6 +25,9 @@
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* @since 1.5.0
*/
class DbMySQLiCore extends Db
{
/**
@@ -33,7 +36,7 @@ class DbMySQLiCore extends Db
public function connect()
{
$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())
die(Tools::displayError('Link to database cannot be established : '.mysqli_connect_error()));
@@ -44,7 +47,7 @@ class DbMySQLiCore extends Db
return $this->_link;
}
/**
* @see DbCore::disconnect()
*/
@@ -52,7 +55,7 @@ class DbMySQLiCore extends Db
{
$this->_link->close();
}
/**
* @see DbCore::_query()
*/
@@ -70,7 +73,7 @@ class DbMySQLiCore extends Db
$result = $this->_result;
return $result->fetch_assoc();
}
/**
* @see DbCore::_numRows()
*/
@@ -78,7 +81,7 @@ class DbMySQLiCore extends Db
{
return $result->num_rows;
}
/**
* @see DbCore::Insert_ID()
*/
@@ -110,7 +113,7 @@ class DbMySQLiCore extends Db
{
return $this->_link->errno;
}
/**
* @see DbCore::getVersion()
*/
@@ -118,7 +121,7 @@ class DbMySQLiCore extends Db
{
return $this->getValue('SELECT VERSION()');
}
/**
* @see DbCore::_escape()
*/
@@ -126,7 +129,7 @@ class DbMySQLiCore extends Db
{
return $this->_link->real_escape_string($str);
}
/**
* @see DbCore::set_db()
*/
+8 -8
View File
@@ -1,6 +1,6 @@
<?php
/*
* 2007-2011 PrestaShop
* 2007-2011 PrestaShop
*
* NOTICE OF LICENSE
*
@@ -38,7 +38,7 @@ $smarty->config_dir = _PS_SMARTY_DIR_.'configs';
$smarty->caching = false;
$smarty->force_compile = (Configuration::get('PS_SMARTY_FORCE_COMPILE') == _PS_SMARTY_FORCE_COMPILE_) ? true : false;
$smarty->compile_check = (Configuration::get('PS_SMARTY_FORCE_COMPILE') == _PS_SMARTY_CHECK_COMPILE_) ? true : false;
$smarty->debugging = false;
$smarty->debugging = false;
$smarty->debugging_ctrl = 'URL'; // 'NONE' on production
$smarty->deprecation_notices = false; // so many depreciated yet not migrated smarty calls
@@ -69,7 +69,7 @@ function smartyTranslate($params, &$smarty)
global $_LANG, $_MODULES, $cookie, $_MODULE;
if (!isset($params['js'])) $params['js'] = 0;
if (!isset($params['mod'])) $params['mod'] = false;
$string = str_replace('\'', '\\\'', $params['s']);
$filename = ((!isset($smarty->compiler_object) OR !is_object($smarty->compiler_object->template)) ? $smarty->template_filepath : $smarty->compiler_object->template->getTemplateFilepath());
$key = Tools::substr(basename($filename), 0, -4).'_'.md5($string);
@@ -88,7 +88,7 @@ function smartyTranslate($params, &$smarty)
$translationsFile = _PS_MODULE_DIR_.$params['mod'].'/'.$iso.'.php';
$key = '<{'.$params['mod'].'}prestashop>'.$key;
}
if(!is_array($_MODULES))
$_MODULES = array();
if (@include_once($translationsFile))
@@ -96,14 +96,14 @@ function smartyTranslate($params, &$smarty)
$_MODULES = array_merge($_MODULES, $_MODULE);
$lang_array = $_MODULES;
}
if (is_array($lang_array) AND key_exists($key, $lang_array))
$msg = $lang_array[$key];
elseif (is_array($lang_array) AND key_exists(Tools::strtolower($key), $lang_array))
$msg = $lang_array[Tools::strtolower($key)];
else
$msg = $params['s'];
if ($msg != $params['s'])
$msg = $params['js'] ? addslashes($msg) : stripslashes($msg);
return $params['js'] ? $msg : Tools::htmlentitiesUTF8($msg);
@@ -124,7 +124,7 @@ function smartyMaxWords($params, &$smarty)
Tools::displayAsDeprecated();
$params['s'] = str_replace('...', ' ...', html_entity_decode($params['s'], ENT_QUOTES, 'UTF-8'));
$words = explode(' ', $params['s']);
foreach($words AS &$word)
if(Tools::strlen($word) > $params['n'])
$word = Tools::substr(trim(chunk_split($word, $params['n']-1, '- ')), 0, -1);
@@ -149,7 +149,7 @@ function smarty_modifier_truncate($string, $length = 80, $etc = '...', $break_wo
{
if (!$length)
return '';
if (Tools::strlen($string) > $length)
{
$length -= min($length, Tools::strlen($etc));
+27 -28
View File
@@ -1,6 +1,6 @@
<?php
/*
* 2007-2011 PrestaShop
* 2007-2011 PrestaShop
*
* NOTICE OF LICENSE
*
@@ -132,7 +132,7 @@ class Tools extends ToolsCore
}
/**
* ALIAS OF dieObject() - Display an error with detailed object
* ALIAS OF dieObject() - Display an error with detailed object
* (display in firefox console if Firephp is enabled)
*
* @param object $object Object to display
@@ -159,7 +159,7 @@ class Tools extends ToolsCore
{
if(PS_USE_FIREPHP)
FB::info($object);
else
else
return parent::p($object);
return $object;
}
@@ -170,19 +170,18 @@ class Tools extends ToolsCore
*/
public static function displayAsDeprecated()
{
if (_PS_DISPLAY_COMPATIBILITY_WARNING_)
{
$backtrace = debug_backtrace();
$callee = next($backtrace);
if(PS_USE_FIREPHP)
FB::warn('Function <strong>'.$callee['function'].'()</strong> is deprecated in <strong>'.$callee['file'].'</strong> on line <strong>'.$callee['line'].'</strong><br />', 'Deprecated method');
else
trigger_error('Function <strong>'.$callee['function'].'()</strong> is deprecated in <strong>'.$callee['file'].'</strong> on line <strong>'.$callee['line'].'</strong><br />', E_USER_WARNING);
$backtrace = debug_backtrace();
$callee = next($backtrace);
if (PS_USE_FIREPHP)
FB::warn('Function <strong>'.$callee['function'].'()</strong> is deprecated in <strong>'.$callee['file'].'</strong> on line <strong>'.$callee['line'].'</strong><br />', 'Deprecated method');
else
trigger_error('Function <strong>'.$callee['function'].'()</strong> is deprecated in <strong>'.$callee['file'].'</strong> on line <strong>'.$callee['line'].'</strong><br />', E_USER_WARNING);
$message = Tools::displayError('The function').' '.$callee['function'].' ('.Tools::displayError('Line').' '.$callee['line'].') '.Tools::displayError('is deprecated and will be removed in the next major version.');
Logger::addLog($message, 3, $callee['class']);
}
$message = Tools::displayError('The function').' '.$callee['function'].' ('.Tools::displayError('Line').' '.$callee['line'].') '.Tools::displayError('is deprecated and will be removed in the next major version.');
Logger::addLog($message, 3, $callee['class']);
}
}
/**
@@ -208,9 +207,9 @@ class Tools extends ToolsCore
/**
* use of FirePHP::error() if allowed
*
* @param mixed $obj
* @param string $label
*
* @param mixed $obj
* @param string $label
* @return void
*/
public static function error($obj, $label = '')
@@ -221,9 +220,9 @@ class Tools extends ToolsCore
/**
* use of FirePHP::warn() if allowed
*
* @param mixed $obj
* @param string $label
*
* @param mixed $obj
* @param string $label
* @return void
*/
public static function warn($obj, $label = '')
@@ -234,9 +233,9 @@ class Tools extends ToolsCore
/**
* use of FirePHP::info() if allowed
*
* @param mixed $obj
* @param string $label
*
* @param mixed $obj
* @param string $label
* @return void
*/
public static function info($obj, $label = '')
@@ -247,9 +246,9 @@ class Tools extends ToolsCore
/**
* use of FirePHP::log() if allowed
*
* @param mixed $obj
* @param string $label
*
* @param mixed $obj
* @param string $label
* @return void
*/
public static function log($obj, $label = '')
@@ -258,10 +257,10 @@ class Tools extends ToolsCore
FB::log($obj,$label);
}
/**
* display debug_backtrace()
* display debug_backtrace()
* (display in firefox console if Firephp is enabled)
*
* @param mixed $obj
*
* @param mixed $obj
* @return void
*/
public static function trace($obj = NULL, $label = '')