// Merge -> 10309

git-svn-id: http://dev.prestashop.com/svn/v1/branches/1.5.x@10333 b9a71923-0436-4b27-9f14-aed3839534dd
This commit is contained in:
rMalie
2011-11-21 11:05:10 +00:00
parent 2537c72189
commit 9d10de0848
365 changed files with 11185 additions and 1571 deletions
+21 -2
View File
@@ -557,6 +557,11 @@ if (Tools::isSubmit('helpAccess'))
if (Tools::isSubmit('getHookableList')) if (Tools::isSubmit('getHookableList'))
{ {
/* PrestaShop demo mode */
if (_PS_MODE_DEMO_)
die('{"hasError" : true, "errors" : ["Live Edit : This functionnality has been disabled"]}');
/* PrestaShop demo mode*/
if (!strlen(Tools::getValue('hooks_list'))) if (!strlen(Tools::getValue('hooks_list')))
die('{"hasError" : true, "errors" : ["Live Edit : no module on this page"]}'); die('{"hasError" : true, "errors" : ["Live Edit : no module on this page"]}');
@@ -589,6 +594,10 @@ if (Tools::isSubmit('getHookableList'))
if (Tools::isSubmit('getHookableModuleList')) if (Tools::isSubmit('getHookableModuleList'))
{ {
/* PrestaShop demo mode */
if (_PS_MODE_DEMO_)
die('{"hasError" : true, "errors" : ["Live Edit : This functionnality has been disabled"]}');
/* PrestaShop demo mode*/
include('../init.php'); include('../init.php');
$hook_name = Tools::getValue('hook'); $hook_name = Tools::getValue('hook');
@@ -609,6 +618,11 @@ if (Tools::isSubmit('getHookableModuleList'))
if (Tools::isSubmit('saveHook')) if (Tools::isSubmit('saveHook'))
{ {
/* PrestaShop demo mode */
if (_PS_MODE_DEMO_)
die('{"hasError" : true, "errors" : ["Live Edit : This functionnality has been disabled"]}');
/* PrestaShop demo mode*/
$hooks_list = explode(',', Tools::getValue('hooks_list')); $hooks_list = explode(',', Tools::getValue('hooks_list'));
$id_shop = (int)Tools::getValue('id_shop'); $id_shop = (int)Tools::getValue('id_shop');
if ($id_shop) if ($id_shop)
@@ -627,10 +641,15 @@ if (Tools::isSubmit('saveHook'))
$hookedModules = explode(',', Tools::getValue($hook)); $hookedModules = explode(',', Tools::getValue($hook));
$i = 1; $i = 1;
$value = ''; $value = '';
$ids = array();
foreach ($hookedModules as $module) foreach ($hookedModules as $module)
{ {
$ids = explode('_', $module); $id = explode('_', $module);
$value .= '('.(int)$ids[1].', '.$id_shop.', (SELECT id_hook FROM '._DB_PREFIX_.'hook WHERE `name` = \''.pSQL($hook).'\' LIMIT 1), '.(int)$i.'),'; if (!in_array($id[1], $ids))
{
$ids[] = $id[1];
$value .= '('.(int)$id[1].', (SELECT id_hook FROM `'._DB_PREFIX_.'hook` WHERE `name` = \''.pSQL($hook).'\' LIMIT 0, 1), '.(int)$i.'),';
}
$i++; $i++;
} }
$value = rtrim($value, ','); $value = rtrim($value, ',');
+2 -2
View File
@@ -84,8 +84,8 @@
$error = TXT_UNKNOWN_REQUEST; $error = TXT_UNKNOWN_REQUEST;
} }
echo "{"; echo "{";
echo "error:'" . $error . "',\n"; echo "error:'" . Tools::safeOutput($error) . "',\n";
echo "path:'" . $path . "'"; echo "path:'" . Tools::safeOutput($path) . "'";
echo "}"; echo "}";
?> ?>
+1 -1
View File
@@ -433,7 +433,7 @@ class AdminUpgrade extends AdminPreferences
else else
{ {
$this->next = 'download'; $this->next = 'download';
$this->nextDesc = $this->l('Shop desactivated. Now downloading (this can takes some times )...'); $this->nextDesc = $this->l('Shop deactivated. Now downloading (this can takes some times )...');
} }
} }
+2 -1
View File
@@ -135,7 +135,8 @@ class AddressCore extends ObjectModel
/* Get and cache address country name */ /* Get and cache address country name */
if ($this->id) if ($this->id)
{ {
$result = Db::getInstance()->getRow('SELECT `name` FROM `'._DB_PREFIX_.'country_lang` $result = Db::getInstance()->getRow('
SELECT `name` FROM `'._DB_PREFIX_.'country_lang`
WHERE `id_country` = '.(int)$this->id_country.' WHERE `id_country` = '.(int)$this->id_country.'
AND `id_lang` = '.($id_lang ? (int)$id_lang : Configuration::get('PS_LANG_DEFAULT'))); AND `id_lang` = '.($id_lang ? (int)$id_lang : Configuration::get('PS_LANG_DEFAULT')));
$this->country = $result['name']; $this->country = $result['name'];
+2 -2
View File
@@ -483,8 +483,8 @@ abstract class AdminTabCore
$this->_childValidation(); $this->_childValidation();
/* Checking for fields validity */ /* Checking for fields validity */
foreach ($rules['validate'] as $field => $function) foreach ($rules['validate'] AS $field => $function)
if (($value = Tools::getValue($field)) !== false && ($field != 'passwd')) if (($value = Tools::getValue($field)) !== false AND !empty($value) AND ($field != 'passwd'))
if (!Validate::$function($value)) if (!Validate::$function($value))
$this->_errors[] = $this->l('the field').' <b>'.call_user_func(array($className, 'displayFieldName'), $field, $className).'</b> '.$this->l('is invalid'); $this->_errors[] = $this->l('the field').' <b>'.call_user_func(array($className, 'displayFieldName'), $field, $className).'</b> '.$this->l('is invalid');
+5
View File
@@ -45,6 +45,11 @@ class CMSCore extends ObjectModel
protected $table = 'cms'; protected $table = 'cms';
protected $identifier = 'id_cms'; protected $identifier = 'id_cms';
protected $webserviceParameters = array(
'objectNodeName' => 'content',
'objectsNodeName' => 'content_management_system',
);
public function getFields() public function getFields()
{ {
$this->validateFields(); $this->validateFields();
+1 -1
View File
@@ -177,7 +177,7 @@ class CategoryCore extends ObjectModel
public function add($autodate = true, $nullValues = false) public function add($autodate = true, $nullValues = false)
{ {
$this->position = self::getLastPosition((int)$this->id_parent); $this->position = self::getLastPosition((int)$this->id_parent);
if (!isset($this->level_depth) || $this->level_depth != 0) if (!isset($this->level_depth))
$this->level_depth = $this->calcLevelDepth(); $this->level_depth = $this->calcLevelDepth();
$ret = parent::add($autodate); $ret = parent::add($autodate);
if (!isset($this->doNotRegenerateNTree) || !$this->doNotRegenerateNTree) if (!isset($this->doNotRegenerateNTree) || !$this->doNotRegenerateNTree)
+1 -1
View File
@@ -108,7 +108,7 @@ class ChartCore
$options = 'xaxis:{mode:"time",timeformat:\''.addslashes($this->format).'\',min:'.$this->from.'000,max:'.$this->to.'000}'; $options = 'xaxis:{mode:"time",timeformat:\''.addslashes($this->format).'\',min:'.$this->from.'000,max:'.$this->to.'000}';
if ($this->granularity == 'd') if ($this->granularity == 'd')
foreach ($this->curves as $curve) foreach ($this->curves as $curve)
for ($i = $this->from; $i <= $this->to; $i += 86400) for ($i = $this->from; $i <= $this->to; $i = strtotime('+1 day', $i))
if (!$curve->getPoint($i)) if (!$curve->getPoint($i))
$curve->setPoint($i, 0); $curve->setPoint($i, 0);
} }
+51 -89
View File
@@ -27,11 +27,7 @@
class CompareProductCore extends ObjectModel class CompareProductCore extends ObjectModel
{ {
public $id; public $id_compare;
public $id_product;
public $id_guest;
public $id_customer; public $id_customer;
@@ -40,80 +36,17 @@ class CompareProductCore extends ObjectModel
public $date_upd; public $date_upd;
protected $fieldRequired = array( protected $fieldRequired = array(
'id_product', 'id_compare',
'id_guest',
'id_customer'); 'id_customer');
protected $fieldsValidate = array( protected $fieldsValidate = array(
'id_product' => 'isUnsignedInt', 'id_compare' => 'isUnsignedInt',
'id_guest' => 'isUnsignedInt',
'id_customer' => 'isUnsignedInt' 'id_customer' => 'isUnsignedInt'
); );
protected $table = 'compare_product'; protected $table = 'compare';
protected $identifier = 'id_compare_product'; protected $identifier = 'id_compare';
/**
* Get all compare products of the guest
* @param int $id_guest
* @return array
*/
public static function getGuestCompareProducts($id_guest)
{
$results = Db::getInstance()->executeS('
SELECT DISTINCT `id_product`
FROM `'._DB_PREFIX_.'compare_product`
WHERE `id_guest` = '.(int)($id_guest));
$compareProducts = null;
if ($results)
foreach($results as $result)
$compareProducts[] = $result['id_product'];
return $compareProducts;
}
/**
* Add a compare product for the guest
* @param int $id_guest, int $id_product
* @return boolean
*/
public static function addGuestCompareProduct($id_guest, $id_product)
{
return Db::getInstance()->execute('
INSERT INTO `'._DB_PREFIX_.'compare_product` (`id_product`, `id_guest`, `id_customer`, `date_add`, `date_upd`)
VALUES ('.(int)($id_product).', '.(int)($id_guest).', 0, NOW(), NOW())
');
}
/**
* Remove a compare product for the guest
* @param int $id_guest, int $id_product
* @return boolean
*/
public static function removeGuestCompareProduct($id_guest, $id_product)
{
return Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'compare_product` WHERE `id_guest` = '.(int)($id_guest).' AND `id_product` = '.(int)($id_product));
}
/**
* Get the number of compare products of the guest
* @param int $id_guest
* @return int
*/
public static function getGuestNumberProducts($id_guest)
{
return (int)(Db::getInstance()->getValue('
SELECT count(`id_compare_product`)
FROM `'._DB_PREFIX_.'compare_product`
WHERE `id_guest` = '.(int)($id_guest)));;
}
/** /**
@@ -121,12 +54,13 @@ class CompareProductCore extends ObjectModel
* @param int $id_customer * @param int $id_customer
* @return array * @return array
*/ */
public static function getCustomerCompareProducts($id_customer) public static function getCompareProducts($id_compare)
{ {
$results = Db::getInstance()->executeS(' $results = Db::getInstance()->executeS('
SELECT DISTINCT `id_product` SELECT DISTINCT `id_product`
FROM `'._DB_PREFIX_.'compare_product` FROM `'._DB_PREFIX_.'compare` c
WHERE `id_customer` = '.(int)($id_customer)); LEFT JOIN `'._DB_PREFIX_.'compare_product` cp ON (cp.`id_compare` = c.`id_compare`)
WHERE cp.`id_compare` = '.(int)($id_compare));
$compareProducts = null; $compareProducts = null;
@@ -143,36 +77,51 @@ class CompareProductCore extends ObjectModel
* @param int $id_customer, int $id_product * @param int $id_customer, int $id_product
* @return boolean * @return boolean
*/ */
public static function addCustomerCompareProduct($id_customer, $id_product) public static function addCompareProduct($id_compare, $id_product)
{ {
if (!$id_compare)
{
$id_customer = false;
if (Context::getContext()->customer)
$id_customer = Context::getContext()->customer->id;
$sql = Db::getInstance()->execute('
INSERT INTO `'._DB_PREFIX_.'compare` (`id_compare`, `id_customer`) VALUES (NULL, "'.($id_customer ? $id_customer: '0').'")');
if ($sql)
{
$id_compare = Db::getInstance()->getValue('SELECT MAX(`id_compare`) FROM `'._DB_PREFIX_.'compare`');
$cookie->id_compare = $id_compare;
}
}
return Db::getInstance()->execute(' return Db::getInstance()->execute('
INSERT INTO `'._DB_PREFIX_.'compare_product` (`id_product`, `id_guest`, `id_customer`, `date_add`, `date_upd`) INSERT INTO `'._DB_PREFIX_.'compare_product` (`id_compare`, `id_product`, `date_add`, `date_upd`)
VALUES ('.(int)($id_product).', 0, '.(int)($id_customer).', NOW(), NOW())'); VALUES ('.(int)($id_compare).', '.(int)($id_product).', NOW(), NOW())');
} }
/** /**
* Remove a compare product for the customer * Remove a compare product for the customer
* @param int $id_customer, int $id_product * @param int $id_compare, int $id_product
* @return boolean * @return boolean
*/ */
public static function removeCustomerCompareProduct($id_customer, $id_product) public static function removeCompareProduct($id_compare, $id_product)
{ {
return Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'compare_product` WHERE `id_customer` = '.(int)($id_customer).' AND `id_product` = '.(int)($id_product)); return Db::getInstance()->execute('
DELETE cp FROM `'._DB_PREFIX_.'compare_product` cp, `'._DB_PREFIX_.'compare` c
WHERE cp.`id_compare`=c.`id_compare`
AND cp.`id_product` = '.(int)$id_product.'
AND c.`id_compare` = '.(int)$id_compare);
} }
/** /**
* Get the number of compare products of the customer * Get the number of compare products of the customer
* @param int $id_customer * @param int $id_compare
* @return int * @return int
*/ */
public static function getCustomerNumberProducts($id_customer) public static function getNumberProducts($id_compare)
{ {
return (int)(Db::getInstance()->getValue(' return (int)(Db::getInstance()->getValue('
SELECT count(`id_compare_product`) SELECT count(`id_compare`)
FROM `'._DB_PREFIX_.'compare_product` FROM `'._DB_PREFIX_.'compare_product`
WHERE `id_customer` = '.(int)($id_customer))); WHERE `id_compare` = '.(int)($id_compare)));
} }
@@ -195,8 +144,21 @@ class CompareProductCore extends ObjectModel
if ($interval != null) if ($interval != null)
{ {
Db::getInstance()->execute(' Db::getInstance()->execute('
DELETE FROM `'._DB_PREFIX_.'compare_product` DELETE cp, c FROM `'._DB_PREFIX_.'compare_product` cp, `'._DB_PREFIX_.'compare` c
WHERE date_upd < DATE_SUB(NOW(), INTERVAL '.pSQL($interval).')'); WHERE cp.date_upd < DATE_SUB(NOW(), INTERVAL 1 WEEK) AND c.`id_compare`=cp.`id_compare`');
} }
} }
/**
* Get the id_compare by id_customer
* @param integer $id_customer
* @return integer $id_compare
*/
public static function getIdCompareByIdCustomer($id_customer)
{
return (int)Db::getInstance()->getValue('
SELECT `id_compare`
FROM `'._DB_PREFIX_.'compare`
WHERE `id_customer`= '.(int)$id_customer);
}
} }
+1
View File
@@ -220,6 +220,7 @@ class CookieCore
*/ */
public function mylogout() public function mylogout()
{ {
unset($this->_content['id_compare']);
unset($this->_content['id_customer']); unset($this->_content['id_customer']);
unset($this->_content['id_guest']); unset($this->_content['id_guest']);
unset($this->_content['is_guest']); unset($this->_content['is_guest']);
+2
View File
@@ -614,6 +614,8 @@ class FrontControllerCore extends Controller
$this->context = Context::getContext(); $this->context = Context::getContext();
$nArray = (int)(Configuration::get('PS_PRODUCTS_PER_PAGE')) != 10 ? array((int)(Configuration::get('PS_PRODUCTS_PER_PAGE')), 10, 20, 50) : array(10, 20, 50); $nArray = (int)(Configuration::get('PS_PRODUCTS_PER_PAGE')) != 10 ? array((int)(Configuration::get('PS_PRODUCTS_PER_PAGE')), 10, 20, 50) : array(10, 20, 50);
// Clean duplicate values
$nArray = array_unique($nArray);
asort($nArray); asort($nArray);
$this->n = abs((int)(Tools::getValue('n', ((isset($this->context->cookie->nb_item_per_page) AND $this->context->cookie->nb_item_per_page >= 10) ? $this->context->cookie->nb_item_per_page : (int)(Configuration::get('PS_PRODUCTS_PER_PAGE')))))); $this->n = abs((int)(Tools::getValue('n', ((isset($this->context->cookie->nb_item_per_page) AND $this->context->cookie->nb_item_per_page >= 10) ? $this->context->cookie->nb_item_per_page : (int)(Configuration::get('PS_PRODUCTS_PER_PAGE'))))));
$this->p = abs((int)(Tools::getValue('p', 1))); $this->p = abs((int)(Tools::getValue('p', 1)));
+6 -6
View File
@@ -112,12 +112,12 @@ class GroupCore extends ObjectModel
public static function getReduction($id_customer = null) public static function getReduction($id_customer = null)
{ {
if (!isset(self::$cache_reduction['customer'][(int)$id_customer])) if (!isset(self::$_cacheReduction['customer'][(int)$id_customer]))
self::$cache_reduction['customer'][(int)$id_customer] = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue(' {
SELECT `reduction` $id_group = $id_customer ? Customer::getDefaultGroupId((int)$id_customer) : (int)Configuration::get('PS_CUSTOMER_GROUP');
FROM `'._DB_PREFIX_.'group` self::$_cacheReduction['customer'][(int)$id_customer] = Group::getReductionByIdGroup($id_group);
WHERE `id_group` = '.((int)$id_customer ? Customer::getDefaultGroupId((int)$id_customer) : (int)Configuration::get('PS_CUSTOMER_GROUP'))); }
return self::$cache_reduction['customer'][(int)$id_customer]; return self::$_cacheReduction['customer'][(int)$id_customer];
} }
public static function getReductionByIdGroup($id_group) public static function getReductionByIdGroup($id_group)
+1 -2
View File
@@ -148,8 +148,7 @@ abstract class ObjectModelCore
$this->id = (int)($id); $this->id = (int)($id);
foreach ($result AS $key => $value) foreach ($result AS $key => $value)
if (key_exists($key, $this)) if (key_exists($key, $this))
// Todo: stripslashes() MUST BE removed in 1.4.6 and later, but is kept in 1.4.5 for a compatibility issue $this->{$key} = $value;
$this->{$key} = stripslashes($value);
if (!$id_lang AND method_exists($this, 'getTranslationsFieldsChild')) if (!$id_lang AND method_exists($this, 'getTranslationsFieldsChild'))
{ {
+19 -1
View File
@@ -631,6 +631,22 @@ class PDFCore extends PDF_PageGroupCore
$pdf->Ln(15); $pdf->Ln(15);
$pdf->ProdTab((self::$delivery ? true : '')); $pdf->ProdTab((self::$delivery ? true : ''));
/* Canada */
$taxable_address = new Address((int)self::$order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
if (!self::$delivery && strtoupper(Country::getIsoById((int)$taxable_address->id_country)) == 'CA')
{
$pdf->Ln(15);
$taxToDisplay = Db::getInstance()->ExecuteS('SELECT * FROM '._DB_PREFIX_.'order_tax WHERE id_order = '.(int)self::$order->id);
foreach ($taxToDisplay AS $t)
{
$pdf->Cell(0, 6, utf8_decode($t['tax_name']).' ('.number_format($t['tax_rate'], 2, '.', '').'%) '.self::convertSign(Tools::displayPrice($t['amount'], self::$currency, true)), 0, 0, 'R');
$pdf->Ln(5);
}
}
/* End */
/* Exit if delivery */ /* Exit if delivery */
if (!self::$delivery) if (!self::$delivery)
{ {
@@ -1055,8 +1071,10 @@ class PDFCore extends PDF_PageGroupCore
*/ */
public function TaxTab(&$priceBreakDown) public function TaxTab(&$priceBreakDown)
{ {
$taxable_address = new Address((int)self::$order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
if (strtoupper(Country::getIsoById((int)$taxable_address->id_country)) == 'CA')
return;
$invoiceAddress = new Address(self::$order->id_address_invoice);
if (Configuration::get('VATNUMBER_MANAGEMENT') AND !empty($invoiceAddress->vat_number) AND $invoiceAddress->id_country != Configuration::get('VATNUMBER_COUNTRY')) if (Configuration::get('VATNUMBER_MANAGEMENT') AND !empty($invoiceAddress->vat_number) AND $invoiceAddress->id_country != Configuration::get('VATNUMBER_COUNTRY'))
{ {
$this->Ln(); $this->Ln();
+131 -4
View File
@@ -255,11 +255,103 @@ abstract class PaymentModuleCore extends Module
// Construct order detail table for the email // Construct order detail table for the email
$productsList = ''; $productsList = '';
$products = $cart->getProducts(); $products = $cart->getProducts();
$storeAllTaxes = array();
foreach ($products AS $key => $product) foreach ($products AS $key => $product)
{ {
$price = Product::getPriceStatic((int)($product['id_product']), false, ($product['id_product_attribute'] ? (int)($product['id_product_attribute']) : NULL), 6, NULL, false, true, $product['cart_quantity'], false, (int)($order->id_customer), (int)($order->id_cart), (int)($order->{Configuration::get('PS_TAX_ADDRESS_TYPE')})); $price = Product::getPriceStatic((int)($product['id_product']), false, ($product['id_product_attribute'] ? (int)($product['id_product_attribute']) : NULL), 6, NULL, false, true, $product['cart_quantity'], false, (int)($order->id_customer), (int)($order->id_cart), (int)($order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}));
$price_wt = Product::getPriceStatic((int)($product['id_product']), true, ($product['id_product_attribute'] ? (int)($product['id_product_attribute']) : NULL), 2, NULL, false, true, $product['cart_quantity'], false, (int)($order->id_customer), (int)($order->id_cart), (int)($order->{Configuration::get('PS_TAX_ADDRESS_TYPE')})); $price_wt = Product::getPriceStatic((int)($product['id_product']), true, ($product['id_product_attribute'] ? (int)($product['id_product_attribute']) : NULL), 2, NULL, false, true, $product['cart_quantity'], false, (int)($order->id_customer), (int)($order->id_cart), (int)($order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}));
/* Store tax info */
$id_country = (int)Country::getDefaultCountryId();
$id_state = 0;
$id_county = 0;
$rate = 0;
$id_address = $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')};
$address_infos = Address::getCountryAndState($id_address);
if ($address_infos['id_country'])
{
$id_country = (int)($address_infos['id_country']);
$id_state = (int)$address_infos['id_state'];
$id_county = (int)County::getIdCountyByZipCode($address_infos['id_state'], $address_infos['postcode']);
}
$allTaxes = TaxRulesGroup::getTaxes((int)Product::getIdTaxRulesGroupByIdProduct((int)$product['id_product']), $id_country, $id_state, $id_county);
$nTax = 0;
foreach ($allTaxes AS $res)
{
if (!isset($storeAllTaxes[$res->id]))
$storeAllTaxes[$res->id] = array();
$storeAllTaxes[$res->id]['name'] = $res->name[(int)$order->id_lang];
$storeAllTaxes[$res->id]['rate'] = $res->rate;
if (!$nTax++)
$storeAllTaxes[$res->id]['amount'] = ($price * (1 + ($res->rate * 0.01))) - $price;
else
{
$priceTmp = $price_wt / (1 + ($res->rate * 0.01));
$storeAllTaxes[$res->id]['amount'] = $price_wt - $priceTmp;
}
}
/* End */
// Add some informations for virtual products
$deadline = '0000-00-00 00:00:00';
$download_hash = NULL;
if ($id_product_download = ProductDownload::getIdFromIdProduct((int)($product['id_product'])))
{
$productDownload = new ProductDownload((int)($id_product_download));
$deadline = $productDownload->getDeadLine();
$download_hash = $productDownload->getHash();
}
// Exclude VAT
if (Tax::excludeTaxeOption())
{
$product['tax'] = 0;
$product['rate'] = 0;
$tax_rate = 0;
}
else
$tax_rate = Tax::getProductTaxRate((int)($product['id_product']), $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
$ecotaxTaxRate = 0;
if (!empty($product['ecotax']))
$ecotaxTaxRate = Tax::getProductEcotaxRate($order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
$product_price = (float)Product::getPriceStatic((int)($product['id_product']), false, ($product['id_product_attribute'] ? (int)($product['id_product_attribute']) : NULL), (Product::getTaxCalculationMethod((int)($order->id_customer)) == PS_TAX_EXC ? 2 : 6), NULL, false, false, $product['cart_quantity'], false, (int)($order->id_customer), (int)($order->id_cart), (int)($order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}), $specificPrice, false, false);
$group_reduction = (float)GroupReduction::getValueForProduct((int)$product['id_product'], $customer->id_default_group) * 100;
if (!$group_reduction)
$group_reduction = Group::getReduction((int)$order->id_customer);
$quantityDiscount = SpecificPrice::getQuantityDiscount((int)$product['id_product'], Shop::getCurrentShop(), (int)$cart->id_currency, (int)$vat_address->id_country, (int)$customer->id_default_group, (int)$product['cart_quantity']);
$unitPrice = Product::getPriceStatic((int)$product['id_product'], true, ($product['id_product_attribute'] ? intval($product['id_product_attribute']) : NULL), 2, NULL, false, true, 1, false, (int)$order->id_customer, NULL, (int)$order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
$quantityDiscountValue = $quantityDiscount ? ((Product::getTaxCalculationMethod((int)$order->id_customer) == PS_TAX_EXC ? Tools::ps_round($unitPrice, 2) : $unitPrice) - $quantityDiscount['price'] * (1 + $tax_rate / 100)) : 0.00;
$query .= '('.(int)($order->id).',
'.(int)($product['id_product']).',
'.(isset($product['id_product_attribute']) ? (int)($product['id_product_attribute']) : 'NULL').',
\''.pSQL($product['name'].((isset($product['attributes']) AND $product['attributes'] != NULL) ? ' - '.$product['attributes'] : '')).'\',
'.(int)($product['cart_quantity']).',
'.$quantityInStock.',
'.$product_price.',
'.(float)(($specificPrice AND $specificPrice['reduction_type'] == 'percentage') ? $specificPrice['reduction'] * 100 : 0.00).',
'.(float)(($specificPrice AND $specificPrice['reduction_type'] == 'amount') ? (!$specificPrice['id_currency'] ? Tools::convertPrice($specificPrice['reduction'], $order->id_currency) : $specificPrice['reduction']) : 0.00).',
'.$group_reduction.',
'.$quantityDiscountValue.',
'.(empty($product['ean13']) ? 'NULL' : '\''.pSQL($product['ean13']).'\'').',
'.(empty($product['upc']) ? 'NULL' : '\''.pSQL($product['upc']).'\'').',
'.(empty($product['reference']) ? 'NULL' : '\''.pSQL($product['reference']).'\'').',
'.(empty($product['supplier_reference']) ? 'NULL' : '\''.pSQL($product['supplier_reference']).'\'').',
'.(float)($product['id_product_attribute'] ? $product['weight_attribute'] : $product['weight']).',
\''.(empty($tax_rate) ? '' : pSQL($product['tax'])).'\',
'.(float)($tax_rate).',
'.(float)Tools::convertPrice(floatval($product['ecotax']), intval($order->id_currency)).',
'.(float)$ecotaxTaxRate.',
'.(($specificPrice AND $specificPrice['from_quantity'] > 1) ? 1 : 0).',
\''.pSQL($deadline).'\',
\''.pSQL($download_hash).'\'),';
$customizationQuantity = 0; $customizationQuantity = 0;
if (isset($customizedDatas[$product['id_product']][$product['id_product_attribute']])) if (isset($customizedDatas[$product['id_product']][$product['id_product_attribute']]))
{ {
@@ -300,10 +392,45 @@ abstract class PaymentModuleCore extends Module
</tr>'; </tr>';
} // end foreach ($products) } // end foreach ($products)
$cartRulesList = '';
$result = $cart->getCartRules(); /* Add carrier tax */
$cartRules = ObjectModel::hydrateCollection('CartRule', $result, (int)$order->id_lang); $shippingCostTaxExcl = $cart->getOrderShippingCost((int)$order->id_carrier, false);
foreach ($cartRules as $cartRule) $allTaxes = TaxRulesGroup::getTaxes((int)Carrier::getIdTaxRulesGroupByIdCarrier((int)$order->id_carrier), $id_country, $id_state, $id_county);
$nTax = 0;
foreach ($allTaxes AS $res)
{
if (!isset($res->id))
continue;
if (!isset($storeAllTaxes[$res->id]))
$storeAllTaxes[$res->id] = array();
if (!isset($storeAllTaxes[$res->id]['amount']))
$storeAllTaxes[$res->id]['amount'] = 0;
$storeAllTaxes[$res->id]['name'] = $res->name[(int)$order->id_lang];
$storeAllTaxes[$res->id]['rate'] = $res->rate;
if (!$nTax++)
$storeAllTaxes[$res->id]['amount'] += ($shippingCostTaxExcl * (1 + ($res->rate * 0.01))) - $shippingCostTaxExcl;
else
{
$priceTmp = $order->total_shipping / (1 + ($res->rate * 0.01));
$storeAllTaxes[$res->id]['amount'] += $order->total_shipping - $priceTmp;
}
}
/* Store taxes */
foreach ($storeAllTaxes AS $t)
Db::getInstance()->Execute('
INSERT INTO '._DB_PREFIX_.'order_tax (id_order, tax_name, tax_rate, amount)
VALUES ('.(int)$order->id.', \''.pSQL($t['name']).'\', \''.(float)($t['rate']).'\', '.(float)$t['amount'].')');
// Insert discounts from cart into order_discount table
$discounts = $cart->getDiscounts();
$discountsList = '';
$total_discount_value = 0;
$shrunk = false;
foreach ($discounts AS $discount)
{ {
$value = $cartRule->getContextualValue(true); $value = $cartRule->getContextualValue(true);
// Todo : has not been tested because order processing wasn't functionnal // Todo : has not been tested because order processing wasn't functionnal
+24 -7
View File
@@ -265,6 +265,7 @@ class ProductCore extends ObjectModel
protected $identifier = 'id_product'; protected $identifier = 'id_product';
protected $webserviceParameters = array( protected $webserviceParameters = array(
'objectMethods' => array('add' => 'addWs', 'update' => 'updateWs'),
'objectNodeNames' => 'products', 'objectNodeNames' => 'products',
'fields' => array( 'fields' => array(
'id_manufacturer' => array('xlink_resource' => 'manufacturers'), 'id_manufacturer' => array('xlink_resource' => 'manufacturers'),
@@ -930,13 +931,13 @@ class ProductCore extends ObjectModel
* @deprecated * @deprecated
*/ */
public function addProductAttribute($price, $weight, $unit_impact, $ecotax, $quantity, $id_images, $reference, public function addProductAttribute($price, $weight, $unit_impact, $ecotax, $quantity, $id_images, $reference,
$supplier_reference = null, $ean13, $default, $location = null, $upc = null) $supplier_reference = null, $ean13, $default, $location = null, $upc = null, $minimal_quantity = 1)
{ {
Tools::displayAsDeprecated(); Tools::displayAsDeprecated();
$id_product_attribute = $this->addAttribute( $id_product_attribute = $this->addAttribute(
$price, $weight, $unit_impact, $ecotax, $id_images, $price, $weight, $unit_impact, $ecotax, $id_images,
$reference, $ean13, $default, $location, $upc $reference, $ean13, $default, $location, $upc, $minimal_quantity
); );
if (!$id_product_attribute) if (!$id_product_attribute)
@@ -996,9 +997,10 @@ class ProductCore extends ObjectModel
* @param string $location Location * @param string $location Location
* @param string $ean13 Ean-13 barcode * @param string $ean13 Ean-13 barcode
* @param boolean $default Is default attribute for product * @param boolean $default Is default attribute for product
* @param integer $minimal_quantity Minimal quantity to add to cart
* @return mixed $id_product_attribute or false * @return mixed $id_product_attribute or false
*/ */
public function addAttribute($price, $weight, $unit_impact, $ecotax, $id_images, $reference, $ean13, $default, $location = null, $upc = null) public function addAttribute($price, $weight, $unit_impact, $ecotax, $id_images, $reference, $ean13, $default, $location = null, $upc = null, $minimal_quantity = 1)
{ {
if (!$this->id) if (!$this->id)
return; return;
@@ -1017,7 +1019,8 @@ class ProductCore extends ObjectModel
'location' => pSQL($location), 'location' => pSQL($location),
'ean13' => pSQL($ean13), 'ean13' => pSQL($ean13),
'upc' => pSQL($upc), 'upc' => pSQL($upc),
'default_on' => (int)$default 'default_on' => (int)$default,
'minimal_quantity' => (int)$minimal_quantity,
), 'INSERT'); ), 'INSERT');
$id_product_attribute = Db::getInstance()->Insert_ID(); $id_product_attribute = Db::getInstance()->Insert_ID();
@@ -1042,11 +1045,11 @@ class ProductCore extends ObjectModel
* @param string $supplier_reference DEPRECATED * @param string $supplier_reference DEPRECATED
*/ */
public function addCombinationEntity($wholesale_price, $price, $weight, $unit_impact, $ecotax, $quantity, public function addCombinationEntity($wholesale_price, $price, $weight, $unit_impact, $ecotax, $quantity,
$id_images, $reference, $supplier_reference, $ean13, $default, $location = null, $upc = null) $id_images, $reference, $supplier_reference, $ean13, $default, $location = null, $upc = null, $minimal_quantity = 1)
{ {
$id_product_attribute = $this->addProductAttribute( $id_product_attribute = $this->addProductAttribute(
$price, $weight, $unit_impact, $ecotax, $quantity, $id_images, $price, $weight, $unit_impact, $ecotax, $quantity, $id_images,
$reference, $supplier_reference, $ean13, $default, $location, $upc $reference, $supplier_reference, $ean13, $default, $location, $upc, $minimal_quantity
); );
$result = Db::getInstance()->execute( $result = Db::getInstance()->execute(
@@ -4106,5 +4109,19 @@ class ProductCore extends ObjectModel
return Db::getInstance()->getValue($query); return Db::getInstance()->getValue($query);
} }
} public function addWs($autodate = true, $nullValues = false)
{
$success = parent::add($autodate, $nullValues);
if ($success)
Search::indexation(false, $this->id);
return $success;
}
public function updateWs($nullValues = false)
{
$success = parent::update($nullValues);
if ($success)
Search::indexation(false, $this->id);
return $success;
}
}
+3 -1
View File
@@ -115,11 +115,13 @@ class TabCore extends ObjectModel
'); ');
if (!$profiles || empty($profiles)) if (!$profiles || empty($profiles))
return false; return false;
/* Query definition */ /* Query definition */
// note : insert ignore should be avoided // note : insert ignore should be avoided
$query = 'INSERT IGNORE INTO `'._DB_PREFIX_.'access` (`id_profile`, `id_tab`, `view`, `add`, `edit`, `delete`) VALUES '; $query = 'INSERT IGNORE INTO `'._DB_PREFIX_.'access` (`id_profile`, `id_tab`, `view`, `add`, `edit`, `delete`) VALUES ';
// default admin // default admin
$query .= '(1, '.(int)$id_tab.', 1, 1, 1, 1),'; $query .= '(1, '.(int)$id_tab.', 1, 1, 1, 1),';
foreach ($profiles as $profile) foreach ($profiles as $profile)
{ {
// no cast needed for profile[id_profile], which cames from db // no cast needed for profile[id_profile], which cames from db
@@ -251,7 +253,7 @@ class TabCore extends ObjectModel
public static function getNewLastPosition($id_parent) public static function getNewLastPosition($id_parent)
{ {
return (Db::getInstance()->getValue(' return (Db::getInstance()->getValue('
SELECT MAX(position)+1 SELECT IFNULL(MAX(position),0)+1
FROM `'._DB_PREFIX_.'tab` FROM `'._DB_PREFIX_.'tab`
WHERE `id_parent` = '.(int)$id_parent WHERE `id_parent` = '.(int)$id_parent
)); ));
+44 -7
View File
@@ -643,7 +643,7 @@ class ToolsCore
* @param integer $id_lang Language id * @param integer $id_lang Language id
* @return array Meta tags * @return array Meta tags
*/ */
public static function getMetaTags($id_lang, $page_name) public static function getMetaTags($id_lang, $page_name, $title = '')
{ {
global $maintenance; global $maintenance;
@@ -670,6 +670,8 @@ class ToolsCore
/* Categories specifics meta tags */ /* Categories specifics meta tags */
elseif ($id_category = self::getValue('id_category')) elseif ($id_category = self::getValue('id_category'))
{ {
if (!empty($title))
$title = ' - '.$title;
$page_number = (int)self::getValue('p'); $page_number = (int)self::getValue('p');
$row = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow(' $row = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT `name`, `meta_title`, `meta_description`, `meta_keywords`, `description` SELECT `name`, `meta_title`, `meta_description`, `meta_keywords`, `description`
@@ -682,10 +684,13 @@ class ToolsCore
// Paginate title // Paginate title
if (!empty($row['meta_title'])) if (!empty($row['meta_title']))
$row['meta_title'] = $row['meta_title'].(!empty($page_number) ? ' ('.$page_number.')' : '').' - '.Configuration::get('PS_SHOP_NAME'); $row['meta_title'] = $title.$row['meta_title'].(!empty($page_number) ? ' ('.$page_number.')' : '').' - '.Configuration::get('PS_SHOP_NAME');
else else
$row['meta_title'] = $row['name'].(!empty($page_number) ? ' ('.$page_number.')' : '').' - '.Configuration::get('PS_SHOP_NAME'); $row['meta_title'] = $row['name'].(!empty($page_number) ? ' ('.$page_number.')' : '').' - '.Configuration::get('PS_SHOP_NAME');
if (!empty($title))
$row['meta_title'] = $title.(!empty($page_number) ? ' ('.$page_number.')' : '').' - '.Configuration::get('PS_SHOP_NAME');
return self::completeMetaTags($row, $row['name']); return self::completeMetaTags($row, $row['name']);
} }
} }
@@ -1227,10 +1232,12 @@ class ToolsCore
return false; return false;
} }
/**
* @deprecated as of 1.5 use Media::minifyHTML()
*/
public static $a = 0;
/**
* @deprecated as of 1.5 use Media::minifyHTML()
*/
public static function minifyHTML($html_content) public static function minifyHTML($html_content)
{ {
Tools::displayAsDeprecated(); Tools::displayAsDeprecated();
@@ -1276,8 +1283,21 @@ class ToolsCore
*/ */
public static function minifyHTMLpregCallback($preg_matches) public static function minifyHTMLpregCallback($preg_matches)
{ {
<<<<<<< .working
Tools::displayAsDeprecated(); Tools::displayAsDeprecated();
return Media::minifyHTMLpregCallback($preg_matches); return Media::minifyHTMLpregCallback($preg_matches);
=======
$args = array();
preg_match_all('/[a-zA-Z0-9]+=[\"\\\'][^\"\\\']*[\"\\\']/is', $preg_matches[2], $args);
$args = $args[0];
sort($args);
// if there is no args in the balise, we don't write a space (avoid previous : <title >, now : <title>)
if (empty($args))
$output = $preg_matches[1].'>';
else
$output = $preg_matches[1].' '.implode(' ', $args).'>';
return $output;
>>>>>>> .merge-right.r10309
} }
/** /**
@@ -1285,8 +1305,25 @@ class ToolsCore
*/ */
public static function packJSinHTML($html_content) public static function packJSinHTML($html_content)
{ {
<<<<<<< .working
Tools::displayAsDeprecated(); Tools::displayAsDeprecated();
return Media::packJSinHTML($html_content); return Media::packJSinHTML($html_content);
=======
if (strlen($html_content) > 0)
{
$htmlContentCopy = $html_content;
$html_content = preg_replace_callback(
'/\\s*(<script\\b[^>]*?>)([\\s\\S]*?)(<\\/script>)\\s*/i'
,array('Tools', 'packJSinHTMLpregCallback')
,$html_content);
// If the string is too big preg_replace return null: http://php.net/manual/en/function.preg-replace-callback.php
// In this case, we don't compress the content
if ($html_content === null)
{
error_log('Error occured in function packJSinHTML');
return $htmlContentCopy;
>>>>>>> .merge-right.r10309
} }
/** /**
@@ -1796,11 +1833,11 @@ FileETag INode MTime Size
$orderByPrefix = ''; $orderByPrefix = '';
if ($prefix) if ($prefix)
{ {
if ($value == 'id_product' || $value == 'date_add' || $value == 'price') if ($value == 'id_product' || $value == 'date_add' || $value == 'date_upd' || $value == 'price')
$orderByPrefix = 'p.'; $orderByPrefix = 'p.';
elseif ($value == 'name') elseif ($value == 'name')
$orderByPrefix = 'pl.'; $orderByPrefix = 'pl.';
elseif ($value == 'manufacturer') elseif ($value == 'manufacturer_name')
$orderByPrefix = 'm.'; $orderByPrefix = 'm.';
elseif ($value == 'position' || empty($value)) elseif ($value == 'position' || empty($value))
$orderByPrefix = 'cp.'; $orderByPrefix = 'cp.';
+14 -8
View File
@@ -39,12 +39,14 @@ class UpgraderCore
public $version_name; public $version_name;
public $version_num; public $version_num;
public $version_is_modified = null;
/** /**
* @var string contains hte url where to download the file * @var string contains hte url where to download the file
*/ */
public $link; public $link;
public $autoupgrade; public $autoupgrade;
public $autoupgrade_module; public $autoupgrade_module;
public $autoupgrade_last_version;
public $changelog; public $changelog;
public $md5; public $md5;
@@ -99,8 +101,7 @@ class UpgraderCore
*/ */
public function checkPSVersion($force = false) public function checkPSVersion($force = false)
{ {
if (empty($this->link))
{
if (class_exists('Configuration')) if (class_exists('Configuration'))
$last_check = Configuration::get('PS_LAST_VERSION_CHECK'); $last_check = Configuration::get('PS_LAST_VERSION_CHECK');
else else
@@ -112,7 +113,6 @@ class UpgraderCore
libxml_set_streams_context(@stream_context_create(array('http' => array('timeout' => 3)))); libxml_set_streams_context(@stream_context_create(array('http' => array('timeout' => 3))));
if ($feed = @simplexml_load_file($this->rss_version_link)) if ($feed = @simplexml_load_file($this->rss_version_link))
{ {
$this->version_name = (string)$feed->version->name; $this->version_name = (string)$feed->version->name;
$this->version_num = (string)$feed->version->num; $this->version_num = (string)$feed->version->num;
$this->link = (string)$feed->download->link; $this->link = (string)$feed->download->link;
@@ -120,6 +120,7 @@ class UpgraderCore
$this->changelog = (string)$feed->download->changelog; $this->changelog = (string)$feed->download->changelog;
$this->autoupgrade = (int)$feed->autoupgrade; $this->autoupgrade = (int)$feed->autoupgrade;
$this->autoupgrade_module = (int)$feed->autoupgrade_module; $this->autoupgrade_module = (int)$feed->autoupgrade_module;
$this->autoupgrade_last_version = (string)$feed->autoupgrade_last_version;
$this->desc = (string)$feed->desc ; $this->desc = (string)$feed->desc ;
$config_last_version = array( $config_last_version = array(
'name' => $this->version_name, 'name' => $this->version_name,
@@ -128,6 +129,7 @@ class UpgraderCore
'md5' => $this->md5, 'md5' => $this->md5,
'autoupgrade' => $this->autoupgrade, 'autoupgrade' => $this->autoupgrade,
'autoupgrade_module' => $this->autoupgrade_module, 'autoupgrade_module' => $this->autoupgrade_module,
'autoupgrade_last_version' => $this->autoupgrade_last_version,
'changelog' => $this->changelog, 'changelog' => $this->changelog,
'desc' => $this->desc 'desc' => $this->desc
); );
@@ -139,8 +141,7 @@ class UpgraderCore
} }
} }
else else
$this->loadFromConfig(); $this->loadFromConfig();
}
// retro-compatibility : // retro-compatibility :
// return array(name,link) if you don't use the last version // return array(name,link) if you don't use the last version
// false otherwise // false otherwise
@@ -173,6 +174,8 @@ class UpgraderCore
$this->autoupgrade = $last_version_check['autoupgrade']; $this->autoupgrade = $last_version_check['autoupgrade'];
if (isset($last_version_check['autoupgrade_module'])) if (isset($last_version_check['autoupgrade_module']))
$this->autoupgrade_module = $last_version_check['autoupgrade_module']; $this->autoupgrade_module = $last_version_check['autoupgrade_module'];
if (isset($last_version_check['autoupgrade_last_version']))
$this->autoupgrade_last_version = $last_version_check['autoupgrade_last_version'];
if (isset($last_version_check['md5'])) if (isset($last_version_check['md5']))
$this->md5 = $last_version_check['md5']; $this->md5 = $last_version_check['md5'];
if (isset($last_version_check['desc'])) if (isset($last_version_check['desc']))
@@ -190,11 +193,13 @@ class UpgraderCore
*/ */
public function getChangedFilesList() public function getChangedFilesList()
{ {
if (count($this->changed_files) == 0) if (is_array($this->changed_files) && count($this->changed_files) == 0)
{ {
$checksum = @simplexml_load_file($this->rss_md5file_link_dir._PS_VERSION_.'.xml'); $checksum = @simplexml_load_file($this->rss_md5file_link_dir._PS_VERSION_.'.xml');
if ($checksum === false) if ($checksum == false)
return false; {
$this->changed_files = false;
}
else else
$this->browseXmlAndCompare($checksum->ps_root_dir[0]); $this->browseXmlAndCompare($checksum->ps_root_dir[0]);
} }
@@ -274,6 +279,7 @@ class UpgraderCore
public function isAuthenticPrestashopVersion() public function isAuthenticPrestashopVersion()
{ {
$this->getChangedFilesList(); $this->getChangedFilesList();
return !$this->version_is_modified; return !$this->version_is_modified;
} }
+1 -1
View File
@@ -43,7 +43,7 @@ class ValidateCore
* @param string $email e-mail address to validate * @param string $email e-mail address to validate
* @return boolean Validity is ok or not * @return boolean Validity is ok or not
*/ */
public static function isEmail($email) public static function isEmail($email, $required = true)
{ {
return !empty($email) AND preg_match('/^[a-z0-9!#$%&\'*+\/=?^`{}|~_-]+[.a-z0-9!#$%&\'*+\/=?^`{}|~_-]*@[a-z0-9]+[._a-z0-9-]*\.[a-z0-9]+$/ui', $email); return !empty($email) AND preg_match('/^[a-z0-9!#$%&\'*+\/=?^`{}|~_-]+[.a-z0-9!#$%&\'*+\/=?^`{}|~_-]*@[a-z0-9]+[._a-z0-9-]*\.[a-z0-9]+$/ui', $email);
} }
+5 -1
View File
@@ -1115,7 +1115,11 @@ class OrderCore extends ObjectModel
return $result; return $result;
} }
public function setCurrentState($id_order_state, $id_employee) /** Set current order state
* @param int $id_order_state
* @param int $id_employee (/!\ not optional except for Webservice.
*/
public function setCurrentState($id_order_state, $id_employee = 0)
{ {
if (empty($id_order_state)) if (empty($id_order_state))
return false; return false;
+2 -1
View File
@@ -122,7 +122,8 @@ class OrderHistoryCore extends ObjectModel
if ($newOS->invoice AND !$order->invoice_number) if ($newOS->invoice AND !$order->invoice_number)
$order->setInvoice(); $order->setInvoice();
if ($newOS->delivery AND !$order->delivery_number) // Update delivery date even if it was already set by another state change
if ($newOS->delivery)
$order->setDelivery(); $order->setDelivery();
Hook::postUpdateOrderStatus((int)($new_order_state), (int)($id_order)); Hook::postUpdateOrderStatus((int)($new_order_state), (int)($id_order));
} }
-1
View File
@@ -27,7 +27,6 @@
define('_PS_MODE_DEV_', true); define('_PS_MODE_DEV_', true);
define('_PS_MODE_DEMO_', false); define('_PS_MODE_DEMO_', false);
define('_PS_DEMO_MAIN_BO_ACCOUNT_', 1);
$currentDir = dirname(__FILE__); $currentDir = dirname(__FILE__);
+1 -1
View File
@@ -115,7 +115,7 @@ function smarty_modifier_truncate($string, $length = 80, $etc = '...', $break_wo
$length -= min($length, Tools::strlen($etc)); $length -= min($length, Tools::strlen($etc));
if (!$break_words && !$middle) if (!$break_words && !$middle)
$string = preg_replace('/\s+?(\S+)?$/u', '', Tools::substr($string, 0, $length+1, $charset)); $string = preg_replace('/\s+?(\S+)?$/u', '', Tools::substr($string, 0, $length+1, $charset));
return !$middle ? Tools::substr($string, 0, $length, $charset).$etc : Tools::substr($string, 0, $length/2, $charset).$etc.Tools::substr($string, -$length/2, $charset); return !$middle ? Tools::substr($string, 0, $length, $charset).$etc : Tools::substr($string, 0, $length/2, $charset).$etc.Tools::substr($string, -$length/2, $length, $charset);
} }
else else
return $string; return $string;
+1
View File
@@ -262,6 +262,7 @@ class AuthControllerCore extends FrontController
} }
else else
{ {
$this->context->cookie->id_compare = isset($this->context->cookie->id_compare) ? $this->context->cookie->id_compare: CompareProduct::getIdCompareByIdCustomer($customer->id);
$this->context->cookie->id_customer = (int)($customer->id); $this->context->cookie->id_customer = (int)($customer->id);
$this->context->cookie->customer_lastname = $customer->lastname; $this->context->cookie->customer_lastname = $customer->lastname;
$this->context->cookie->customer_firstname = $customer->firstname; $this->context->cookie->customer_firstname = $customer->firstname;
+1
View File
@@ -249,6 +249,7 @@ class CartControllerCore extends FrontController
$id_country = (isset($deliveryAddress) && $deliveryAddress->id) ? $deliveryAddress->id_country : Configuration::get('PS_COUNTRY_DEFAULT'); $id_country = (isset($deliveryAddress) && $deliveryAddress->id) ? $deliveryAddress->id_country : Configuration::get('PS_COUNTRY_DEFAULT');
$result['carriers'] = Carrier::getCarriersForOrder(Country::getIdZone($id_country), $groups); $result['carriers'] = Carrier::getCarriersForOrder(Country::getIdZone($id_country), $groups);
//$result['checked'] = Carrier::getDefaultCarrierSelection($result['carriers'], (int)$this->cart->id_carrier); //$result['checked'] = Carrier::getDefaultCarrierSelection($result['carriers'], (int)$this->cart->id_carrier);
$result['HOOK_EXTRACARRIER'] = Module::hookExec('extraCarrier', array('address' => (isset($deliveryAddress) && (int)$deliveryAddress->id) ? $deliveryAddress : null));
} }
$result['summary'] = $this->context->cart->getSummaryDetails(); $result['summary'] = $this->context->cart->getSummaryDetails();
$result['customizedDatas'] = Product::getAllCustomizedDatas($this->context->cart->id, null, true); $result['customizedDatas'] = Product::getAllCustomizedDatas($this->context->cart->id, null, true);
+3 -4
View File
@@ -83,10 +83,9 @@ class CategoryControllerCore extends FrontController
public function initContent() public function initContent()
{ {
if (isset($this->context->customer->id)) if (isset($this->context->cookie->id_compare))
$this->context->smarty->assign('compareProducts', CompareProduct::getCustomerCompareProducts($this->context->customer->id)); $this->context->smarty->assign('compareProducts', CompareProduct::getCompareProducts((int)$this->context->cookie->id_compare));
else if (isset($this->context->customer->id_guest))
$this->context->smarty->assign('compareProducts', CompareProduct::getGuestCompareProducts($this->context->customer->id_guest));
$this->assignScenes(); $this->assignScenes();
if ($this->category->id != 1) if ($this->category->id != 1)
+10 -23
View File
@@ -43,32 +43,21 @@ class CompareControllerCore extends FrontController
*/ */
public function displayAjax() public function displayAjax()
{ {
//Add or remove product with Ajax // Add or remove product with Ajax
if (Tools::getValue('id_product') && Tools::getValue('action')) if (Tools::getValue('ajax') && Tools::getValue('id_product') && Tools::getValue('action'))
{ {
if (Tools::getValue('action') == 'add') if (Tools::getValue('action') == 'add')
{ {
if (isset($this->context->customer->id)) $id_compare = isset($this->context->cookie->id_compare) ? $this->context->cookie->id_compare: false;
{ if (CompareProduct::getNumberProducts($id_compare) < Configuration::get('PS_COMPARATOR_MAX_ITEM'))
if (CompareProduct::getCustomerNumberProducts($this->context->customer->id) < Configuration::get('PS_COMPARATOR_MAX_ITEM')) CompareProduct::addCompareProduct($id_compare, (int)Tools::getValue('id_product'));
CompareProduct::addCustomerCompareProduct((int)$this->context->customer->id, (int)Tools::getValue('id_product'));
else
die('0');
}
else else
{ die('0');
if ((isset($this->context->customer->id_guest) && CompareProduct::getGuestNumberProducts($this->context->customer->id_guest) < Configuration::get('PS_COMPARATOR_MAX_ITEM')))
CompareProduct::addGuestCompareProduct((int)$this->context->customer->id_guest, (int)Tools::getValue('id_product'));
else
die('0');
}
} }
else if (Tools::getValue('action') == 'remove') else if (Tools::getValue('action') == 'remove')
{ {
if (isset($this->context->customer->id)) if (isset(self::$cookie->id_compare))
CompareProduct::removeCustomerCompareProduct((int)$this->context->customer->id, (int)Tools::getValue('id_product')); CompareProduct::removeCompareProduct((int)$this->context->cookie->id_compare, (int)Tools::getValue('id_product'));
else if (isset($this->context->customer->id_guest))
CompareProduct::removeGuestCompareProduct((int)$this->context->customer->id_guest, (int)Tools::getValue('id_product'));
else else
die('0'); die('0');
} }
@@ -95,10 +84,8 @@ class CompareControllerCore extends FrontController
if ($product_list = Tools::getValue('compare_product_list') && ($postProducts = (isset($product_list) ? rtrim($product_list, '|') : ''))) if ($product_list = Tools::getValue('compare_product_list') && ($postProducts = (isset($product_list) ? rtrim($product_list, '|') : '')))
$ids = array_unique(explode('|', $postProducts)); $ids = array_unique(explode('|', $postProducts));
else if (isset($this->context->customer->id)) else if (isset(self::$cookie->id_compare))
$ids = CompareProduct::getCustomerCompareProducts($this->context->customer->id); $ids = CompareProduct::getCompareProducts($this->context->cookie->id_compare);
else if (isset($this->context->customer->id_guest))
$ids = CompareProduct::getGuestCompareProducts($this->context->customer->id_guest);
else else
$ids = null; $ids = null;
+9 -3
View File
@@ -76,6 +76,14 @@ class OrderControllerCore extends ParentOrderController
$this->context->smarty->assign('address_list', array()); $this->context->smarty->assign('address_list', array());
} }
public function postProcess()
{
// Update carrier selected on preProccess in order to fix a bug of
// block cart when it's hooked on leftcolumn
if ($this->step == 3 && Tools::isSubmit('processCarrier'))
$this->processCarrier();
}
/** /**
* Assign template vars related to page content * Assign template vars related to page content
* @see FrontController::initContent() * @see FrontController::initContent()
@@ -118,11 +126,9 @@ class OrderControllerCore extends ParentOrderController
case 3: case 3:
// Test that the conditions (so active) were accepted by the customer // Test that the conditions (so active) were accepted by the customer
$cgv = Tools::getValue('cgv'); $cgv = Tools::getValue('cgv');
if (Configuration::get('PS_CONDITIONS') && (!Validate::isBool($cgv))) if (Configuration::get('PS_CONDITIONS') && (!Validate::isBool($cgv) || $cgv == false))
Tools::redirect('index.php?controller=order&step=2'); Tools::redirect('index.php?controller=order&step=2');
if (Tools::isSubmit('processCarrier'))
$this->processCarrier();
$this->autoStep(); $this->autoStep();
// Bypass payment step if total is 0 // Bypass payment step if total is 0
+5 -2
View File
@@ -207,10 +207,13 @@ class ProductControllerCore extends FrontController
protected function assignPriceAndTax() protected function assignPriceAndTax()
{ {
$id_customer = (isset($this->context->customer) ? (int)$this->context->customer->id : 0); $id_customer = (isset($this->context->customer) ? (int)$this->context->customer->id : 0);
$group_reduction = (100 - Group::getReduction($id_customer)) / 100;
$id_group = (isset($this->context->customer) ? $this->context->customer->id_default_group : _PS_DEFAULT_CUSTOMER_GROUP_); $id_group = (isset($this->context->customer) ? $this->context->customer->id_default_group : _PS_DEFAULT_CUSTOMER_GROUP_);
$id_country = (int)$id_customer ? Customer::getCurrentCountry($id_customer) : Configuration::get('PS_COUNTRY_DEFAULT'); $id_country = (int)$id_customer ? Customer::getCurrentCountry($id_customer) : Configuration::get('PS_COUNTRY_DEFAULT');
$group_reduction = GroupReduction::getValueForProduct($this->product->id, $id_group);
if ($group_reduction == 0)
$group_reduction = Group::getReduction((int)$this->context->cookie->id_customer) / 100;
// Tax // Tax
$tax = (float)$this->product->getTaxesRate(new Address((int)$this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')})); $tax = (float)$this->product->getTaxesRate(new Address((int)$this->context->cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}));
$this->context->smarty->assign('tax_rate', $tax); $this->context->smarty->assign('tax_rate', $tax);
@@ -248,7 +251,7 @@ class ProductControllerCore extends FrontController
'ecotax_tax_exc' => Tools::ps_round($this->product->ecotax, 2), 'ecotax_tax_exc' => Tools::ps_round($this->product->ecotax, 2),
'ecotaxTax_rate' => $ecotax_rate, 'ecotaxTax_rate' => $ecotax_rate,
'productPriceWithoutEcoTax' => (float)$product_price_without_eco_tax, 'productPriceWithoutEcoTax' => (float)$product_price_without_eco_tax,
'group_reduction' => $group_reduction, 'group_reduction' => (1 - $group_reduction),,
'no_tax' => Tax::excludeTaxeOption() || !$this->product->getTaxesRate($address), 'no_tax' => Tax::excludeTaxeOption() || !$this->product->getTaxesRate($address),
'ecotax' => (!count($this->errors) && $this->product->ecotax > 0 ? Tools::convertPrice((float)$this->product->ecotax) : 0), 'ecotax' => (!count($this->errors) && $this->product->ecotax > 0 ? Tools::convertPrice((float)$this->product->ecotax) : 0),
'tax_enabled' => Configuration::get('PS_TAX') 'tax_enabled' => Configuration::get('PS_TAX')
+1 -1
View File
@@ -1,4 +1,4 @@
ID;Alias*;Active (0/1);Customer e-mail;Manufacturer;Supplier;Company;Lastname*;Firstname*;Address 1*;Address 2;Postcode* / Zipcode*;City*;Country*;State;Other;Phone;Mobile Phone;VAT number id;Alias*;Active (0/1);Customer e-mail;Manufacturer;Supplier;Company;Lastname*;Firstname*;Address 1*;Address 2;Postcode* / Zipcode*;City*;Country*;State;Other;Phone;Mobile Phone;VAT number
1;My Adress;1;johndoe@prestashop.com;;;;Doe;John;16, Main street;2nd floor;75000;PARIS ;France;;;140138844;; 1;My Adress;1;johndoe@prestashop.com;;;;Doe;John;16, Main street;2nd floor;75000;PARIS ;France;;;140138844;;
2;My work;1;johndoe@prestashop.com;;;My Company;Doe;John;535, Baker street;;13000;Marseile;France;;;235445588;; 2;My work;1;johndoe@prestashop.com;;;My Company;Doe;John;535, Baker street;;13000;Marseile;France;;;235445588;;
3;My work;0;;Apple Computer, Inc;;;Jobs;Steve;1 Infinite Loop;;95014;CUPERTINO;United States;California;;(800) 275-2273;; 3;My work;0;;Apple Computer, Inc;;;Jobs;Steve;1 Infinite Loop;;95014;CUPERTINO;United States;California;;(800) 275-2273;;
1 ID id Alias* Active (0/1) Customer e-mail Manufacturer Supplier Company Lastname* Firstname* Address 1* Address 2 Postcode* / Zipcode* City* Country* State Other Phone Mobile Phone VAT number
2 1 1 My Adress 1 johndoe@prestashop.com Doe John 16, Main street 2nd floor 75000 PARIS France 140138844
3 2 2 My work 1 johndoe@prestashop.com My Company Doe John 535, Baker street 13000 Marseile France 235445588
4 3 3 My work 0 Apple Computer, Inc Jobs Steve 1 Infinite Loop 95014 CUPERTINO United States California (800) 275-2273
+1 -1
View File
@@ -1,4 +1,4 @@
ID;Active (0/1);Name*;Parent Category;Description;Meta-title;Meta-keywords;Meta-description;URL rewritten;Image URL id;Active (0/1);Name*;Parent Category;Description;Meta-title;Meta-keywords;Meta-description;URL rewritten;Image URL
2;1;iPods;Home;Now that you can buy movies from the iTunes Store and sync them to your iPod, the whole world is your theater.;;;;music-ipods;http://youlinktotheimage.com/img1000.jpg 2;1;iPods;Home;Now that you can buy movies from the iTunes Store and sync them to your iPod, the whole world is your theater.;;;;music-ipods;http://youlinktotheimage.com/img1000.jpg
3;1;Accessories;Home;Wonderful accessories for your iPod;;;;accessories-ipod;http://youlinktotheimage.com/img1001.jpg 3;1;Accessories;Home;Wonderful accessories for your iPod;;;;accessories-ipod;http://youlinktotheimage.com/img1001.jpg
4;1;Laptops;Home;The latest Intel processor, a bigger hard drive, plenty of memory, and even more new features all fit inside just one liberating inch. The new Mac laptops have the performance, power, and connectivity of a desktop computer. Without the desk part.;Apple laptops;Apple laptops MacBook Air;Powerful and chic Apple laptops;laptops;http://youlinktotheimage.com/img1002.jpg 4;1;Laptops;Home;The latest Intel processor, a bigger hard drive, plenty of memory, and even more new features all fit inside just one liberating inch. The new Mac laptops have the performance, power, and connectivity of a desktop computer. Without the desk part.;Apple laptops;Apple laptops MacBook Air;Powerful and chic Apple laptops;laptops;http://youlinktotheimage.com/img1002.jpg
1 ID id Active (0/1) Name* Parent Category Description Meta-title Meta-keywords Meta-description URL rewritten Image URL
2 2 2 1 iPods Home Now that you can buy movies from the iTunes Store and sync them to your iPod, the whole world is your theater. music-ipods http://youlinktotheimage.com/img1000.jpg
3 3 3 1 Accessories Home Wonderful accessories for your iPod accessories-ipod http://youlinktotheimage.com/img1001.jpg
4 4 4 1 Laptops Home The latest Intel processor, a bigger hard drive, plenty of memory, and even more new features all fit inside just one liberating inch. The new Mac laptops have the performance, power, and connectivity of a desktop computer. Without the desk part. Apple laptops Apple laptops MacBook Air Powerful and chic Apple laptops laptops http://youlinktotheimage.com/img1002.jpg
+1 -1
View File
@@ -1,3 +1,3 @@
ID;Active (0/1);Gender ID (Mr=1, Ms=2, else 9);E-mail*;Password*;Birthday;Lastname*;Firstname*;Newletter (0/1);Opt-in (0/1) id;Active (0/1);Gender ID (Mr=1, Ms=2, else 9);E-mail*;Password*;Birthday;Lastname*;Firstname*;Newletter (0/1);Opt-in (0/1)
1;1;1;johndoe@prestashop.com;#res152EDRF;sous quelle forme ? ;Doe;John;1;1 1;1;1;johndoe@prestashop.com;#res152EDRF;sous quelle forme ? ;Doe;John;1;1
2;1;2;mariedoe@prestashop.com;58@ret26#;sous quelle forme ? ;Doe;Marie;0;1 2;1;2;mariedoe@prestashop.com;58@ret26#;sous quelle forme ? ;Doe;Marie;0;1
1 ID id Active (0/1) Gender ID (Mr=1, Ms=2, else 9) E-mail* Password* Birthday Lastname* Firstname* Newletter (0/1) Opt-in (0/1)
2 1 1 1 1 johndoe@prestashop.com #res152EDRF sous quelle forme ? Doe John 1 1
3 2 2 1 2 mariedoe@prestashop.com 58@ret26# sous quelle forme ? Doe Marie 0 1
+1 -1
View File
@@ -1,3 +1,3 @@
ID;Active (0/1);Name*;Description;Short description;Meta-title;Meta-keywords;Meta-description id;Active (0/1);Name*;Description;Short description;Meta-title;Meta-keywords;Meta-description
1;1;Apple Computer, Inc;;;;; 1;1;Apple Computer, Inc;;;;;
2;1;Shure Incorporated;;;;; 2;1;Shure Incorporated;;;;;
1 ID id Active (0/1) Name* Description Short description Meta-title Meta-keywords Meta-description
2 1 1 1 Apple Computer, Inc
3 2 2 1 Shure Incorporated
+1 -1
View File
@@ -1,3 +1,3 @@
ID;Active (0/1);Name*;Categories (x,y,z,...);Price tax excl. Or Price tax excl;Tax rules id;Wholesale price;On sale (0/1);Discount amount;Discount percent;Discount from (yyy-mm-dd);Discount to (yyy-mm-dd);Reference #;Supplier reference #;Supplier;Manufacturer;EAN13;UPC;Ecotax;Weight;Quantity;Short description;Description;Tags (x,y,z,...);Meta-title;Meta-keywords;Meta-description;URL rewritten;Text when in-stock;Text if back-order allowed;Image URLs (x,y,z,...);Feature;Only available online id;Active (0/1);Name*;Categories (x,y,z,...);Price tax excl. Or Price tax excl;Tax rules id;Wholesale price;On sale (0/1);Discount amount;Discount percent;Discount from (yyy-mm-dd);Discount to (yyy-mm-dd);Reference #;Supplier reference #;Supplier;Manufacturer;EAN13;UPC;Ecotax;Weight;Quantity;Short description;Description;Tags (x,y,z,...);Meta-title;Meta-keywords;Meta-description;URL rewritten;Text when in-stock;Text if back-order allowed;Image URLs (x,y,z,...);Feature;Only available online
1;1;iPod Nano;Home, iPods;49;1;;1;;;;;92458844;54778855;AppleStore;Apple Computer, Inc;;;;0.5;800;New design. New features. Now i….;Curved ahead of the curve. For those about to rock, we give you nine amazing colors. But that's only part of the story. Feel the curved, all-aluminum and glass de...;apple, ipod, nano;;;;ipod-nano;In stock;;http://youdomain.com/img.jpg, http://yourdomain.com/img1.jpg;; 1;1;iPod Nano;Home, iPods;49;1;;1;;;;;92458844;54778855;AppleStore;Apple Computer, Inc;;;;0.5;800;New design. New features. Now i….;Curved ahead of the curve. For those about to rock, we give you nine amazing colors. But that's only part of the story. Feel the curved, all-aluminum and glass de...;apple, ipod, nano;;;;ipod-nano;In stock;;http://youdomain.com/img.jpg, http://yourdomain.com/img1.jpg;;
2;1;iPod shuffle;Home, iPods;66.05;1;79;1;;;;;92458845;54778855;AppleStore;Apple Computer, Inc;;;;0;500;iPod shuffle, the world’s most wearabl….;;ipod, shuffle;;;;ipod-shuffle;In stock;;http://youdomain.com/img25.jpg, http://yourdomain.com/img30.jpg;; 2;1;iPod shuffle;Home, iPods;66.05;1;79;1;;;;;92458845;54778855;AppleStore;Apple Computer, Inc;;;;0;500;iPod shuffle, the world’s most wearabl….;;ipod, shuffle;;;;ipod-shuffle;In stock;;http://youdomain.com/img25.jpg, http://yourdomain.com/img30.jpg;;
1 ID id Active (0/1) Name* Categories (x,y,z,...) Price tax excl. Or Price tax excl Tax rules id Wholesale price On sale (0/1) Discount amount Discount percent Discount from (yyy-mm-dd) Discount to (yyy-mm-dd) Reference # Supplier reference # Supplier Manufacturer EAN13 UPC Ecotax Weight Quantity Short description Description Tags (x,y,z,...) Meta-title Meta-keywords Meta-description URL rewritten Text when in-stock Text if back-order allowed Image URLs (x,y,z,...) Feature Only available online
2 1 1 1 iPod Nano Home, iPods 49 1 1 92458844 54778855 AppleStore Apple Computer, Inc 0.5 800 New design. New features. Now i…. Curved ahead of the curve. For those about to rock, we give you nine amazing colors. But that's only part of the story. Feel the curved, all-aluminum and glass de... apple, ipod, nano ipod-nano In stock http://youdomain.com/img.jpg, http://yourdomain.com/img1.jpg
3 2 2 1 iPod shuffle Home, iPods 66.05 1 79 1 92458845 54778855 AppleStore Apple Computer, Inc 0 500 iPod shuffle, the world’s most wearabl…. ipod, shuffle ipod-shuffle In stock http://youdomain.com/img25.jpg, http://yourdomain.com/img30.jpg
+1 -1
View File
@@ -1,3 +1,3 @@
ID;Active (0/1);Name*;Description;Short description;Meta-title;Meta-keywords;Meta-description id;Active (0/1);Name*;Description;Short description;Meta-title;Meta-keywords;Meta-description
1;1;Applestore;;;;; 1;1;Applestore;;;;;
2;1;Shure Online Store;;;;; 2;1;Shure Online Store;;;;;
1 ID id Active (0/1) Name* Description Short description Meta-title Meta-keywords Meta-description
2 1 1 1 Applestore
3 2 2 1 Shure Online Store
+2
View File
@@ -251,6 +251,7 @@ function imageResize($sourceFile, $destFile, $destWidth = NULL, $destHeight = NU
} }
imagecopyresampled($destImage, $sourceImage, (int)(($destWidth - $nextWidth) / 2), (int)(($destHeight - $nextHeight) / 2), 0, 0, $nextWidth, $nextHeight, $sourceWidth, $sourceHeight); imagecopyresampled($destImage, $sourceImage, (int)(($destWidth - $nextWidth) / 2), (int)(($destHeight - $nextHeight) / 2), 0, 0, $nextWidth, $nextHeight, $sourceWidth, $sourceHeight);
return (returnDestImage($fileType, $destImage, $destFile)); return (returnDestImage($fileType, $destImage, $destFile));
} }
@@ -326,6 +327,7 @@ function returnDestImage($type, $ressource, $filename)
$quality = (Configuration::get('PS_PNG_QUALITY') === false ? 7 : Configuration::get('PS_PNG_QUALITY')); $quality = (Configuration::get('PS_PNG_QUALITY') === false ? 7 : Configuration::get('PS_PNG_QUALITY'));
$flag = imagepng($ressource, $filename, (int)$quality); $flag = imagepng($ressource, $filename, (int)$quality);
break; break;
case 'jpg':
case 'jpeg': case 'jpeg':
default: default:
$quality = (Configuration::get('PS_JPEG_QUALITY') === false ? 90 : Configuration::get('PS_JPEG_QUALITY')); $quality = (Configuration::get('PS_JPEG_QUALITY') === false ? 90 : Configuration::get('PS_JPEG_QUALITY'));
+3 -2
View File
@@ -355,9 +355,9 @@ if ($lm->getIncludeTradFilename())
<h2><?php echo lang('What do you want to do?')?></h2> <h2><?php echo lang('What do you want to do?')?></h2>
<form id="formSetMethod" action="<?php $_SERVER['REQUEST_URI']; ?>" method="post"> <form id="formSetMethod" action="<?php $_SERVER['REQUEST_URI']; ?>" method="post">
<p><input <?php echo (!($oldversion AND !$tooOld AND !$sameVersions AND !$installOfOldVersion)) ? 'checked="checked"' : '' ?> type="radio" value="install" name="typeInstall" id="typeInstallInstall" style="vertical-align: middle;" /> <label for="typeInstallInstall"><?php echo lang('I want to').' <b>'.lang('install').'</b> '.lang('a new online shop with PrestaShop'); ?></label></p> <p><input <?php echo (!($oldversion AND !$tooOld AND !$sameVersions AND !$installOfOldVersion)) ? 'checked="checked"' : '' ?> type="radio" value="install" name="typeInstall" id="typeInstallInstall" style="vertical-align: middle;" /> <label for="typeInstallInstall"><?php echo lang('I want to <b>install</b> a new online shop with PrestaShop'); ?></label></p>
<p style="font-style: italic;"><?php echo lang('- or -'); ?></p> <p style="font-style: italic;"><?php echo lang('- or -'); ?></p>
<p <?php echo ($oldversion AND !$tooOld AND !$sameVersions AND !$installOfOldVersion) ? '' : 'class="disabled"'; ?>><input <?php echo ($oldversion AND !$tooOld AND !$sameVersions AND !$installOfOldVersion) ? 'checked="checked"' : 'disabled="disabled"'; ?> type="radio" value="upgrade" name="typeInstall" id="typeInstallUpgrade" style="vertical-align: middle;" /> <label <?php echo ($oldversion === false) ? 'class="disabled"' : ''; ?> for="typeInstallUpgrade"><?php echo lang('I want to').' <b>'.lang('update').'</b> '.lang('my existing PrestaShop to a newer version'); ?> <?php echo ($oldversion === false) ? lang('(No previous version detected)') : ("(".(($tooOld) ? lang('Your current version is too old, updates are possible only from version').' '.MINIMUM_VERSION_TO_UPDATE.' '.lang('and higher') : ($installOfOldVersion ? lang('Your current version is already up-to-date') : lang('Currently installed version detected:').' <b>v'.$oldversion.'</b>')).")") ?></label></p> <p <?php echo ($oldversion AND !$tooOld AND !$sameVersions AND !$installOfOldVersion) ? '' : 'class="disabled"'; ?>><input <?php echo ($oldversion AND !$tooOld AND !$sameVersions AND !$installOfOldVersion) ? 'checked="checked"' : 'disabled="disabled"'; ?> type="radio" value="upgrade" name="typeInstall" id="typeInstallUpgrade" style="vertical-align: middle;" /> <label <?php echo ($oldversion === false) ? 'class="disabled"' : ''; ?> for="typeInstallUpgrade"><?php echo lang('I want to <b>update</b> my existing PrestaShop to a newer version'); ?> <?php echo ($oldversion === false) ? lang('(No previous version detected)') : ("(".(($tooOld) ? lang('Your current version is too old, updates are possible only from version').' '.MINIMUM_VERSION_TO_UPDATE.' '.lang('and higher') : ($installOfOldVersion ? lang('Your current version is already up-to-date') : lang('Currently installed version detected:').' <b>v'.$oldversion.'</b>')).")") ?></label></p>
</form> </form>
<h2><?php echo lang('License Agreement')?></h2> <h2><?php echo lang('License Agreement')?></h2>
<div style="height:200px; border:1px solid #ccc; margin-bottom:8px; padding:5px; background:#fff; overflow: auto; overflow-x:hidden; overflow-y:scroll;"> <div style="height:200px; border:1px solid #ccc; margin-bottom:8px; padding:5px; background:#fff; overflow: auto; overflow-x:hidden; overflow-y:scroll;">
@@ -1364,3 +1364,4 @@ if ($lm->getIncludeTradFilename())
</ul> </ul>
</body> </body>
</html> </html>
+3 -6
View File
@@ -277,12 +277,9 @@ $_LANG['Other activity...'] = 'Andere activiteit...';
$_LANG['Modules'] = 'Módulos'; $_LANG['Modules'] = 'Módulos';
$_LANG['Benefits'] = 'Vorteile'; $_LANG['Benefits'] = 'Vorteile';
$_LANG['Create a MySQL database using phpMyAdmin (or by asking your hosting provider)'] = ''; $_LANG['Create a MySQL database using phpMyAdmin (or by asking your hosting provider)'] = '';
$_LANG['- or -'] = ''; $_LANG['- or -'] = '- oder -';
$_LANG['I want to'] = ''; $_LANG['I want to <b>install</b> a new online shop with PrestaShop'] = 'Ich m&ouml;chte einen neuen PrestaShop <b>installieren</b>';
$_LANG['install'] = ''; $_LANG['I want to <b>update</b> my existing PrestaShop to a newer version'] = 'Ich m&ouml;chte meinen <b>aktuellen</b> PrestaShop mit einer neueren Version aktualisieren';
$_LANG['a new online shop with PrestaShop'] = '';
$_LANG['update'] = '';
$_LANG['my existing PrestaShop to a newer version'] = '';
$_LANG['Your current version is too old, updates are possible only from version'] = ''; $_LANG['Your current version is too old, updates are possible only from version'] = '';
$_LANG['and higher'] = ''; $_LANG['and higher'] = '';
$_LANG['PHP settings (for assistance, ask your hosting provider):'] = ''; $_LANG['PHP settings (for assistance, ask your hosting provider):'] = '';
+2 -5
View File
@@ -281,11 +281,8 @@ $_LANG['Modules'] = 'Módulos';
$_LANG['Benefits'] = 'Beneficios'; $_LANG['Benefits'] = 'Beneficios';
$_LANG['Create a MySQL database using phpMyAdmin (or by asking your hosting provider)'] = 'Crear un base de datos MySQL usando phpMyAdmin (o preguntele a su proveedor de alojamiento web)'; $_LANG['Create a MySQL database using phpMyAdmin (or by asking your hosting provider)'] = 'Crear un base de datos MySQL usando phpMyAdmin (o preguntele a su proveedor de alojamiento web)';
$_LANG['- or -'] = ' - o -'; $_LANG['- or -'] = ' - o -';
$_LANG['I want to'] = 'Yo quiero'; $_LANG['I want to <b>install</b> a new online shop with PrestaShop'] = 'Yo quiero <b>installar</b> una nueva tienda online con PrestaShop';
$_LANG['install'] = 'installar'; $_LANG['I want to <b>update</b> my existing PrestaShop to a newer version'] = 'Quiero actualizar mi actual PrestaShop, a una nueva versi&oacute;n m&aacute;s reciente';
$_LANG['a new online shop with PrestaShop'] = 'una nueva tienda online con PrestaShop';
$_LANG['update'] = 'actualizar';
$_LANG['my existing PrestaShop to a newer version'] = 'mi tienda PrestaShop actual a una nueva version';
$_LANG['Your current version is too old, updates are possible only from version'] = 'Su version actual esta antigua, actualizaciones solo estan disponibles desde la version'; $_LANG['Your current version is too old, updates are possible only from version'] = 'Su version actual esta antigua, actualizaciones solo estan disponibles desde la version';
$_LANG['and higher'] = 'y en adelante'; $_LANG['and higher'] = 'y en adelante';
$_LANG['PHP settings (for assistance, ask your hosting provider):'] = 'PHP parámetros (para assistencia, preguntale a su proveedor de alojamiento web)'; $_LANG['PHP settings (for assistance, ask your hosting provider):'] = 'PHP parámetros (para assistencia, preguntale a su proveedor de alojamiento web)';
+2 -5
View File
@@ -287,11 +287,8 @@ $_LANG['Modules'] = 'Modules';
$_LANG['Benefits'] = 'Avantages'; $_LANG['Benefits'] = 'Avantages';
$_LANG['Create a MySQL database using phpMyAdmin (or by asking your hosting provider)'] = 'Créer une base de données MySQL en utilisant phpMyAdmin (ou en demandant à votre hébergeur)'; $_LANG['Create a MySQL database using phpMyAdmin (or by asking your hosting provider)'] = 'Créer une base de données MySQL en utilisant phpMyAdmin (ou en demandant à votre hébergeur)';
$_LANG['- or -'] = '- ou -'; $_LANG['- or -'] = '- ou -';
$_LANG['I want to'] = 'Je souhaite'; $_LANG['I want to <b>install</b> a new online shop with PrestaShop'] = 'Je souhaite <b>installer</b> une nouvelle boutique avec PrestaShop';
$_LANG['install'] = 'installer'; $_LANG['I want to <b>update</b> my existing PrestaShop to a newer version'] = 'Je veux <b>mettre à jour</b> ma boutique PrestaShop vers une nouvelle version';
$_LANG['a new online shop with PrestaShop'] = 'une nouvelle boutique avec PrestaShop';
$_LANG['update'] = 'mettre à jour';
$_LANG['my existing PrestaShop to a newer version'] = 'ma boutique PrestaShop vers une nouvelle version';
$_LANG['Your current version is too old, updates are possible only from version'] = 'Votre version actuelle est trop ancienne, les mises à jour sont autorisées à partir de la version'; $_LANG['Your current version is too old, updates are possible only from version'] = 'Votre version actuelle est trop ancienne, les mises à jour sont autorisées à partir de la version';
$_LANG['and higher'] = 'et versions supérieures'; $_LANG['and higher'] = 'et versions supérieures';
$_LANG['PHP settings (for assistance, ask your hosting provider):'] = 'Paramètres PHP (Demandez de l\'aide à votre hébergeur si nécessaire)'; $_LANG['PHP settings (for assistance, ask your hosting provider):'] = 'Paramètres PHP (Demandez de l\'aide à votre hébergeur si nécessaire)';
+5 -6
View File
@@ -266,12 +266,9 @@ $_LANG['Other activity...'] = 'Altre attività ...';
$_LANG['Modules'] = 'Moduli'; $_LANG['Modules'] = 'Moduli';
$_LANG['Benefits'] = 'Vantaggi'; $_LANG['Benefits'] = 'Vantaggi';
$_LANG['Create a MySQL database using phpMyAdmin (or by asking your hosting provider)'] = ''; $_LANG['Create a MySQL database using phpMyAdmin (or by asking your hosting provider)'] = '';
$_LANG['- or -'] = ''; $_LANG['- or -'] = '- o -';
$_LANG['I want to'] = ''; $_LANG['I want to <b>install</b> a new online shop with PrestaShop'] = 'Voglio <b>installare</b> un nuovo shop con PrestaShop';
$_LANG['install'] = ''; $_LANG['I want to <b>update</b> my existing PrestaShop to a newer version'] = 'Voglio <b>aggiornare</b> il mio PrestaShop esistente alla nuova versione';
$_LANG['a new online shop with PrestaShop'] = '';
$_LANG['update'] = '';
$_LANG['my existing PrestaShop to a newer version'] = '';
$_LANG['Your current version is too old, updates are possible only from version'] = ''; $_LANG['Your current version is too old, updates are possible only from version'] = '';
$_LANG['and higher'] = ''; $_LANG['and higher'] = '';
$_LANG['PHP settings (for assistance, ask your hosting provider):'] = ''; $_LANG['PHP settings (for assistance, ask your hosting provider):'] = '';
@@ -283,3 +280,5 @@ $_LANG['Ok, please deactivate the following modules, I will reactivate them late
$_LANG['You will be able to manually reactivate them in your Back Office once the update process has succeeded.'] = ''; $_LANG['You will be able to manually reactivate them in your Back Office once the update process has succeeded.'] = '';
$_LANG['No more information'] = ''; $_LANG['No more information'] = '';
$_LANG['If your theme is not valid, you may experience some problems in your front-office aspect, but don\'t panic ! To solve this, you can make it compatible by correcting the validators errors or by using a theme compatible with '] = ''; $_LANG['If your theme is not valid, you may experience some problems in your front-office aspect, but don\'t panic ! To solve this, you can make it compatible by correcting the validators errors or by using a theme compatible with '] = '';
$_LANG['-- Select your country --'] = '-- scegliere il paese --';
$_LANG['-- Select your timezone --'] = '-- Scegli il fuso orario --';
+1
View File
@@ -115,3 +115,4 @@ if (isset($_GET['method']))
break; break;
} }
} }
@@ -0,0 +1,49 @@
<?php
/*
* 2007-2011 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 http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2011 PrestaShop SA
* @version Release: $Revision$
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
function hook_blocksearch_on_header()
{
if ($id_module = Db::getInstance()->getValue('SELECT `id_module` FROM `'._DB_PREFIX_.'module` WHERE `name` = \'blocksearch\''))
{
$id_hook = Db::getInstance()->getValue('
SELECT `id_hook`
FROM `'._DB_PREFIX_.'hook`
WHERE `name` = \'header\'
');
$position = Db::getInstance()->getValue('
SELECT MAX(`position`)
FROM `'._DB_PREFIX_.'hook_module`
WHERE `id_hook` = '.(int)$id_hook.'
');
Db::getInstance()->Execute('
INSERT INTO `'._DB_PREFIX_.'hook_module` (`id_module`, `id_hook`, `position`)
VALUES ('.(int)$id_module.', '.(int)$id_hook.', '.($position+1).')
');
}
}
+97
View File
@@ -0,0 +1,97 @@
<?php
/*
* 2007-2011 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 http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2011 PrestaShop SA
* @version Release: $Revision$
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
function update_order_canada()
{
$sql ='SHOW TABLES LIKE \''._DB_PREFIX_.'order_tax\'';
$table = Db::getInstance()->ExecuteS($sql);
if (!count($table))
{
Db::getInstance()->Execute('
CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'order_tax` (
`id_order` int(11) NOT NULL,
`tax_name` varchar(40) NOT NULL,
`tax_rate` decimal(6,3) NOT NULL,
`amount` decimal(20,6) NOT NULL
) ENGINE=ENGINE_TYPE DEFAULT CHARSET=utf8');
$address_field = Configuration::get('PS_TAX_ADDRESS_TYPE');
$sql = 'SELECT `id_order`
FROM `'._DB_PREFIX_.'orders` o
LEFT JOIN `'._DB_PREFIX_.'address` a ON (a.`id_address` = o.`'.bqSQL($address_field).'`)
LEFT JOIN `'._DB_PREFIX_.'country` c ON (c.`id_country` = a.`id_country`)
WHERE c.`iso_code` = "CA"';
$id_order_list = Db::getInstance()->ExecuteS($sql);
$values = '';
foreach ($id_order_list as $id_order)
{
$amount = array();
$id_order = $id_order['id_order'];
$order = new Order((int)$id_order);
if (!Validate::isLoadedObject($order))
continue;
$products = $order->getProducts();
foreach ($products as $product)
{
if (!array_key_exists($product['tax_name'], $amount))
$amount[$product['tax_name']] = array('amount' => 0, 'rate' => $product['tax_rate']);
if ($order->getTaxCalculationMethod() == PS_TAX_EXC)
{
$total_product = $product['product_price'] * $product['product_quantity'];
$amount_tmp = Tools::ps_round($total_product * ($product['tax_rate'] / 100), 2);
$amount[$product['tax_name']]['amount'] += Tools::ps_round($total_product * ($product['tax_rate'] / 100), 2);
}
else
{
$total_product = $product['product_price'] * $product['product_quantity'];
$amount_tmp = Tools::ps_round($total_product - ($total_product / (1 + ($product['tax_rate'] / 100))), 2);
$amount[$product['tax_name']]['amount'] += Tools::ps_round($total_product - ($total_product / (1 + ($product['tax_rate'] / 100))), 2);
}
}
foreach ($amount as $tax_name => $tax_infos)
$values .= '('.(int)$order->id.', \''.pSQL($tax_name).'\', \''.pSQL($tax_infos['rate']).'\', '.(float)$tax_infos['amount'].'),';
unset($order);
}
if (!empty($values))
{
$values = rtrim($values, ",");
Db::getInstance()->Execute('
INSERT INTO `'._DB_PREFIX_.'order_tax` (id_order, tax_name, tax_rate, amount)
VALUES '.$values);
}
}
}
+24 -8
View File
@@ -380,14 +380,18 @@ CREATE TABLE `PREFIX_cms_category_lang` (
KEY `category_name` (`name`) KEY `category_name` (`name`)
) ENGINE=ENGINE_TYPE DEFAULT CHARSET=utf8; ) ENGINE=ENGINE_TYPE DEFAULT CHARSET=utf8;
CREATE TABLE `PREFIX_compare_product` ( CREATE TABLE `PREFIX_compare` (
`id_compare_product` int(10) unsigned NOT NULL AUTO_INCREMENT, `id_compare` int(10) unsigned NOT NULL auto_increment,
`id_product` int(10) unsigned NOT NULL,
`id_guest` int(10) unsigned NOT NULL,
`id_customer` int(10) unsigned NOT NULL, `id_customer` int(10) unsigned NOT NULL,
PRIMARY KEY (`id_compare`)
) ENGINE=ENGINE_TYPE DEFAULT CHARSET=utf8;
CREATE TABLE `PREFIX_compare_product` (
`id_compare` int(10) unsigned NOT NULL,
`id_product` int(10) unsigned NOT NULL,
`date_add` datetime NOT NULL, `date_add` datetime NOT NULL,
`date_upd` datetime NOT NULL, `date_upd` datetime NOT NULL,
PRIMARY KEY (`id_compare_product`) PRIMARY KEY (`id_compare`,`id_product`)
) ENGINE=ENGINE_TYPE DEFAULT CHARSET=utf8; ) ENGINE=ENGINE_TYPE DEFAULT CHARSET=utf8;
CREATE TABLE `PREFIX_configuration` ( CREATE TABLE `PREFIX_configuration` (
@@ -1095,6 +1099,12 @@ CREATE TABLE `PREFIX_order_detail` (
KEY `id_order_id_order_detail` (`id_order`, `id_order_detail`) KEY `id_order_id_order_detail` (`id_order`, `id_order_detail`)
) ENGINE=ENGINE_TYPE DEFAULT CHARSET=utf8; ) ENGINE=ENGINE_TYPE DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `PREFIX_order_tax` (
`id_order` int(11) NOT NULL,
`tax_name` varchar(40) NOT NULL,
`tax_rate` decimal(6,3) NOT NULL,
`amount` decimal(20,6) NOT NULL
) ENGINE=ENGINE_TYPE DEFAULT CHARSET=utf8;
CREATE TABLE `PREFIX_order_cart_rule` ( CREATE TABLE `PREFIX_order_cart_rule` (
`id_order_cart_rule` int(10) unsigned NOT NULL auto_increment, `id_order_cart_rule` int(10) unsigned NOT NULL auto_increment,
@@ -1544,7 +1554,7 @@ CREATE TABLE `PREFIX_specific_price` (
`id_group` INT UNSIGNED NOT NULL, `id_group` INT UNSIGNED NOT NULL,
`id_product_attribute` INT UNSIGNED NOT NULL, `id_product_attribute` INT UNSIGNED NOT NULL,
`price` DECIMAL(20, 6) NOT NULL, `price` DECIMAL(20, 6) NOT NULL,
`from_quantity` SMALLINT UNSIGNED NOT NULL, `from_quantity` mediumint(8) UNSIGNED NOT NULL,
`reduction` DECIMAL(20, 6) NOT NULL, `reduction` DECIMAL(20, 6) NOT NULL,
`reduction_type` ENUM('amount', 'percentage') NOT NULL, `reduction_type` ENUM('amount', 'percentage') NOT NULL,
`from` DATETIME NOT NULL, `from` DATETIME NOT NULL,
@@ -1668,8 +1678,8 @@ CREATE TABLE `PREFIX_store` (
`address2` varchar(128) DEFAULT NULL, `address2` varchar(128) DEFAULT NULL,
`city` varchar(64) NOT NULL, `city` varchar(64) NOT NULL,
`postcode` varchar(12) NOT NULL, `postcode` varchar(12) NOT NULL,
`latitude` decimal(10,8) DEFAULT NULL, `latitude` decimal(11,8) DEFAULT NULL,
`longitude` decimal(10,8) DEFAULT NULL, `longitude` decimal(11,8) DEFAULT NULL,
`hours` varchar(254) DEFAULT NULL, `hours` varchar(254) DEFAULT NULL,
`phone` varchar(16) DEFAULT NULL, `phone` varchar(16) DEFAULT NULL,
`fax` varchar(16) DEFAULT NULL, `fax` varchar(16) DEFAULT NULL,
@@ -1857,6 +1867,12 @@ PRIMARY KEY (`id_carrier`, `id_shop`),
KEY `id_shop` (`id_shop`) KEY `id_shop` (`id_shop`)
) ENGINE=ENGINE_TYPE DEFAULT CHARSET=utf8; ) ENGINE=ENGINE_TYPE DEFAULT CHARSET=utf8;
CREATE TABLE `PREFIX_address_format` (
`id_country` int(10) unsigned NOT NULL,
`format` varchar(255) NOT NULL DEFAULT '',
PRIMARY KEY (`id_country`)
) ENGINE=ENGINE_TYPE DEFAULT CHARSET=utf8;
CREATE TABLE `PREFIX_cms_shop` ( CREATE TABLE `PREFIX_cms_shop` (
`id_cms` INT( 11 ) UNSIGNED NOT NULL, `id_cms` INT( 11 ) UNSIGNED NOT NULL,
`id_shop` INT( 11 ) UNSIGNED NOT NULL , `id_shop` INT( 11 ) UNSIGNED NOT NULL ,
+84 -3
View File
@@ -72,7 +72,7 @@ INSERT INTO `PREFIX_hook_module` (`id_module`, `id_hook`, `position`) VALUES (3,
(35, 33, 2),(36, 33, 3),(37, 33, 4),(39, 37, 1),(40, 32, 8),(41, 32, 9),(42, 32, 10),(43, 32, 11),(42, 14, 6),(43, 14, 7),(44, 32, 12),(45, 32, 13),(46, 32, 15), (35, 33, 2),(36, 33, 3),(37, 33, 4),(39, 37, 1),(40, 32, 8),(41, 32, 9),(42, 32, 10),(43, 32, 11),(42, 14, 6),(43, 14, 7),(44, 32, 12),(45, 32, 13),(46, 32, 15),
(47, 32, 14),(48, 32, 16),(49, 32, 17),(55, 32, 22),(50, 32, 18),(51, 32, 19),(51, 45, 1),(25, 25, 1),(41, 20, 2),(52, 32, 20),(53, 32, 21),(17, 9, 2),(18, 9, 3),(24, 9, 4),(9, 9, 5), (47, 32, 14),(48, 32, 16),(49, 32, 17),(55, 32, 22),(50, 32, 18),(51, 32, 19),(51, 45, 1),(25, 25, 1),(41, 20, 2),(52, 32, 20),(53, 32, 21),(17, 9, 2),(18, 9, 3),(24, 9, 4),(9, 9, 5),
(15, 9, 6),(5, 9, 7),(8, 9, 8),(10, 9, 9),(20, 9, 10),(11, 9, 11),(16, 9, 12),(22, 9, 13),(13, 9, 14),(14, 9, 15),(12, 9, 16),(7, 9, 17),(21, 9, 18),(10, 60, 1),(10, 61, 1),(10, 62, 1), (15, 9, 6),(5, 9, 7),(8, 9, 8),(10, 9, 9),(20, 9, 10),(11, 9, 11),(16, 9, 12),(22, 9, 13),(13, 9, 14),(14, 9, 15),(12, 9, 16),(7, 9, 17),(21, 9, 18),(10, 60, 1),(10, 61, 1),(10, 62, 1),
(54, 9, 19),(10,66,1); (54, 9, 19),(10,66,1),(19,9,20);
CREATE TABLE `PREFIX_pagenotfound` ( CREATE TABLE `PREFIX_pagenotfound` (
`id_pagenotfound` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT, `id_pagenotfound` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
@@ -866,6 +866,85 @@ INSERT INTO `PREFIX_search_word` (`id_word`, `id_lang`, `word`) VALUES (1, 1, 'i
INSERT INTO `PREFIX_access` (`id_profile`, `id_tab`, `view`, `add`, `edit`, `delete`) (SELECT 2, id_tab, 1, 1, 1, 1 FROM PREFIX_tab); INSERT INTO `PREFIX_access` (`id_profile`, `id_tab`, `view`, `add`, `edit`, `delete`) (SELECT 2, id_tab, 1, 1, 1, 1 FROM PREFIX_tab);
INSERT INTO `PREFIX_access` (`id_profile`, `id_tab`, `view`, `add`, `edit`, `delete`) VALUES INSERT INTO `PREFIX_access` (`id_profile`, `id_tab`, `view`, `add`, `edit`, `delete`) VALUES
(2, 1, 1, 1, 1, 1),
(2, 2, 1, 1, 1, 1),
(2, 3, 1, 1, 1, 1),
(2, 4, 0, 0, 0, 0),
(2, 5, 1, 1, 1, 1),
(2, 6, 0, 0, 0, 0),
(2, 7, 0, 0, 0, 0),
(2, 8, 0, 0, 0, 0),
(2, 9, 0, 0, 0, 0),
(2, 10, 0, 0, 0, 0),
(2, 11, 0, 0, 0, 0),
(2, 12, 1, 1, 1, 1),
(2, 13, 1, 1, 1, 1),
(2, 14, 0, 0, 0, 0),
(2, 15, 0, 0, 0, 0),
(2, 16, 0, 0, 0, 0),
(2, 17, 1, 1, 1, 1),
(2, 18, 0, 0, 0, 0),
(2, 19, 0, 0, 0, 0),
(2, 20, 1, 1, 1, 1),
(2, 21, 1, 1, 1, 1),
(2, 22, 0, 0, 0, 0),
(2, 23, 0, 0, 0, 0),
(2, 24, 0, 0, 0, 0),
(2, 26, 0, 0, 0, 0),
(2, 27, 0, 0, 0, 0),
(2, 28, 0, 0, 0, 0),
(2, 29, 0, 0, 0, 0),
(2, 30, 0, 0, 0, 0),
(2, 31, 0, 0, 0, 0),
(2, 32, 0, 0, 0, 0),
(2, 33, 0, 0, 0, 0),
(2, 34, 1, 1, 1, 1),
(2, 35, 0, 0, 0, 0),
(2, 36, 0, 0, 0, 0),
(2, 37, 0, 0, 0, 0),
(2, 38, 0, 0, 0, 0),
(2, 39, 0, 0, 0, 0),
(2, 40, 0, 0, 0, 0),
(2, 41, 0, 0, 0, 0),
(2, 42, 1, 1, 1, 1),
(2, 43, 0, 0, 0, 0),
(2, 44, 0, 0, 0, 0),
(2, 46, 0, 0, 0, 0),
(2, 47, 1, 1, 1, 1),
(2, 48, 0, 0, 0, 0),
(2, 49, 1, 1, 1, 1),
(2, 51, 0, 0, 0, 0),
(2, 52, 0, 0, 0, 0),
(2, 53, 0, 0, 0, 0),
(2, 54, 0, 0, 0, 0),
(2, 55, 1, 1, 1, 1),
(2, 56, 0, 0, 0, 0),
(2, 57, 0, 0, 0, 0),
(2, 58, 0, 0, 0, 0),
(2, 59, 1, 1, 1, 1),
(2, 60, 1, 1, 1, 1),
(2, 61, 0, 0, 0, 0),
(2, 62, 0, 0, 0, 0),
(2, 63, 0, 0, 0, 0),
(2, 64, 0, 0, 0, 0),
(2, 65, 0, 0, 0, 0),
(2, 66, 0, 0, 0, 0),
(2, 67, 0, 0, 0, 0),
(2, 68, 0, 0, 0, 0),
(2, 69, 0, 0, 0, 0),
(2, 70, 0, 0, 0, 0),
(2, 71, 0, 0, 0, 0),
(2, 72, 0, 0, 0, 0),
(2, 73, 1, 1, 1, 1),
(2, 80, 0, 0, 0, 0),
(2, 81, 0, 0, 0, 0),
(2, 82, 0, 0, 0, 0),
(2, 83, 0, 0, 0, 0),
(2, 84, 0, 0, 0, 0),
(2, 85, 0, 0, 0, 0),
(2, 86, 0, 0, 0, 0),
(2, 87, 0, 0, 0, 0),
(2, 88, 1, 1, 1, 1),
(3, 1, 1, 1, 1, 1), (3, 1, 1, 1, 1, 1),
(3, 2, 1, 1, 1, 1), (3, 2, 1, 1, 1, 1),
(3, 3, 1, 1, 1, 1), (3, 3, 1, 1, 1, 1),
@@ -945,7 +1024,6 @@ INSERT INTO `PREFIX_access` (`id_profile`, `id_tab`, `view`, `add`, `edit`, `del
(3, 86, 0, 0, 0, 0), (3, 86, 0, 0, 0, 0),
(3, 87, 0, 0, 0, 0), (3, 87, 0, 0, 0, 0),
(3, 88, 0, 0, 0, 0), (3, 88, 0, 0, 0, 0),
(3, 89, 0, 0, 0, 0),
(3, 90, 0, 0, 0, 0), (3, 90, 0, 0, 0, 0),
(3, 91, 0, 0, 0, 0), (3, 91, 0, 0, 0, 0),
(3, 92, 0, 0, 0, 0), (3, 92, 0, 0, 0, 0),
@@ -1041,6 +1119,7 @@ INSERT INTO `PREFIX_access` (`id_profile`, `id_tab`, `view`, `add`, `edit`, `del
(4, 85, 0, 0, 0, 0), (4, 85, 0, 0, 0, 0),
(4, 86, 0, 0, 0, 0), (4, 86, 0, 0, 0, 0),
(4, 87, 0, 0, 0, 0), (4, 87, 0, 0, 0, 0),
<<<<<<< .working
(4, 88, 0, 0, 0, 0), (4, 88, 0, 0, 0, 0),
(4, 89, 0, 0, 0, 0), (4, 89, 0, 0, 0, 0),
(4, 90, 0, 0, 0, 0), (4, 90, 0, 0, 0, 0),
@@ -1156,7 +1235,9 @@ INSERT INTO `PREFIX_access` (`id_profile`, `id_tab`, `view`, `add`, `edit`, `del
(5, 103, 1, 1, 1, 1), (5, 103, 1, 1, 1, 1),
(5, 104, 1, 1, 1, 1), (5, 104, 1, 1, 1, 1),
(5, 105, 0, 0, 0, 0), (5, 105, 0, 0, 0, 0),
(5, 106, 0, 0, 0, 0); (5, 106, 0, 0, 0, 0),
(4, 88, 1, 1, 1, 1);
>>>>>>> .merge-right.r10309
INSERT INTO `PREFIX_module_access` (`id_profile`, `id_module`, `configure`, `view`) (SELECT 2, id_module, 0, 1 FROM PREFIX_module); INSERT INTO `PREFIX_module_access` (`id_profile`, `id_module`, `configure`, `view`) (SELECT 2, id_module, 0, 1 FROM PREFIX_module);
INSERT INTO `PREFIX_module_access` (`id_profile`, `id_module`, `configure`, `view`) (SELECT 3, id_module, 0, 1 FROM PREFIX_module); INSERT INTO `PREFIX_module_access` (`id_profile`, `id_module`, `configure`, `view`) (SELECT 3, id_module, 0, 1 FROM PREFIX_module);
+3 -2
View File
@@ -1052,8 +1052,8 @@ INSERT INTO `PREFIX_tab_lang` (`id_lang`, `id_tab`, `name`) VALUES
INSERT INTO `PREFIX_tab_lang` (`id_lang`, `id_tab`, `name`) VALUES INSERT INTO `PREFIX_tab_lang` (`id_lang`, `id_tab`, `name`) VALUES
(4, 1, 'Katalog'),(4, 2, 'Kunden'),(4, 3, 'Bestellungen'),(4, 4, 'Zahlung'), (4, 1, 'Katalog'),(4, 2, 'Kunden'),(4, 3, 'Bestellungen'),(4, 4, 'Zahlung'),
(4, 5, 'Versandkosten'),(4, 6, 'Statistik'),(4, 7, 'Module'),(4, 8, 'Voreinstellungen'),(4, 9, 'Tools'),(4, 10, 'Hersteller'),(4, 11, 'Attribute und Gruppen'), (4, 5, 'Versandkosten'),(4, 6, 'Statistik'),(4, 7, 'Module'),(4, 8, 'Voreinstellungen'),(4, 9, 'Tools'),(4, 10, 'Hersteller'),(4, 11, 'Attribute und Gruppen'),
(4, 12, 'Adressen'),(4, 13, 'Status'),(4, 14, 'Gutscheine'),(4, 15, 'Währungen'),(4, 16, 'Steuern'),(4, 17, 'Lieferanten'),(4, 18, 'Länder'), (4, 12, 'Adressen'),(4, 13, 'Status'),(4, 14, 'Gutscheine'),(4, 15, 'Währungen'),(4, 16, 'Steuern'),(4, 17, 'Versanddienst'),(4, 18, 'Länder'),
(4, 19, 'Zonen'),(4, 20, 'Preislagen'),(4, 21, 'Gewichtsklassen'),(4, 22, 'Positionen'),(4, 23, 'Datenbank'),(4, 24, 'E-Mail'),(4, 26, 'Bild'), (4, 19, 'Zonen'),(4, 20, 'Preisspanne'),(4, 21, 'Gewichtsklassen'),(4, 22, 'Positionen'),(4, 23, 'Datenbank'),(4, 24, 'E-Mail'),(4, 26, 'Bild'),
(4, 27, 'Produkte'),(4, 28, 'Kontakte'),(4, 29, 'Mitarbeiter'),(4, 30, 'Profile'),(4, 31, 'Berechtigungen'),(4, 32, 'Sprachen'),(4, 33, 'Übersetzungen'), (4, 27, 'Produkte'),(4, 28, 'Kontakte'),(4, 29, 'Mitarbeiter'),(4, 30, 'Profile'),(4, 31, 'Berechtigungen'),(4, 32, 'Sprachen'),(4, 33, 'Übersetzungen'),
(4, 34, 'Zulieferer'),(4, 35, 'Tabs'),(4, 36, 'Funktionen'),(4, 37, 'Schnellzugriff'),(4, 38, 'Themen'),(4, 39, 'Kontaktinformation'),(4, 40, 'Alias'), (4, 34, 'Zulieferer'),(4, 35, 'Tabs'),(4, 36, 'Funktionen'),(4, 37, 'Schnellzugriff'),(4, 38, 'Themen'),(4, 39, 'Kontaktinformation'),(4, 40, 'Alias'),
(4, 41, 'Import'),(4, 42, 'Rechnungen'),(4, 43, 'Suche'),(4, 44, 'Lokalisierung'),(4, 46, 'Staaten'),(4, 47, 'Warenrücksendungen'),(4, 48, 'PDF'), (4, 41, 'Import'),(4, 42, 'Rechnungen'),(4, 43, 'Suche'),(4, 44, 'Lokalisierung'),(4, 46, 'Staaten'),(4, 47, 'Warenrücksendungen'),(4, 48, 'PDF'),
@@ -1061,6 +1061,7 @@ INSERT INTO `PREFIX_tab_lang` (`id_lang`, `id_tab`, `name`) VALUES
(4, 55, 'Lieferscheine'),(4, 56, 'SEO & URLs'),(4, 57, 'CMS'),(4, 58, 'Image Mapping'),(4, 59, 'Kundennachrichten'),(4, 60, 'Tracking'), (4, 55, 'Lieferscheine'),(4, 56, 'SEO & URLs'),(4, 57, 'CMS'),(4, 58, 'Image Mapping'),(4, 59, 'Kundennachrichten'),(4, 60, 'Tracking'),
(4, 61, 'Suchmaschinen'),(4, 62, 'Referrer'),(4, 63, 'Gruppen'),(4, 64, 'Generatoren'),(4, 65, 'Warenkörbe'),(4, 66, 'Tags'),(4, 67, 'Suche'), (4, 61, 'Suchmaschinen'),(4, 62, 'Referrer'),(4, 63, 'Gruppen'),(4, 64, 'Generatoren'),(4, 65, 'Warenkörbe'),(4, 66, 'Tags'),(4, 67, 'Suche'),
(4, 68, 'Anhänge'),(4, 69, 'Konfigurationsinformationen'),(4, 70, 'Leistung'),(4, 71, 'Kundenservice'),(4, 72, 'Webservice'),(4, 73, 'Lagerbewegungen'), (4, 68, 'Anhänge'),(4, 69, 'Konfigurationsinformationen'),(4, 70, 'Leistung'),(4, 71, 'Kundenservice'),(4, 72, 'Webservice'),(4, 73, 'Lagerbewegungen'),
<<<<<<< .working
(4, 80, 'Module und Themenkatalog'),(4, 81, 'Mein Konto'),(4, 82, 'Shops'),(4, 83, 'Themen'),(4, 84, 'Geotargeting'),(4, 85, 'Steuerregeln'),(4, 86, 'Log'), (4, 80, 'Module und Themenkatalog'),(4, 81, 'Mein Konto'),(4, 82, 'Shops'),(4, 83, 'Themen'),(4, 84, 'Geotargeting'),(4, 85, 'Steuerregeln'),(4, 86, 'Log'),
(4, 87,'Home'), (4, 88, 'Shops'), (4, 89, 'Group Shops'), (4, 90, 'Shop Urls'),(4, 91, 'Genders'),(4, 92, 'SQL Manager'), (4, 87,'Home'), (4, 88, 'Shops'), (4, 89, 'Group Shops'), (4, 90, 'Shop Urls'),(4, 91, 'Genders'),(4, 92, 'SQL Manager'),
(4, 93, 'Products'), (4, 93, 'Products'),
+25
View File
@@ -0,0 +1,25 @@
SET NAMES 'utf8';
/* PHP:update_order_canada(); */;
CREATE TABLE IF NOT EXISTS `PREFIX_compare` (
`id_compare` int(10) unsigned NOT NULL AUTO_INCREMENT,
`id_customer` int(10) unsigned NOT NULL,
PRIMARY KEY (`id_compare`)
) ENGINE=ENGINE_TYPE DEFAULT CHARSET=utf8;
ALTER TABLE `PREFIX_compare_product` DROP `id_compare_product` , DROP `id_guest` , DROP `id_customer` ;
ALTER TABLE `PREFIX_compare_product`
ADD `id_compare` int(10) unsigned NOT NULL,
ADD PRIMARY KEY(
`id_compare`,
`id_product`);
ALTER TABLE `PREFIX_store` CHANGE `latitude` `latitude` DECIMAL(11, 8) NULL DEFAULT NULL;
ALTER TABLE `PREFIX_store` CHANGE `longitude` `longitude` DECIMAL(11, 8) NULL DEFAULT NULL;
ALTER TABLE `PREFIX_address_format` ADD PRIMARY KEY (`id_country`);
ALTER TABLE `PREFIX_address_format` DROP INDEX `country`;
/* PHP:hook_blocksearch_on_header(); */;
+4
View File
@@ -141,6 +141,10 @@ require_once(_PS_INSTALLER_PHP_UPGRADE_DIR_.'update_feature_detachable_cache.php
require_once(_PS_INSTALLER_PHP_UPGRADE_DIR_.'add_accounting_tab.php'); require_once(_PS_INSTALLER_PHP_UPGRADE_DIR_.'add_accounting_tab.php');
require_once(_PS_INSTALLER_PHP_UPGRADE_DIR_.'hook_blocksearch_on_header.php');
require_once(_PS_INSTALLER_PHP_UPGRADE_DIR_.'update_order_canada.php');
//old version detection //old version detection
global $oldversion, $logger; global $oldversion, $logger;
$oldversion = false; $oldversion = false;
+3 -5
View File
@@ -39,11 +39,9 @@ virtual_product_nb_days, is_shareable)
$('#attribute_quantity').html(quantity); $('#attribute_quantity').html(quantity);
$('#attribute_quantity').show(); $('#attribute_quantity').show();
$('#attr_qty_stock').show(); $('#attr_qty_stock').show();
if(available_date != undefined)
getE('available_date').value = available_date; $('#attribute_minimal_quantity').val(minimal_quantity);
else
getE('available_date').value = '0000-00-00';
getE('minimal_quantity').value = minimal_quantity;
getE('attribute_reference').value = reference; getE('attribute_reference').value = reference;
getE('virtual_product_name_attribute').value = virtual_product_name_attribute; getE('virtual_product_name_attribute').value = virtual_product_name_attribute;
+8 -33
View File
@@ -3,7 +3,6 @@ var hooks_list = new Array();
var hookable_list = new Array(); var hookable_list = new Array();
var timer; var timer;
$(document).ready(function() { $(document).ready(function() {
$('body').css('margin-bottom', '45px'); $('body').css('margin-bottom', '45px');
$('#fancy').fancybox({ $('#fancy').fancybox({
autoDimensions: true, autoDimensions: true,
@@ -23,8 +22,7 @@ $(document).ready(function() {
if (href != undefined && href != '#' && href.substr(0, baseDir.length) == baseDir) { if (href != undefined && href != '#' && href.substr(0, baseDir.length) == baseDir) {
if (search.length == 0) { if (search.length == 0) {
$(this).attr('search', hrefAdd); $(this).attr('search', hrefAdd);
} } else {
else {
$(this).attr('search', search + '&' + hrefAdd); $(this).attr('search', search + '&' + hrefAdd);
} }
} }
@@ -37,23 +35,19 @@ $(document).ready(function() {
}); });
return false; return false;
}); });
$('#cancelMove').unbind('click').click(function() { $('#cancelMove').unbind('click').click(function() {
$('#' + cancelMove + '').sortable('cancel'); $('#' + cancelMove + '').sortable('cancel');
return false; return false;
}); });
$('#saveLiveEdit').unbind('click').click(function() { $('#saveLiveEdit').unbind('click').click(function() {
saveModulePosition(); saveModulePosition();
return false; return false;
}); });
$('#closeLiveEdit').unbind('click').click(function() { $('#closeLiveEdit').unbind('click').click(function() {
$("#live_edit_feedback_str").html('<div style="padding:10px;"><p style="margin-bottom:10px;">' + confirmClose + '</p><p style="height:1.6em;display:block"><a style="margin:auto;float:left" class="button" href="#" onclick="closeLiveEdit();">' + confirm + '</a><a style="margin:auto;float:right;" class="button" href="#" onclick="closeFancybox();">' + cancel + '</a></p></div>'); $("#live_edit_feedback_str").html('<div style="padding:10px;"><p style="margin-bottom:10px;">' + confirmClose + '</p><p style="height:1.6em;display:block"><a style="margin:auto;float:left" class="button" href="#" onclick="closeLiveEdit();">' + confirm + '</a><a style="margin:auto;float:right;" class="button" href="#" onclick="closeFancybox();">' + cancel + '</a></p></div>');
$("#fancy").attr('href', '#live_edit_feedback'); $("#fancy").attr('href', '#live_edit_feedback');
$("#fancy").trigger("click"); $("#fancy").trigger("click");
}); });
$('.add_module_live_edit').unbind('click').click(function() { $('.add_module_live_edit').unbind('click').click(function() {
$("#live_edit_feedback_str").html('<div style="padding:10px"><img src="img/loadingAnimation.gif"></div>'); $("#live_edit_feedback_str").html('<div style="padding:10px"><img src="img/loadingAnimation.gif"></div>');
$("#fancy").attr('href', '#live_edit_feedback'); $("#fancy").attr('href', '#live_edit_feedback');
@@ -62,17 +56,14 @@ $(document).ready(function() {
getHookableModuleList(id.substr(4, id.length)); getHookableModuleList(id.substr(4, id.length));
return false; return false;
}); });
$('.dndHook').each(function() { $('.dndHook').each(function() {
var id_hook = $(this).attr('id'); var id_hook = $(this).attr('id');
var new_target = ''; var new_target = '';
var old_target = ''; var old_target = '';
var cancel = false; var cancel = false;
$('#' + id_hook + '').sortable({ $('#' + id_hook + '').sortable({
opacity: 0.5, opacity: 0.5,
cursor: 'move', cursor: 'move',
connectWith: '.dndHook', connectWith: '.dndHook',
receive: function(event, ui) { receive: function(event, ui) {
if (new_target == '') { if (new_target == '') {
@@ -83,11 +74,9 @@ $(document).ready(function() {
new_target = ui.item[0].parentNode.id; new_target = ui.item[0].parentNode.id;
}, },
stop: function(event, ui) { stop: function(event, ui) {
if (cancel) { if (cancel) {
$(this).sortable('cancel'); $(this).sortable('cancel');
} } else {
else {
old_target = event.target.id; old_target = event.target.id;
cancelMove = old_target; cancelMove = old_target;
if (new_target == '') new_target = old_target; if (new_target == '') new_target = old_target;
@@ -103,8 +92,7 @@ $(document).ready(function() {
border: '1px solid #72CB67', border: '1px solid #72CB67',
background: '#DFFAD3' background: '#DFFAD3'
}); });
} } else {
else {
ui.placeholder.css({ ui.placeholder.css({
visibility: 'visible', visibility: 'visible',
border: '1px solid #EC9B9B', border: '1px solid #EC9B9B',
@@ -126,17 +114,12 @@ function getHookableList() {
dataType: 'json', dataType: 'json',
data: 'ajax=true&getHookableList&hooks_list=' + hooks_list + '&modules_list=' + modules_list + '&id_shop=' + get('id_shop'), data: 'ajax=true&getHookableList&hooks_list=' + hooks_list + '&modules_list=' + modules_list + '&id_shop=' + get('id_shop'),
success: function(jsonData) { success: function(jsonData) {
if (jsonData.hasError) if (jsonData.hasError) {
{
var errors = ''; var errors = '';
for(error in jsonData.errors) for (error in jsonData.errors) //IE6 bug fix
//IE6 bug fix if (error != 'indexOf') errors += jsonData.errors[error] + "\n";
if(error != 'indexOf')
errors += jsonData.errors[error] + "\n";
alert(errors); alert(errors);
} } else hookable_list = jsonData;
else
hookable_list = jsonData;
}, },
error: function(XMLHttpRequest, textStatus, errorThrown) { error: function(XMLHttpRequest, textStatus, errorThrown) {
$('#live_edit_feedback_str').html('<div class="live_edit_feed_back_ko"><img src="img/admin/error.png"><h3>TECHNICAL ERROR:</h3>' + loadFail + '<br><br><a style="margin:auto" class="button" href="#" onclick="closeFancybox();">' + close + '</a></div>'); $('#live_edit_feedback_str').html('<div class="live_edit_feed_back_ko"><img src="img/admin/error.png"><h3>TECHNICAL ERROR:</h3>' + loadFail + '<br><br><a style="margin:auto" class="button" href="#" onclick="closeFancybox();">' + close + '</a></div>');
@@ -145,9 +128,7 @@ function getHookableList() {
} }
}); });
} }
function getHookableModuleList(hook) { function getHookableModuleList(hook) {
$.ajax({ $.ajax({
type: 'GET', type: 'GET',
url: baseDir + ad + '/ajax.php', url: baseDir + ad + '/ajax.php',
@@ -155,7 +136,6 @@ function getHookableModuleList(hook) {
dataType: 'json', dataType: 'json',
data: 'ajax=true&getHookableModuleList&hook=' + hook + '&id_shop=' + get('id_shop'), data: 'ajax=true&getHookableModuleList&hook=' + hook + '&id_shop=' + get('id_shop'),
success: function(jsonData) { success: function(jsonData) {
var select = '<select id="select_module">'; var select = '<select id="select_module">';
for (var i = 0; i < jsonData.length; i++) { for (var i = 0; i < jsonData.length; i++) {
select += '<option value="' + jsonData[i].id + '">' + jsonData[i].name + '</option>'; select += '<option value="' + jsonData[i].id + '">' + jsonData[i].name + '</option>';
@@ -168,7 +148,6 @@ function getHookableModuleList(hook) {
} }
}); });
} }
function saveModulePosition() { function saveModulePosition() {
$("#live_edit_feedback_str").html('<div style="padding:10px"><img src="img/loadingAnimation.gif"></div>'); $("#live_edit_feedback_str").html('<div style="padding:10px"><img src="img/loadingAnimation.gif"></div>');
$("#fancy").attr('href', '#live_edit_feedback'); $("#fancy").attr('href', '#live_edit_feedback');
@@ -197,17 +176,14 @@ function saveModulePosition() {
} }
}); });
} }
function closeFancybox() { function closeFancybox() {
clearTimeout(timer); clearTimeout(timer);
$.fancybox.close(); $.fancybox.close();
$('#live_edit_feedback_str').html(''); $('#live_edit_feedback_str').html('');
} }
function closeLiveEdit(){ function closeLiveEdit(){
window.location.href = window.location.protocol+'//'+window.location.host+window.location.pathname; window.location.href = window.location.protocol+'//'+window.location.host+window.location.pathname;
} }
function hideFeedback() { function hideFeedback() {
$('#live_edit_feed_back').fadeOut('slow', function() { $('#live_edit_feed_back').fadeOut('slow', function() {
$.fancybox.close(); $.fancybox.close();
@@ -221,8 +197,7 @@ function get(name) {
var results = regex.exec(window.location.href); var results = regex.exec(window.location.href);
if (results == null) { if (results == null) {
return ""; return "";
} } else {
else {
return results[1]; return results[1];
} }
} }
@@ -0,0 +1,95 @@
/*
* jQuery creditcard2 extension for the jQuery Validation plugin (http://plugins.jquery.com/project/validate).
* Ported from http://www.braemoor.co.uk/software/creditcard.shtml by John Gardner, with some enhancements.
*
* Author: Jack Killpatrick
* Copyright (c) 2010 iHwy, Inc.
*
* Version 1.0.1 (1/12/2010)
* Tested with jquery 1.2.6, but will probably work with earlier versions.
*
* History:
* 1.0.0 - released 2008-11-17
* 1.0.1 - released 2010-01-12 -> updated card prefixes based on data at: http://en.wikipedia.org/wiki/Credit_card_number and added support for LaserCard
*
* Visit http://www.ihwy.com/labs/jquery-validate-credit-card-extension.aspx for usage information
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*/
function validateCC(cardNo, cardName)
{
//jQuery.validator.addMethod("creditcard2", function(value, element, param) {
var cards = new Array();
cards[0] = { cardName: "Visa", lengths: "13,16", prefixes: "4", checkdigit: true };
cards[1] = { cardName: "MasterCard", lengths: "16", prefixes: "51,52,53,54,55", checkdigit: true };
cards[2] = { cardName: "DinersClub", lengths: "14,16", prefixes: "305,36,38,54,55", checkdigit: true };
cards[3] = { cardName: "CarteBlanche", lengths: "14", prefixes: "300,301,302,303,304,305", checkdigit: true };
cards[4] = { cardName: "AmEx", lengths: "15", prefixes: "34,37", checkdigit: true };
cards[5] = { cardName: "Discover", lengths: "16", prefixes: "6011,622,64,65", checkdigit: true };
cards[6] = { cardName: "JCB", lengths: "16", prefixes: "35", checkdigit: true };
cards[7] = { cardName: "enRoute", lengths: "15", prefixes: "2014,2149", checkdigit: true };
cards[8] = { cardName: "Solo", lengths: "16,18,19", prefixes: "6334, 6767", checkdigit: true };
cards[9] = { cardName: "Switch", lengths: "16,18,19", prefixes: "4903,4905,4911,4936,564182,633110,6333,6759", checkdigit: true };
cards[10] = { cardName: "Maestro", lengths: "12,13,14,15,16,18,19", prefixes: "5018,5020,5038,6304,6759,6761", checkdigit: true };
cards[11] = { cardName: "VisaElectron", lengths: "16", prefixes: "417500,4917,4913,4508,4844", checkdigit: true };
cards[12] = { cardName: "LaserCard", lengths: "16,17,18,19", prefixes: "6304,6706,6771,6709", checkdigit: true };
var cardType = -1;
for (var i = 0; i < cards.length; i++) {
if (cardName.toLowerCase() == cards[i].cardName.toLowerCase()) {
cardType = i;
break;
}
}
if (cardType == -1) { return false; } // card type not found
cardNo = cardNo.replace(/[\s-]/g, ""); // remove spaces and dashes
if (cardNo.length == 0) { return false; } // no length
var cardexp = /^[0-9]{13,19}$/;
if (!cardexp.exec(cardNo)) { return false; } // has chars or wrong length
cardNo = cardNo.replace(/\D/g, ""); // strip down to digits
if (cards[cardType].checkdigit) {
var checksum = 0;
var mychar = "";
var j = 1;
var calc;
for (i = cardNo.length - 1; i >= 0; i--) {
calc = Number(cardNo.charAt(i)) * j;
if (calc > 9) {
checksum = checksum + 1;
calc = calc - 10;
}
checksum = checksum + calc;
if (j == 1) { j = 2 } else { j = 1 };
}
if (checksum % 10 != 0) { return false; } // not mod10
}
var lengthValid = false;
var prefixValid = false;
var prefix = new Array();
var lengths = new Array();
prefix = cards[cardType].prefixes.split(",");
for (i = 0; i < prefix.length; i++) {
var exp = new RegExp("^" + prefix[i]);
if (exp.test(cardNo)) prefixValid = true;
}
if (!prefixValid) { return false; } // invalid prefix
lengths = cards[cardType].lengths.split(",");
for (j = 0; j < lengths.length; j++) {
if (cardNo.length == lengths[j]) lengthValid = true;
}
if (!lengthValid) { return false; } // wrong length
return true;
}
+4
View File
@@ -51,5 +51,9 @@
<unit type="base_distance" value="ft" /> <unit type="base_distance" value="ft" />
<unit type="long_distance" value="mi" /> <unit type="long_distance" value="mi" />
</units> </units>
<configurations>
<configuration name="PS_TAX_DISPLAY" value="1" />
</configurations>
<group_default price_display_method="1" />
</localizationPack> </localizationPack>
+21 -17
View File
@@ -75,8 +75,8 @@ class authorizeAIM extends PaymentModule
public function install() public function install()
{ {
return (parent::install() AND $this->registerHook('orderConfirmation') AND return (parent::install() && $this->registerHook('orderConfirmation') && $this->registerHook('payment')
$this->registerHook('payment') AND Configuration::updateValue('AUTHORIZE_AIM_DEMO', 1)); AND $this->registerHook('header') && Configuration::updateValue('AUTHORIZE_AIM_DEMO', 1));
} }
public function uninstall() public function uninstall()
@@ -199,18 +199,23 @@ class authorizeAIM extends PaymentModule
} }
} }
/** public function hookHeader()
* Set the detail of a payment - Call before the validate order init {
* correctly the pcc object Tools::addJS(_PS_JS_DIR_.'jquery/jquery.validate.creditcard2-1.0.1.js');
* See Authorize documentation to know the associated key => value }
* @param array fields
*/ /**
public function setTransactionDetail($response) * Set the detail of a payment - Call before the validate order init
{ * correctly the pcc object
// If Exist we can store the details * See Authorize documentation to know the associated key => value
if (isset($this->pcc)) * @param array fields
{ */
$this->pcc->transaction_id = (string)$response[6]; public function setTransactionDetail($response)
{
// If Exist we can store the details
if (isset($this->pcc))
{
$this->pcc->transaction_id = (string)$response[6];
// 50 => Card number (XXXX0000) // 50 => Card number (XXXX0000)
$this->pcc->card_number = (string)substr($response[50], -4); $this->pcc->card_number = (string)substr($response[50], -4);
@@ -222,7 +227,6 @@ class authorizeAIM extends PaymentModule
// 68 => Owner name // 68 => Owner name
$this->pcc->card_holder = (string)$response[68]; $this->pcc->card_holder = (string)$response[68];
} }
} }
} }
?>
+36 -25
View File
@@ -30,22 +30,14 @@
<p style="color: red;">{l s='Error, please verify the card information' mod='authorizeaim'}</p> <p style="color: red;">{l s='Error, please verify the card information' mod='authorizeaim'}</p>
{/if} {/if}
<form id="aut" name="authorizeaim_form" action="{$module_dir}validation.php" method="post"> <form id="aut" name="authorizeaim_form" id="authorizeaim_form" action="{$module_dir}validation.php" method="post">
<span style="border: 1px solid #595A5E;display: block;padding: 0.6em;text-decoration: none;margin-left: 0.7em;"> <span style="border: 1px solid #595A5E;display: block;padding: 0.6em;text-decoration: none;margin-left: 0.7em;">
<a id="click_authorizeaim" href="#" title="{l s='Pay with authorizeaim' mod='authorizeaim'}" style="display: block;text-decoration: none;"> <a id="click_authorizeaim" href="#" title="{l s='Pay with authorizeaim' mod='authorizeaim'}" style="display: block;text-decoration: none; font-weight: bold;">
{if $cards.visa == 1} {if $cards.visa == 1}<img src="{$module_dir}cards/visa.gif" alt="{l s='visa logo' mod='authorizeaim'}" style="vertical-align: middle;" />{/if}
<img src="{$module_dir}cards/visa.gif" alt="{l s='visa logo' mod='authorizeaim'}" /> {if $cards.mastercard == 1}<img src="{$module_dir}cards/mastercard.gif" alt="{l s='mastercard logo' mod='authorizeaim'}" style="vertical-align: middle;" />{/if}
{/if} {if $cards.discover == 1}<img src="{$module_dir}cards/discover.gif" alt="{l s='discover logo' mod='authorizeaim'}" style="vertical-align: middle;" />{/if}
{if $cards.mastercard == 1} {if $cards.ax == 1}<img src="{$module_dir}cards/ax.gif" alt="{l s='american express logo' mod='authorizeaim'}" style="vertical-align: middle;" />{/if}
<img src="{$module_dir}cards/mastercard.gif" alt="{l s='mastercard logo' mod='authorizeaim'}" /> &nbsp;&nbsp;{l s='Secured credit card payment with Authorize.net' mod='authorizeaim'}
{/if}
{if $cards.discover == 1}
<img src="{$module_dir}cards/discover.gif" alt="{l s='discover logo' mod='authorizeaim'}" />
{/if}
{if $cards.ax == 1}
<img src="{$module_dir}cards/ax.gif" alt="{l s='american express logo' mod='authorizeaim'}" />
{/if}
{l s='Secured credit card payment with Authorize.net' mod='authorizeaim'}
</a> </a>
{if $isFailed == 0} {if $isFailed == 0}
@@ -53,16 +45,28 @@
{else} {else}
<div id="aut2"> <div id="aut2">
{/if} {/if}
<br /> <br /><br />
<img src="{$module_dir}logoa.gif" alt="secure payment" style="float: left;margin-top:40px;"/> <div style="width: 136px; height: 165px; float: left; padding-top:40px; padding-right: 20px; border-right: 1px solid #DDD;">
<img src="{$module_dir}logoa.gif" alt="secure payment" />
</div>
{foreach from=$p key=k item=v} {foreach from=$p key=k item=v}
<input type="hidden" name="{$k}" value="{$v}" /> <input type="hidden" name="{$k}" value="{$v}" />
{/foreach} {/foreach}
<label style="margin-left: 50px;display: block;width: 85px;float: left;">{l s='Full name' mod='authorizeaim'}</label> <input type="text" name="name" size="20" maxlength="25S" /><img src="{$module_dir}secure.png" alt="" style="margin-left: 5px;" /><br /><br /> <label style="margin-top: 4px; margin-left: 40px;display: block;width: 90px;float: left;">{l s='Full name' mod='authorizeaim'}</label> <input type="text" name="name" id="fullname" size="30" maxlength="25S" /><img src="{$module_dir}secure.png" alt="" style="margin-left: 5px;" /><br /><br />
<label style="margin-left: 50px;display: block;width: 85px;float: left;">{l s='Card number' mod='authorizeaim'}</label> <input type="text" id="ccn" name="x_card_num" size="16" maxlength="16" autocomplete="Off"/><img src="{$module_dir}secure.png" alt="" style="margin-left: 5px;" /><br /><br />
<label style="margin-left: 50px;display: block;width: 85px;float: left;">{l s='Expiration date' mod='authorizeaim'}</label> <label style="margin-top: 4px; margin-left: 40px;display: block;width: 90px;float: left;">{l s='Card Type' mod='authorizeaim'}</label>
<select id="cardType">
{if $cards.ax == 1}<option value="AmEx">American Express</option>{/if}
{if $cards.visa == 1}<option value="Visa">Visa</option>{/if}
{if $cards.mastercard == 1}<option value="MasterCard">MasterCard</option>{/if}
{if $cards.discover == 1}<option value="Discover">Discover</option>{/if}
</select>
<img src="{$module_dir}secure.png" alt="" style="margin-left: 5px;" /><br /><br />
<label style="margin-top: 4px; margin-left: 40px;display: block;width: 90px;float: left;">{l s='Card number' mod='authorizeaim'}</label> <input type="text" name="x_card_num" id="cardnum" size="30" maxlength="16" autocomplete="Off" /><img src="{$module_dir}secure.png" alt="" style="margin-left: 5px;" /><br /><br />
<label style="margin-top: 4px; margin-left: 40px;display: block;width: 90px;float: left;">{l s='Expiration date' mod='authorizeaim'}</label>
<select id="x_exp_date_m" name="x_exp_date_m" style="width:60px;">{section name=date_m start=01 loop=13} <select id="x_exp_date_m" name="x_exp_date_m" style="width:60px;">{section name=date_m start=01 loop=13}
<option value="{$smarty.section.date_m.index}">{$smarty.section.date_m.index}</option>{/section} <option value="{$smarty.section.date_m.index}">{$smarty.section.date_m.index}</option>{/section}
</select> </select>
@@ -71,15 +75,16 @@
<option value="{$smarty.section.date_y.index}">20{$smarty.section.date_y.index}</option>{/section} <option value="{$smarty.section.date_y.index}">20{$smarty.section.date_y.index}</option>{/section}
</select> </select>
<img src="{$module_dir}secure.png" alt="" style="margin-left: 5px;" /><br /><br /> <img src="{$module_dir}secure.png" alt="" style="margin-left: 5px;" /><br /><br />
<label style="margin-left: 186px;display: block;width: 85px;float: left;">{l s='CVV' mod='authorizeaim'}</label> <input type="text" name="x_card_code" size="4" maxlength="4" /><img src="{$module_dir}secure.png" alt="" style="margin-left: 5px;"/> <img src="{$module_dir}help.png" id="cvv_help" title="{l s='the 3 last digits on the back of your credit card' mod='authorizeaim'}" alt="" /><br /><br /> <label style="margin-top: 4px; margin-left: 40px;display: block;width: 90px;float: left;">{l s='CVV' mod='authorizeaim'}</label> <input type="text" name="x_card_code" id="x_card_code" size="4" maxlength="4" /><img src="{$module_dir}secure.png" alt="" style="margin-left: 5px;"/> <img src="{$module_dir}help.png" id="cvv_help" title="{l s='the 3 last digits on the back of your credit card' mod='authorizeaim'}" alt="" /><br /><br />
<img src="{$module_dir}cvv.png" id="cvv_help_img" alt=""style="display: none;margin-left: 211px;" /> <img src="{$module_dir}cvv.png" id="cvv_help_img" alt=""style="display: none;margin-left: 211px;" />
<input type="button" id="asubmit" value="{l s='Validate order' mod='authorizeaim'}" style="margin-left: 236px;" class="button"/> <input type="button" id="asubmit" value="{l s='Validate order' mod='authorizeaim'}" style="margin-left: 129px; padding-left: 25px; padding-right: 25px;" class="button" />
</div> </div>
</span> </span>
</form> </form>
</p> </p>
<script type="text/javascript"> <script type="text/javascript">
var mess_error = "{l s='Your card number is false' mod='authorizeaim' js=1}"; var mess_error = "{l s='Please check your credit card information (Credit card type, number and expiration date)' mod='authorizeaim' js=1}";
var mess_error2 = "{l s='Please specify your Full Name' mod='authorizeaim' js=1}";
{literal} {literal}
$(document).ready(function(){ $(document).ready(function(){
$('#x_exp_date_m').children('option').each(function() $('#x_exp_date_m').children('option').each(function()
@@ -107,8 +112,13 @@
$('#cvv_help').unbind(); $('#cvv_help').unbind();
}); });
$('#asubmit').click(function(){ $('#asubmit').click(function()
if ($('#ccn').val() < 13) {
if ($('#fullname').val() == '')
{
alert(mess_error2);
}
else if (!validateCC($('#cardnum').val(), $('#cardType').val()) || $('#x_card_code').val() == '')
{ {
alert(mess_error); alert(mess_error);
} }
@@ -118,5 +128,6 @@
} }
}); });
}); });
{/literal} {/literal}
</script> </script>
+73 -17
View File
@@ -49,7 +49,7 @@ if(empty($_POST['action']) OR !in_array($_POST['action'],array('upgradeDb')))
// Add Upgrader class : if > 1.4.5.0 , uses core class // Add Upgrader class : if > 1.4.5.0 , uses core class
// otherwise, use Upgrader.php in modules. // otherwise, use Upgrader.php in modules.
// in both cases, use override if files exists // in both cases, use override if files exists
if (!version_compare(_PS_VERSION_,'1.4.5.0','<') && file_exists(_PS_ROOT_DIR_.'/classes/Upgrader.php')) if (!version_compare(_PS_VERSION_,'1.4.6.0','<') && file_exists(_PS_ROOT_DIR_.'/classes/Upgrader.php'))
require_once(_PS_ROOT_DIR_.'/classes/Upgrader.php'); require_once(_PS_ROOT_DIR_.'/classes/Upgrader.php');
else else
require_once(dirname(__FILE__).'/Upgrader.php'); require_once(dirname(__FILE__).'/Upgrader.php');
@@ -118,6 +118,8 @@ class AdminSelfUpgrade extends AdminSelfTab
public $prodRootDir = ''; public $prodRootDir = '';
public $adminDir = ''; public $adminDir = '';
public $rootWritable = false; public $rootWritable = false;
public $lastAutoupgradeVersion = '';
public $svnDir = 'svn'; public $svnDir = 'svn';
public $destDownloadFilename = 'prestashop.zip'; public $destDownloadFilename = 'prestashop.zip';
public $toUpgradeFileList = 'filesToUpgrade.list'; public $toUpgradeFileList = 'filesToUpgrade.list';
@@ -156,7 +158,7 @@ class AdminSelfUpgrade extends AdminSelfTab
* value = the next step you want instead * value = the next step you want instead
* example : public static $skipAction = array('download' => 'upgradeFiles'); * example : public static $skipAction = array('download' => 'upgradeFiles');
*/ */
public static $skipAction; public static $skipAction = array();
public $useSvn; public $useSvn;
protected $_includeContainer = false; protected $_includeContainer = false;
@@ -276,14 +278,42 @@ class AdminSelfUpgrade extends AdminSelfTab
public function configOk() public function configOk()
{ {
$allowed = (ConfigurationTest::test_fopen() && $this->rootWritable); $allowed_array = $this->getCheckCurrentConfig();
$allowed &= !Configuration::get('PS_SHOP_ENABLE'); $allowed = array_product($allowed_array);
$allowed &= $this->upgrader->autoupgrade;
$allowed &= (Configuration::get('PS_AUTOUP_KEEP_TRAD') !== false);
return $allowed; return $allowed;
} }
public function getcheckCurrentConfig()
{
static $allowed_array;
if(empty($allowed_array))
{
$allowed_array = array();
$allowed_array['fopen'] = ConfigurationTest::test_fopen();
$allowed_array['root_writable'] = $this->rootWritable;
$allowed_array['shop_enabled'] = !Configuration::get('PS_SHOP_ENABLE');
$allowed_array['autoupgrade_allowed'] = $this->upgrader->autoupgrade;
$module_version = '0.1';
if ($module_version = simplexml_load_file(dirname(__FILE__).'/config.xml'))
$module_version = (string)$module_version->version;
$allowed_array['module_version_ok'] = version_compare($module_version, $this->upgrader->autoupgrade_last_version, '>=');
// if one option has been defined, all options are.
$allowed_array['module_configured'] = (Configuration::get('PS_AUTOUP_KEEP_TRAD') !== false);
}
return $allowed_array;
}
public function checkAutoupgradeLastVersion(){
if ($module_version = simplexml_load_file(_PS_MODULE_DIR_.'autoupgrade'.'/config.xml'))
$module_version = (string)$module_version['version'];
else
$module_version = '';
return version_compare($this->upgrader->autoupgrade_last_version, $module_version, '==');
}
/** /**
* isUpgradeAllowed checks if all server configuration is valid for upgrade * isUpgradeAllowed checks if all server configuration is valid for upgrade
* *
@@ -315,7 +345,7 @@ class AdminSelfUpgrade extends AdminSelfTab
$this->action = empty($_REQUEST['action'])?null:$_REQUEST['action']; $this->action = empty($_REQUEST['action'])?null:$_REQUEST['action'];
$this->currentParams = empty($_REQUEST['params'])?null:$_REQUEST['params']; $this->currentParams = empty($_REQUEST['params'])?null:$_REQUEST['params'];
// test writable recursively // test writable recursively
if(version_compare(_PS_VERSION_,'1.4.5.0','<')) if(version_compare(_PS_VERSION_,'1.4.6.0','<') || !class_exists('ConfigurationTest', false))
{ {
require_once('ConfigurationTest.php'); require_once('ConfigurationTest.php');
if(!class_exists('ConfigurationTest', false) AND class_exists('ConfigurationTestCore')) if(!class_exists('ConfigurationTest', false) AND class_exists('ConfigurationTestCore'))
@@ -324,8 +354,9 @@ class AdminSelfUpgrade extends AdminSelfTab
if (ConfigurationTest::test_dir($this->prodRootDir,true)) if (ConfigurationTest::test_dir($this->prodRootDir,true))
$this->rootWritable = true; $this->rootWritable = true;
if (!in_array($this->action,array('upgradeFile', 'upgradeDb', 'upgradeComplete','rollback','restoreFiles','restoreDb'))) if (!in_array($this->action, array('upgradeFile', 'upgradeDb', 'upgradeComplete','rollback','restoreFiles','restoreDb', 'checkFilesVersion')))
{ {
$this->upgrader = new Upgrader(); $this->upgrader = new Upgrader();
$this->upgrader->checkPSVersion(); $this->upgrader->checkPSVersion();
$this->nextParams['install_version'] = $this->upgrader->version_num; $this->nextParams['install_version'] = $this->upgrader->version_num;
@@ -464,8 +495,21 @@ class AdminSelfUpgrade extends AdminSelfTab
} }
public function ajaxProcessCheckFilesVersion() public function ajaxProcessCheckFilesVersion()
{ {
if ($this->upgrader->isAuthenticPrestashopVersion() !== false) $this->_loadDbRelatedClasses();
$this->upgrader = new Upgrader();
$changedFileList = $this->upgrader->getChangedFilesList();
if ($this->upgrader->isAuthenticPrestashopVersion() == true
&& !is_array($changedFileList) )
{ {
$this->nextParams['status'] = 'error';
$this->nextParams['msg'] = '[TECHNICAL ERROR] Unable to check files';
$testOrigCore = false;
}
else
{
if ($this->upgrader->isAuthenticPrestashopVersion() != false)
{
$this->nextParams['status'] = 'ok'; $this->nextParams['status'] = 'ok';
$testOrigCore = true; $testOrigCore = true;
} }
@@ -475,7 +519,6 @@ class AdminSelfUpgrade extends AdminSelfTab
$this->nextParams['status'] = 'warn'; $this->nextParams['status'] = 'warn';
} }
$changedFileList = $this->upgrader->getChangedFilesList();
if (!isset($changedFileList['core'])) if (!isset($changedFileList['core']))
$changedFileList['core'] = array(); $changedFileList['core'] = array();
if (!isset($changedFileList['translation'])) if (!isset($changedFileList['translation']))
@@ -495,6 +538,7 @@ class AdminSelfUpgrade extends AdminSelfTab
} }
$this->nextParams['result'] = $changedFileList; $this->nextParams['result'] = $changedFileList;
} }
}
public function ajaxProcessUpgradeNow() public function ajaxProcessUpgradeNow()
{ {
@@ -1461,8 +1505,7 @@ class AdminSelfUpgrade extends AdminSelfTab
*/ */
public function displayConf() public function displayConf()
{ {
if (version_compare(_PS_VERSION_,'1.4.5.0','<') AND false)
if (version_compare(_PS_VERSION_,'1.4.6.0','<') AND false)
$this->_errors[] = Tools::displayError('This class depends of several files modified in 1.4.5.0 version and should not be used in an older version'); $this->_errors[] = Tools::displayError('This class depends of several files modified in 1.4.5.0 version and should not be used in an older version');
parent::displayConf(); parent::displayConf();
} }
@@ -1470,7 +1513,7 @@ class AdminSelfUpgrade extends AdminSelfTab
public function ajaxPreProcess() public function ajaxPreProcess()
{ {
/* PrestaShop demo mode */ /* PrestaShop demo mode */
if (_PS_MODE_DEMO_) if (defined('_PS_MODE_DEMO_') && _PS_MODE_DEMO_)
return; return;
/* PrestaShop demo mode*/ /* PrestaShop demo mode*/
@@ -1597,6 +1640,19 @@ txtError[37] = "'.$this->l('The config/defines.inc.php file was not found. Where
<p>'.$this->l('All the following points must be ok in order to allow the upgrade.').'</p> <p>'.$this->l('All the following points must be ok in order to allow the upgrade.').'</p>
<b>'.$this->l('Root directory').' : </b>'.$this->prodRootDir.'<br/><br/>'; <b>'.$this->l('Root directory').' : </b>'.$this->prodRootDir.'<br/><br/>';
if ($this->checkAutoupgradeLastVersion())
$srcModuleVersion = '../img/admin/enabled.gif';
else
$srcModuleVersion = '../img/admin/disabled.gif';
if ($module_version = simplexml_load_file(dirname(__FILE__).'/config.xml'))
$module_version = (string)$module_version->version;
$content .= '<b>'.$this->l('Module version').' : </b>'
.'<img src="'.$srcModuleVersion.'" /> '
.sprintf($this->lastAutoupgradeVersion?
$this->l('You have the last version (%s)'):$this->l('You currently use the version %1$s of the autoupgrade module. Please install the last version (%2$s)'), $module_version, $this->upgrader->autoupgrade_last_version).'<br/><br/>';
if ($this->rootWritable) if ($this->rootWritable)
$srcRootWritable = '../img/admin/enabled.gif'; $srcRootWritable = '../img/admin/enabled.gif';
else else
@@ -1673,7 +1729,7 @@ txtError[37] = "'.$this->l('The config/defines.inc.php file was not found. Where
$content .= '<script type="text/javascript"> $content .= '<script type="text/javascript">
$("#currentConfigurationToggle").click(function(e){e.preventDefault();$("#currentConfiguration").toggle()});' $("#currentConfigurationToggle").click(function(e){e.preventDefault();$("#currentConfiguration").toggle()});'
.($this->configOk()?'$("#currentConfiguration").hide();$("#currentConfigurationToggle").after("<img src=\"../img/admin/enabled.gif\" />");':'').'</script>'; .($this->configOk()?'$("#currentConfiguration").hide();$("#currentConfigurationToggle").after("<img src=\"../img/admin/enabled.gif\" />");':'').'</script>';
$content .= '<div style="float:left"> $content .= '<div style="clear:left">&nbsp;</div><div style="float:left">
<h1>'.sprintf($this->l('Your current prestashop version : %s '),_PS_VERSION_).'</h1>'; <h1>'.sprintf($this->l('Your current prestashop version : %s '),_PS_VERSION_).'</h1>';
$content .= '<p>'.sprintf($this->l('Last version is %1$s (%2$s) '), $this->upgrader->version_name, $this->upgrader->version_num).'</p>'; $content .= '<p>'.sprintf($this->l('Last version is %1$s (%2$s) '), $this->upgrader->version_name, $this->upgrader->version_num).'</p>';
@@ -1773,14 +1829,13 @@ txtError[37] = "'.$this->l('The config/defines.inc.php file was not found. Where
public function display() public function display()
{ {
/* PrestaShop demo mode */ /* PrestaShop demo mode */
if (_PS_MODE_DEMO_) if (defined('_PS_MODE_DEMO_') && _PS_MODE_DEMO_)
{ {
echo '<div class="error">'.Tools::displayError('This functionnality has been disabled.').'</div>'; echo '<div class="error">'.Tools::displayError('This functionnality has been disabled.').'</div>';
return; return;
} }
/* PrestaShop demo mode*/ /* PrestaShop demo mode*/
if(isset($_GET['refreshCurrentVersion'])) if(isset($_GET['refreshCurrentVersion']))
{ {
$upgrader = new Upgrader(); $upgrader = new Upgrader();
@@ -2264,6 +2319,7 @@ function handleError(res)
, ,
error: function(res,textStatus,jqXHR) error: function(res,textStatus,jqXHR)
{ {
//$("#checkPrestaShopFilesVersion").html("<img src=\"../img/admin/warning.gif\" /> "+textStatus);
if (textStatus == "timeout" && action == "download") if (textStatus == "timeout" && action == "download")
{ {
updateInfoStep("'.$this->l('Your server can\'t download the file. Please upload it first by ftp in your admin/autoupgrade directory').'"); updateInfoStep("'.$this->l('Your server can\'t download the file. Please upload it first by ftp in your admin/autoupgrade directory').'");
+49 -17
View File
@@ -39,15 +39,26 @@ class UpgraderCore
public $version_name; public $version_name;
public $version_num; public $version_num;
public $version_is_modified = null;
/** /**
* @var string contains hte url where to download the file * @var string contains hte url where to download the file
*/ */
public $link; public $link;
public $autoupgrade; public $autoupgrade;
public $autoupgrade_module; public $autoupgrade_module;
public $autoupgrade_last_version;
public $changelog; public $changelog;
public $md5; public $md5;
public function __construct($autoload = false)
{
if ($autoload)
{
$this->loadFromConfig();
// checkPSVersion to get need_upgrade
$this->checkPSVersion();
}
}
public function __get($var) public function __get($var)
{ {
if ($var == 'need_upgrade') if ($var == 'need_upgrade')
@@ -90,8 +101,7 @@ class UpgraderCore
*/ */
public function checkPSVersion($force = false) public function checkPSVersion($force = false)
{ {
if (empty($this->link))
{
if (class_exists('Configuration')) if (class_exists('Configuration'))
$last_check = Configuration::get('PS_LAST_VERSION_CHECK'); $last_check = Configuration::get('PS_LAST_VERSION_CHECK');
else else
@@ -103,7 +113,6 @@ class UpgraderCore
libxml_set_streams_context(@stream_context_create(array('http' => array('timeout' => 3)))); libxml_set_streams_context(@stream_context_create(array('http' => array('timeout' => 3))));
if ($feed = @simplexml_load_file($this->rss_version_link)) if ($feed = @simplexml_load_file($this->rss_version_link))
{ {
$this->version_name = (string)$feed->version->name; $this->version_name = (string)$feed->version->name;
$this->version_num = (string)$feed->version->num; $this->version_num = (string)$feed->version->num;
$this->link = (string)$feed->download->link; $this->link = (string)$feed->download->link;
@@ -111,6 +120,7 @@ class UpgraderCore
$this->changelog = (string)$feed->download->changelog; $this->changelog = (string)$feed->download->changelog;
$this->autoupgrade = (int)$feed->autoupgrade; $this->autoupgrade = (int)$feed->autoupgrade;
$this->autoupgrade_module = (int)$feed->autoupgrade_module; $this->autoupgrade_module = (int)$feed->autoupgrade_module;
$this->autoupgrade_last_version = (string)$feed->autoupgrade_last_version;
$this->desc = (string)$feed->desc ; $this->desc = (string)$feed->desc ;
$config_last_version = array( $config_last_version = array(
'name' => $this->version_name, 'name' => $this->version_name,
@@ -119,6 +129,7 @@ class UpgraderCore
'md5' => $this->md5, 'md5' => $this->md5,
'autoupgrade' => $this->autoupgrade, 'autoupgrade' => $this->autoupgrade,
'autoupgrade_module' => $this->autoupgrade_module, 'autoupgrade_module' => $this->autoupgrade_module,
'autoupgrade_last_version' => $this->autoupgrade_last_version,
'changelog' => $this->changelog, 'changelog' => $this->changelog,
'desc' => $this->desc 'desc' => $this->desc
); );
@@ -130,8 +141,29 @@ class UpgraderCore
} }
} }
else else
$this->loadFromConfig();
// retro-compatibility :
// return array(name,link) if you don't use the last version
// false otherwise
if (version_compare(_PS_VERSION_, $this->version_num, '<'))
{ {
$this->need_upgrade = true;
return array('name' => $this->version_name, 'link' => $this->link);
}
else
return false;
}
/**
* load the last version informations stocked in base
*
* @return $this
*/
public function loadFromConfig()
{
$last_version_check = @unserialize(Configuration::get('PS_LAST_VERSION')); $last_version_check = @unserialize(Configuration::get('PS_LAST_VERSION'));
if($last_version_check)
{
if (isset($last_version_check['name'])) if (isset($last_version_check['name']))
$this->version_name = $last_version_check['name']; $this->version_name = $last_version_check['name'];
if (isset($last_version_check['num'])) if (isset($last_version_check['num']))
@@ -142,6 +174,8 @@ class UpgraderCore
$this->autoupgrade = $last_version_check['autoupgrade']; $this->autoupgrade = $last_version_check['autoupgrade'];
if (isset($last_version_check['autoupgrade_module'])) if (isset($last_version_check['autoupgrade_module']))
$this->autoupgrade_module = $last_version_check['autoupgrade_module']; $this->autoupgrade_module = $last_version_check['autoupgrade_module'];
if (isset($last_version_check['autoupgrade_last_version']))
$this->autoupgrade_last_version = $last_version_check['autoupgrade_last_version'];
if (isset($last_version_check['md5'])) if (isset($last_version_check['md5']))
$this->md5 = $last_version_check['md5']; $this->md5 = $last_version_check['md5'];
if (isset($last_version_check['desc'])) if (isset($last_version_check['desc']))
@@ -149,26 +183,23 @@ class UpgraderCore
if (isset($last_version_check['changelog'])) if (isset($last_version_check['changelog']))
$this->changelog = $last_version_check['changelog']; $this->changelog = $last_version_check['changelog'];
} }
return $this;
} }
// retro-compatibility :
// return array(name,link) if you don't use the last version
// false otherwise
if (version_compare(_PS_VERSION_, $this->version_num, '<'))
{
$this->need_upgrade = true;
return array('name' => $this->version_name, 'link' => $this->link);
}
else
return false;
}
/**
* return an array of files
* that the md5file does not match to the original md5file (provided by $rss_md5file_link_dir )
* @return void
*/
public function getChangedFilesList() public function getChangedFilesList()
{ {
if (count($this->changed_files) == 0) if (is_array($this->changed_files) && count($this->changed_files) == 0)
{ {
$checksum = @simplexml_load_file($this->rss_md5file_link_dir._PS_VERSION_.'.xml'); $checksum = @simplexml_load_file($this->rss_md5file_link_dir._PS_VERSION_.'.xml');
if ($checksum === false) if ($checksum == false)
return false; {
$this->changed_files = false;
}
else else
$this->browseXmlAndCompare($checksum->ps_root_dir[0]); $this->browseXmlAndCompare($checksum->ps_root_dir[0]);
} }
@@ -248,6 +279,7 @@ class UpgraderCore
public function isAuthenticPrestashopVersion() public function isAuthenticPrestashopVersion()
{ {
$this->getChangedFilesList(); $this->getChangedFilesList();
return !$this->version_is_modified; return !$this->version_is_modified;
} }
+16 -6
View File
@@ -31,7 +31,10 @@ class Autoupgrade extends Module
{ {
$this->name = 'autoupgrade'; $this->name = 'autoupgrade';
$this->tab = 'administration'; $this->tab = 'administration';
$this->version = 0.1; // version number x.y.z
// y+1 means a major bugfix or improvement
// z+1 means a bugfix
$this->version = '0.2.1';
if (!defined('_PS_ADMIN_DIR_')) if (!defined('_PS_ADMIN_DIR_'))
{ {
@@ -53,7 +56,6 @@ class Autoupgrade extends Module
public function install() public function install()
{ {
$res = true; $res = true;
// before adding AdminSelfUpgrade, we should remove AdminUpgrade // before adding AdminSelfUpgrade, we should remove AdminUpgrade
$idTab = Tab::getIdFromClassName('AdminUpgrade'); $idTab = Tab::getIdFromClassName('AdminUpgrade');
@@ -72,7 +74,9 @@ class Autoupgrade extends Module
$tab->class_name = 'AdminSelfUpgrade'; $tab->class_name = 'AdminSelfUpgrade';
$tab->module = 'autoupgrade'; $tab->module = 'autoupgrade';
$tab->id_parent = 9; $tab->id_parent = 9;
$tab->name = array_fill(1, sizeof(Language::getLanguages(false)), 'Upgrade'); $languages = Language::getLanguages(false);
foreach ($languages as $lang)
$tab->name[$lang['id_lang']] = 'Upgrade';
$res &= $tab->save(); $res &= $tab->save();
} }
else else
@@ -103,12 +107,18 @@ class Autoupgrade extends Module
public function uninstall() public function uninstall()
{ {
$idtab = Configuration::get('PS_AUTOUPDATE_MODULE_IDTAB'); $id_tab = Configuration::get('PS_AUTOUPDATE_MODULE_IDTAB');
$tab = new Tab($idtab,1); if ($id_tab)
{
$tab = new Tab($id_tab,1);
$res = $tab->delete(); $res = $tab->delete();
}
else
$res = true;
// for people in 1.4.4.0 or 1.4.4.1, we have to remove that file
// and of course delete it in the database.
if (file_exists(_PS_ADMIN_DIR_.DIRECTORY_SEPARATOR.'tabs'.'AdminUpgrade.php')) if (file_exists(_PS_ADMIN_DIR_.DIRECTORY_SEPARATOR.'tabs'.'AdminUpgrade.php'))
{ {
// Should we create the correct AdminUpgrade tab (not the module)
if($idOldTab = Tab::getIdFromClassName('AdminUpgrade')) if($idOldTab = Tab::getIdFromClassName('AdminUpgrade'))
{ {
$tab = new Tab($idOldTab); $tab = new Tab($idOldTab);
+1 -1
View File
@@ -2,7 +2,7 @@
<module> <module>
<name>autoupgrade</name> <name>autoupgrade</name>
<displayName><![CDATA[Autoupgrade module]]></displayName> <displayName><![CDATA[Autoupgrade module]]></displayName>
<version><![CDATA[0.1]]></version> <version><![CDATA[0.2.1]]></version>
<description><![CDATA[Provides an automated method to upgrade your shop to the last PrestaShop version. Caution : custom theme are not updated.]]></description> <description><![CDATA[Provides an automated method to upgrade your shop to the last PrestaShop version. Caution : custom theme are not updated.]]></description>
<author><![CDATA[]]></author> <author><![CDATA[]]></author>
<tab><![CDATA[administration]]></tab> <tab><![CDATA[administration]]></tab>
+2 -2
View File
@@ -21,7 +21,7 @@ $_MODULE['<{autoupgrade}prestashop>adminselfupgrade_8d8e0207549d32c6f86424640303
$_MODULE['<{autoupgrade}prestashop>adminselfupgrade_c62f82b25de72c3b0bb07225c49fe9d0'] = '%1$s fichier(s) du coeur a été modifié (sur %2$s au total)'; $_MODULE['<{autoupgrade}prestashop>adminselfupgrade_c62f82b25de72c3b0bb07225c49fe9d0'] = '%1$s fichier(s) du coeur a été modifié (sur %2$s au total)';
$_MODULE['<{autoupgrade}prestashop>adminselfupgrade_7b2f224649ef2ad10a2d73595d67a876'] = 'Démarrage mise à niveau ...'; $_MODULE['<{autoupgrade}prestashop>adminselfupgrade_7b2f224649ef2ad10a2d73595d67a876'] = 'Démarrage mise à niveau ...';
$_MODULE['<{autoupgrade}prestashop>adminselfupgrade_6b2d0404b7faba0e791e15a52586a149'] = 'Basculer vers svn checkout (useSvn activé)'; $_MODULE['<{autoupgrade}prestashop>adminselfupgrade_6b2d0404b7faba0e791e15a52586a149'] = 'Basculer vers svn checkout (useSvn activé)';
$_MODULE['<{autoupgrade}prestashop>adminselfupgrade_f0e38ac0c558a7f216ae98382b9e58f5'] = 'Site désactivé. Téléchargement en cours (peut prendre '; $_MODULE['<{autoupgrade}prestashop>adminselfupgrade_13b35313a987313838f0105902bb6742'] = 'Boutique désactivée. Téléchargement en cours... (ce qui peut prendre un certain temps) ...';
$_MODULE['<{autoupgrade}prestashop>adminselfupgrade_6824d57b7af37f605bd97d34defc3761'] = 'Exportation svn terminée. Suppression des fichiers exemples...'; $_MODULE['<{autoupgrade}prestashop>adminselfupgrade_6824d57b7af37f605bd97d34defc3761'] = 'Exportation svn terminée. Suppression des fichiers exemples...';
$_MODULE['<{autoupgrade}prestashop>adminselfupgrade_f70307d8297e48a8783d41e6f3313d51'] = 'Erreur lors de l\'export SVN'; $_MODULE['<{autoupgrade}prestashop>adminselfupgrade_f70307d8297e48a8783d41e6f3313d51'] = 'Erreur lors de l\'export SVN';
$_MODULE['<{autoupgrade}prestashop>adminselfupgrade_4eecd9c195e46c054ef7da6d9d1a738b'] = 'Extraction terminée. Suppression des fichiers exemples...'; $_MODULE['<{autoupgrade}prestashop>adminselfupgrade_4eecd9c195e46c054ef7da6d9d1a738b'] = 'Extraction terminée. Suppression des fichiers exemples...';
@@ -144,7 +144,7 @@ $_MODULE['<{autoupgrade}prestashop>adminselfupgrade_af566be1636d11ecc8ddb728a155
$_MODULE['<{autoupgrade}prestashop>adminselfupgrade_ea4d3af79ad2392b7c0cca4b8ddd7028'] = 'Vous avez déjà la dernière version disponible.'; $_MODULE['<{autoupgrade}prestashop>adminselfupgrade_ea4d3af79ad2392b7c0cca4b8ddd7028'] = 'Vous avez déjà la dernière version disponible.';
$_MODULE['<{autoupgrade}prestashop>adminselfupgrade_bafd7322c6e97d25b6299b5d6fe8920b'] = 'Non'; $_MODULE['<{autoupgrade}prestashop>adminselfupgrade_bafd7322c6e97d25b6299b5d6fe8920b'] = 'Non';
$_MODULE['<{autoupgrade}prestashop>adminselfupgrade_93cba07454f06a4a960172bbd6e2a435'] = 'Oui'; $_MODULE['<{autoupgrade}prestashop>adminselfupgrade_93cba07454f06a4a960172bbd6e2a435'] = 'Oui';
$_MODULE['<{autoupgrade}prestashop>adminselfupgrade_3d9f7f5927158b5a7dac0d65b4537265'] = 'Boutique désactivée'; $_MODULE['<{autoupgrade}prestashop>adminselfupgrade_69af703e1b0af65d0eb16b85e3ebd738'] = 'Boutique désactivée';
$_MODULE['<{autoupgrade}prestashop>adminselfupgrade_94af5df6182efd3591d0ccccaa04bd5c'] = 'Limite de temps PHP'; $_MODULE['<{autoupgrade}prestashop>adminselfupgrade_94af5df6182efd3591d0ccccaa04bd5c'] = 'Limite de temps PHP';
$_MODULE['<{autoupgrade}prestashop>adminselfupgrade_075ae3d2fc31640504f814f60e5ef713'] = 'désactivée'; $_MODULE['<{autoupgrade}prestashop>adminselfupgrade_075ae3d2fc31640504f814f60e5ef713'] = 'désactivée';
$_MODULE['<{autoupgrade}prestashop>adminselfupgrade_783e8e29e6a8c3e22baa58a19420eb4f'] = 'secondes'; $_MODULE['<{autoupgrade}prestashop>adminselfupgrade_783e8e29e6a8c3e22baa58a19420eb4f'] = 'secondes';
+3 -2
View File
@@ -274,7 +274,8 @@ return;
var removedProductData = null; var removedProductData = null;
var removedProductDomId = null; var removedProductDomId = null;
//look for a product to delete... //look for a product to delete...
$('#'+parentId+' #cart_block_list dl.products dt').each(function(){ $('#'+parentId+' #cart_block_list dl.products dt').each(function()
{
//retrieve idProduct and idCombination from the displayed product in the block cart //retrieve idProduct and idCombination from the displayed product in the block cart
var domIdProduct = $(this).attr('id'); var domIdProduct = $(this).attr('id');
var firstCut = domIdProduct.replace('cart_block_product_', ''); var firstCut = domIdProduct.replace('cart_block_product_', '');
@@ -299,7 +300,6 @@ return;
removedProductId = $(this).attr('id'); removedProductId = $(this).attr('id');
//return false; // Regarding that the customer can only remove products one by one, we break the loop //return false; // Regarding that the customer can only remove products one by one, we break the loop
} }
});
//if there is a removed product, delete it from the displayed block cart //if there is a removed product, delete it from the displayed block cart
if (removedProductId != null) if (removedProductId != null)
@@ -324,6 +324,7 @@ return;
}); });
}); });
} }
});
} }
}); });
}, },
@@ -24,5 +24,5 @@
* International Registred Trademark & Property of PrestaShop SA * International Registred Trademark & Property of PrestaShop SA
*} *}
<div id="product_list" class="clear"> <div id="product_list" class="clear">
<p class="warning">{l s='There are no products.'}</p> <p class="warning">{l s='There are no products.' mod='blocklayered'}</p>
</div> </div>
+138 -149
View File
@@ -20,7 +20,7 @@
* *
* @author PrestaShop SA <contact@prestashop.com> * @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2011 PrestaShop SA * @copyright 2007-2011 PrestaShop SA
* @version Release: $Revision: 9630 $ * @version Release: $Revision$
* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0) * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
* International Registred Trademark & Property of PrestaShop SA * International Registred Trademark & Property of PrestaShop SA
*/ */
@@ -91,23 +91,23 @@ class BlockLayered extends Module
Configuration::deleteByName('PS_LAYERED_SHOW_QTIES'); Configuration::deleteByName('PS_LAYERED_SHOW_QTIES');
Configuration::deleteByName('PS_LAYERED_INDEXED'); Configuration::deleteByName('PS_LAYERED_INDEXED');
Db::getInstance()->execute('DROP TABLE IF EXISTS '._DB_PREFIX_.'layered_price_index'); Db::getInstance()->Execute('DROP TABLE IF EXISTS '._DB_PREFIX_.'layered_price_index');
Db::getInstance()->execute('DROP TABLE IF EXISTS '._DB_PREFIX_.'layered_friendly_url'); Db::getInstance()->Execute('DROP TABLE IF EXISTS '._DB_PREFIX_.'layered_friendly_url');
Db::getInstance()->execute('DROP TABLE IF EXISTS '._DB_PREFIX_.'layered_indexable_attribute_group'); Db::getInstance()->Execute('DROP TABLE IF EXISTS '._DB_PREFIX_.'layered_indexable_attribute_group');
Db::getInstance()->execute('DROP TABLE IF EXISTS '._DB_PREFIX_.'layered_indexable_feature'); Db::getInstance()->Execute('DROP TABLE IF EXISTS '._DB_PREFIX_.'layered_indexable_feature');
Db::getInstance()->execute('DROP TABLE IF EXISTS '._DB_PREFIX_.'layered_indexable_attribute_group_lang_value'); Db::getInstance()->Execute('DROP TABLE IF EXISTS '._DB_PREFIX_.'layered_indexable_attribute_group_lang_value');
Db::getInstance()->execute('DROP TABLE IF EXISTS '._DB_PREFIX_.'layered_indexable_feature_lang_value'); Db::getInstance()->Execute('DROP TABLE IF EXISTS '._DB_PREFIX_.'layered_indexable_feature_lang_value');
Db::getInstance()->execute('DROP TABLE IF EXISTS '._DB_PREFIX_.'layered_category'); Db::getInstance()->Execute('DROP TABLE IF EXISTS '._DB_PREFIX_.'layered_category');
Db::getInstance()->execute('DROP TABLE IF EXISTS '._DB_PREFIX_.'layered_filter'); Db::getInstance()->Execute('DROP TABLE IF EXISTS '._DB_PREFIX_.'layered_filter');
Db::getInstance()->execute('DROP TABLE IF EXISTS '._DB_PREFIX_.'layered_product_attribute'); Db::getInstance()->Execute('DROP TABLE IF EXISTS '._DB_PREFIX_.'layered_product_attribute');
return parent::uninstall(); return parent::uninstall();
} }
private static function installPriceIndexTable() private static function installPriceIndexTable()
{ {
Db::getInstance()->execute('DROP TABLE IF EXISTS `'._DB_PREFIX_.'layered_price_index`'); Db::getInstance()->Execute('DROP TABLE IF EXISTS `'._DB_PREFIX_.'layered_price_index`');
Db::getInstance()->execute(' Db::getInstance()->Execute('
CREATE TABLE `'._DB_PREFIX_.'layered_price_index` ( CREATE TABLE `'._DB_PREFIX_.'layered_price_index` (
`id_product` INT NOT NULL, `id_currency` INT NOT NULL, `id_product` INT NOT NULL, `id_currency` INT NOT NULL,
`price_min` INT NOT NULL, `price_max` INT NOT NULL, `price_min` INT NOT NULL, `price_max` INT NOT NULL,
@@ -117,8 +117,8 @@ class BlockLayered extends Module
private function installFriendlyUrlTable() private function installFriendlyUrlTable()
{ {
Db::getInstance()->execute('DROP TABLE IF EXISTS `'._DB_PREFIX_.'layered_friendly_url`'); Db::getInstance()->Execute('DROP TABLE IF EXISTS `'._DB_PREFIX_.'layered_friendly_url`');
Db::getInstance()->execute(' Db::getInstance()->Execute('
CREATE TABLE `'._DB_PREFIX_.'layered_friendly_url` ( CREATE TABLE `'._DB_PREFIX_.'layered_friendly_url` (
`id_layered_friendly_url` INT NOT NULL AUTO_INCREMENT, `id_layered_friendly_url` INT NOT NULL AUTO_INCREMENT,
`url_key` varchar(32) NOT NULL, `url_key` varchar(32) NOT NULL,
@@ -127,24 +127,24 @@ class BlockLayered extends Module
PRIMARY KEY (`id_layered_friendly_url`), PRIMARY KEY (`id_layered_friendly_url`),
INDEX `id_lang` (`id_lang`)) ENGINE = '._MYSQL_ENGINE_); INDEX `id_lang` (`id_lang`)) ENGINE = '._MYSQL_ENGINE_);
Db::getInstance()->execute('CREATE INDEX `url_key` ON `'._DB_PREFIX_.'layered_friendly_url`(url_key(5))'); Db::getInstance()->Execute('CREATE INDEX `url_key` ON `'._DB_PREFIX_.'layered_friendly_url`(url_key(5))');
} }
private function installIndexableAttributeTable() private function installIndexableAttributeTable()
{ {
// Attributes Groups // Attributes Groups
Db::getInstance()->execute('DROP TABLE IF EXISTS `'._DB_PREFIX_.'layered_indexable_attribute_group`'); Db::getInstance()->Execute('DROP TABLE IF EXISTS `'._DB_PREFIX_.'layered_indexable_attribute_group`');
Db::getInstance()->execute(' Db::getInstance()->Execute('
CREATE TABLE `'._DB_PREFIX_.'layered_indexable_attribute_group` ( CREATE TABLE `'._DB_PREFIX_.'layered_indexable_attribute_group` (
`id_attribute_group` INT NOT NULL, `id_attribute_group` INT NOT NULL,
`indexable` BOOL NOT NULL DEFAULT 0, `indexable` BOOL NOT NULL DEFAULT 0,
PRIMARY KEY (`id_attribute_group`)) ENGINE = '._MYSQL_ENGINE_); PRIMARY KEY (`id_attribute_group`)) ENGINE = '._MYSQL_ENGINE_);
Db::getInstance()->execute(' Db::getInstance()->Execute('
INSERT INTO `'._DB_PREFIX_.'layered_indexable_attribute_group` INSERT INTO `'._DB_PREFIX_.'layered_indexable_attribute_group`
SELECT id_attribute_group, 1 FROM `'._DB_PREFIX_.'attribute_group`'); SELECT id_attribute_group, 1 FROM `'._DB_PREFIX_.'attribute_group`');
Db::getInstance()->execute('DROP TABLE IF EXISTS `'._DB_PREFIX_.'layered_indexable_attribute_group_lang_value`'); Db::getInstance()->Execute('DROP TABLE IF EXISTS `'._DB_PREFIX_.'layered_indexable_attribute_group_lang_value`');
Db::getInstance()->execute(' Db::getInstance()->Execute('
CREATE TABLE `'._DB_PREFIX_.'layered_indexable_attribute_group_lang_value` ( CREATE TABLE `'._DB_PREFIX_.'layered_indexable_attribute_group_lang_value` (
`id_attribute_group` INT NOT NULL, `id_attribute_group` INT NOT NULL,
`id_lang` INT NOT NULL, `id_lang` INT NOT NULL,
@@ -153,8 +153,8 @@ class BlockLayered extends Module
PRIMARY KEY (`id_attribute_group`, `id_lang`)) ENGINE = '._MYSQL_ENGINE_); PRIMARY KEY (`id_attribute_group`, `id_lang`)) ENGINE = '._MYSQL_ENGINE_);
// Attributes // Attributes
Db::getInstance()->execute('DROP TABLE IF EXISTS `'._DB_PREFIX_.'layered_indexable_attribute_lang_value`'); Db::getInstance()->Execute('DROP TABLE IF EXISTS `'._DB_PREFIX_.'layered_indexable_attribute_lang_value`');
Db::getInstance()->execute(' Db::getInstance()->Execute('
CREATE TABLE `'._DB_PREFIX_.'layered_indexable_attribute_lang_value` ( CREATE TABLE `'._DB_PREFIX_.'layered_indexable_attribute_lang_value` (
`id_attribute` INT NOT NULL, `id_attribute` INT NOT NULL,
`id_lang` INT NOT NULL, `id_lang` INT NOT NULL,
@@ -164,19 +164,19 @@ class BlockLayered extends Module
// Features // Features
Db::getInstance()->execute('DROP TABLE IF EXISTS `'._DB_PREFIX_.'layered_indexable_feature`'); Db::getInstance()->Execute('DROP TABLE IF EXISTS `'._DB_PREFIX_.'layered_indexable_feature`');
Db::getInstance()->execute(' Db::getInstance()->Execute('
CREATE TABLE `'._DB_PREFIX_.'layered_indexable_feature` ( CREATE TABLE `'._DB_PREFIX_.'layered_indexable_feature` (
`id_feature` INT NOT NULL, `id_feature` INT NOT NULL,
`indexable` BOOL NOT NULL DEFAULT 0, `indexable` BOOL NOT NULL DEFAULT 0,
PRIMARY KEY (`id_feature`)) ENGINE = '._MYSQL_ENGINE_); PRIMARY KEY (`id_feature`)) ENGINE = '._MYSQL_ENGINE_);
Db::getInstance()->execute(' Db::getInstance()->Execute('
INSERT INTO `'._DB_PREFIX_.'layered_indexable_feature` INSERT INTO `'._DB_PREFIX_.'layered_indexable_feature`
SELECT id_feature, 1 FROM `'._DB_PREFIX_.'feature`'); SELECT id_feature, 1 FROM `'._DB_PREFIX_.'feature`');
Db::getInstance()->execute('DROP TABLE IF EXISTS `'._DB_PREFIX_.'layered_indexable_feature_lang_value`'); Db::getInstance()->Execute('DROP TABLE IF EXISTS `'._DB_PREFIX_.'layered_indexable_feature_lang_value`');
Db::getInstance()->execute(' Db::getInstance()->Execute('
CREATE TABLE `'._DB_PREFIX_.'layered_indexable_feature_lang_value` ( CREATE TABLE `'._DB_PREFIX_.'layered_indexable_feature_lang_value` (
`id_feature` INT NOT NULL, `id_feature` INT NOT NULL,
`id_lang` INT NOT NULL, `id_lang` INT NOT NULL,
@@ -185,8 +185,8 @@ class BlockLayered extends Module
PRIMARY KEY (`id_feature`, `id_lang`)) ENGINE = '._MYSQL_ENGINE_); PRIMARY KEY (`id_feature`, `id_lang`)) ENGINE = '._MYSQL_ENGINE_);
// Features values // Features values
Db::getInstance()->execute('DROP TABLE IF EXISTS `'._DB_PREFIX_.'layered_indexable_feature_value_lang_value`'); Db::getInstance()->Execute('DROP TABLE IF EXISTS `'._DB_PREFIX_.'layered_indexable_feature_value_lang_value`');
Db::getInstance()->execute(' Db::getInstance()->Execute('
CREATE TABLE `'._DB_PREFIX_.'layered_indexable_feature_value_lang_value` ( CREATE TABLE `'._DB_PREFIX_.'layered_indexable_feature_value_lang_value` (
`id_feature_value` INT NOT NULL, `id_feature_value` INT NOT NULL,
`id_lang` INT NOT NULL, `id_lang` INT NOT NULL,
@@ -201,8 +201,8 @@ class BlockLayered extends Module
*/ */
public function installProductAttributeTable() public function installProductAttributeTable()
{ {
Db::getInstance()->execute('DROP TABLE IF EXISTS `'._DB_PREFIX_.'layered_product_attribute`'); Db::getInstance()->Execute('DROP TABLE IF EXISTS `'._DB_PREFIX_.'layered_product_attribute`');
Db::getInstance()->execute(' Db::getInstance()->Execute('
CREATE TABLE `'._DB_PREFIX_.'layered_product_attribute` ( CREATE TABLE `'._DB_PREFIX_.'layered_product_attribute` (
`id_attribute` int(10) unsigned NOT NULL, `id_attribute` int(10) unsigned NOT NULL,
`id_product` int(10) unsigned NOT NULL, `id_product` int(10) unsigned NOT NULL,
@@ -222,7 +222,7 @@ class BlockLayered extends Module
else else
Db::getInstance()->execute('DELETE FROM '._DB_PREFIX_.'layered_product_attribute WHERE id_product = '.(int)$id_product); Db::getInstance()->execute('DELETE FROM '._DB_PREFIX_.'layered_product_attribute WHERE id_product = '.(int)$id_product);
Db::getInstance()->execute('INSERT INTO `'._DB_PREFIX_.'layered_product_attribute` (`id_attribute`, `id_product`, `id_attribute_group`) Db::getInstance()->Execute('INSERT INTO `'._DB_PREFIX_.'layered_product_attribute` (`id_attribute`, `id_product`, `id_attribute_group`)
SELECT pac.id_attribute, pa.id_product, ag.id_attribute_group SELECT pac.id_attribute, pa.id_product, ag.id_attribute_group
FROM '._DB_PREFIX_.'product_attribute pa FROM '._DB_PREFIX_.'product_attribute pa
INNER JOIN '._DB_PREFIX_.'product_attribute_combination pac ON pac.id_product_attribute = pa.id_product_attribute INNER JOIN '._DB_PREFIX_.'product_attribute_combination pac ON pac.id_product_attribute = pa.id_product_attribute
@@ -242,7 +242,7 @@ class BlockLayered extends Module
Db::getInstance()->execute('TRUNCATE '._DB_PREFIX_.'layered_friendly_url'); Db::getInstance()->execute('TRUNCATE '._DB_PREFIX_.'layered_friendly_url');
$attributeValuesByLang = array(); $attributeValuesByLang = array();
$filters = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('SELECT lc.*, id_lang, name, link_rewrite, cl.id_category $filters = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('SELECT lc.*, id_lang, name, link_rewrite, cl.id_category
FROM '._DB_PREFIX_.'layered_category lc FROM '._DB_PREFIX_.'layered_category lc
INNER JOIN '._DB_PREFIX_.'category_lang cl ON (cl.id_category = lc.id_category AND lc.id_category <> 1 ) INNER JOIN '._DB_PREFIX_.'category_lang cl ON (cl.id_category = lc.id_category AND lc.id_category <> 1 )
GROUP BY type, id_value, id_lang'); GROUP BY type, id_value, id_lang');
@@ -253,7 +253,7 @@ class BlockLayered extends Module
switch ($filter['type']) switch ($filter['type'])
{ {
case 'id_attribute_group': case 'id_attribute_group':
$attributes = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(' $attributes = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT agl.public_name name, a.id_attribute_group id_name, al.name value, a.id_attribute id_value, al.id_lang, SELECT agl.public_name name, a.id_attribute_group id_name, al.name value, a.id_attribute id_value, al.id_lang,
liagl.url_name name_url_name, lial.url_name value_url_name liagl.url_name name_url_name, lial.url_name value_url_name
FROM '._DB_PREFIX_.'attribute_group ag FROM '._DB_PREFIX_.'attribute_group ag
@@ -284,7 +284,7 @@ class BlockLayered extends Module
break; break;
case 'id_feature': case 'id_feature':
$features = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(' $features = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT fl.name name, fl.id_feature id_name, fvl.id_feature_value id_value, fvl.value value, fl.id_lang, fl.id_lang, SELECT fl.name name, fl.id_feature id_name, fvl.id_feature_value id_value, fvl.value value, fl.id_lang, fl.id_lang,
lifl.url_name name_url_name, lifvl.url_name value_url_name lifl.url_name name_url_name, lifvl.url_name value_url_name
FROM '._DB_PREFIX_.'feature_lang fl FROM '._DB_PREFIX_.'feature_lang fl
@@ -314,7 +314,7 @@ class BlockLayered extends Module
break; break;
case 'category': case 'category':
$categories = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(' $categories = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT cl.name, cl.id_lang, c.id_category SELECT cl.name, cl.id_lang, c.id_category
FROM '._DB_PREFIX_.'category c FROM '._DB_PREFIX_.'category c
INNER JOIN '._DB_PREFIX_.'category_lang cl ON (c.id_category = cl.id_category) INNER JOIN '._DB_PREFIX_.'category_lang cl ON (c.id_category = cl.id_category)
@@ -332,7 +332,7 @@ class BlockLayered extends Module
break; break;
case 'manufacturer': case 'manufacturer':
$manufacturers = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(' $manufacturers = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT m.name as name,l.id_lang as id_lang, id_manufacturer SELECT m.name as name,l.id_lang as id_lang, id_manufacturer
FROM '._DB_PREFIX_.'manufacturer m , '._DB_PREFIX_.'lang l FROM '._DB_PREFIX_.'manufacturer m , '._DB_PREFIX_.'lang l
WHERE l.id_lang = '.(int)$filter['id_lang'].' '); WHERE l.id_lang = '.(int)$filter['id_lang'].' ');
@@ -378,23 +378,23 @@ class BlockLayered extends Module
{ {
// Foreach attributes generate a couple "/<attribute_name>_<atttribute_value>". For example: color_blue // Foreach attributes generate a couple "/<attribute_name>_<atttribute_value>". For example: color_blue
foreach ($attributeValues as $attribute) foreach ($attributeValues as $attribute)
foreach ($attribute as $param) foreach ($attribute as $param)
{
$selectedFilters = array();
$link = '/'.str_replace('-', '_', Tools::link_rewrite($param['name'])).'-'.str_replace('-', '_', Tools::link_rewrite($param['value']));
$selectedFilters[$param['type']] = array();
if (!isset($param['id_id_value']))
$param['id_id_value'] = $param['id_value'];
$selectedFilters[$param['type']][$param['id_id_value']] = $param['id_value'];
$urlKey = md5($link);
$idLayeredFriendlyUrl = Db::getInstance()->getValue('SELECT id_layered_friendly_url
FROM `'._DB_PREFIX_.'layered_friendly_url` WHERE `id_lang` = '.$id_lang.' AND `url_key` = \''.$urlKey.'\'');
if ($idLayeredFriendlyUrl == false)
{ {
Db::getInstance()->AutoExecute(_DB_PREFIX_.'layered_friendly_url', array('url_key' => $urlKey, 'data' => serialize($selectedFilters), 'id_lang' => $id_lang), 'INSERT'); $selectedFilters = array();
$idLayeredFriendlyUrl = Db::getInstance()->Insert_ID(); $link = '/'.str_replace('-', '_', Tools::link_rewrite($param['name'])).'-'.str_replace('-', '_', Tools::link_rewrite($param['value']));
$selectedFilters[$param['type']] = array();
if (!isset($param['id_id_value']))
$param['id_id_value'] = $param['id_value'];
$selectedFilters[$param['type']][$param['id_id_value']] = $param['id_value'];
$urlKey = md5($link);
$idLayeredFriendlyUrl = Db::getInstance()->getValue('SELECT id_layered_friendly_url
FROM `'._DB_PREFIX_.'layered_friendly_url` WHERE `id_lang` = '.$id_lang.' AND `url_key` = \''.$urlKey.'\'');
if ($idLayeredFriendlyUrl == false)
{
Db::getInstance()->AutoExecute(_DB_PREFIX_.'layered_friendly_url', array('url_key' => $urlKey, 'data' => serialize($selectedFilters), 'id_lang' => $id_lang), 'INSERT');
$idLayeredFriendlyUrl = Db::getInstance()->Insert_ID();
}
} }
}
} }
if ($ajax) if ($ajax)
return '{"result": 1}'; return '{"result": 1}';
@@ -474,15 +474,15 @@ class BlockLayered extends Module
if (!$params['id_feature'] || Tools::getValue('layered_indexable') === false) if (!$params['id_feature'] || Tools::getValue('layered_indexable') === false)
return; return;
Db::getInstance()->execute('DELETE FROM '._DB_PREFIX_.'layered_indexable_feature WHERE id_feature = '.(int)$params['id_feature']); Db::getInstance()->Execute('DELETE FROM '._DB_PREFIX_.'layered_indexable_feature WHERE id_feature = '.(int)$params['id_feature']);
Db::getInstance()->execute('INSERT INTO '._DB_PREFIX_.'layered_indexable_feature VALUES ('.(int)$params['id_feature'].', '.(int)Tools::getValue('layered_indexable').')'); Db::getInstance()->Execute('INSERT INTO '._DB_PREFIX_.'layered_indexable_feature VALUES ('.(int)$params['id_feature'].', '.(int)Tools::getValue('layered_indexable').')');
Db::getInstance()->execute('DELETE FROM '._DB_PREFIX_.'layered_indexable_feature_lang_value WHERE id_feature = '.(int)$params['id_feature']); // don't care about the id_lang Db::getInstance()->Execute('DELETE FROM '._DB_PREFIX_.'layered_indexable_feature_lang_value WHERE id_feature = '.(int)$params['id_feature']); // don't care about the id_lang
foreach (Language::getLanguages(false) as $language) foreach (Language::getLanguages(false) as $language)
{ {
// Data are validated by method "hookPostProcessFeature" // Data are validated by method "hookPostProcessFeature"
$id_lang = (int)$language['id_lang']; $id_lang = (int)$language['id_lang'];
Db::getInstance()->execute('INSERT INTO '._DB_PREFIX_.'layered_indexable_feature_lang_value Db::getInstance()->Execute('INSERT INTO '._DB_PREFIX_.'layered_indexable_feature_lang_value
VALUES ('.(int)$params['id_feature'].', '.$id_lang.', \''.pSQL(Tools::link_rewrite(Tools::getValue('url_name_'.$id_lang))).'\', VALUES ('.(int)$params['id_feature'].', '.$id_lang.', \''.pSQL(Tools::link_rewrite(Tools::getValue('url_name_'.$id_lang))).'\',
\''.pSQL(Tools::safeOutput(Tools::getValue('meta_title_'.$id_lang), true)).'\')'); \''.pSQL(Tools::safeOutput(Tools::getValue('meta_title_'.$id_lang), true)).'\')');
} }
@@ -493,12 +493,12 @@ class BlockLayered extends Module
if (!$params['id_feature_value']) if (!$params['id_feature_value'])
return; return;
Db::getInstance()->execute('DELETE FROM '._DB_PREFIX_.'layered_indexable_feature_value_lang_value WHERE id_feature_value = '.(int)$params['id_feature_value']); // don't care about the id_lang Db::getInstance()->Execute('DELETE FROM '._DB_PREFIX_.'layered_indexable_feature_value_lang_value WHERE id_feature_value = '.(int)$params['id_feature_value']); // don't care about the id_lang
foreach (Language::getLanguages(false) as $language) foreach (Language::getLanguages(false) as $language)
{ {
// Data are validated by method "hookPostProcessFeatureValue" // Data are validated by method "hookPostProcessFeatureValue"
$id_lang = (int)$language['id_lang']; $id_lang = (int)$language['id_lang'];
Db::getInstance()->execute('INSERT INTO '._DB_PREFIX_.'layered_indexable_feature_value_lang_value Db::getInstance()->Execute('INSERT INTO '._DB_PREFIX_.'layered_indexable_feature_value_lang_value
VALUES ('.(int)$params['id_feature_value'].', '.$id_lang.', \''.pSQL(Tools::link_rewrite(Tools::getValue('url_name_'.$id_lang))).'\', VALUES ('.(int)$params['id_feature_value'].', '.$id_lang.', \''.pSQL(Tools::link_rewrite(Tools::getValue('url_name_'.$id_lang))).'\',
\''.pSQL(Tools::safeOutput(Tools::getValue('meta_title_'.$id_lang), true)).'\')'); \''.pSQL(Tools::safeOutput(Tools::getValue('meta_title_'.$id_lang), true)).'\')');
} }
@@ -508,7 +508,7 @@ class BlockLayered extends Module
{ {
if (!$params['id_feature_value']) if (!$params['id_feature_value'])
return; return;
Db::getInstance()->execute('DELETE FROM '._DB_PREFIX_.'layered_indexable_feature_value_lang_value WHERE id_feature_value = '.(int)$params['id_feature_value']); Db::getInstance()->Execute('DELETE FROM '._DB_PREFIX_.'layered_indexable_feature_value_lang_value WHERE id_feature_value = '.(int)$params['id_feature_value']);
} }
public function hookPostProcessFeatureValue($params) public function hookPostProcessFeatureValue($params)
@@ -522,7 +522,7 @@ class BlockLayered extends Module
$default_form_language = (int)(Configuration::get('PS_LANG_DEFAULT')); $default_form_language = (int)(Configuration::get('PS_LANG_DEFAULT'));
$langValue = array(); $langValue = array();
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS( $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS(
'SELECT url_name, meta_title, id_lang FROM '._DB_PREFIX_.'layered_indexable_feature_value_lang_value 'SELECT url_name, meta_title, id_lang FROM '._DB_PREFIX_.'layered_indexable_feature_value_lang_value
WHERE id_feature_value = '.(int)$params['id_feature_value']); WHERE id_feature_value = '.(int)$params['id_feature_value']);
if ($result) if ($result)
@@ -565,12 +565,12 @@ class BlockLayered extends Module
if (!$params['id_attribute']) if (!$params['id_attribute'])
return; return;
Db::getInstance()->execute('DELETE FROM '._DB_PREFIX_.'layered_indexable_attribute_lang_value WHERE id_attribute = '.(int)$params['id_attribute']); // don't care about the id_lang Db::getInstance()->Execute('DELETE FROM '._DB_PREFIX_.'layered_indexable_attribute_lang_value WHERE id_attribute = '.(int)$params['id_attribute']); // don't care about the id_lang
foreach (Language::getLanguages(false) as $language) foreach (Language::getLanguages(false) as $language)
{ {
// Data are validated by method "hookPostProcessAttribute" // Data are validated by method "hookPostProcessAttribute"
$id_lang = (int)$language['id_lang']; $id_lang = (int)$language['id_lang'];
Db::getInstance()->execute('INSERT INTO '._DB_PREFIX_.'layered_indexable_attribute_lang_value Db::getInstance()->Execute('INSERT INTO '._DB_PREFIX_.'layered_indexable_attribute_lang_value
VALUES ('.(int)$params['id_attribute'].', '.$id_lang.', \''.pSQL(Tools::link_rewrite(Tools::getValue('url_name_'.$id_lang))).'\', VALUES ('.(int)$params['id_attribute'].', '.$id_lang.', \''.pSQL(Tools::link_rewrite(Tools::getValue('url_name_'.$id_lang))).'\',
\''.pSQL(Tools::safeOutput(Tools::getValue('meta_title_'.$id_lang), true)).'\')'); \''.pSQL(Tools::safeOutput(Tools::getValue('meta_title_'.$id_lang), true)).'\')');
} }
@@ -580,7 +580,7 @@ class BlockLayered extends Module
{ {
if (!$params['id_attribute']) if (!$params['id_attribute'])
return; return;
Db::getInstance()->execute('DELETE FROM '._DB_PREFIX_.'layered_indexable_attribute_lang_value WHERE id_attribute = '.(int)$params['id_attribute']); Db::getInstance()->Execute('DELETE FROM '._DB_PREFIX_.'layered_indexable_attribute_lang_value WHERE id_attribute = '.(int)$params['id_attribute']);
} }
public function hookPostProcessAttribute($params) public function hookPostProcessAttribute($params)
@@ -594,7 +594,7 @@ class BlockLayered extends Module
$default_form_language = (int)(Configuration::get('PS_LANG_DEFAULT')); $default_form_language = (int)(Configuration::get('PS_LANG_DEFAULT'));
$langValue = array(); $langValue = array();
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS( $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS(
'SELECT url_name, meta_title, id_lang FROM '._DB_PREFIX_.'layered_indexable_attribute_lang_value 'SELECT url_name, meta_title, id_lang FROM '._DB_PREFIX_.'layered_indexable_attribute_lang_value
WHERE id_attribute = '.(int)$params['id_attribute']); WHERE id_attribute = '.(int)$params['id_attribute']);
if ($result) if ($result)
@@ -641,7 +641,7 @@ class BlockLayered extends Module
{ {
if (!$params['id_feature']) if (!$params['id_feature'])
return; return;
Db::getInstance()->execute('DELETE FROM '._DB_PREFIX_.'layered_indexable_feature WHERE id_feature = '.(int)$params['id_feature']); Db::getInstance()->Execute('DELETE FROM '._DB_PREFIX_.'layered_indexable_feature WHERE id_feature = '.(int)$params['id_feature']);
} }
public function hookAfterSaveAttributeGroup($params) public function hookAfterSaveAttributeGroup($params)
@@ -649,15 +649,15 @@ class BlockLayered extends Module
if (!$params['id_attribute_group'] || Tools::getValue('layered_indexable') === false) if (!$params['id_attribute_group'] || Tools::getValue('layered_indexable') === false)
return; return;
Db::getInstance()->execute('DELETE FROM '._DB_PREFIX_.'layered_indexable_attribute_group WHERE id_attribute_group = '.(int)$params['id_attribute_group']); Db::getInstance()->Execute('DELETE FROM '._DB_PREFIX_.'layered_indexable_attribute_group WHERE id_attribute_group = '.(int)$params['id_attribute_group']);
Db::getInstance()->execute('INSERT INTO '._DB_PREFIX_.'layered_indexable_attribute_group VALUES ('.(int)$params['id_attribute_group'].', '.(int)Tools::getValue('layered_indexable').')'); Db::getInstance()->Execute('INSERT INTO '._DB_PREFIX_.'layered_indexable_attribute_group VALUES ('.(int)$params['id_attribute_group'].', '.(int)Tools::getValue('layered_indexable').')');
Db::getInstance()->execute('DELETE FROM '._DB_PREFIX_.'layered_indexable_attribute_group_lang_value WHERE id_attribute_group = '.(int)$params['id_attribute_group']); // don't care about the id_lang Db::getInstance()->Execute('DELETE FROM '._DB_PREFIX_.'layered_indexable_attribute_group_lang_value WHERE id_attribute_group = '.(int)$params['id_attribute_group']); // don't care about the id_lang
foreach (Language::getLanguages(false) as $language) foreach (Language::getLanguages(false) as $language)
{ {
// Data are validated by method "hookPostProcessAttributeGroup" // Data are validated by method "hookPostProcessAttributeGroup"
$id_lang = (int)$language['id_lang']; $id_lang = (int)$language['id_lang'];
Db::getInstance()->execute('INSERT INTO '._DB_PREFIX_.'layered_indexable_attribute_group_lang_value Db::getInstance()->Execute('INSERT INTO '._DB_PREFIX_.'layered_indexable_attribute_group_lang_value
VALUES ('.(int)$params['id_attribute_group'].', '.$id_lang.', \''.pSQL(Tools::link_rewrite(Tools::getValue('url_name_'.$id_lang))).'\', VALUES ('.(int)$params['id_attribute_group'].', '.$id_lang.', \''.pSQL(Tools::link_rewrite(Tools::getValue('url_name_'.$id_lang))).'\',
\''.pSQL(Tools::safeOutput(Tools::getValue('meta_title_'.$id_lang), true)).'\')'); \''.pSQL(Tools::safeOutput(Tools::getValue('meta_title_'.$id_lang), true)).'\')');
} }
@@ -689,8 +689,8 @@ class BlockLayered extends Module
if (!$params['id_attribute_group']) if (!$params['id_attribute_group'])
return; return;
Db::getInstance()->execute('DELETE FROM '._DB_PREFIX_.'layered_indexable_attribute_group WHERE id_attribute_group = '.(int)$params['id_attribute_group']); Db::getInstance()->Execute('DELETE FROM '._DB_PREFIX_.'layered_indexable_attribute_group WHERE id_attribute_group = '.(int)$params['id_attribute_group']);
Db::getInstance()->execute('DELETE FROM '._DB_PREFIX_.'layered_indexable_attribute_group_lang_value WHERE id_attribute_group = '.(int)$params['id_attribute_group']); Db::getInstance()->Execute('DELETE FROM '._DB_PREFIX_.'layered_indexable_attribute_group_lang_value WHERE id_attribute_group = '.(int)$params['id_attribute_group']);
} }
public function hookAttributeGroupForm($params) public function hookAttributeGroupForm($params)
@@ -701,7 +701,7 @@ class BlockLayered extends Module
WHERE id_attribute_group = '.(int)$params['id_attribute_group']); WHERE id_attribute_group = '.(int)$params['id_attribute_group']);
$langValue = array(); $langValue = array();
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS( $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS(
'SELECT url_name, meta_title, id_lang FROM '._DB_PREFIX_.'layered_indexable_attribute_group_lang_value 'SELECT url_name, meta_title, id_lang FROM '._DB_PREFIX_.'layered_indexable_attribute_group_lang_value
WHERE id_attribute_group = '.(int)$params['id_attribute_group']); WHERE id_attribute_group = '.(int)$params['id_attribute_group']);
if ($result) if ($result)
@@ -760,7 +760,7 @@ class BlockLayered extends Module
$indexable = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('SELECT indexable FROM '._DB_PREFIX_.'layered_indexable_feature WHERE id_feature = '.(int)$params['id_feature']); $indexable = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('SELECT indexable FROM '._DB_PREFIX_.'layered_indexable_feature WHERE id_feature = '.(int)$params['id_feature']);
$langValue = array(); $langValue = array();
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS( $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS(
'SELECT url_name, meta_title, id_lang FROM '._DB_PREFIX_.'layered_indexable_feature_lang_value 'SELECT url_name, meta_title, id_lang FROM '._DB_PREFIX_.'layered_indexable_feature_lang_value
WHERE id_feature = '.(int)$params['id_feature']); WHERE id_feature = '.(int)$params['id_feature']);
if ($result) if ($result)
@@ -858,8 +858,7 @@ class BlockLayered extends Module
if (($nbProducts > 0 && !$full || $cursor < $nbProducts && $full) && !$ajax) if (($nbProducts > 0 && !$full || $cursor < $nbProducts && $full) && !$ajax)
{ {
$token = substr(Tools::encrypt('blocklayered/index'), 0, 10); $token = substr(Tools::encrypt('blocklayered/index'), 0, 10);
if (!Tools::file_get_contents(Tools::getCurrentUrlProtocolPrefix().Tools::getHttpHost(). if (!Tools::file_get_contents(Tools::getCurrentUrlProtocolPrefix().Tools::getHttpHost().__PS_BASE_URI__.'modules/blocklayered/blocklayered-price-indexer.php?token='.$token.'&cursor='.(int)$cursor.'&full='.(int)$full))
__PS_BASE_URI__.'modules/blocklayered/blocklayered-price-indexer.php?token='.$token.'&cursor='.(int)$cursor.'&full='.(int)$full))
self::indexPrices((int)$cursor, (int)$full); self::indexPrices((int)$cursor, (int)$full);
return $cursor; return $cursor;
} }
@@ -901,7 +900,7 @@ class BlockLayered extends Module
WHERE `active` = 1 AND psi.id_product is null WHERE `active` = 1 AND psi.id_product is null
ORDER by id_product LIMIT 0,'.(int)$length; ORDER by id_product LIMIT 0,'.(int)$length;
foreach (Db::getInstance()->executeS($query) as $product) foreach (Db::getInstance()->ExecuteS($query) as $product)
self::indexProductPrices((int)$product['id_product'], ($smart && $full)); self::indexProductPrices((int)$product['id_product'], ($smart && $full));
return (int)($cursor + $length); return (int)($cursor + $length);
@@ -913,7 +912,7 @@ class BlockLayered extends Module
if (is_null($groups)) if (is_null($groups))
{ {
$groups = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('SELECT id_group FROM `'._DB_PREFIX_.'group_reduction`'); $groups = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('SELECT id_group FROM `'._DB_PREFIX_.'group_reduction`');
if (!$groups) if (!$groups)
$groups = array(); $groups = array();
} }
@@ -937,7 +936,7 @@ class BlockLayered extends Module
WHERE id_product = '.(int)$idProduct.' WHERE id_product = '.(int)$idProduct.'
GROUP BY id_product'); GROUP BY id_product');
$productMinPrices = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(' $productMinPrices = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT id_shop, id_currency, id_country, id_group, from_quantity SELECT id_shop, id_currency, id_country, id_group, from_quantity
FROM `'._DB_PREFIX_.'specific_price` FROM `'._DB_PREFIX_.'specific_price`
WHERE id_product = '.(int)$idProduct); WHERE id_product = '.(int)$idProduct);
@@ -1006,7 +1005,7 @@ class BlockLayered extends Module
$values[] = '('.(int)$idProduct.', '.(int)$currency['id_currency'].', $values[] = '('.(int)$idProduct.', '.(int)$currency['id_currency'].',
'.(int)$minPrice[$currency['id_currency']].', '.(int)($maxPrice[$currency['id_currency']] * (100 + $maxTaxRate) / 100).')'; '.(int)$minPrice[$currency['id_currency']].', '.(int)($maxPrice[$currency['id_currency']] * (100 + $maxTaxRate) / 100).')';
Db::getInstance()->execute(' Db::getInstance()->Execute('
INSERT INTO `'._DB_PREFIX_.'layered_price_index` (id_product, id_currency, price_min, price_max) INSERT INTO `'._DB_PREFIX_.'layered_price_index` (id_product, id_currency, price_min, price_max)
VALUES '.implode(',', $values).' VALUES '.implode(',', $values).'
ON DUPLICATE KEY UPDATE id_product = id_product # avoid duplicate keys'); ON DUPLICATE KEY UPDATE id_product = id_product # avoid duplicate keys');
@@ -1036,8 +1035,6 @@ class BlockLayered extends Module
$idLang = (int)$cookie->id_lang; $idLang = (int)$cookie->id_lang;
$category = new Category((int)Tools::getValue('id_category')); $category = new Category((int)Tools::getValue('id_category'));
$categoryMetas = Tools::getMetaTags($idLang, '');
$categoryTitle = (empty($category->meta_title[$idLang]) ? $category->name[$idLang] : $category->meta_title[$idLang]);
// Generate meta title and meta description // Generate meta title and meta description
$title = ''; $title = '';
@@ -1045,22 +1042,25 @@ class BlockLayered extends Module
foreach ($filterBlock['title_values'] as $key => $val) foreach ($filterBlock['title_values'] as $key => $val)
$title .= $key.' '.implode('/', $val).' – '; $title .= $key.' '.implode('/', $val).' – ';
$title = rtrim($title, ' – '); $title = rtrim($title, ' – ');
$categoryMetas = Tools::getMetaTags($idLang, '', $title);
$categoryTitle = (empty($category->meta_title[$idLang]) ? $category->name[$idLang] : $category->meta_title[$idLang]);
if (!empty($title)) if (!empty($title))
{ {
$smarty->assign('meta_title', ucfirst(strtolower(preg_replace('/^'.$categoryTitle.'/', $categoryTitle.' – '.$title, $categoryMetas['meta_title'])))); $smarty->assign('meta_title', $categoryTitle.$categoryMetas['meta_title']);
$smarty->assign('meta_description', rtrim($categoryTitle.' – '.$title.' – '.$categoryMetas['meta_description'], ' – ')); $smarty->assign('meta_description', $categoryTitle.$categoryMetas['meta_description']);
} }
else else
$smarty->assign('meta_title', ucfirst(strtolower($categoryMetas['meta_title']))); $smarty->assign('meta_title', $categoryMetas['meta_title']);
$metaKeyWordsComplement = substr(str_replace(' – ', ', ', strtolower($title)), 1000); $metaKeyWordsComplement = substr(str_replace(' – ', ', ', strtolower($title)), 1000);
if (!empty($metaKeyWordsComplement)) if (!empty($metaKeyWordsComplement))
$smarty->assign('meta_keywords', rtrim($categoryTitle.', '.$metaKeyWordsComplement.', '.$categoryMetas['meta_keywords'], ', ')); $smarty->assign('meta_keywords', rtrim($categoryTitle.', '.$metaKeyWordsComplement.', '.$categoryMetas['meta_keywords'], ', '));
$this->context->controller->addJs($this->_path.'blocklayered.js'); Tools::addJS(($this->_path).'blocklayered.js');
$this->context->controller->addJqueryUI('ui.slider'); Tools::addJS(_PS_JS_DIR_.'jquery/jquery-ui-1.8.10.custom.min.js');
$this->context->controller->addCSS($this->_path.'blocklayered.css', 'all'); Tools::addCSS(_PS_CSS_DIR_.'jquery-ui-1.8.10.custom.css', 'all');
Tools::addCSS(($this->_path).'blocklayered.css', 'all');
Tools::addJS(_PS_JS_DIR_.'jquery/jquery.scrollTo-1.4.2-min.js'); Tools::addJS(_PS_JS_DIR_.'jquery/jquery.scrollTo-1.4.2-min.js');
} }
@@ -1095,7 +1095,7 @@ class BlockLayered extends Module
public function hookCategoryDeletion($params) public function hookCategoryDeletion($params)
{ {
Db::getInstance()->execute('DELETE FROM '._DB_PREFIX_.'layered_category WHERE id_category = '.(int)$params['category']->id); Db::getInstance()->Execute('DELETE FROM '._DB_PREFIX_.'layered_category WHERE id_category = '.(int)$params['category']->id);
} }
public function getContent() public function getContent()
@@ -1117,12 +1117,12 @@ class BlockLayered extends Module
else else
{ {
if (isset($_POST['id_layered_filter']) && $_POST['id_layered_filter']) if (isset($_POST['id_layered_filter']) && $_POST['id_layered_filter'])
Db::getInstance()->execute('DELETE FROM '._DB_PREFIX_.'layered_filter WHERE id_layered_filter = '.(int)Tools::getValue('id_layered_filter')); Db::getInstance()->Execute('DELETE FROM '._DB_PREFIX_.'layered_filter WHERE id_layered_filter = '.(int)Tools::getValue('id_layered_filter'));
if (Tools::getValue('scope') == 1) if (Tools::getValue('scope') == 1)
{ {
Db::getInstance()->execute('TRUNCATE TABLE '._DB_PREFIX_.'layered_filter'); Db::getInstance()->Execute('TRUNCATE TABLE '._DB_PREFIX_.'layered_filter');
$categories = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('SELECT id_category FROM '._DB_PREFIX_.'category'); $categories = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('SELECT id_category FROM '._DB_PREFIX_.'category');
foreach ($categories as $category) foreach ($categories as $category)
$_POST['categoryBox'][] = (int)$category['id_category']; $_POST['categoryBox'][] = (int)$category['id_category'];
} }
@@ -1134,7 +1134,7 @@ class BlockLayered extends Module
foreach ($_POST['categoryBox'] as &$categoryBoxTmp) foreach ($_POST['categoryBox'] as &$categoryBoxTmp)
$categoryBoxTmp = (int)$categoryBoxTmp; $categoryBoxTmp = (int)$categoryBoxTmp;
Db::getInstance()->execute('DELETE FROM '._DB_PREFIX_.'layered_category WHERE id_category IN ('.implode(',', array_map('intval', $_POST['categoryBox'])).')'); Db::getInstance()->Execute('DELETE FROM '._DB_PREFIX_.'layered_category WHERE id_category IN ('.implode(',', array_map('intval', $_POST['categoryBox'])).')');
$filterValues = array(); $filterValues = array();
foreach ($_POST['categoryBox'] as $idc) foreach ($_POST['categoryBox'] as $idc)
@@ -1168,7 +1168,7 @@ class BlockLayered extends Module
} }
} }
Db::getInstance()->execute(rtrim($sqlToInsert, ',')); Db::getInstance()->Execute(rtrim($sqlToInsert, ','));
$valuesToInsert = array( $valuesToInsert = array(
'name' => pSQL(Tools::getValue('layered_tpl_name')), 'name' => pSQL(Tools::getValue('layered_tpl_name')),
@@ -1180,7 +1180,7 @@ class BlockLayered extends Module
Db::getInstance()->AutoExecute(_DB_PREFIX_.'layered_filter', $valuesToInsert, 'INSERT'); Db::getInstance()->AutoExecute(_DB_PREFIX_.'layered_filter', $valuesToInsert, 'INSERT');
echo '<div class="conf"> echo '<div class="conf"><img src="../img/admin/ok2.png" alt="" />
'.$this->l('Your filter').' "'.Tools::safeOutput(Tools::getValue('layered_tpl_name')).'" '. '.$this->l('Your filter').' "'.Tools::safeOutput(Tools::getValue('layered_tpl_name')).'" '.
((isset($_POST['id_layered_filter']) && $_POST['id_layered_filter']) ? $this->l('was updated successfully.') : $this->l('was added successfully.')).'</div>'; ((isset($_POST['id_layered_filter']) && $_POST['id_layered_filter']) ? $this->l('was updated successfully.') : $this->l('was added successfully.')).'</div>';
} }
@@ -1193,7 +1193,7 @@ class BlockLayered extends Module
$html .= ' $html .= '
<div class="conf"> <div class="conf">
'.$this->l('Settings saved successfully').' <img src="../img/admin/ok2.png" alt="" /> '.$this->l('Settings saved successfully').'
</div>'; </div>';
} }
else if (isset($_GET['deleteFilterTemplate'])) else if (isset($_GET['deleteFilterTemplate']))
@@ -1205,11 +1205,11 @@ class BlockLayered extends Module
if ($layeredValues) if ($layeredValues)
{ {
Db::getInstance()->execute('DELETE FROM '._DB_PREFIX_.'layered_filter WHERE id_layered_filter = '.(int)$_GET['id_layered_filter'].' LIMIT 1'); Db::getInstance()->Execute('DELETE FROM '._DB_PREFIX_.'layered_filter WHERE id_layered_filter = '.(int)$_GET['id_layered_filter'].' LIMIT 1');
$html .= ' $html .= '
<div class="conf"> <div class="conf">
'.$this->l('Filters template deleted, categories updated (reverted to default Filters template).').' <img src="../img/admin/ok2.png" alt="" /> '.$this->l('Filters template deleted, categories updated (reverted to default Filters template).').'
</div>'; </div>';
} }
else else
@@ -1223,7 +1223,7 @@ class BlockLayered extends Module
$html .= ' $html .= '
<div id="ajax-message-ok" class="conf ajax-message" style="display: none"> <div id="ajax-message-ok" class="conf ajax-message" style="display: none">
<span class="message"></span> <img alt="" src="../img/admin/ok2.png"><span class="message"></span>
</div> </div>
<div id="ajax-message-ko" class="error ajax-message" style="display: none"> <div id="ajax-message-ko" class="error ajax-message" style="display: none">
<img src="../img/admin/error2.png" alt="" /><span class="message"></span> <img src="../img/admin/error2.png" alt="" /><span class="message"></span>
@@ -1243,41 +1243,40 @@ class BlockLayered extends Module
</script>'; </script>';
$categoryList = array(); $categoryList = array();
foreach (Db::getInstance()->executeS('SELECT id_category FROM `'._DB_PREFIX_.'category`') as $category) foreach (Db::getInstance()->ExecuteS('SELECT id_category FROM `'._DB_PREFIX_.'category`') as $category)
if ($category['id_category'] != 1) if ($category['id_category'] != 1)
$categoryList[] = $category['id_category']; $categoryList[] = $category['id_category'];
$base_url = Tools::getCurrentUrlProtocolPrefix().Tools::getHttpHost().__PS_BASE_URI__;
$html .= ' $html .= '
<a class="bold ajaxcall-recurcive" <a class="bold ajaxcall-recurcive"
style="width: 250px; text-align:center;display:block;border:1px solid #aaa;text-decoration:none;background-color:#fafafa;color:#123456;margin:2px;padding:2px" style="width: 250px; text-align:center;display:block;border:1px solid #aaa;text-decoration:none;background-color:#fafafa;color:#123456;margin:2px;padding:2px"
href="'.$base_url.'modules/blocklayered/blocklayered-price-indexer.php'.'?token='.substr(Tools::encrypt('blocklayered/index'), 0, 10).'">'. href="'.Tools::getCurrentUrlProtocolPrefix().Tools::getHttpHost().__PS_BASE_URI__.'modules/blocklayered/blocklayered-price-indexer.php'.'?token='.substr(Tools::encrypt('blocklayered/index'), 0, 10).'">'.
$this->l('Index all missing prices').'</a> $this->l('Index all missing prices').'</a>
<br /> <br />
<a class="bold ajaxcall-recurcive" <a class="bold ajaxcall-recurcive"
style="width: 250px; text-align:center;display:block;border:1px solid #aaa;text-decoration:none;background-color:#fafafa;color:#123456;margin:2px;padding:2px" id="full-index" style="width: 250px; text-align:center;display:block;border:1px solid #aaa;text-decoration:none;background-color:#fafafa;color:#123456;margin:2px;padding:2px" id="full-index"
href="'.$base_url.'modules/blocklayered/blocklayered-price-indexer.php'.'?token='.substr(Tools::encrypt('blocklayered/index'), 0, 10).'&full=1">'. href="'.Tools::getCurrentUrlProtocolPrefix().Tools::getHttpHost().__PS_BASE_URI__.'modules/blocklayered/blocklayered-price-indexer.php'.'?token='.substr(Tools::encrypt('blocklayered/index'), 0, 10).'&full=1">'.
$this->l('Re-build entire price index').'</a> $this->l('Re-build entire price index').'</a>
<br /> <br />
<a class="bold ajaxcall" id="attribute-indexer" <a class="bold ajaxcall" id="attribute-indexer"
style="width: 250px; text-align:center;display:block;border:1px solid #aaa;text-decoration:none;background-color:#fafafa;color:#123456;margin:2px;padding:2px" id="full-index" style="width: 250px; text-align:center;display:block;border:1px solid #aaa;text-decoration:none;background-color:#fafafa;color:#123456;margin:2px;padding:2px" id="full-index"
href="'.$base_url.'modules/blocklayered/blocklayered-attribute-indexer.php'.'?token='.substr(Tools::encrypt('blocklayered/index'), 0, 10).'">'. href="'.Tools::getCurrentUrlProtocolPrefix().Tools::getHttpHost().__PS_BASE_URI__.'modules/blocklayered/blocklayered-attribute-indexer.php'.'?token='.substr(Tools::encrypt('blocklayered/index'), 0, 10).'">'.
$this->l('Build attribute index').'</a> $this->l('Build attribute index').'</a>
<br /> <br />
<a class="bold ajaxcall" id="url-indexer" <a class="bold ajaxcall" id="url-indexer"
style="width: 250px; text-align:center;display:block;border:1px solid #aaa;text-decoration:none;background-color:#fafafa;color:#123456;margin:2px;padding:2px" id="full-index" style="width: 250px; text-align:center;display:block;border:1px solid #aaa;text-decoration:none;background-color:#fafafa;color:#123456;margin:2px;padding:2px" id="full-index"
href="'.$base_url.'modules/blocklayered/blocklayered-url-indexer.php'.'?token='.substr(Tools::encrypt('blocklayered/index'), 0, 10).'&truncate=1">'. href="'.Tools::getCurrentUrlProtocolPrefix().Tools::getHttpHost().__PS_BASE_URI__.'modules/blocklayered/blocklayered-url-indexer.php'.'?token='.substr(Tools::encrypt('blocklayered/index'), 0, 10).'&truncate=1">'.
$this->l('Build url index').'</a> $this->l('Build url index').'</a>
<br /> <br />
<br /> <br />
'.$this->l('You can set a cron job that will re-build price index using the following URL:').'<br /><b>'. '.$this->l('You can set a cron job that will re-build price index using the following URL:').'<br /><b>'.
$base_url.'modules/blocklayered/blocklayered-price-indexer.php'.'?token='.substr(Tools::encrypt('blocklayered/index'), 0, 10).'&full=1</b> Tools::getCurrentUrlProtocolPrefix().Tools::getHttpHost().__PS_BASE_URI__.'modules/blocklayered/blocklayered-price-indexer.php'.'?token='.substr(Tools::encrypt('blocklayered/index'), 0, 10).'&full=1</b>
<br /> <br />
'.$this->l('You can set a cron job that will re-build url index using the following URL:').'<br /><b>'. '.$this->l('You can set a cron job that will re-build url index using the following URL:').'<br /><b>'.
$base_url.'modules/blocklayered/blocklayered-url-indexer.php'.'?token='.substr(Tools::encrypt('blocklayered/index'), 0, 10).'&truncate=1</b> Tools::getCurrentUrlProtocolPrefix().Tools::getHttpHost().__PS_BASE_URI__.'modules/blocklayered/blocklayered-url-indexer.php'.'?token='.substr(Tools::encrypt('blocklayered/index'), 0, 10).'&truncate=1</b>
<br /> <br />
'.$this->l('You can set a cron job that will re-build attribute index using the following URL:').'<br /><b>'. '.$this->l('You can set a cron job that will re-build attribute index using the following URL:').'<br /><b>'.
$base_url.'modules/blocklayered/blocklayered-attribute-indexer.php'.'?token='.substr(Tools::encrypt('blocklayered/index'), 0, 10).'</b> Tools::getCurrentUrlProtocolPrefix().Tools::getHttpHost().__PS_BASE_URI__.'modules/blocklayered/blocklayered-attribute-indexer.php'.'?token='.substr(Tools::encrypt('blocklayered/index'), 0, 10).'</b>
<br /><br /> <br /><br />
'.$this->l('A nightly rebuild is recommended.').' '.$this->l('A nightly rebuild is recommended.').'
<script type="text/javascript"> <script type="text/javascript">
@@ -1399,7 +1398,7 @@ class BlockLayered extends Module
<fieldset class="width4"> <fieldset class="width4">
<legend><img src="../img/admin/cog.gif" alt="" />'.$this->l('Existing filters templates').'</legend>'; <legend><img src="../img/admin/cog.gif" alt="" />'.$this->l('Existing filters templates').'</legend>';
$filtersTemplates = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('SELECT * FROM '._DB_PREFIX_.'layered_filter ORDER BY date_add DESC'); $filtersTemplates = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('SELECT * FROM '._DB_PREFIX_.'layered_filter ORDER BY date_add DESC');
if (count($filtersTemplates)) if (count($filtersTemplates))
{ {
$html .= '<p>'.count($filtersTemplates).' '.$this->l('filters templates are configured:').'</p> $html .= '<p>'.count($filtersTemplates).' '.$this->l('filters templates are configured:').'</p>
@@ -1481,17 +1480,10 @@ class BlockLayered extends Module
<li>'.$this->l('Press "Save this selection" or close the window to save').'</li> <li>'.$this->l('Press "Save this selection" or close the window to save').'</li>
</ol>'; </ol>';
$trads = array();
$selectedCat = array(); $selectedCat = array();
// Translations are not automatic for the moment ;) foreach (Helper::$translationsKeysForAdminCategorieTree as $key)
$trads = array( $trads[$key] = $this->l($key);
'Home' => $this->l('Home'),
'selected' => $this->l('selected'),
'Collapse All' => $this->l('Collapse All'),
'Expand All' => $this->l('Expand All'),
'Check All' => $this->l('Check All'),
'Uncheck All' => $this->l('Uncheck All'),
'search' => $this->l('Search a category')
);
$html .= Helper::renderAdminCategorieTree($trads, $selectedCat, 'categoryBox'); $html .= Helper::renderAdminCategorieTree($trads, $selectedCat, 'categoryBox');
$html .= ' $html .= '
@@ -1939,7 +1931,7 @@ class BlockLayered extends Module
} }
} }
$idCurrency = (int)$this->context->currency->id; $idCurrency = Currency::getCurrent()->id;
$priceFilterQueryIn = ''; // All products with price range between price filters limits $priceFilterQueryIn = ''; // All products with price range between price filters limits
$priceFilterQueryOut = ''; // All products with a price filters limit on it price range $priceFilterQueryOut = ''; // All products with a price filters limit on it price range
if (isset($priceFilter) && $priceFilter) if (isset($priceFilter) && $priceFilter)
@@ -1959,14 +1951,14 @@ class BlockLayered extends Module
AND psi.`id_currency` = '.(int)$idCurrency; AND psi.`id_currency` = '.(int)$idCurrency;
} }
$allProductsOut = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(' $allProductsOut = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT p.`id_product` id_product SELECT p.`id_product` id_product
FROM `'._DB_PREFIX_.'product` p FROM `'._DB_PREFIX_.'product` p
'.$priceFilterQueryOut.' '.$priceFilterQueryOut.'
'.$queryFiltersFrom.' '.$queryFiltersFrom.'
WHERE 1 '.$queryFiltersWhere.' GROUP BY id_product', false); WHERE 1 '.$queryFiltersWhere.' GROUP BY id_product', false);
$allProductsIn = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(' $allProductsIn = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT p.`id_product` id_product SELECT p.`id_product` id_product
FROM `'._DB_PREFIX_.'product` p FROM `'._DB_PREFIX_.'product` p
'.$priceFilterQueryIn.' '.$priceFilterQueryIn.'
@@ -1993,7 +1985,7 @@ class BlockLayered extends Module
else else
{ {
$n = (int)Tools::getValue('n', Configuration::get('PS_PRODUCTS_PER_PAGE')); $n = (int)Tools::getValue('n', Configuration::get('PS_PRODUCTS_PER_PAGE'));
$this->products = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(' $this->products = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT p.id_product, p.on_sale, p.out_of_stock, p.available_for_order, p.quantity, p.minimal_quantity, p.id_category_default, p.customizable, p.show_price, p.`weight`, SELECT p.id_product, p.on_sale, p.out_of_stock, p.available_for_order, p.quantity, p.minimal_quantity, p.id_category_default, p.customizable, p.show_price, p.`weight`,
p.ean13, pl.available_later, pl.description_short, pl.link_rewrite, pl.name, i.id_image, il.legend, m.name manufacturer_name, p.condition, p.id_manufacturer, p.ean13, pl.available_later, pl.description_short, pl.link_rewrite, pl.name, i.id_image, il.legend, m.name manufacturer_name, p.condition, p.id_manufacturer,
DATEDIFF(p.`date_add`, DATEDIFF(p.`date_add`,
@@ -2028,7 +2020,7 @@ class BlockLayered extends Module
$parent = new Category((int)$id_parent); $parent = new Category((int)$id_parent);
/* Get the filters for the current category */ /* Get the filters for the current category */
$filters = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('SELECT * FROM '._DB_PREFIX_.'layered_category WHERE id_category = '.(int)$id_parent.' $filters = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('SELECT * FROM '._DB_PREFIX_.'layered_category WHERE id_category = '.(int)$id_parent.'
GROUP BY `type`, id_value ORDER BY position ASC'); GROUP BY `type`, id_value ORDER BY position ASC');
// Remove all empty selected filters // Remove all empty selected filters
foreach ($selectedFilters as $key => $value) foreach ($selectedFilters as $key => $value)
@@ -2151,6 +2143,7 @@ class BlockLayered extends Module
WHERE c.id_parent = '.(int)$id_parent.' WHERE c.id_parent = '.(int)$id_parent.'
GROUP BY c.id_category ORDER BY level_depth, c.position'; GROUP BY c.id_category ORDER BY level_depth, c.position';
} }
foreach ($filters as $filterTmp) foreach ($filters as $filterTmp)
{ {
$methodName = 'get'.ucfirst($filterTmp['type']).'FilterSubQuery'; $methodName = 'get'.ucfirst($filterTmp['type']).'FilterSubQuery';
@@ -2174,7 +2167,7 @@ class BlockLayered extends Module
$products = false; $products = false;
if (!empty($sqlQuery['from'])) if (!empty($sqlQuery['from']))
$products = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sqlQuery['select']."\n".$sqlQuery['from']."\n".$sqlQuery['join']."\n".$sqlQuery['where']."\n".$sqlQuery['group']); $products = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sqlQuery['select']."\n".$sqlQuery['from']."\n".$sqlQuery['join']."\n".$sqlQuery['where']."\n".$sqlQuery['group']);
foreach ($filters as $filterTmp) foreach ($filters as $filterTmp)
{ {
@@ -2191,7 +2184,7 @@ class BlockLayered extends Module
{ {
case 'price': case 'price':
$priceArray = array('type_lite' => 'price', 'type' => 'price', 'id_key' => 0, 'name' => $this->l('Price'), $priceArray = array('type_lite' => 'price', 'type' => 'price', 'id_key' => 0, 'name' => $this->l('Price'),
'slider' => true, 'max' => '0', 'min' => null, 'values' => array ('1' => 0), 'unit' => (int)$this->context->currency->sign); 'slider' => true, 'max' => '0', 'min' => null, 'values' => array ('1' => 0), 'unit' => Currency::getCurrent()->sign);
if (isset($products) && $products) if (isset($products) && $products)
foreach ($products as $product) foreach ($products as $product)
{ {
@@ -2364,7 +2357,7 @@ class BlockLayered extends Module
$nonIndexable = array(); $nonIndexable = array();
// Get all non indexable attribute groups // Get all non indexable attribute groups
foreach (Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(' foreach (Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT public_name SELECT public_name
FROM `'._DB_PREFIX_.'attribute_group_lang` agl FROM `'._DB_PREFIX_.'attribute_group_lang` agl
LEFT JOIN `'._DB_PREFIX_.'layered_indexable_attribute_group` liag LEFT JOIN `'._DB_PREFIX_.'layered_indexable_attribute_group` liag
@@ -2374,7 +2367,7 @@ class BlockLayered extends Module
$nonIndexable[] = Tools::link_rewrite($attribute['public_name']); $nonIndexable[] = Tools::link_rewrite($attribute['public_name']);
// Get all non indexable features // Get all non indexable features
foreach (Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(' foreach (Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT name SELECT name
FROM `'._DB_PREFIX_.'feature_lang` fl FROM `'._DB_PREFIX_.'feature_lang` fl
LEFT JOIN `'._DB_PREFIX_.'layered_indexable_feature` lif LEFT JOIN `'._DB_PREFIX_.'layered_indexable_feature` lif
@@ -2385,7 +2378,6 @@ class BlockLayered extends Module
//generate SEO link //generate SEO link
$paramSelected = ''; $paramSelected = '';
$param_product_url = '';
$optionCheckedArray = array(); $optionCheckedArray = array();
$paramGroupSelectedArray = array(); $paramGroupSelectedArray = array();
$titleValues = array(); $titleValues = array();
@@ -2420,9 +2412,6 @@ class BlockLayered extends Module
$paramSelected .= '/'.str_replace('-', '_', Tools::link_rewrite($filterName)).$paramGroupSelected; $paramSelected .= '/'.str_replace('-', '_', Tools::link_rewrite($filterName)).$paramGroupSelected;
$optionCheckedArray[Tools::link_rewrite($filterName)] = $paramGroupSelected; $optionCheckedArray[Tools::link_rewrite($filterName)] = $paramGroupSelected;
} }
// select only attribute and group attribute to display an unique product combination link
if (!empty($paramGroupSelected) && $typeFilter['type'] == 'id_attribute_group')
$param_product_url .= '/'.str_replace('-', '_', Tools::link_rewrite($filterName)).$paramGroupSelected;
} }
$blackList = array('weight','price'); $blackList = array('weight','price');
@@ -2454,16 +2443,14 @@ class BlockLayered extends Module
else else
{ {
// Remove selected parameters // Remove selected parameters
$optionCheckedCloneArray[Tools::link_rewrite($filterName)] = str_replace( $optionCheckedCloneArray[Tools::link_rewrite($filterName)] = str_replace('-'.str_replace('-', '_', Tools::link_rewrite($valueName)), '', $optionCheckedCloneArray[Tools::link_rewrite($filterName)]);
'-'.str_replace('-', '_', Tools::link_rewrite($valueName)),
'',
$optionCheckedCloneArray[Tools::link_rewrite($filterName)]);
if (empty($optionCheckedCloneArray[Tools::link_rewrite($filterName)])) if (empty($optionCheckedCloneArray[Tools::link_rewrite($filterName)]))
unset($optionCheckedCloneArray[Tools::link_rewrite($filterName)]); unset($optionCheckedCloneArray[Tools::link_rewrite($filterName)]);
} }
$parameters = ''; $parameters = '';
foreach ($optionCheckedCloneArray as $keyGroup => $valueGroup) foreach ($optionCheckedCloneArray as $keyGroup => $valueGroup)
$parameters .= '/'.str_replace('-', '_', $keyGroup).$valueGroup; $parameters .= '/'.str_replace('-', '_', $keyGroup).$valueGroup;
// Check if there is an non indexable attribute or feature in the url // Check if there is an non indexable attribute or feature in the url
foreach ($nonIndexable as $value) foreach ($nonIndexable as $value)
if (strpos($parameters, '/'.$value) !== false) if (strpos($parameters, '/'.$value) !== false)
@@ -2492,7 +2479,7 @@ class BlockLayered extends Module
$cache = array('layered_show_qties' => (int)Configuration::get('PS_LAYERED_SHOW_QTIES'), 'id_category_layered' => (int)$id_parent, $cache = array('layered_show_qties' => (int)Configuration::get('PS_LAYERED_SHOW_QTIES'), 'id_category_layered' => (int)$id_parent,
'selected_filters' => $selectedFilters, 'n_filters' => (int)$nFilters, 'nbr_filterBlocks' => count($filterBlocks), 'filters' => $filterBlocks, 'selected_filters' => $selectedFilters, 'n_filters' => (int)$nFilters, 'nbr_filterBlocks' => count($filterBlocks), 'filters' => $filterBlocks,
'title_values' => $titleValues, 'current_friendly_url' => htmlentities($paramSelected), 'param_product_url' => htmlentities($param_product_url), 'nofollow' => !empty($paramSelected) || $nofollow); 'title_values' => $titleValues, 'current_friendly_url' => htmlentities($paramSelected), 'nofollow' => !empty($paramSelected) || $nofollow);
return $cache; return $cache;
} }
@@ -2528,16 +2515,18 @@ class BlockLayered extends Module
private static function getPriceFilterSubQuery($filterValue) private static function getPriceFilterSubQuery($filterValue)
{ {
$idCurrency = (int)Context::getContext()->currency->id; $idCurrency = (int)Currency::getCurrent()->id;
$priceFilterQuery = ''; $priceFilterQuery = '';
if (isset($filterValue) && $filterValue) if (isset($filterValue) && $filterValue)
{ {
$idCurrency = Currency::getCurrent()->id;
$priceFilterQuery = ' $priceFilterQuery = '
INNER JOIN `'._DB_PREFIX_.'layered_price_index` psi ON (psi.id_product = p.id_product AND psi.id_currency = '.(int)$idCurrency.' INNER JOIN `'._DB_PREFIX_.'layered_price_index` psi ON (psi.id_product = p.id_product AND psi.id_currency = '.(int)$idCurrency.'
AND psi.price_min <= '.(int)$filterValue[1].' AND psi.price_max >= '.(int)$filterValue[0].') '; AND psi.price_min <= '.(int)$filterValue[1].' AND psi.price_max >= '.(int)$filterValue[0].') ';
} }
else else
{ {
$idCurrency = Currency::getCurrent()->id;
$priceFilterQuery = ' $priceFilterQuery = '
INNER JOIN `'._DB_PREFIX_.'layered_price_index` psi INNER JOIN `'._DB_PREFIX_.'layered_price_index` psi
ON (psi.id_product = p.id_product AND psi.id_currency = '.(int)$idCurrency.') '; ON (psi.id_product = p.id_product AND psi.id_currency = '.(int)$idCurrency.') ';
@@ -2669,7 +2658,7 @@ class BlockLayered extends Module
foreach ($categoryBox as &$value) foreach ($categoryBox as &$value)
$value = (int)$value; $value = (int)$value;
$attributeGroups = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(' $attributeGroups = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT ag.id_attribute_group, ag.is_color_group, agl.name, COUNT(DISTINCT(a.id_attribute)) n SELECT ag.id_attribute_group, ag.is_color_group, agl.name, COUNT(DISTINCT(a.id_attribute)) n
FROM '._DB_PREFIX_.'attribute_group ag FROM '._DB_PREFIX_.'attribute_group ag
LEFT JOIN '._DB_PREFIX_.'attribute_group_lang agl ON (agl.id_attribute_group = ag.id_attribute_group) LEFT JOIN '._DB_PREFIX_.'attribute_group_lang agl ON (agl.id_attribute_group = ag.id_attribute_group)
@@ -2682,7 +2671,7 @@ class BlockLayered extends Module
(count($categoryBox) ? ' AND cp.id_category IN ('.implode(',', $categoryBox).')' : '').' (count($categoryBox) ? ' AND cp.id_category IN ('.implode(',', $categoryBox).')' : '').'
GROUP BY ag.id_attribute_group'); GROUP BY ag.id_attribute_group');
$features = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(' $features = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT fl.id_feature, fl.name, COUNT(DISTINCT(fv.id_feature_value)) n SELECT fl.id_feature, fl.name, COUNT(DISTINCT(fv.id_feature_value)) n
FROM '._DB_PREFIX_.'feature_lang fl FROM '._DB_PREFIX_.'feature_lang fl
LEFT JOIN '._DB_PREFIX_.'feature_value fv ON (fv.id_feature = fl.id_feature) LEFT JOIN '._DB_PREFIX_.'feature_value fv ON (fv.id_feature = fl.id_feature)
@@ -2839,14 +2828,14 @@ class BlockLayered extends Module
$categoryCount = ''; $categoryCount = '';
if ($nbProducts == 0) if ($nbProducts == 0)
$product_list_tpl = 'blocklayered-no-products.tpl'; $product_list = $this->display(__FILE__, 'blocklayered-no-products.tpl');
else else
$product_list_tpl = _PS_THEME_DIR_.'product-list.tpl'; $product_list = $smarty->fetch(_PS_THEME_DIR_.'product-list.tpl');
/* We are sending an array in jSon to the .js controller, it will update both the filters and the products zones */ /* We are sending an array in jSon to the .js controller, it will update both the filters and the products zones */
return Tools::jsonEncode(array( return Tools::jsonEncode(array(
'filtersBlock' => $this->generateFiltersBlock($selectedFilters), 'filtersBlock' => $this->generateFiltersBlock($selectedFilters),
'productList' => $smarty->fetch($product_list_tpl), 'productList' => $product_list,
'pagination' => $smarty->fetch(_PS_THEME_DIR_.'pagination.tpl'), 'pagination' => $smarty->fetch(_PS_THEME_DIR_.'pagination.tpl'),
'categoryCount' => $categoryCount)); 'categoryCount' => $categoryCount));
} }
@@ -2890,8 +2879,8 @@ class BlockLayered extends Module
@ini_set('memory_limit', '128M'); @ini_set('memory_limit', '128M');
/* Delete and re-create the layered categories table */ /* Delete and re-create the layered categories table */
Db::getInstance()->execute('DROP TABLE IF EXISTS '._DB_PREFIX_.'layered_category'); Db::getInstance()->Execute('DROP TABLE IF EXISTS '._DB_PREFIX_.'layered_category');
Db::getInstance()->execute(' Db::getInstance()->Execute('
CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'layered_category` ( CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'layered_category` (
`id_layered_category` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, `id_layered_category` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`id_category` INT(10) UNSIGNED NOT NULL, `id_category` INT(10) UNSIGNED NOT NULL,
@@ -2902,7 +2891,7 @@ class BlockLayered extends Module
KEY `id_category` (`id_category`,`type`) KEY `id_category` (`id_category`,`type`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;'); /* MyISAM + latin1 = Smaller/faster */ ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;'); /* MyISAM + latin1 = Smaller/faster */
Db::getInstance()->execute(' Db::getInstance()->Execute('
CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'layered_filter` ( CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'layered_filter` (
`id_layered_filter` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, `id_layered_filter` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` VARCHAR(64) NOT NULL, `name` VARCHAR(64) NOT NULL,
@@ -2924,7 +2913,7 @@ class BlockLayered extends Module
$nCategories = array(); $nCategories = array();
$doneCategories = array(); $doneCategories = array();
$attributeGroups = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(' $attributeGroups = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT a.id_attribute, a.id_attribute_group SELECT a.id_attribute, a.id_attribute_group
FROM '._DB_PREFIX_.'attribute a FROM '._DB_PREFIX_.'attribute a
LEFT JOIN '._DB_PREFIX_.'product_attribute_combination pac ON (pac.id_attribute = a.id_attribute) LEFT JOIN '._DB_PREFIX_.'product_attribute_combination pac ON (pac.id_attribute = a.id_attribute)
@@ -2939,7 +2928,7 @@ class BlockLayered extends Module
while ($row = $db->nextRow($attributeGroups)) while ($row = $db->nextRow($attributeGroups))
$attributeGroupsById[(int)$row['id_attribute']] = (int)$row['id_attribute_group']; $attributeGroupsById[(int)$row['id_attribute']] = (int)$row['id_attribute_group'];
$features = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS(' $features = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT fv.id_feature_value, fv.id_feature SELECT fv.id_feature_value, fv.id_feature
FROM '._DB_PREFIX_.'feature_value fv FROM '._DB_PREFIX_.'feature_value fv
LEFT JOIN '._DB_PREFIX_.'feature_product fp ON (fp.id_feature_value = fv.id_feature_value) LEFT JOIN '._DB_PREFIX_.'feature_product fp ON (fp.id_feature_value = fv.id_feature_value)
@@ -2953,7 +2942,7 @@ class BlockLayered extends Module
while ($row = $db->nextRow($features)) while ($row = $db->nextRow($features))
$featuresById[(int)$row['id_feature_value']] = (int)$row['id_feature']; $featuresById[(int)$row['id_feature_value']] = (int)$row['id_feature'];
$result = $db->executeS(' $result = $db->ExecuteS('
SELECT p.id_product, GROUP_CONCAT(DISTINCT fv.id_feature_value) features, GROUP_CONCAT(DISTINCT cp.id_category) categories, GROUP_CONCAT(DISTINCT pac.id_attribute) attributes SELECT p.id_product, GROUP_CONCAT(DISTINCT fv.id_feature_value) features, GROUP_CONCAT(DISTINCT cp.id_category) categories, GROUP_CONCAT(DISTINCT pac.id_attribute) attributes
FROM '._DB_PREFIX_.'product p FROM '._DB_PREFIX_.'product p
LEFT JOIN '._DB_PREFIX_.'category_product cp ON (cp.id_product = p.id_product) LEFT JOIN '._DB_PREFIX_.'category_product cp ON (cp.id_product = p.id_product)
@@ -3034,7 +3023,7 @@ class BlockLayered extends Module
} }
} }
if ($toInsert) if ($toInsert)
Db::getInstance()->execute(rtrim($queryCategory, ',')); Db::getInstance()->Execute(rtrim($queryCategory, ','));
} }
} }
} }
+1 -1
View File
@@ -97,7 +97,7 @@ param_product_url = '#{$param_product_url}';
</li> </li>
{/foreach} {/foreach}
{else} {else}
<label for="{$filter.type}">{l s='Range:'}</label> <span id="layered_{$filter.type}_range"></span> <label for="{$filter.type}">{l s='Range:' mod='blocklayered'}</label> <span id="layered_{$filter.type}_range"></span>
<div style="margin: 6px 0 6px 6px; width: 93%;"> <div style="margin: 6px 0 6px 6px; width: 93%;">
<div style="margin-top:5px;" class="layered_slider" id="layered_{$filter.type}_slider"></div> <div style="margin-top:5px;" class="layered_slider" id="layered_{$filter.type}_slider"></div>
</div> </div>
+14 -10
View File
@@ -46,11 +46,21 @@ class BlockSearch extends Module
public function install() public function install()
{ {
if (!parent::install() || !$this->registerHook('top')) if (!parent::install() || !$this->registerHook('top') || !$this->registerHook('header'))
return false; return false;
return true; return true;
} }
public function hookHeader($params)
{
if (Configuration::get('PS_SEARCH_AJAX'))
{
Tools::addCSS(_PS_CSS_DIR_.'jquery.autocomplete.css');
Tools::addJS(_PS_JS_DIR_.'jquery/jquery.autocomplete.js');
}
Tools::addCSS(_THEME_CSS_DIR_.'product_list.css');
Tools::addCSS(($this->_path).'blocksearch.css', 'all');
}
public function hookLeftColumn($params) public function hookLeftColumn($params)
{ {
@@ -79,15 +89,9 @@ class BlockSearch extends Module
{ {
$this->context->smarty->assign('ENT_QUOTES', ENT_QUOTES); $this->context->smarty->assign('ENT_QUOTES', ENT_QUOTES);
$this->context->smarty->assign('search_ssl', Tools::usingSecureMode()); $this->context->smarty->assign('search_ssl', Tools::usingSecureMode());
$this->context->smarty->assign('ajaxsearch', Configuration::get('PS_SEARCH_AJAX'));
$this->context->smarty->assign('instantsearch', Configuration::get('PS_INSTANT_SEARCH'));
$ajax_search = (int)Configuration::get('PS_SEARCH_AJAX'); return true;
$this->context->smarty->assign('ajaxsearch', $ajax_search);
$instant_search = (int)(Configuration::get('PS_INSTANT_SEARCH'));
$this->context->smarty->assign('instantsearch', $instant_search);
if ($ajax_search)
$this->context->controller->addJqueryPlugin('autocomplete');
$this->context->controller->addCSS(_THEME_CSS_DIR_.'product_list.css');
$this->context->controller->addCSS(($this->_path).'blocksearch.css', 'all');
} }
} }
+4
View File
@@ -0,0 +1,4 @@
<?php
global $_MODULE;
$_MODULE = array();
+2
View File
@@ -60,8 +60,10 @@
</span> </span>
<a href="javascript:;" class="clear button" onclick="WishlistProductManage('wlp_bought', 'delete', '{$id_wishlist}', '{$product.id_product}', '{$product.id_product_attribute}', $('#quantity_{$product.id_product}_{$product.id_product_attribute}').val(), $('#priority_{$product.id_product}_{$product.id_product_attribute}').val());" title="{l s='Delete' mod='blockwishlist'}">{l s='Delete' mod='blockwishlist'}</a> <a href="javascript:;" class="clear button" onclick="WishlistProductManage('wlp_bought', 'delete', '{$id_wishlist}', '{$product.id_product}', '{$product.id_product_attribute}', $('#quantity_{$product.id_product}_{$product.id_product_attribute}').val(), $('#priority_{$product.id_product}_{$product.id_product_attribute}').val());" title="{l s='Delete' mod='blockwishlist'}">{l s='Delete' mod='blockwishlist'}</a>
<a href="javascript:;" class="exclusive" onclick="WishlistProductManage('wlp_bought_{$product.id_product_attribute}', 'update', '{$id_wishlist}', '{$product.id_product}', '{$product.id_product_attribute}', $('#quantity_{$product.id_product}_{$product.id_product_attribute}').val(), $('#priority_{$product.id_product}_{$product.id_product_attribute}').val());" title="{l s='Save' mod='blockwishlist'}">{l s='Save' mod='blockwishlist'}</a> <a href="javascript:;" class="exclusive" onclick="WishlistProductManage('wlp_bought_{$product.id_product_attribute}', 'update', '{$id_wishlist}', '{$product.id_product}', '{$product.id_product_attribute}', $('#quantity_{$product.id_product}_{$product.id_product_attribute}').val(), $('#priority_{$product.id_product}_{$product.id_product_attribute}').val());" title="{l s='Save' mod='blockwishlist'}">{l s='Save' mod='blockwishlist'}</a>
<br />
</li> </li>
</ul> </ul>
<div class="clear">&nbsp;</div>
{/foreach} {/foreach}
</div> </div>
<div class="clear"></div> <div class="clear"></div>
+1
View File
@@ -87,6 +87,7 @@
</li> </li>
</div> </div>
</ul> </ul>
<div class="clear">&nbsp;</div>
{/foreach} {/foreach}
<p class="clear" /> <p class="clear" />
</div> </div>
+1 -2
View File
@@ -406,7 +406,7 @@ class dibs extends PaymentModule
} }
/** /**
* Set the detail of a payment to prepare the validate order * Set the detail of a payment - Call after un validateOrder
* See Authorize documentation to know the associated key => value * See Authorize documentation to know the associated key => value
* @param array fields * @param array fields
* @return bool success state * @return bool success state
@@ -429,6 +429,5 @@ class dibs extends PaymentModule
// 68 => Owner name // 68 => Owner name
$this->pcc->card_holder = ''; $this->pcc->card_holder = '';
} }
} }
} }
+2 -3
View File
@@ -42,11 +42,10 @@ if (count($_POST))
$message = nl2br(strip_tags($message)); $message = nl2br(strip_tags($message));
if ($valid_order === true) if ($valid_order === true)
{ {
$obj_dibs->setTransactionDetail($posted_values); $obj_dibs->setTransactionDetail($posted_values);
$obj_dibs->validateOrder((int)$posted_values['orderid'], Configuration::get('PS_OS_PAYMENT'), $obj_dibs->validateOrder((int)$posted_values['orderid'], Configuration::get('PS_OS_PAYMENT'),
(float)((int)$posted_values['amount'] / 100), $obj_dibs->displayName, $message, array(), NULL, false, $secure_cart[2]); (float)((int)$posted_values['amount'] / 100), $obj_dibs->displayName, $message, array(), NULL, false, $secure_cart[2]);
} }
else if ($valid_order === false) else if ($valid_order === false)
$obj_dibs->validateOrder((int)$posted_values['orderid'], Configuration::get('PS_OS_ERROR'), 0, $obj_dibs->displayName, $obj_dibs->validateOrder((int)$posted_values['orderid'], Configuration::get('PS_OS_ERROR'), 0, $obj_dibs->displayName, $message, array(), NULL, false, $secure_cart[2]);
$message, array(), NULL, false, $secure_cart[2]);
} }
+1 -1
View File
@@ -2,7 +2,7 @@
<module> <module>
<name>ebay</name> <name>ebay</name>
<displayName><![CDATA[eBay]]></displayName> <displayName><![CDATA[eBay]]></displayName>
<version><![CDATA[1.3.1]]></version> <version><![CDATA[1.3.5]]></version>
<description><![CDATA[Open your shop on the eBay market place !]]></description> <description><![CDATA[Open your shop on the eBay market place !]]></description>
<author><![CDATA[PrestaShop]]></author> <author><![CDATA[PrestaShop]]></author>
<tab><![CDATA[market_place]]></tab> <tab><![CDATA[market_place]]></tab>
+4 -1
View File
@@ -1140,7 +1140,9 @@ class eBayRequest
else $reference = $skuItem; else $reference = $skuItem;
} }
$reference = trim($reference);
if (!empty($reference))
{
$id_product = Db::getInstance()->getValue(' $id_product = Db::getInstance()->getValue('
SELECT `id_product` FROM `'._DB_PREFIX_.'product` SELECT `id_product` FROM `'._DB_PREFIX_.'product`
WHERE `reference` = \''.pSQL($reference).'\''); WHERE `reference` = \''.pSQL($reference).'\'');
@@ -1156,6 +1158,7 @@ class eBayRequest
} }
} }
} }
}
$orderList[] = array( $orderList[] = array(
'id_order_ref' => (string)$order->OrderID, 'id_order_ref' => (string)$order->OrderID,
+68 -17
View File
@@ -59,7 +59,7 @@ class Ebay extends Module
{ {
$this->name = 'ebay'; $this->name = 'ebay';
$this->tab = 'market_place'; $this->tab = 'market_place';
$this->version = '1.3.1'; $this->version = '1.3.5';
$this->author = 'PrestaShop'; $this->author = 'PrestaShop';
parent::__construct (); parent::__construct ();
$this->displayName = $this->l('eBay'); $this->displayName = $this->l('eBay');
@@ -93,12 +93,17 @@ class Ebay extends Module
if (!Configuration::get('EBAY_SECURITY_TOKEN')) if (!Configuration::get('EBAY_SECURITY_TOKEN'))
Configuration::updateValue('EBAY_SECURITY_TOKEN', Tools::passwdGen(30)); Configuration::updateValue('EBAY_SECURITY_TOKEN', Tools::passwdGen(30));
/* For 1.4.3 and less compatibility */ // For 1.4.3 and less compatibility
$updateConfig = array('PS_OS_CHEQUE', 'PS_OS_PAYMENT', 'PS_OS_PREPARATION', 'PS_OS_SHIPPING', 'PS_OS_CANCELED', 'PS_OS_REFUND', 'PS_OS_ERROR', 'PS_OS_OUTOFSTOCK', 'PS_OS_BANKWIRE', 'PS_OS_PAYPAL', 'PS_OS_WS_PAYMENT'); $updateConfig = array('PS_OS_CHEQUE' => 1, 'PS_OS_PAYMENT' => 2, 'PS_OS_PREPARATION' => 3, 'PS_OS_SHIPPING' => 4, 'PS_OS_DELIVERED' => 5, 'PS_OS_CANCELED' => 6,
if (!Configuration::get('PS_OS_PAYMENT')) 'PS_OS_REFUND' => 7, 'PS_OS_ERROR' => 8, 'PS_OS_OUTOFSTOCK' => 9, 'PS_OS_BANKWIRE' => 10, 'PS_OS_PAYPAL' => 11, 'PS_OS_WS_PAYMENT' => 12);
foreach ($updateConfig as $u) foreach ($updateConfig as $u => $v)
if (!Configuration::get($u) && defined('_'.$u.'_')) if (!Configuration::get($u) || (int)Configuration::get($u) < 1)
{
if (defined('_'.$u.'_') && (int)constant('_'.$u.'_') > 0)
Configuration::updateValue($u, constant('_'.$u.'_')); Configuration::updateValue($u, constant('_'.$u.'_'));
else
Configuration::updateValue($u, $v);
}
// Check if installed // Check if installed
if (self::isInstalled($this->name)) if (self::isInstalled($this->name))
@@ -326,6 +331,9 @@ class Ebay extends Module
if (!Configuration::get('EBAY_PAYPAL_EMAIL')) if (!Configuration::get('EBAY_PAYPAL_EMAIL'))
return false; return false;
// Fix hook update product attribute
$this->hookupdateProductAttributeEbay();
// If no update yet // If no update yet
if (!Configuration::get('EBAY_ORDER_LAST_UPDATE')) if (!Configuration::get('EBAY_ORDER_LAST_UPDATE'))
Configuration::updateValue('EBAY_ORDER_LAST_UPDATE', date('Y-m-d').'T'.date('H:i:s').'.000Z'); Configuration::updateValue('EBAY_ORDER_LAST_UPDATE', date('Y-m-d').'T'.date('H:i:s').'.000Z');
@@ -361,8 +369,6 @@ class Ebay extends Module
{ {
if (!Db::getInstance()->getValue('SELECT `id_ebay_order` FROM `'._DB_PREFIX_.'ebay_order` WHERE `id_order_ref` = \''.pSQL($order['id_order_ref']).'\'')) if (!Db::getInstance()->getValue('SELECT `id_ebay_order` FROM `'._DB_PREFIX_.'ebay_order` WHERE `id_order_ref` = \''.pSQL($order['id_order_ref']).'\''))
{ {
$id_customer = (int)Db::getInstance()->getValue('SELECT `id_customer` FROM `'._DB_PREFIX_.'customer` WHERE `active` = 1 AND `email` = \''.pSQL($order['email']).'\' AND `deleted` = 0'.(substr(_PS_VERSION_, 0, 3) == '1.3' ? '' : ' AND `is_guest` = 0'));
// Check for empty name // Check for empty name
$order['firstname'] = trim($order['firstname']); $order['firstname'] = trim($order['firstname']);
$order['familyname'] = trim($order['familyname']); $order['familyname'] = trim($order['familyname']);
@@ -375,6 +381,9 @@ class Ebay extends Module
if (Validate::isEmail($order['email']) && !empty($order['firstname']) && !empty($order['familyname'])) if (Validate::isEmail($order['email']) && !empty($order['firstname']) && !empty($order['familyname']))
{ {
// Getting the customer
$id_customer = (int)Db::getInstance()->getValue('SELECT `id_customer` FROM `'._DB_PREFIX_.'customer` WHERE `active` = 1 AND `email` = \''.pSQL($order['email']).'\' AND `deleted` = 0'.(substr(_PS_VERSION_, 0, 3) == '1.3' ? '' : ' AND `is_guest` = 0'));
// Add customer if he doesn't exist // Add customer if he doesn't exist
if ($id_customer < 1) if ($id_customer < 1)
{ {
@@ -434,7 +443,7 @@ class Ebay extends Module
$cartAdd->id_customer = $id_customer; $cartAdd->id_customer = $id_customer;
$cartAdd->id_address_invoice = $id_address; $cartAdd->id_address_invoice = $id_address;
$cartAdd->id_address_delivery = $id_address; $cartAdd->id_address_delivery = $id_address;
$cartAdd->id_carrier = 1; $cartAdd->id_carrier = 0;
$cartAdd->id_lang = $this->id_lang; $cartAdd->id_lang = $this->id_lang;
$cartAdd->id_currency = Currency::getIdByIsoCode('EUR'); $cartAdd->id_currency = Currency::getIdByIsoCode('EUR');
$cartAdd->recyclable = 0; $cartAdd->recyclable = 0;
@@ -446,7 +455,7 @@ class Ebay extends Module
$cartAdd->update(); $cartAdd->update();
// Check number of products in the cart // Check number of products in the cart
if ($cartNbProducts > 0) if ($cartNbProducts > 0 && !Db::getInstance()->getValue('SELECT `id_ebay_order` FROM `'._DB_PREFIX_.'ebay_order` WHERE `id_order_ref` = \''.pSQL($order['id_order_ref']).'\''))
{ {
// Fix on sending e-mail // Fix on sending e-mail
Db::getInstance()->autoExecute(_DB_PREFIX_.'customer', array('email' => 'NOSEND-EBAY'), 'UPDATE', '`id_customer` = '.(int)$id_customer); Db::getInstance()->autoExecute(_DB_PREFIX_.'customer', array('email' => 'NOSEND-EBAY'), 'UPDATE', '`id_customer` = '.(int)$id_customer);
@@ -466,16 +475,19 @@ class Ebay extends Module
Db::getInstance()->autoExecute(_DB_PREFIX_.'customer', array('email' => pSQL($order['email'])), 'UPDATE', '`id_customer` = '.(int)$id_customer); Db::getInstance()->autoExecute(_DB_PREFIX_.'customer', array('email' => pSQL($order['email'])), 'UPDATE', '`id_customer` = '.(int)$id_customer);
// Update price (because of possibility of price impact) // Update price (because of possibility of price impact)
foreach ($order['product_list'] as $product)
{
$tax_rate = Db::getInstance()->getValue('SELECT `tax_rate` FROM `'._DB_PREFIX_.'order_detail` WHERE `id_order` = '.(int)$id_order.' AND `product_id` = '.(int)$product['id_product'].' AND `product_attribute_id` = '.(int)$product['id_product_attribute']);
Db::getInstance()->autoExecute(_DB_PREFIX_.'order_detail', array('product_price' => floatval($product['price'] / (1 + ($tax_rate / 100))), 'reduction_percent' => 0), 'UPDATE', '`id_order` = '.(int)$id_order.' AND `product_id` = '.(int)$product['id_product'].' AND `product_attribute_id` = '.(int)$product['id_product_attribute']);
}
$updateOrder = array( $updateOrder = array(
'total_paid' => floatval($order['amount']), 'total_paid' => floatval($order['amount']),
'total_paid_real' => floatval($order['amount']), 'total_paid_real' => floatval($order['amount']),
'total_products' => floatval($order['amount']), 'total_products' => floatval(Db::getInstance()->getValue('SELECT SUM(`product_price`) FROM `'._DB_PREFIX_.'order_detail` WHERE `id_order` = '.(int)$id_order)),
'total_products_wt' => floatval($order['amount']), 'total_products_wt' => floatval($order['amount'] - $order['shippingServiceCost']),
'total_shipping' => floatval($order['shippingServiceCost']), 'total_shipping' => floatval($order['shippingServiceCost']),
); );
Db::getInstance()->autoExecute(_DB_PREFIX_.'orders', $updateOrder, 'UPDATE', '`id_order` = '.(int)$id_order); Db::getInstance()->autoExecute(_DB_PREFIX_.'orders', $updateOrder, 'UPDATE', '`id_order` = '.(int)$id_order);
foreach ($order['product_list'] as $product)
Db::getInstance()->autoExecute(_DB_PREFIX_.'order_detail', array('product_price' => floatval($product['price']), 'tax_rate' => 0, 'reduction_percent' => 0), 'UPDATE', '`id_order` = '.(int)$id_order.' AND `product_id` = '.(int)$product['id_product'].' AND `product_attribute_id` = '.(int)$product['id_product_attribute']);
// Register the ebay order ref // Register the ebay order ref
Db::getInstance()->autoExecute(_DB_PREFIX_.'ebay_order', array('id_order_ref' => pSQL($order['id_order_ref']), 'id_order' => (int)$id_order), 'INSERT'); Db::getInstance()->autoExecute(_DB_PREFIX_.'ebay_order', array('id_order_ref' => pSQL($order['id_order_ref']), 'id_order' => (int)$id_order), 'INSERT');
@@ -511,11 +523,20 @@ class Ebay extends Module
// Alias // Alias
public function hookupdateproduct($params) { $this->hookaddproduct($params); } public function hookupdateproduct($params) { $this->hookaddproduct($params); }
public function hookupdateProductAttribute($params) public function hookupdateProductAttribute($params) { }
public function hookupdateProductAttributeEbay()
{ {
if (isset($_POST['submitProductAttribute']) && isset($_POST['id_product_attribute']))
{
$params = array();
$params['id_product_attribute'] = (int)$_POST['id_product_attribute'];
if ($params['id_product_attribute'] > 0)
{
$id_product = Db::getInstance()->getValue('SELECT `id_product` FROM `'._DB_PREFIX_.'product_attribute` WHERE `id_product_attribute` = '.(int)$params['id_product_attribute']); $id_product = Db::getInstance()->getValue('SELECT `id_product` FROM `'._DB_PREFIX_.'product_attribute` WHERE `id_product_attribute` = '.(int)$params['id_product_attribute']);
$params['product'] = new Product($id_product); $params['product'] = new Product($id_product);
$this->hookaddproduct($params); $this->hookaddproduct($params);
}
}
} }
public function hookdeleteproduct($params) { $this->hookaddproduct($params); } public function hookdeleteproduct($params) { $this->hookaddproduct($params); }
public function hookheader($params) { $this->hookbackOfficeTop($params); } public function hookheader($params) { $this->hookbackOfficeTop($params); }
@@ -1633,6 +1654,31 @@ class Ebay extends Module
'picturesLarge' => $picturesLarge, 'picturesLarge' => $picturesLarge,
); );
// Fix hook update product
if (isset($this->context->employee) && $this->context->employee->id > 0 && isset($_POST['submitProductAttribute']) && isset($_POST['id_product_attribute']) && isset($_POST['attribute_mvt_quantity']) && isset($_POST['id_mvt_reason']))
{
if (substr(_PS_VERSION_, 0, 3) == '1.3')
{
$id_product_attribute_fix = (int)$_POST['id_product_attribute'];
$quantity_fix = (int)$_POST['attribute_quantity'];
if ($id_product_attribute_fix > 0 && $quantity_fix > 0 && isset($datas['variations'][$product->id.'-'.$id_product_attribute_fix]['quantity']))
$datas['variations'][$product->id.'-'.$id_product_attribute_fix]['quantity'] = (int)$quantity_fix;
}
else
{
$action = Db::getInstance()->getValue('SELECT `sign` FROM `'._DB_PREFIX_.'stock_mvt_reason` WHERE `id_stock_mvt_reason` = '.(int)$_POST['id_mvt_reason']);
$id_product_attribute_fix = (int)$_POST['id_product_attribute'];
$quantity_fix = (int)$_POST['attribute_mvt_quantity'];
if ($id_product_attribute_fix > 0 && $quantity_fix > 0 && isset($datas['variations'][$product->id.'-'.$id_product_attribute_fix]['quantity']))
{
if ($action > 0)
$datas['variations'][$product->id.'-'.$id_product_attribute_fix]['quantity'] += (int)$quantity_fix;
if ($action < 0)
$datas['variations'][$product->id.'-'.$id_product_attribute_fix]['quantity'] -= (int)$quantity_fix;
}
}
}
// Price Update // Price Update
if (isset($p['noPriceUpdate'])) if (isset($p['noPriceUpdate']))
$datas['noPriceUpdate'] = $p['noPriceUpdate']; $datas['noPriceUpdate'] = $p['noPriceUpdate'];
@@ -1646,9 +1692,14 @@ class Ebay extends Module
// Load eBay Description // Load eBay Description
$features = $product->getFrontFeatures((int)($this->id_lang));
$featuresHtml = '';
if (isset($features))
foreach ($features as $f)
$featuresHtml .= '<b>'.$f['name'].'</b> : '.$f['value'].'<br/>';
$datas['description'] = str_replace( $datas['description'] = str_replace(
array('{DESCRIPTION_SHORT}', '{DESCRIPTION}', '{EBAY_IDENTIFIER}', '{EBAY_SHOP}', '{SLOGAN}', '{PRODUCT_NAME}'), array('{DESCRIPTION_SHORT}', '{DESCRIPTION}', '{FEATURES}', '{EBAY_IDENTIFIER}', '{EBAY_SHOP}', '{SLOGAN}', '{PRODUCT_NAME}'),
array($datas['description_short'], $datas['description'], Configuration::get('EBAY_IDENTIFIER'), Configuration::get('EBAY_SHOP'), '', $product->name), array($datas['description_short'], $datas['description'], $featuresHtml, Configuration::get('EBAY_IDENTIFIER'), Configuration::get('EBAY_SHOP'), '', $product->name),
Configuration::get('EBAY_PRODUCT_TEMPLATE') Configuration::get('EBAY_PRODUCT_TEMPLATE')
); );
+2 -2
View File
@@ -2,9 +2,9 @@
<module> <module>
<name>ekomi</name> <name>ekomi</name>
<displayName><![CDATA[eKomi]]></displayName> <displayName><![CDATA[eKomi]]></displayName>
<version><![CDATA[1.1]]></version> <version><![CDATA[1.2]]></version>
<description><![CDATA[Adds an eKomi block]]></description> <description><![CDATA[Adds an eKomi block]]></description>
<author><![CDATA[]]></author> <author><![CDATA[PrestaShop]]></author>
<tab><![CDATA[advertising_marketing]]></tab> <tab><![CDATA[advertising_marketing]]></tab>
<is_configurable>1</is_configurable> <is_configurable>1</is_configurable>
<need_instance>0</need_instance> <need_instance>0</need_instance>
+21 -2
View File
@@ -33,17 +33,31 @@ class Ekomi extends Module
private $_html = ''; private $_html = '';
private $_postErrors = array(); private $_postErrors = array();
public $id_lang;
public $iso_lang;
function __construct() function __construct()
{ {
$this->name = 'ekomi'; $this->name = 'ekomi';
$this->tab = 'advertising_marketing'; $this->tab = 'advertising_marketing';
$this->version = 1.1; $this->author = 'PrestaShop';
$this->version = 1.2;
$this->need_instance = 0; $this->need_instance = 0;
parent::__construct(); parent::__construct();
$this->displayName = $this->l('eKomi'); $this->displayName = $this->l('eKomi');
$this->description = $this->l('Adds an eKomi block'); $this->description = $this->l('Adds an eKomi block');
if (self::isInstalled($this->name))
{
$this->id_lang = (int)Configuration::get('PS_LANG_DEFAULT');
$this->iso_lang = pSQL(Language::getIsoById($this->id_lang));
/* Check Mail Directory */
if (!file_exists(dirname(__FILE__.'/'.$this->iso_lang.'/')))
$this->warning .= $this->l('directory').' "'.$this->iso_lang.'" does not exist ';
}
} }
public function install() public function install()
@@ -115,6 +129,10 @@ class Ekomi extends Module
if (!Configuration::get('PS_EKOMI_EMAIL')) if (!Configuration::get('PS_EKOMI_EMAIL'))
return true; return true;
/* Check Mail Directory */
if (!file_exists(dirname(__FILE__.'/'.$this->iso_lang.'/')))
return true;
/* Email generation */ /* Email generation */
$subject = '[Ekomi-Prestashop] '.Configuration::get('PS_SHOP_NAME'); $subject = '[Ekomi-Prestashop] '.Configuration::get('PS_SHOP_NAME');
$templateVars = array( $templateVars = array(
@@ -125,8 +143,9 @@ class Ekomi extends Module
); );
/* Email sending */ /* Email sending */
if (!Mail::Send(1, 'ekomi', $subject, $templateVars, Configuration::get('PS_EKOMI_EMAIL'), NULL, $params['customer']->email, Configuration::get('PS_SHOP_NAME'), NULL, NULL, dirname(__FILE__).'/mails/')) if (!Mail::Send((int)$this->id_lang, 'ekomi', $subject, $templateVars, Configuration::get('PS_EKOMI_EMAIL'), NULL, $params['customer']->email, Configuration::get('PS_SHOP_NAME'), NULL, NULL, dirname(__FILE__).'/mails/'))
return true; return true;
return true; return true;
} }
} }
+1
View File
@@ -4,6 +4,7 @@ global $_MODULE;
$_MODULE = array(); $_MODULE = array();
$_MODULE['<{ekomi}prestashop>ekomi_c0858307dfd3d91768c79ec116820b60'] = 'eKomi'; $_MODULE['<{ekomi}prestashop>ekomi_c0858307dfd3d91768c79ec116820b60'] = 'eKomi';
$_MODULE['<{ekomi}prestashop>ekomi_d245187b3591f5f6f723ece2217bb637'] = 'Ajouter un bloc eKomi'; $_MODULE['<{ekomi}prestashop>ekomi_d245187b3591f5f6f723ece2217bb637'] = 'Ajouter un bloc eKomi';
$_MODULE['<{ekomi}prestashop>ekomi_5f8f22b8cdbaeee8cf857673a9b6ba20'] = 'répertoire';
$_MODULE['<{ekomi}prestashop>ekomi_f4d1ea475eaa85102e2b4e6d95da84bd'] = 'Confirmation'; $_MODULE['<{ekomi}prestashop>ekomi_f4d1ea475eaa85102e2b4e6d95da84bd'] = 'Confirmation';
$_MODULE['<{ekomi}prestashop>ekomi_c888438d14855d7d96a2724ee9c306bd'] = 'Configuration mise à jour'; $_MODULE['<{ekomi}prestashop>ekomi_c888438d14855d7d96a2724ee9c306bd'] = 'Configuration mise à jour';
$_MODULE['<{ekomi}prestashop>ekomi_f4f70727dc34561dfde1a3c529b6205c'] = 'Configuration'; $_MODULE['<{ekomi}prestashop>ekomi_f4f70727dc34561dfde1a3c529b6205c'] = 'Configuration';
@@ -112,6 +112,7 @@ class AdminEnvoiMoinsCher extends AdminTab
private function displayOrders($orders) private function displayOrders($orders)
{ {
$emc = new Envoimoinscher();
echo '<table cellspacing="0" cellpadding="0" class="table" align="center" style="margin:10px 0px 0px 25px;"> echo '<table cellspacing="0" cellpadding="0" class="table" align="center" style="margin:10px 0px 0px 25px;">
<tr> <tr>
<th><input type="checkbox" name="checkme" class="noborder" onclick="checkDelBoxes(this.form, \'ordersBox[]\', this.checked)" /></th> <th><input type="checkbox" name="checkme" class="noborder" onclick="checkDelBoxes(this.form, \'ordersBox[]\', this.checked)" /></th>
+1 -1
View File
@@ -2,7 +2,7 @@
<module> <module>
<name>fedexcarrier</name> <name>fedexcarrier</name>
<displayName><![CDATA[Fedex Carrier]]></displayName> <displayName><![CDATA[Fedex Carrier]]></displayName>
<version><![CDATA[1.2.4]]></version> <version><![CDATA[1.2.5]]></version>
<description><![CDATA[Offer your customers, different delivery methods with Fedex]]></description> <description><![CDATA[Offer your customers, different delivery methods with Fedex]]></description>
<author><![CDATA[PrestaShop]]></author> <author><![CDATA[PrestaShop]]></author>
<tab><![CDATA[shipping_logistics]]></tab> <tab><![CDATA[shipping_logistics]]></tab>
+7 -1
View File
@@ -56,7 +56,7 @@ class FedexCarrier extends CarrierModule
{ {
$this->name = 'fedexcarrier'; $this->name = 'fedexcarrier';
$this->tab = 'shipping_logistics'; $this->tab = 'shipping_logistics';
$this->version = '1.2.4'; $this->version = '1.2.5';
$this->author = 'PrestaShop'; $this->author = 'PrestaShop';
$this->limited_countries = array('us'); $this->limited_countries = array('us');
@@ -349,6 +349,10 @@ class FedexCarrier extends CarrierModule
$alert['webserviceTest'] = 1; $alert['webserviceTest'] = 1;
if (!extension_loaded('soap')) if (!extension_loaded('soap'))
$alert['soap'] = 1; $alert['soap'] = 1;
if (!ini_get('allow_url_fopen'))
$alert['url_fopen'] = 1;
if (!extension_loaded('openssl'))
$alert['openssl'] = 1;
if (!count($alert)) if (!count($alert))
@@ -360,6 +364,8 @@ class FedexCarrier extends CarrierModule
$this->_html .= '<br />'.(isset($alert['deliveryServices']) ? '<img src="'._PS_IMG_.'admin/warn2.png" />' : '<img src="'._PS_IMG_.'admin/module_install.png" />').' 2) '.$this->l('Select your available delivery service'); $this->_html .= '<br />'.(isset($alert['deliveryServices']) ? '<img src="'._PS_IMG_.'admin/warn2.png" />' : '<img src="'._PS_IMG_.'admin/module_install.png" />').' 2) '.$this->l('Select your available delivery service');
$this->_html .= '<br />'.(isset($alert['webserviceTest']) ? '<img src="'._PS_IMG_.'admin/warn2.png" />' : '<img src="'._PS_IMG_.'admin/module_install.png" />').' 3) '.$this->l('Webservice test connection').($this->_webserviceError ? ' : '.$this->_webserviceError : ''); $this->_html .= '<br />'.(isset($alert['webserviceTest']) ? '<img src="'._PS_IMG_.'admin/warn2.png" />' : '<img src="'._PS_IMG_.'admin/module_install.png" />').' 3) '.$this->l('Webservice test connection').($this->_webserviceError ? ' : '.$this->_webserviceError : '');
$this->_html .= '<br />'.(isset($alert['soap']) ? '<img src="'._PS_IMG_.'admin/warn2.png" />' : '<img src="'._PS_IMG_.'admin/module_install.png" />').' 4) '.$this->l('Soap is enabled'); $this->_html .= '<br />'.(isset($alert['soap']) ? '<img src="'._PS_IMG_.'admin/warn2.png" />' : '<img src="'._PS_IMG_.'admin/module_install.png" />').' 4) '.$this->l('Soap is enabled');
$this->_html .= '<br />'.(isset($alert['url_fopen']) ? '<img src="'._PS_IMG_.'admin/warn2.png" />' : '<img src="'._PS_IMG_.'admin/module_install.png" />').' 5) '.$this->l('Url fopen is enabled');
$this->_html .= '<br />'.(isset($alert['openssl']) ? '<img src="'._PS_IMG_.'admin/warn2.png" />' : '<img src="'._PS_IMG_.'admin/module_install.png" />').' 6) '.$this->l('OpenSSL is enabled');
} }
+1 -1
View File
@@ -2,7 +2,7 @@
<module> <module>
<name>gsitemap</name> <name>gsitemap</name>
<displayName><![CDATA[Google sitemap]]></displayName> <displayName><![CDATA[Google sitemap]]></displayName>
<version><![CDATA[1.7]]></version> <version><![CDATA[1.8]]></version>
<description><![CDATA[Generate your Google sitemap file]]></description> <description><![CDATA[Generate your Google sitemap file]]></description>
<author><![CDATA[PrestaShop]]></author> <author><![CDATA[PrestaShop]]></author>
<tab><![CDATA[seo]]></tab> <tab><![CDATA[seo]]></tab>
+64 -77
View File
@@ -156,73 +156,13 @@ XML;
$xml = new SimpleXMLElement($xmlString); $xml = new SimpleXMLElement($xmlString);
if (Configuration::get('PS_REWRITING_SETTINGS') AND sizeof($langs) > 1) if (Configuration::get('PS_REWRITING_SETTINGS') && count($langs) > 1)
foreach($langs as $lang) foreach($langs as $lang)
$this->_addSitemapNode($xml, Tools::getShopDomain(true, true).__PS_BASE_URI__.$lang['iso_code'].'/', '1.00', 'daily', date('Y-m-d')); $this->_addSitemapNode($xml, Tools::getShopDomain(true, true).__PS_BASE_URI__.$lang['iso_code'].'/', '1.00', 'daily', date('Y-m-d'));
else else
$this->_addSitemapNode($xml, Tools::getShopDomain(true, true).__PS_BASE_URI__, '1.00', 'daily', date('Y-m-d')); $this->_addSitemapNode($xml, Tools::getShopDomain(true, true).__PS_BASE_URI__, '1.00', 'daily', date('Y-m-d'));
/* CMS Generator */ /* Product Generator */
if (Configuration::get('GSITEMAP_ALL_CMS') OR !Module::isInstalled('blockcms'))
$sql = 'SELECT DISTINCT '.(Configuration::get('PS_REWRITING_SETTINGS') ? 'cl.id_cms, cl.link_rewrite, cl.id_lang' : 'cl.id_cms').'
FROM '._DB_PREFIX_.'cms_lang cl
LEFT JOIN '._DB_PREFIX_.'lang l ON (cl.id_lang = l.id_lang)
LEFT JOIN '._DB_PREFIX_.'cms_shop cs ON cs.id_cms = cl.id_cms
WHERE l.`active` = 1
AND cs.id_shop = '.$shopID.'
ORDER BY cl.id_cms, cl.id_lang ASC';
else if (Module::isInstalled('blockcms'))
$sql = 'SELECT DISTINCT '.(Configuration::get('PS_REWRITING_SETTINGS') ? 'cl.id_cms, cl.link_rewrite, cl.id_lang' : 'cl.id_cms').'
FROM '._DB_PREFIX_.'cms_block_page b
LEFT JOIN '._DB_PREFIX_.'cms_lang cl ON (b.id_cms = cl.id_cms)
LEFT JOIN '._DB_PREFIX_.'lang l ON (cl.id_lang = l.id_lang)
LEFT JOIN '._DB_PREFIX_.'cms_shop cs ON cs.id_cms = cl.id_cms
WHERE l.`active` = 1
AND cs.id_shop = '.$shopID.'
ORDER BY cl.id_cms, cl.id_lang ASC';
$cmss = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql);
foreach ($cmss AS $cms)
{
$tmpLink = Configuration::get('PS_REWRITING_SETTINGS') ? $this->context->link->getCMSLink((int)$cms['id_cms'], $cms['link_rewrite'], false, (int)$cms['id_lang']) : $this->context->link->getCMSLink((int)$cms['id_cms']);
$this->_addSitemapNode($xml, $tmpLink, '0.8', 'daily');
}
/* Categories Generator */
$limits = Category::getInterval($shop->getCategory());
if (Configuration::get('PS_REWRITING_SETTINGS'))
{
$sql = 'SELECT c.id_category, c.level_depth, link_rewrite, DATE_FORMAT(IF(date_upd,date_upd,date_add), \'%Y-%m-%d\') AS date_upd, cl.id_lang
FROM '._DB_PREFIX_.'category c
LEFT JOIN '._DB_PREFIX_.'category_lang cl ON c.id_category = cl.id_category AND cl.id_shop = '.$shopID.'
LEFT JOIN '._DB_PREFIX_.'lang l ON cl.id_lang = l.id_lang
WHERE l.`active` = 1
AND c.`active` = 1
AND c.id_category != 1
AND nleft >= '.$limits['nleft'].'
AND nright <= '.$limits['nright'].'
ORDER BY cl.id_category, cl.id_lang ASC';
$categories = Db::getInstance()->executeS($sql);
}
else
{
$sql = 'SELECT c.id_category, c.level_depth, DATE_FORMAT(IF(date_upd,date_upd,date_add), \'%Y-%m-%d\') AS date_upd
FROM '._DB_PREFIX_.'category c
WHERE nleft >= '.$limits['nleft'].'
AND nright <= '.$limits['nright'].'
ORDER BY c.id_category ASC';
$categories = Db::getInstance()->executeS($sql);
}
foreach($categories as $category)
{
if (($priority = 0.9 - ($category['level_depth'] / 10)) < 0.1)
$priority = 0.1;
$tmpLink = Configuration::get('PS_REWRITING_SETTINGS') ? $this->context->link->getCategoryLink((int)$category['id_category'], $category['link_rewrite'], (int)$category['id_lang']) : $this->context->link->getCategoryLink((int)$category['id_category']);
$this->_addSitemapNode($xml, $tmpLink, $priority, 'weekly', substr($category['date_upd'], 0, 10));
}
$sql = 'SELECT p.id_product, pl.link_rewrite, DATE_FORMAT(IF(date_upd,date_upd,date_add), \'%Y-%m-%d\') date_upd, pl.id_lang, cl.`link_rewrite` category, ean13, i.id_image, il.legend legend_image, ( $sql = 'SELECT p.id_product, pl.link_rewrite, DATE_FORMAT(IF(date_upd,date_upd,date_add), \'%Y-%m-%d\') date_upd, pl.id_lang, cl.`link_rewrite` category, ean13, i.id_image, il.legend legend_image, (
SELECT MIN(level_depth) SELECT MIN(level_depth)
FROM '._DB_PREFIX_.'product p2 FROM '._DB_PREFIX_.'product p2
@@ -245,7 +185,7 @@ XML;
$tmp = null; $tmp = null;
$res = null; $res = null;
foreach($products AS $product) foreach ($products as $product)
{ {
if ($tmp == $product['id_product']) if ($tmp == $product['id_product'])
$res[$tmp]['images'] []= array('id_image' => $product['id_image'], 'legend_image' => $product['legend_image']); $res[$tmp]['images'] []= array('id_image' => $product['id_image'], 'legend_image' => $product['legend_image']);
@@ -268,18 +208,65 @@ XML;
$sitemap = $this->_addSitemapNodeImage($sitemap, $product); $sitemap = $this->_addSitemapNodeImage($sitemap, $product);
} }
/* Categories Generator */
if (Configuration::get('PS_REWRITING_SETTINGS'))
$categories = Db::getInstance()->ExecuteS('
SELECT c.id_category, c.level_depth, link_rewrite, DATE_FORMAT(IF(date_upd,date_upd,date_add), \'%Y-%m-%d\') AS date_upd, cl.id_lang
FROM '._DB_PREFIX_.'category c
LEFT JOIN '._DB_PREFIX_.'category_lang cl ON c.id_category = cl.id_category
LEFT JOIN '._DB_PREFIX_.'lang l ON cl.id_lang = l.id_lang
WHERE l.`active` = 1 AND c.`active` = 1 AND c.id_category != 1
ORDER BY cl.id_category, cl.id_lang ASC');
else
$categories = Db::getInstance()->ExecuteS(
'SELECT c.id_category, c.level_depth, DATE_FORMAT(IF(date_upd,date_upd,date_add), \'%Y-%m-%d\') AS date_upd
FROM '._DB_PREFIX_.'category c
ORDER BY c.id_category ASC');
foreach($categories as $category)
{
if (($priority = 0.9 - ($category['level_depth'] / 10)) < 0.1)
$priority = 0.1;
$tmpLink = Configuration::get('PS_REWRITING_SETTINGS') ? $link->getCategoryLink((int)$category['id_category'], $category['link_rewrite'], (int)$category['id_lang']) : $link->getCategoryLink((int)$category['id_category']);
$this->_addSitemapNode($xml, htmlspecialchars($tmpLink), $priority, 'weekly', substr($category['date_upd'], 0, 10));
}
/* CMS Generator */
if (Configuration::get('GSITEMAP_ALL_CMS') || !Module::isInstalled('blockcms'))
$sql_cms = '
SELECT DISTINCT '.(Configuration::get('PS_REWRITING_SETTINGS') ? 'cl.id_cms, cl.link_rewrite, cl.id_lang' : 'cl.id_cms').
' FROM '._DB_PREFIX_.'cms_lang cl
LEFT JOIN '._DB_PREFIX_.'lang l ON (cl.id_lang = l.id_lang)
WHERE l.`active` = 1
ORDER BY cl.id_cms, cl.id_lang ASC';
else if (Module::isInstalled('blockcms'))
$sql_cms = '
SELECT DISTINCT '.(Configuration::get('PS_REWRITING_SETTINGS') ? 'cl.id_cms, cl.link_rewrite, cl.id_lang' : 'cl.id_cms').
' FROM '._DB_PREFIX_.'cms_block_page b
LEFT JOIN '._DB_PREFIX_.'cms_lang cl ON (b.id_cms = cl.id_cms)
LEFT JOIN '._DB_PREFIX_.'lang l ON (cl.id_lang = l.id_lang)
WHERE l.`active` = 1
ORDER BY cl.id_cms, cl.id_lang ASC';
$cmss = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql_cms);
foreach($cmss as $cms)
{
$tmpLink = Configuration::get('PS_REWRITING_SETTINGS') ? $link->getCMSLink((int)$cms['id_cms'], $cms['link_rewrite'], false, (int)$cms['id_lang']) : $link->getCMSLink((int)$cms['id_cms']);
$this->_addSitemapNode($xml, $tmpLink, '0.8', 'daily');
}
/* Add classic pages (contact, best sales, new products...) */ /* Add classic pages (contact, best sales, new products...) */
$pages = array( $pages = array(
'authentication' => true, 'supplier' => false,
'best-sales' => false,
'contact' => true,
'discount' => false,
'index' => false,
'manufacturer' => false, 'manufacturer' => false,
'new-products' => false, 'new-products' => false,
'prices-drop' => false, 'prices-drop' => false,
'supplier' => false, 'stores' => false,
'store' => false); 'authentication' => true,
'best-sales' => false,
'contact-form' => true);
// Don't show suppliers and manufacturers if they are disallowed // Don't show suppliers and manufacturers if they are disallowed
if (!Module::getInstanceByName('blockmanufacturer')->id && !Configuration::get('PS_DISPLAY_SUPPLIERS')) if (!Module::getInstanceByName('blockmanufacturer')->id && !Configuration::get('PS_DISPLAY_SUPPLIERS'))
@@ -290,11 +277,11 @@ XML;
// Generate nodes for pages // Generate nodes for pages
if(Configuration::get('PS_REWRITING_SETTINGS')) if(Configuration::get('PS_REWRITING_SETTINGS'))
foreach ($pages AS $page => $ssl) foreach ($pages as $page => $ssl)
foreach($langs as $lang) foreach($langs as $lang)
$this->_addSitemapNode($xml, $this->context->link->getPageLink($page, $ssl, $lang['id_lang']), '0.5', 'monthly'); $this->_addSitemapNode($xml, $this->context->link->getPageLink($page, $ssl, $lang['id_lang']), '0.5', 'monthly');
else else
foreach($pages AS $page => $ssl) foreach($pages as $page => $ssl)
$this->_addSitemapNode($xml, $this->context->link->getPageLink($page, $ssl), '0.5', 'monthly'); $this->_addSitemapNode($xml, $this->context->link->getPageLink($page, $ssl), '0.5', 'monthly');
$xmlString = $xml->asXML(); $xmlString = $xml->asXML();
@@ -344,14 +331,14 @@ XML;
private function _displaySitemap() private function _displaySitemap()
{ {
if (file_exists(GSITEMAP_FILE) AND filesize(GSITEMAP_FILE)) if (file_exists(GSITEMAP_FILE) && filesize(GSITEMAP_FILE))
{ {
$fp = fopen(GSITEMAP_FILE, 'r'); $fp = fopen(GSITEMAP_FILE, 'r');
$fstat = fstat($fp); $fstat = fstat($fp);
fclose($fp); fclose($fp);
$xml = simplexml_load_file(GSITEMAP_FILE); $xml = simplexml_load_file(GSITEMAP_FILE);
$nbPages = sizeof($xml->url); $nbPages = count($xml->url);
$this->_html .= '<p>'.$this->l('Your Google sitemap file is online at the following address:').'<br /> $this->_html .= '<p>'.$this->l('Your Google sitemap file is online at the following address:').'<br />
<a href="'.Tools::getShopDomain(true, true).__PS_BASE_URI__.'sitemap.xml" target="_blank"><b>'.Tools::getShopDomain(true, true).__PS_BASE_URI__.'sitemap.xml</b></a></p><br />'; <a href="'.Tools::getShopDomain(true, true).__PS_BASE_URI__.'sitemap.xml" target="_blank"><b>'.Tools::getShopDomain(true, true).__PS_BASE_URI__.'sitemap.xml</b></a></p><br />';
@@ -380,15 +367,15 @@ XML;
public function getContent() public function getContent()
{ {
$this->_html .= '<h2>'.$this->l('Search Engine Optimization').'</h2> $this->_html .= '<h2>'.$this->l('Search Engine Optimization').'</h2>
'.$this->l('See').' <a href="https://www.google.com/webmasters/tools/docs/en/about.html" style="font-weight:bold;text-decoration:underline;" target="_blank"> '.$this->l('See').' <a href="http://www.google.com/support/webmasters/bin/answer.py?hl=en&answer=156184&from=40318&rd=1" style="font-weight:bold;text-decoration:underline;" target="_blank">
'.$this->l('this page').'</a> '.$this->l('for more information').'<br /><br />'; '.$this->l('this page').'</a> '.$this->l('for more information').'<br /><br />';
if (Tools::isSubmit('btnSubmit')) if (Tools::isSubmit('btnSubmit'))
{ {
$this->_postValidation(); $this->_postValidation();
if (!sizeof($this->_postErrors)) if (!count($this->_postErrors))
$this->_postProcess(); $this->_postProcess();
else else
foreach ($this->_postErrors AS $err) foreach ($this->_postErrors as $err)
$this->_html .= '<div class="alert error">'.$err.'</div>'; $this->_html .= '<div class="alert error">'.$err.'</div>';
} }
+17
View File
@@ -0,0 +1,17 @@
<?php
include_once('../../config/config.inc.php');
include_once('../../init.php');
include_once('../../modules/importerosc/importerosc.php');
if (!Tools::getValue('ajax') || Tools::getValue('token') != sha1(_COOKIE_KEY_.'importosc'))
die('INVALID TOKEN');
$importOsc = new importerosc();
$importOsc->server = Tools::getValue('server');
$importOsc->user = Tools::getValue('user');
$importOsc->passwd = Tools::getValue('password');
$importOsc->database = Tools::getValue('database');
$importOsc->prefix = Tools::getValue('prefix');
die($importOsc->createLevelAndCalculate());
+5
View File
@@ -20,3 +20,8 @@ $_MODULE['<{importerosc}prestashop>importerosc_14ae0ea02f571a833786d13d9ca6a897'
$_MODULE['<{importerosc}prestashop>importerosc_e307db07b3975fef922a80d07455ee5e'] = 'Base de données'; $_MODULE['<{importerosc}prestashop>importerosc_e307db07b3975fef922a80d07455ee5e'] = 'Base de données';
$_MODULE['<{importerosc}prestashop>importerosc_dac130bdd2c5492a8108a4145bd9f04a'] = 'Préfixe base de données'; $_MODULE['<{importerosc}prestashop>importerosc_dac130bdd2c5492a8108a4145bd9f04a'] = 'Préfixe base de données';
$_MODULE['<{importerosc}prestashop>importerosc_6bdc02625540b5264cffe801c37a82dd'] = '(Le préfixe est optionnel. Si toute votre base de données commence par \"pref_\", votre préfixe est \"pref_\")'; $_MODULE['<{importerosc}prestashop>importerosc_6bdc02625540b5264cffe801c37a82dd'] = '(Le préfixe est optionnel. Si toute votre base de données commence par \"pref_\", votre préfixe est \"pref_\")';
$_MODULE['<{importerosc}prestashop>importerosc_4685343b5e2e0f0fbee63dddafde693f'] = 'Vous essayez d\'importer des catégories et nous avons détecté que votre base de données osCommerce n\'ont pas le champs \"niveau\" dans la table catégorie. Vous devez avoir ce champs pour continuer l\'importation de catégories.';
$_MODULE['<{importerosc}prestashop>importerosc_16f35420186575c2a1d9c0b59edf6ad3'] = 'Cliquez ici pour ajouter et de calculer le champs niveau';
$_MODULE['<{importerosc}prestashop>importerosc_fced104d747e0855ceff3020653104ab'] = 'Le champ \"niveau\" a été créé et calculé, vous pouvez continuer';
$_MODULE['<{importerosc}prestashop>importerosc_b405d0bebeedbdc1773a44ac36b8ffc4'] = 'Il est fortement recommandé de sauvegarder votre base de données avant de continuer. Avez-vous fait une sauvegarde?';
$_MODULE['<{importerosc}prestashop>importerosc_9f95fc55011203d91d50a0ed512f805f'] = 'Impossible de \"ALTER TABLE\"';
+145 -6
View File
@@ -61,10 +61,14 @@ class importerosc extends ImportModule
public function displaySpecificOptions() public function displaySpecificOptions()
{ {
$html = '';
if (!$this->checkCategoriesLevel())
$html .= $this->displayCategoriesLevelConf();
$langagues = $this->executeS('SELECT * FROM `'.bqSQL($this->prefix).'languages`'); $langagues = $this->executeS('SELECT * FROM `'.bqSQL($this->prefix).'languages`');
$curencies = $this->executeS('SELECT * FROM `'.bqSQL($this->prefix).'currencies`'); $curencies = $this->executeS('SELECT * FROM `'.bqSQL($this->prefix).'currencies`');
$html = '<label style=\'width:220px\'>'.$this->l('Default osCommerce language : ').'</label> $html .= '<label style=\'width:220px\'>'.$this->l('Default osCommerce language : ').'</label>
<div class="margin-form"> <div class="margin-form">
<select name=\'defaultOscLang\'><option value=\'0\'>------</option>'; <select name=\'defaultOscLang\'><option value=\'0\'>------</option>';
foreach($langagues AS $lang) foreach($langagues AS $lang)
@@ -148,9 +152,10 @@ class importerosc extends ImportModule
$identifier = 'id_country'; $identifier = 'id_country';
$defaultIdLang = $this->getDefaultIdLang(); $defaultIdLang = $this->getDefaultIdLang();
$countries = $this->executeS(' $countries = $this->executeS('
SELECT countries_id as id_country, countries_name as name, countries_iso_code_2 as iso_code, `'.bqSQL($defaultIdLang).'̀ as id_lang, SELECT countries_id as id_country, countries_name as name, countries_iso_code_2 as iso_code, '.(int)$defaultIdLang.' as id_lang,
1 as id_zone, 0 as id_currency, 1 as contains_states, 1 as need_identification_number, 1 as active, 1 as display_tax_label 1 as id_zone, 0 as id_currency, 1 as contains_states, 1 as need_identification_number, 1 as active, 1 as display_tax_label
FROM `'.bqSQL($this->prefix).'countries` as c LIMIT '.(int)($limit).' , '.(int)$nrb_import); FROM `'.bqSQL($this->prefix).'countries` as c LIMIT '.(int)($limit).' , '.(int)$nrb_import);
return $this->autoFormat($countries, $identifier, $keyLanguage, $multiLangFields); return $this->autoFormat($countries, $identifier, $keyLanguage, $multiLangFields);
} }
@@ -219,19 +224,19 @@ class importerosc extends ImportModule
$multiLangFields = array('name', 'link_rewrite'); $multiLangFields = array('name', 'link_rewrite');
$keyLanguage = 'id_lang'; $keyLanguage = 'id_lang';
$identifier = 'id_category'; $identifier = 'id_category';
$categories = $this->executeS(' $categories = $this->executeS('
SELECT c.categories_id as id_category, c.parent_id as id_parent, 0 as level_depth, cd.language_id as id_lang, cd.categories_name as name , 1 as active, categories_image as images SELECT c.categories_id as id_category, c.parent_id as id_parent, level as level_depth, cd.language_id as id_lang, cd.categories_name as name , 1 as active, categories_image as images
FROM `'.bqSQL($this->prefix).'categories` c FROM `'.bqSQL($this->prefix).'categories` c
LEFT JOIN `'.bqSQL($this->prefix).'categories_description` cd ON (c.categories_id = cd.categories_id) LEFT JOIN `'.bqSQL($this->prefix).'categories_description` cd ON (c.categories_id = cd.categories_id)
WHERE cd.categories_name IS NOT NULL AND cd.language_id IS NOT NULL WHERE cd.categories_name IS NOT NULL AND cd.language_id IS NOT NULL
ORDER BY c.categories_id, cd.language_id ORDER BY c.level ASC , c.`categories_id`
LIMIT '.(int)($limit).' , '.(int)$nrb_import); LIMIT '.(int)($limit).' , '.(int)$nrb_import);
foreach($categories as& $cat) foreach($categories as& $cat)
{ {
$cat['link_rewrite'] = Tools::link_rewrite($cat['name']); $cat['link_rewrite'] = Tools::link_rewrite($cat['name']);
$cat['images'] = array(Tools::getProtocol().Tools::getValue('shop_url').'/images/'.$cat['images']); $cat['images'] = array(Tools::getProtocol().Tools::getValue('shop_url').'/images/'.$cat['images']);
} }
return $this->autoFormat($categories, $identifier, $keyLanguage, $multiLangFields); return $this->autoFormat($categories, $identifier, $keyLanguage, $multiLangFields);
} }
@@ -256,6 +261,7 @@ class importerosc extends ImportModule
SELECT p.`products_options_values_id` as id_attribute, p.`products_options_values_name` as name, p.`language_id` as id_lang , po.`products_options_id` as id_attribute_group SELECT p.`products_options_values_id` as id_attribute, p.`products_options_values_name` as name, p.`language_id` as id_lang , po.`products_options_id` as id_attribute_group
FROM `'.bqSQL($this->prefix).'products_options_values` p FROM `'.bqSQL($this->prefix).'products_options_values` p
LEFT JOIN `'.bqSQL($this->prefix).'products_options_values_to_products_options` po ON (po.products_options_values_id = p.products_options_values_id) LEFT JOIN `'.bqSQL($this->prefix).'products_options_values_to_products_options` po ON (po.products_options_values_id = p.products_options_values_id)
ORDER BY p.`products_options_values_id`
LIMIT '.(int)($limit).' , '.(int)$nrb_import); LIMIT '.(int)($limit).' , '.(int)$nrb_import);
return $this->autoFormat($countries, $identifier, $keyLanguage, $multiLangFields); return $this->autoFormat($countries, $identifier, $keyLanguage, $multiLangFields);
} }
@@ -274,6 +280,7 @@ class importerosc extends ImportModule
FROM `'.bqSQL($this->prefix).'products` p FROM `'.bqSQL($this->prefix).'products` p
LEFT JOIN `'.bqSQL($this->prefix).'products_description` pd ON (p.products_id = pd.products_id) LEFT JOIN `'.bqSQL($this->prefix).'products_description` pd ON (p.products_id = pd.products_id)
WHERE pd.products_name IS NOT NULL AND pd.language_id IS NOT NULL WHERE pd.products_name IS NOT NULL AND pd.language_id IS NOT NULL
ORDER BY p.`products_id`
LIMIT '.(int)($limit).' , '.(int)$nrb_import); LIMIT '.(int)($limit).' , '.(int)$nrb_import);
$this->Execute('CREATE TABLE IF NOT EXISTS`products_images` ( $this->Execute('CREATE TABLE IF NOT EXISTS`products_images` (
@@ -462,7 +469,8 @@ class importerosc extends ImportModule
public function displayConfigConnector() public function displayConfigConnector()
{ {
$content = '<label>'.$this->l('Server').' : </label> $content = '<script>var type_connector = "db";</script>
<label>'.$this->l('Server').' : </label>
<div class="margin-form"> <div class="margin-form">
<input type="text" name="server" id="server" value=""> <input type="text" name="server" id="server" value="">
<p>'.$this->l('(eg : mysql.mydomain.com)').'</p> <p>'.$this->l('(eg : mysql.mydomain.com)').'</p>
@@ -488,6 +496,137 @@ class importerosc extends ImportModule
return $content; return $content;
} }
public function checkCategoriesLevel()
{
$columns = $this->ExecuteS('SHOW COLUMNS FROM `'.bqSQL($this->prefix).'categories` ');
foreach($columns as $field)
if ($field['Field'] == 'level')
return true;
return false;
}
public function displayCategoriesLevelConf()
{
$html = '<div class="warn" id="warn_category_level" style="width:450px;display:none">
<img src="../img/admin/warn2.png">
'.$this->l('You are trying to import categories and we\'ve detected, that your oscommerce database don\'t have the field "level" in the table categorie. You must have this field to continue the import of categories.');
$html .= '<button class="button" onclick="addAndCalculateLevel();" style="padding:10px;font-size:13px;text:align:center">'.$this->l('Click to add and calculate the filed "level" .').'</button> <span id="loading" style="display:none"><img src="../img/loader.gif"></span></div>
<div class="conf" id="conf_category_level" style="width:450px;display:none"><img src="../img/admin/ok2.png">'.$this->l('Level field\'s has been created and calculated, You can continue').'</div>';
$html .= '
<script>
$(document).ready(function (){
function checkCategorySelected()
{
if ($(\'#id_category_on:radio\').attr(\'checked\'))
{
$(\'#warn_category_level\').show();
$(\'#checkAndSaveConfig\').attr(\'disabled\', \'disabled\');
$(\'#checkAndSaveConfig\').hide();
}
else
{
$(\'#warn_category_level\').hide();
$(\'#checkAndSaveConfig\').removeAttr(\'disabled\');
$(\'#checkAndSaveConfig\').show();
}
}
checkCategorySelected();
$(\'input[name="getCategories"]\').change( function () {
checkCategorySelected();
});
});
function addAndCalculateLevel()
{
if (confirm(\''.$this->l('It is highly recommended to backup your database before proceeding. Did you make a backup?').'\'))
{
$(\'#loading\').show();
$.ajax({
type: "GET",
url: "../modules/importerosc/ajax.php",
async: false,
cache: false,
dataType : "json",
data: "ajax=true&token='.sha1(_COOKIE_KEY_.'importosc').'&server="+$(\'#server\').val()+"&user="+$(\'#user\').val()+"&password="+$(\'#password\').val()+"&database="+$(\'#database\').val()+"&prefix="+$(\'#prefix\').val() ,
success: function (jsonData)
{
if (jsonData.hasError)
alert(jsonData.error);
else
{
$(\'#warn_category_level\').remove();
$(\'#checkAndSaveConfig\').removeAttr(\'disabled\');
$(\'#checkAndSaveConfig\').show();
$(\'#conf_category_level\').show();
}
},
error: function (XMLHttpRequest, textStatus, errorThrown)
{
}
});
}
return false;
}
</script>';
return $html;
}
public function createLevelAndCalculate()
{
if ($this->checkCategoriesLevel())
die('{"hasError" : false}');
if ($this->createLevel())
$this->calculateLevel();
else
die('{"hasError" : true, "error" : "'.$this->l('Can not ALTER TABLE').'"}');
}
public function createLevel()
{
return $this->Execute('ALTER TABLE `'.bqSQL($this->prefix).'categories` ADD `level` INT NOT NULL');
}
public function calculateLevel()
{
$this->updateLevel($this->getSubCat(0), 1);
die('{"hasError" : false}');
}
public function updateLevel($ids_cat, $level = 1)
{
$this->Execute('
UPDATE `'.bqSQL($this->prefix).'categories`
SET level = '.(int)$level.'
WHERE categories_id IN ('.implode(',', $ids_cat).')');
foreach($ids_cat as $id)
if ($sub_cat = $this->getSubCat($id))
$this->updateLevel($sub_cat, $level + 1);
}
public function getSubCat($id_parent)
{
$result = $this->ExecuteS('SELECT `categories_id` FROM `'.bqSQL($this->prefix).'categories` WHERE `parent_id`='.(int)$id_parent);
if (!is_array($result) OR empty($result))
return false;
return $this->formatCategoriesIds($result);
}
public function formatCategoriesIds($result)
{
$return = array();
foreach($result as $key => $val)
$return[] = $val['categories_id'];
return $return;
}
} }
?> ?>
+2 -2
View File
@@ -544,7 +544,7 @@ class Loyalty extends Module
$loyalty->id_customer = (int)$params['customer']->id; $loyalty->id_customer = (int)$params['customer']->id;
$loyalty->id_order = (int)$params['order']->id; $loyalty->id_order = (int)$params['order']->id;
$loyalty->points = LoyaltyModule::getOrderNbPoints($params['order']); $loyalty->points = LoyaltyModule::getOrderNbPoints($params['order']);
if ((int)(Configuration::get('PS_LOYALTY_NONE_AWARD')) AND (int)($loyalty->points) == 0) if (!Configuration::get('PS_LOYALTY_NONE_AWARD') AND (int)$loyalty->points == 0)
$loyalty->id_loyalty_state = LoyaltyStateModule::getNoneAwardId(); $loyalty->id_loyalty_state = LoyaltyStateModule::getNoneAwardId();
else else
$loyalty->id_loyalty_state = LoyaltyStateModule::getDefaultId(); $loyalty->id_loyalty_state = LoyaltyStateModule::getDefaultId();
@@ -569,7 +569,7 @@ class Loyalty extends Module
{ {
if (!Validate::isLoadedObject($loyalty = new LoyaltyModule(LoyaltyModule::getByOrderId($order->id)))) if (!Validate::isLoadedObject($loyalty = new LoyaltyModule(LoyaltyModule::getByOrderId($order->id))))
return false; return false;
if ((int)(Configuration::get('PS_LOYALTY_NONE_AWARD')) AND $loyalty->id_loyalty_state == LoyaltyStateModule::getNoneAwardId()) if ((int)Configuration::get('PS_LOYALTY_NONE_AWARD') AND $loyalty->id_loyalty_state == LoyaltyStateModule::getNoneAwardId())
return true; return true;
if ($newOrder->id == $this->loyaltyStateValidation->id_order_state) if ($newOrder->id == $this->loyaltyStateValidation->id_order_state)
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 673 B

+47
View File
@@ -0,0 +1,47 @@
// JavaScript Document
$(document).ready(function() {
$('#button_test_mailjet').click(function() {
$("#mailjet_test_ok").hide();
$("#mailjet_test_ko").hide();
$("#div_email_test").show(500);
});
$('#button_send_mailjet').click(function() {
var token = $(this).attr('rel');
$("#button_test_mailjet").hide();
$("#image_ajax_mailjet").show();
$("#div_email_test").hide();
$.ajax({
type: 'GET',
url: "../modules/mailjet/ajax.php",
async: true,
cache: false,
dataType : "html",
data: 'token=' + token + '&mailjet_api_key=' + $("#mailjet_api_key").val() + '&mailjet_secret_key=' + $("#mailjet_secret_key").val() + '&email_from=' + escape($("#email_from").val()),
success: function(html)
{
$("#button_test_mailjet").show();
$("#image_ajax_mailjet").hide();
var retour = html.split("|");
if (retour[0] == "true")
{
$("#mailjet_test_ok").show(500);
} else {
$("#mailjet_activation_no").attr('checked', true);
$("#mailjet_error_message").html(retour[1]);
$("#mailjet_test_ko").show(500);
}
},
error: function(jqxhr, status, errorThrown)
{
$("#mailjet_activation_no").attr('checked', true);
$("#mailjet_error_message").html(errorThrown);
$("#mailjet_test_ko").show(500);
}
});
});
});
+67
View File
@@ -0,0 +1,67 @@
<?php
/*
* Copyright (c) 2011 Mailjet SAS
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author Dream me up
* @copyright 2011 Mailjet SAS
* @version Release: $Revision: 1.4 $
* @license hhttp://opensource.org/licenses/mit-license MIT License
* International Registred Trademark & Property of Mailjet SAS
*/
require('../../config/config.inc.php');
require('mailjet.php');
if (Tools::getValue('token') == '' || Tools::getValue('token') != Configuration::get('MAILJET_TOKEN'))
die('Invalid Token');
$obj_mailjet = new Mailjet();
$email_from = urldecode($_GET['email_from']);
try {
$sujet = $obj_mailjet->l('Mailjet Test E-mail');
$message = $obj_mailjet->l('Hello').",\r\n\r\n".$obj_mailjet->l('This E-mail confirms you that Mailjet has successfully been installed on your shop.');
$result = Mail::sendMailTest(true, "in.mailjet.com", $message, $sujet, "text/plain", $email_from, $email_from, $_GET['mailjet_api_key'], $_GET['mailjet_secret_key'], $smtpPort = 465, "tls");
if ($result === true)
echo "true";
else
{
if ($result == 999)
$result = $obj_mailjet->l('The E-mail was not successfully sent');
echo "false|".$result;
reset_config_mailjet();
}
} catch(Exception $e) {
echo "false|".$e->getMessage();
reset_config_mailjet();
}
function reset_config_mailjet()
{
Configuration::updateValue('MAILJET_ACTIVATE', 0);
Configuration::updateValue('PS_MAIL_METHOD', 1);
Configuration::updateValue('PS_MAIL_SERVER', "");
Configuration::updateValue('PS_MAIL_USER', "");
Configuration::updateValue('PS_MAIL_PASSWD', "");
Configuration::updateValue('PS_MAIL_SMTP_ENCRYPTION', "");
Configuration::updateValue('PS_MAIL_SMTP_PORT', 25);
}
+12
View File
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8" ?>
<module>
<name>mailjet</name>
<displayName><![CDATA[Mailjet]]></displayName>
<version><![CDATA[1.0]]></version>
<description><![CDATA[This modules sends through Mailjet all email coming from your Prestashop installation]]></description>
<author><![CDATA[]]></author>
<tab><![CDATA[front_office_features]]></tab>
<is_configurable>1</is_configurable>
<need_instance>1</need_instance>
<limited_countries></limited_countries>
</module>
+29
View File
@@ -0,0 +1,29 @@
<?php
global $_MODULE;
$_MODULE = array();
$_MODULE['<{mailjet}prestashop>ajax_64b88c69849c8b362e7f97c6eaab574d'] = 'E-mail de test';
$_MODULE['<{mailjet}prestashop>ajax_8b1a9953c4611296a827abf8c47804d7'] = 'Bonjour';
$_MODULE['<{mailjet}prestashop>ajax_c38b28d6adf75b2b2936de1f2168b6e6'] = 'Cet e-mail vous confirme que Mailjet a été correctement installé sur votre boutique.';
$_MODULE['<{mailjet}prestashop>ajax_cfc9dca01a0503813a5f9585ba6780d1'] = 'L\'e-mail n\'a pas pu être envoyé';
$_MODULE['<{mailjet}prestashop>mailjet_c127c5641733ecedcce7c33ed849401e'] = 'Ce module vous permet d\'envoyer vos e-mail PrestaShop via Mailjet';
$_MODULE['<{mailjet}prestashop>mailjet_9ccb2eaeed6c7e95ecaf108373619300'] = 'Ce module est activé mais la clé API ou la clé secrète ne sont pas correctement remplies.';
$_MODULE['<{mailjet}prestashop>mailjet_64b88c69849c8b362e7f97c6eaab574d'] = 'E-mail de test';
$_MODULE['<{mailjet}prestashop>mailjet_8b1a9953c4611296a827abf8c47804d7'] = 'Bonjour';
$_MODULE['<{mailjet}prestashop>mailjet_c38b28d6adf75b2b2936de1f2168b6e6'] = 'Cet e-mail vous confirme que Mailjet a été correctement installé sur votre boutique.';
$_MODULE['<{mailjet}prestashop>mailjet_cfc9dca01a0503813a5f9585ba6780d1'] = 'L\'e-mail n\'a pas pu être envoyé';
$_MODULE['<{mailjet}prestashop>mailjet_c888438d14855d7d96a2724ee9c306bd'] = 'Configuraiton mise à jour';
$_MODULE['<{mailjet}prestashop>mailjet_9e3f29ea93d121e237085def4ee29f74'] = 'Ce module vous permet d\'envoyer vos e-mail PrestaShop (et ceux de la plupart de vos modules) via Mailjet';
$_MODULE['<{mailjet}prestashop>mailjet_f4f70727dc34561dfde1a3c529b6205c'] = 'Configuration';
$_MODULE['<{mailjet}prestashop>mailjet_6ad7efc596f5720291e748ff2185733f'] = 'Clé API Mailjet';
$_MODULE['<{mailjet}prestashop>mailjet_a02496bddaea8e6616bf285fc37973be'] = 'Clé secrète Mailjet';
$_MODULE['<{mailjet}prestashop>mailjet_ed1d12d25d1a1ec139c84015ae766a7f'] = 'Envoyer vos e-mails via Mailjet';
$_MODULE['<{mailjet}prestashop>mailjet_93cba07454f06a4a960172bbd6e2a435'] = 'Oui';
$_MODULE['<{mailjet}prestashop>mailjet_bafd7322c6e97d25b6299b5d6fe8920b'] = 'Non';
$_MODULE['<{mailjet}prestashop>mailjet_63ade95d66cda885393aab6f5f5e4e76'] = 'Authentification réussie ! Votre configuration est correcte.';
$_MODULE['<{mailjet}prestashop>mailjet_424ab525513861737da68b0700b5cd20'] = 'Une erreur est survenue :';
$_MODULE['<{mailjet}prestashop>mailjet_79dfc1f365ed194bb9fc0da20f1a3857'] = 'Si vous ne comprenez pas cette erreur, veuillez contacter';
$_MODULE['<{mailjet}prestashop>mailjet_d496cec7c628e4438ee719315942e2d6'] = ' E-mail de / à :';
$_MODULE['<{mailjet}prestashop>mailjet_94966d90747b97d1f0f206c98a8b1ac3'] = 'Envoyer';
$_MODULE['<{mailjet}prestashop>mailjet_540caa299a719ee320cf416ffae7adca'] = 'Test de configuration';
$_MODULE['<{mailjet}prestashop>mailjet_d4dccb8ca2dac4e53c01bd9954755332'] = 'Sauvegarder la configuration';
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

+213
View File
@@ -0,0 +1,213 @@
<?php
/*
* Copyright (c) 2011 Mailjet SAS
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @author Dream me up
* @copyright 2011 Mailjet SAS
* @version Release: $Revision: 1.4 $
* @license hhttp://opensource.org/licenses/mit-license MIT License
* International Registred Trademark & Property of Mailjet SAS
*/
// Security
if (!defined('_PS_VERSION_'))
exit;
class Mailjet extends Module
{
/*
** Construct Method
**
*/
public function __construct()
{
$this->name = 'mailjet';
$this->tab = 'front_office_features';
$this->version = '1.0';
$this->displayName = 'Mailjet';
parent::__construct();
$this->description = $this->l('This modules sends through Mailjet all email coming from your Prestashop installation');
if (Configuration::get('MAILJET_ACTIVATE') == 1 && (strlen(Configuration::get('MAILJET_API_KEY')) < 3 || strlen(Configuration::get('MAILJET_SECRET_KEY')) < 3))
$this->warning = $this->l('The module is activated but api key or secret key are not correctly set.');
// Defines ajax lang variables in way to translate them
$this->l('Mailjet Test E-mail');
$this->l('Hello');
$this->l('This E-mail confirms you that Mailjet has successfully been installed on your shop.');
$this->l('The E-mail was not successfully sent');
}
/*
** Install / Uninstall Methods
**
*/
public function install()
{
// Can't do anything else for retrocompatibility
if (md5_file(dirname(__FILE__).'/override/Message.php') != md5_file(dirname(__FILE__).'/../../tools/swift/Swift/Message.php'))
return false;
if (!@copy(dirname(__FILE__).'/override/Message-mailjet.php', dirname(__FILE__).'/../../tools/swift/Swift/Message.php'))
return false;
// Create Token
Configuration::updateValue('MAILJET_TOKEN', md5(rand()));
// Install module
if (!parent::install())
return false;
return true;
}
public function uninstall()
{
// Can't do anything else for retrocompatibility
if (md5_file(dirname(__FILE__).'/override/Message-mailjet.php') != md5_file(dirname(__FILE__).'/../../tools/swift/Swift/Message.php'))
return false;
if (!@copy(dirname(__FILE__).'/override/Message.php', dirname(__FILE__).'/../../tools/swift/Swift/Message.php'))
return false;
// Uninstall module
Configuration::updateValue('PS_MAIL_METHOD', 1);
Configuration::updateValue('PS_MAIL_SERVER', "");
Configuration::updateValue('PS_MAIL_USER', "");
Configuration::updateValue('PS_MAIL_PASSWD', "");
Configuration::updateValue('PS_MAIL_SMTP_ENCRYPTION', "");
Configuration::updateValue('PS_MAIL_SMTP_PORT', 25);
if (!Configuration::deleteByName('MAILJET_TOKEN') OR !Configuration::deleteByName('MAILJET_SECRET_KEY') OR !Configuration::deleteByName('MAILJET_API_KEY') OR !parent::uninstall())
return false;
return true;
}
/*
** Form Config Methods
**
*/
public function getContent()
{
global $cookie;
$lang = new Language((int)($cookie->id_lang));
if (!in_array($lang->iso_code, array('fr', 'en', 'es')))
$lang->iso_code = 'en';
$output = '<script type="text/javascript" src="'.__PS_BASE_URI__.'modules/'.$this->name.'/ajax.js"></script>
<p style="margin-bottom: 5px;"><img src="'.__PS_BASE_URI__.'modules/'.$this->name.'/logo-mailjet.jpg" alt="" /></p>';
if (Tools::isSubmit('submitMailjet'))
{
Configuration::updateValue('MAILJET_API_KEY', pSQL(Tools::getValue('mailjet_api_key')));
Configuration::updateValue('MAILJET_SECRET_KEY', pSQL(Tools::getValue('mailjet_secret_key')));
Configuration::updateValue('MAILJET_ACTIVATE', (int)(Tools::getValue('mailjet_activation')));
// If mailjet activation, let's configure
if ((int)Tools::getValue('mailjet_activation') == 1)
{
Configuration::updateValue('PS_MAIL_METHOD', 2);
Configuration::updateValue('PS_MAIL_SERVER', "in.mailjet.com");
Configuration::updateValue('PS_MAIL_USER', pSQL(Configuration::get('MAILJET_API_KEY')));
Configuration::updateValue('PS_MAIL_PASSWD', pSQL(Configuration::get('MAILJET_SECRET_KEY')));
Configuration::updateValue('PS_MAIL_SMTP_ENCRYPTION', "tls");
Configuration::updateValue('PS_MAIL_SMTP_PORT', 465);
}
else
{
Configuration::updateValue('PS_MAIL_METHOD', 1);
Configuration::updateValue('PS_MAIL_SERVER', "");
Configuration::updateValue('PS_MAIL_USER', "");
Configuration::updateValue('PS_MAIL_PASSWD', "");
Configuration::updateValue('PS_MAIL_SMTP_ENCRYPTION', "");
Configuration::updateValue('PS_MAIL_SMTP_PORT', 25);
}
$output .= '
<div class="conf confirm">
<img src="../img/admin/ok.gif" alt="" title="" />
'.$this->l('Settings updated').'
</div>';
}
$chk_yes = "";
$chk_no = " checked=\"checked\"";
if ((int)(Tools::getValue('mailjet_activation', Configuration::get('MAILJET_ACTIVATE'))) == 1)
{
$chk_yes = ' checked="checked"';
$chk_no = '';
}
$output .= '
<div>
<p style="margin-bottom:10px;">
<b>'.$this->l('This module sends through Mailjet all email coming from your Prestashop installation (and most third party modules)').'.</b>
</p>
<form action="'.htmlentities($_SERVER['REQUEST_URI']).'" method="post">
<fieldset>
<legend><img src="../img/admin/cog.gif" alt="" class="middle" />'.$this->l('Settings').'</legend>
<label>'.$this->l('Mailjet API Key:').'</label>
<div class="margin-form">
<input type="text" name="mailjet_api_key" id="mailjet_api_key" size="30" value="'.htmlentities(Tools::getValue('mailjet_api_key', Configuration::get('MAILJET_API_KEY'))).'" />
</div>
<hr size="1" style="margin-bottom: 20px;" noshade />
<label>'.$this->l('Mailjet Secret Key').'</label>
<div class="margin-form">
<input type="text" name="mailjet_secret_key" id="mailjet_secret_key" size="30" value="'.htmlentities(Tools::getValue('mailjet_secret_key', Configuration::get('MAILJET_SECRET_KEY'))).'" />
</div>
<hr size="1" style="margin-bottom: 20px;" noshade />
<label style="vertical-align: middle;">'.$this->l('Send Email through Mailjet:').'</label>
<div class="margin-form" style="margin-top: 5px;">
<input type="radio" name="mailjet_activation" value="1" style="vertical-align: middle;" '.$chk_yes.' /> '.$this->l('Yes').'&nbsp;
<input type="radio" name="mailjet_activation" id="mailjet_activation_no" value="0" style="vertical-align: middle;" '.$chk_no.' /> '.$this->l('No').'
</div>
<hr size="1" style="margin-bottom: 20px;" noshade />
<div class="conf confirm" id="mailjet_test_ok" style="display:none">
<img src="../img/admin/ok.gif" alt="" title="" />
'.$this->l('Authentication successful ! Your configuration is correct.').'
</div>
<div class="conf error" id="mailjet_test_ko" style="display:none">
<img src="../img/admin/forbbiden.gif" alt="" title="" />
'.$this->l('An Error has occured : ').'<span id="mailjet_error_message"></span>
<p>'.$this->l('If you don\'t understand this error please contact').' <a href="http://fr.mailjet.com/support" target="_blank">Mailjet Support</a></p>
</div>
<div id="div_email_test" style="display:none">
<p style="text-align:center">'.$this->l('E-mail From / to :').'&nbsp;<input type="text" id="email_from" value="'.htmlentities(Configuration::get('PS_SHOP_EMAIL')).'" size="40" />&nbsp;<input type="button" name="sendTestMailjet" value="'.$this->l('Send').'" class="button" rel="'.htmlentities(Configuration::get('MAILJET_TOKEN')).'" id="button_send_mailjet" /></p>
<hr size="1" style="margin-bottom: 20px;" noshade />
</div>
<center><input type="button" name="testMailjet" value="'.$this->l('Test Configuration').'" class="button" id="button_test_mailjet" /><img src="'.__PS_BASE_URI__.'modules/'.$this->name.'/ajax-mailjet.gif" id="image_ajax_mailjet" style="display:none" />&nbsp;<input type="submit" name="submitMailjet" value="'.$this->l('Save settings').'" class="button" /></center>
</fieldset>
</form>
</div>';
return $output;
}
}
+798
View File
@@ -0,0 +1,798 @@
<?php
/**
* Swift Mailer Message Component
* Composes MIME 1.0 messages meeting various RFC standards
* Deals with attachments, embedded images, multipart bodies, forwarded messages...
* Please read the LICENSE file
* @copyright Chris Corbyn <chris@w3style.co.uk>
* @author Chris Corbyn <chris@w3style.co.uk>
* @package Swift_Message
* @license GNU Lesser General Public License
*/
require_once dirname(__FILE__) . "/ClassLoader.php";
Swift_ClassLoader::load("Swift_Address");
Swift_ClassLoader::load("Swift_Message_Mime");
Swift_ClassLoader::load("Swift_Message_Image");
Swift_ClassLoader::load("Swift_Message_Part");
/**
* Swift Message class
* @package Swift_Message
* @author Chris Corbyn <chris@w3style.co.uk>
*/
class Swift_Message extends Swift_Message_Mime
{
/**
* Constant from a high priority message (pretty meaningless)
*/
const PRIORITY_HIGH = 1;
/**
* Constant for a low priority message
*/
const PRIORITY_LOW = 5;
/**
* Constant for a normal priority message
*/
const PRIORITY_NORMAL = 3;
/**
* The MIME warning for client not supporting multipart content
* @var string
*/
protected $mimeWarning = null;
/**
* The version of the library (Swift) if known.
* @var string
*/
protected $libVersion = "";
/**
* A container for references to other objects.
* This is used in some very complex logic when sub-parts get shifted around.
* @var array
*/
protected $references = array(
"parent" => array("alternative" => null, "mixed" => null, "related" => null),
"alternative" => array(),
"mixed" => array(),
"related" => array()
);
/**
* Ctor.
* @param string Message subject
* @param string Body
* @param string Content-type
* @param string Encoding
* @param string Charset
*/
public function __construct($subject="", $body=null, $type="text/plain", $encoding=null, $charset=null)
{
parent::__construct();
if (function_exists("date_default_timezone_set") && function_exists("date_default_timezone_get"))
{
date_default_timezone_set(@date_default_timezone_get());
}
$this->setReturnPath(null);
$this->setTo("");
$this->setFrom("");
$this->setCc(null);
$this->setBcc(null);
$this->setReplyTo(null);
$this->setSubject($subject);
$this->setDate(time());
if (defined("Swift::VERSION"))
{
$this->libVersion = Swift::VERSION;
$this->headers->set("X-LibVersion", $this->libVersion);
}
$this->headers->set("MIME-Version", "1.0");
$this->headers->set("X-Mailjet-Partner", "prestashop");
$this->setContentType($type);
$this->setCharset($charset);
$this->setFlowed(true);
$this->setEncoding($encoding);
foreach (array_keys($this->references["parent"]) as $key)
{
$this->setReference("parent", $key, $this);
}
$this->setMimeWarning(
"This is a message in multipart MIME format. Your mail client should not be displaying this. " .
"Consider upgrading your mail client to view this message correctly."
);
if ($body !== null)
{
$this->setData($body);
if ($charset === null)
{
Swift_ClassLoader::load("Swift_Message_Encoder");
if (Swift_Message_Encoder::instance()->isUTF8($body)) $this->setCharset("utf-8");
else $this->setCharset("iso-8859-1");
}
}
}
/**
* Sets a reference so when nodes are nested, operations can be redirected.
* This really should be refactored to use just one array rather than dynamic variables.
* @param string Key 1
* @param string Key 2
* @param Object Reference
*/
protected function setReference($where, $key, $ref)
{
if ($ref === $this) $this->references[$where][$key] = false;
else $this->references[$where][$key] = $ref;
}
/**
* Get a reference to an object (for complex reasons).
* @param string Key 1
* @param string Key 2
* @return Object
*/
protected function getReference($where, $key)
{
if (!$this->references[$where][$key]) return $this;
else return $this->references[$where][$key];
}
/**
* Get the level in the MIME hierarchy at which this section should appear.
* @return string
*/
public function getLevel()
{
return Swift_Message_Mime::LEVEL_TOP;
}
/**
* Set the message id literally.
* Unless you know what you are doing you should be using generateId() rather than this method,
* otherwise you may break compliancy with RFC 2822.
* @param string The message ID string.
*/
public function setId($id)
{
$this->headers->set("Message-ID", $id);
}
/**
* Create a RFC 2822 compliant message id, optionally based upon $idstring.
* The message ID includes information about the current time, the server and some random characters.
* @param string An optional string the base the ID on
* @return string The generated message ID, including the <> quotes.
* @author Cristian Rodriguez <judas.iscariote@flyspray.org>
*/
public function generateId($idstring=null)
{
$midparams = array(
"utctime" => gmstrftime("%Y%m%d%H%M%S"),
"pid" => getmypid(),
"randint" => mt_rand(),
"customstr" => (preg_match("/^(?<!\\.)[a-z0-9\\.]+(?!\\.)\$/iD", $idstring) ? $idstring : "swift") ,
"hostname" => (isset($_SERVER["SERVER_NAME"]) ? $_SERVER["SERVER_NAME"] : php_uname("n")),
);
$this->setId(vsprintf("<%s.%d.%d.%s@%s>", $midparams));
return $this->getId();
}
/**
* Get the generated message ID for this message, including the <> quotes.
* If generated automatically, or using generateId() this method returns a RFC2822 compliant Message-ID.
* @return string
* @author Cristian Rodriguez <judas.iscariote@flyspray.org>
*/
public function getId()
{
return $this->headers->has("Message-ID") ? $this->headers->get("Message-ID") : null;
}
/**
* Set the address in the Return-Path: header
* @param string The bounce-detect address
*/
public function setReturnPath($address)
{
if ($address instanceof Swift_Address) $address = $address->build(true);
$this->headers->set("Return-Path", $address);
}
/**
* Return the address used in the Return-Path: header
* @return string
* @param boolean Return the address for SMTP command
*/
public function getReturnPath($smtp=false)
{
if ($this->headers->has("Return-Path"))
{
if (!$smtp) return $this->headers->get("Return-Path");
else
{
$path = $this->headers->get("Return-Path");
if (strpos($path, ">") > strpos($path, "<")) return substr($path, ($start = strpos($path, "<")), ($start + strrpos($path, ">") + 1));
else return "<" . $path . ">";
}
}
}
/**
* Set the address in the From: header
* @param string The address to set as From
*/
public function setFrom($from)
{
if ($from instanceof Swift_Address) $from = $from->build();
$this->headers->set("From", $from);
}
/**
* Get the address used in the From: header
* @return string
*/
public function getFrom()
{
if ($this->headers->has("From")) return $this->headers->get("From");
}
/**
* Set the list of recipients in the To: header
* @param mixed An array or a string
*/
public function setTo($to)
{
if ($to)
{
if (!is_array($to)) $to = array($to);
foreach ($to as $key => $value)
{
if ($value instanceof Swift_Address) $to[$key] = $value->build();
}
}
$this->headers->set("To", $to);
}
/**
* Return the list of recipients in the To: header
* @return array
*/
public function getTo()
{
if ($this->headers->has("To"))
{
$to = $this->headers->get("To");
if ($to == "") return array();
else return (array) $to;
}
}
/**
* Set the list of recipients in the Reply-To: header
* @param mixed An array or a string
*/
public function setReplyTo($replyto)
{
if ($replyto)
{
if (!is_array($replyto)) $replyto = array($replyto);
foreach ($replyto as $key => $value)
{
if ($value instanceof Swift_Address) $replyto[$key] = $value->build();
}
}
$this->headers->set("Reply-To", $replyto);
}
/**
* Return the list of recipients in the Reply-To: header
* @return array
*/
public function getReplyTo()
{
if ($this->headers->has("Reply-To"))
{
$reply_to = $this->headers->get("Reply-To");
if ($reply_to == "") return array();
else return (array) $reply_to;
}
}
/**
* Set the list of recipients in the Cc: header
* @param mixed An array or a string
*/
public function setCc($cc)
{
if ($cc)
{
if (!is_array($cc)) $cc = array($cc);
foreach ($cc as $key => $value)
{
if ($value instanceof Swift_Address) $cc[$key] = $value->build();
}
}
$this->headers->set("Cc", $cc);
}
/**
* Return the list of recipients in the Cc: header
* @return array
*/
public function getCc()
{
if ($this->headers->has("Cc"))
{
$cc = $this->headers->get("Cc");
if ($cc == "") return array();
else return (array) $cc;
}
}
/**
* Set the list of recipients in the Bcc: header
* @param mixed An array or a string
*/
public function setBcc($bcc)
{
if ($bcc)
{
if (!is_array($bcc)) $bcc = array($bcc);
foreach ($bcc as $key => $value)
{
if ($value instanceof Swift_Address) $bcc[$key] = $value->build();
}
}
$this->headers->set("Bcc", $bcc);
}
/**
* Return the list of recipients in the Bcc: header
* @return array
*/
public function getBcc()
{
if ($this->headers->has("Bcc"))
{
$bcc = $this->headers->get("Bcc");
if ($bcc == "") return array();
else return (array) $bcc;
}
}
/**
* Set the subject in the headers
* @param string The subject of the email
*/
public function setSubject($subject)
{
$this->headers->set("Subject", $subject);
}
/**
* Get the current subject used in the headers
* @return string
*/
public function getSubject()
{
return $this->headers->get("Subject");
}
/**
* Set the date in the headers in RFC 2822 format
* @param int The time as a UNIX timestamp
*/
public function setDate($date)
{
$this->headers->set("Date", date("r", $date));
}
/**
* Get the date as it looks in the headers
* @return string
*/
public function getDate()
{
return strtotime($this->headers->get("Date"));
}
/**
* Set the charset of the document
* @param string The charset used
*/
public function setCharset($charset)
{
$this->headers->setAttribute("Content-Type", "charset", $charset);
if (($this->getEncoding() == "7bit") && (strtolower($charset) == "utf-8" || strtolower($charset) == "utf8")) $this->setEncoding("8bit");
}
/**
* Get the charset used in the document
* Returns null if none is set
* @return string
*/
public function getCharset()
{
if ($this->headers->hasAttribute("Content-Type", "charset"))
{
return $this->headers->getAttribute("Content-Type", "charset");
}
else
{
return null;
}
}
/**
* Set the "format" attribute to flowed
* @param boolean On or Off
*/
public function setFlowed($flowed=true)
{
$value = null;
if ($flowed) $value = "flowed";
$this->headers->setAttribute("Content-Type", "format", $value);
}
/**
* Check if the message format is set as flowed
* @return boolean
*/
public function isFlowed()
{
if ($this->headers->hasAttribute("Content-Type", "format")
&& $this->headers->getAttribute("Content-Type", "format") == "flowed")
{
return true;
}
else return false;
}
/**
* Set the message prioirty in the mail client (don't rely on this)
* @param int The priority as a value between 1 (high) and 5 (low)
*/
public function setPriority($priority)
{
$priority = (int) $priority;
if ($priority > self::PRIORITY_LOW) $priority = self::PRIORITY_LOW;
if ($priority < self::PRIORITY_HIGH) $priority = self::PRIORITY_HIGH;
$label = array(1 => "High", 2 => "High", 3 => "Normal", 4 => "Low", 5 => "Low");
$this->headers->set("X-Priority", $priority);
$this->headers->set("X-MSMail-Priority", $label[$priority]);
$this->headers->set("X-MimeOLE", "Produced by SwiftMailer " . $this->libVersion);
}
/**
* Request that the client send back a read-receipt (don't rely on this!)
* @param string Request address
*/
public function requestReadReceipt($request)
{
if ($request instanceof Swift_Address) $request = $request->build();
if (!$request)
{
$this->headers->set("Disposition-Notification-To", null);
$this->headers->set("X-Confirm-Reading-To", null);
$this->headers->set("Return-Receipt-To", null);
}
else
{
$this->headers->set("Disposition-Notification-To", $request);
$this->headers->set("X-Confirm-Reading-To", $request);
$this->headers->set("Return-Receipt-To", $request);
}
}
/**
* Check if a read receipt has been requested for this message
* @return boolean
*/
public function wantsReadReceipt()
{
return $this->headers->has("Disposition-Notification-To");
}
/**
* Get the current message priority
* Returns NULL if none set
* @return int
*/
public function getPriority()
{
if ($this->headers->has("X-Priority")) return $this->headers->get("X-Priority");
else return null;
}
/**
* Alias for setData()
* @param mixed Body
*/
public function setBody($body)
{
$this->setData($body);
}
/**
* Alias for getData()
* @return mixed The document body
*/
public function getBody()
{
return $this->getData();
}
/**
* Set the MIME warning message which is displayed to old clients
* @var string The full warning message (in 7bit ascii)
*/
public function setMimeWarning($text)
{
$this->mimeWarning = (string) $text;
}
/**
* Get the MIME warning which is displayed to old clients
* @return string
*/
public function getMimeWarning()
{
return $this->mimeWarning;
}
/**
* Attach a mime part or an attachment of some sort
* Any descendant of Swift_Message_Mime can be added safely (including other Swift_Message objects for mail forwarding!!)
* @param Swift_Message_Mime The document to attach
* @param string An identifier to use (one is returned otherwise)
* @return string The identifier for the part
*/
public function attach(Swift_Message_Mime $child, $id=null)
{
try {
switch ($child->getLevel())
{
case Swift_Message_Mime::LEVEL_ALTERNATIVE:
$sign = (strtolower($child->getContentType()) == "text/plain") ? -1 : 1;
$id = $this->getReference("parent", "alternative")->addChild($child, $id, $sign);
$this->setReference("alternative", $id, $child);
break;
case Swift_Message_Mime::LEVEL_RELATED:
$id = "cid:" . $child->getContentId();
$id = $this->getReference("parent", "related")->addChild($child, $id, 1);
$this->setReference("related", $id, $child);
break;
case Swift_Message_Mime::LEVEL_MIXED: default:
$id = $this->getReference("parent", "mixed")->addChild($child, $id, 1);
$this->setReference("mixed", $id, $child);
break;
}
$this->postAttachFixStructure();
$this->fixContentType();
return $id;
} catch (Swift_Message_MimeException $e) {
throw new Swift_Message_MimeException("Something went wrong whilst trying to move some MIME parts during an attach(). " .
"The MIME component threw an exception:<br />" . $e->getMessage());
}
}
/**
* Remove a nested MIME part
* @param string The ID of the attached part
* @throws Swift_Message_MimeException If no such part exists
*/
public function detach($id)
{
try {
switch (true)
{
case array_key_exists($id, $this->references["alternative"]):
$this->getReference("parent", "alternative")->removeChild($id);
unset($this->references["alternative"][$id]);
break;
case array_key_exists($id, $this->references["related"]):
$this->getReference("parent", "related")->removeChild($id);
unset($this->references["related"][$id]);
break;
case array_key_exists($id, $this->references["mixed"]):
$this->getReference("parent", "mixed")->removeChild($id);
unset($this->references["mixed"][$id]);
break;
default:
throw new Swift_Message_MimeException("Unable to detach part identified by ID '" . $id . "' since it's not registered.");
break;
}
$this->postDetachFixStructure();
$this->fixContentType();
} catch (Swift_Message_MimeException $e) {
throw new Swift_Message_MimeException("Something went wrong whilst trying to move some MIME parts during a detach(). " .
"The MIME component threw an exception:<br />" . $e->getMessage());
}
}
/**
* Sets the correct content type header by looking at what types of data we have set
*/
protected function fixContentType()
{
if (!empty($this->references["mixed"])) $this->setContentType("multipart/mixed");
elseif (!empty($this->references["related"])) $this->setContentType("multipart/related");
elseif (!empty($this->references["alternative"])) $this->setContentType("multipart/alternative");
}
/**
* Move a branch of the tree, containing all it's MIME parts onto another branch
* @param string The content type on the branch itself
* @param string The content type which may exist in the branch's parent
* @param array The array containing all the nodes presently
* @param string The location of the branch now
* @param string The location of the branch after moving
* @param string The key to identify the branch by in it's new location
*/
protected function moveBranchIn($type, $nested_type, $from, $old_branch, $new_branch, $tag)
{
$new = new Swift_Message_Part();
$new->setContentType($type);
$this->getReference("parent", $new_branch)->addChild($new, $tag, -1);
switch ($new_branch)
{
case "related": $this->setReference("related", $tag, $new);//relatedRefs[$tag] = $new;
break;
case "mixed": $this->setReference("mixed", $tag, $new);//mixedRefs[$tag] = $new;
break;
}
foreach ($from as $id => $ref)
{
if (!$ref) $ref = $this;
$sign = (strtolower($ref->getContentType()) == "text/plain"
|| strtolower($ref->getContentType()) == $nested_type) ? -1 : 1;
switch ($new_branch)
{
case "related": $this->getReference("related", $tag)->addChild($ref, $id, $sign);
break;
case "mixed": $this->getReference("mixed", $tag)->addChild($ref, $id, $sign);
break;
}
$this->getReference("parent", $old_branch)->removeChild($id);
}
$this->setReference("parent", $old_branch, $new); //parentRefs[$old_branch] = $new;
}
/**
* Analyzes the mixing of MIME types in a mulitpart message an re-arranges if needed
* It looks complicated and long winded but the concept is pretty simple, even if putting it
* in code does me make want to cry!
*/
protected function postAttachFixStructure()
{
switch (true)
{
case (!empty($this->references["mixed"]) && !empty($this->references["related"]) && !empty($this->references["alternative"])):
if (!isset($this->references["related"]["_alternative"]))
{
$this->moveBranchIn(
"multipart/alternative", "multipart/alternative", $this->references["alternative"], "alternative", "related", "_alternative");
}
if (!isset($this->references["mixed"]["_related"]))
{
$this->moveBranchIn(
"multipart/related", "multipart/alternative", $this->references["related"], "related", "mixed", "_related");
}
break;
case (!empty($this->references["mixed"]) && !empty($this->references["related"])):
if (!isset($this->references["mixed"]["_related"]))
{
$this->moveBranchIn(
"multipart/related", "multipart/related", $this->references["related"], "related", "mixed", "_related");
}
break;
case (!empty($this->references["mixed"]) && !empty($this->references["alternative"])):
if (!isset($this->references["mixed"]["_alternative"]))
{
$this->moveBranchIn(
"multipart/alternative", null, $this->references["alternative"], "alternative", "mixed", "_alternative");
}
break;
case (!empty($this->references["related"]) && !empty($this->references["alternative"])):
if (!isset($this->references["related"]["_alternative"]))
{
$this->moveBranchIn(
"multipart/alternative", "multipart/alternative", $this->references["alternative"], "alternative", "related", "_alternative");
}
break;
}
}
/**
* Move a branch further toward the top of the tree
* @param array The array containing MIME parts from the old branch
* @param string The name of the old branch
* @param string The name of the new branch
* @param string The key of the branch being moved
*/
protected function moveBranchOut($from, $old_branch, $new_branch, $tag)
{
foreach ($from as $id => $ref)
{
if (!$ref) $ref = $this;
$sign = (strtolower($ref->getContentType()) == "text/html"
|| strtolower($ref->getContentType()) == "multipart/alternative") ? -1 : 1;
$this->getReference("parent", $new_branch)->addChild($ref, $id, $sign);
switch ($new_branch)
{
case "related": $this->getReference("related", $tag)->removeChild($id);
break;
case "mixed": $this->getReference("parent", $old_branch)->removeChild($id);
break;
}
}
$this->getReference("parent", $new_branch)->removeChild($tag);
$mixed = $this->getReference("parent", $new_branch);//parentRefs[$new_branch];
$this->setReference("parent", $old_branch, $mixed);//parentRefs[$old_branch] = $mixed;
switch ($new_branch)
{
case "related": unset($this->references["related"][$tag]);
break;
case "mixed": unset($this->references["mixed"][$tag]);
break;
}
}
/**
* Analyzes the mixing of MIME types in a mulitpart message an re-arranges if needed
* It looks complicated and long winded but the concept is pretty simple, even if putting it
* in code does me make want to cry!
*/
protected function postDetachFixStructure()
{
switch (true)
{
case (!empty($this->references["mixed"]) && !empty($this->references["related"]) && !empty($this->references["alternative"])):
if (array_keys($this->references["related"]) == array("_alternative"))
{
$alt = $this->getReference("parent", "related")->getChild("_alternative");
$this->getReference("parent", "mixed")->addChild($alt, "_alternative", -1);
$this->setReference("mixed", "_alternative", $alt);//mixedRefs["_alternative"] = $alt;
$this->getReference("parent", "related")->removeChild("_alternative");
unset($this->references["related"]["_alternative"]);
$this->getReference("parent", "mixed")->removeChild("_related");
unset($this->references["mixed"]["_related"]);
}
if (array_keys($this->references["mixed"]) == array("_related"))
{
$this->moveBranchOut($this->references["related"], "related", "mixed", "_related");
}
break;
case (!empty($this->references["mixed"]) && !empty($this->references["related"])):
if (array_keys($this->references["mixed"]) == array("_related"))
{
$this->moveBranchOut($this->references["related"], "related", "mixed", "_related");
}
if (isset($this->references["related"]["_alternative"]))
{
$this->detach("_alternative");
}
break;
case (!empty($this->references["mixed"]) && !empty($this->references["alternative"])):
if (array_keys($this->references["mixed"]) == array("_alternative"))
{
$this->moveBranchOut($this->references["alternative"], "alternative", "mixed", "_alternative");
}
break;
case (!empty($this->references["related"]) && !empty($this->references["alternative"])):
if (array_keys($this->references["related"]) == array("_alternative"))
{
$this->moveBranchOut($this->references["alternative"], "alternative", "related", "_alternative");
}
break;
case (!empty($this->references["mixed"])):
if (isset($this->references["mixed"]["_related"])) $this->detach("_related");
case (!empty($this->references["related"])):
if (isset($this->references["related"]["_alternative"]) || isset($this->references["mixed"]["_alternative"]))
$this->detach("_alternative");
break;
}
}
/**
* Execute needed logic prior to compilation
*/
public function preBuild()
{
$data = $this->getData();
if (!($enc = $this->getEncoding()))
{
$this->setEncoding("8bit");
}
if ($this->getCharset() === null && !$this->numChildren())
{
Swift_ClassLoader::load("Swift_Message_Encoder");
if (is_string($data) && Swift_Message_Encoder::instance()->isUTF8($data))
{
$this->setCharset("utf-8");
}
elseif(is_string($data) && Swift_Message_Encoder::instance()->is7BitAscii($data))
{
$this->setCharset("us-ascii");
if (!$enc) $this->setEncoding("7bit");
}
else $this->setCharset("iso-8859-1");
}
elseif ($this->numChildren())
{
if (!$this->getData())
{
$this->setData($this->getMimeWarning());
$this->setLineWrap(76);
}
if ($this->getCharset() !== null) $this->setCharset(null);
if ($this->isFlowed()) $this->setFlowed(false);
$this->setEncoding("7bit");
}
}
}
+797
View File
@@ -0,0 +1,797 @@
<?php
/**
* Swift Mailer Message Component
* Composes MIME 1.0 messages meeting various RFC standards
* Deals with attachments, embedded images, multipart bodies, forwarded messages...
* Please read the LICENSE file
* @copyright Chris Corbyn <chris@w3style.co.uk>
* @author Chris Corbyn <chris@w3style.co.uk>
* @package Swift_Message
* @license GNU Lesser General Public License
*/
require_once dirname(__FILE__) . "/ClassLoader.php";
Swift_ClassLoader::load("Swift_Address");
Swift_ClassLoader::load("Swift_Message_Mime");
Swift_ClassLoader::load("Swift_Message_Image");
Swift_ClassLoader::load("Swift_Message_Part");
/**
* Swift Message class
* @package Swift_Message
* @author Chris Corbyn <chris@w3style.co.uk>
*/
class Swift_Message extends Swift_Message_Mime
{
/**
* Constant from a high priority message (pretty meaningless)
*/
const PRIORITY_HIGH = 1;
/**
* Constant for a low priority message
*/
const PRIORITY_LOW = 5;
/**
* Constant for a normal priority message
*/
const PRIORITY_NORMAL = 3;
/**
* The MIME warning for client not supporting multipart content
* @var string
*/
protected $mimeWarning = null;
/**
* The version of the library (Swift) if known.
* @var string
*/
protected $libVersion = "";
/**
* A container for references to other objects.
* This is used in some very complex logic when sub-parts get shifted around.
* @var array
*/
protected $references = array(
"parent" => array("alternative" => null, "mixed" => null, "related" => null),
"alternative" => array(),
"mixed" => array(),
"related" => array()
);
/**
* Ctor.
* @param string Message subject
* @param string Body
* @param string Content-type
* @param string Encoding
* @param string Charset
*/
public function __construct($subject="", $body=null, $type="text/plain", $encoding=null, $charset=null)
{
parent::__construct();
if (function_exists("date_default_timezone_set") && function_exists("date_default_timezone_get"))
{
date_default_timezone_set(@date_default_timezone_get());
}
$this->setReturnPath(null);
$this->setTo("");
$this->setFrom("");
$this->setCc(null);
$this->setBcc(null);
$this->setReplyTo(null);
$this->setSubject($subject);
$this->setDate(time());
if (defined("Swift::VERSION"))
{
$this->libVersion = Swift::VERSION;
$this->headers->set("X-LibVersion", $this->libVersion);
}
$this->headers->set("MIME-Version", "1.0");
$this->setContentType($type);
$this->setCharset($charset);
$this->setFlowed(true);
$this->setEncoding($encoding);
foreach (array_keys($this->references["parent"]) as $key)
{
$this->setReference("parent", $key, $this);
}
$this->setMimeWarning(
"This is a message in multipart MIME format. Your mail client should not be displaying this. " .
"Consider upgrading your mail client to view this message correctly."
);
if ($body !== null)
{
$this->setData($body);
if ($charset === null)
{
Swift_ClassLoader::load("Swift_Message_Encoder");
if (Swift_Message_Encoder::instance()->isUTF8($body)) $this->setCharset("utf-8");
else $this->setCharset("iso-8859-1");
}
}
}
/**
* Sets a reference so when nodes are nested, operations can be redirected.
* This really should be refactored to use just one array rather than dynamic variables.
* @param string Key 1
* @param string Key 2
* @param Object Reference
*/
protected function setReference($where, $key, $ref)
{
if ($ref === $this) $this->references[$where][$key] = false;
else $this->references[$where][$key] = $ref;
}
/**
* Get a reference to an object (for complex reasons).
* @param string Key 1
* @param string Key 2
* @return Object
*/
protected function getReference($where, $key)
{
if (!$this->references[$where][$key]) return $this;
else return $this->references[$where][$key];
}
/**
* Get the level in the MIME hierarchy at which this section should appear.
* @return string
*/
public function getLevel()
{
return Swift_Message_Mime::LEVEL_TOP;
}
/**
* Set the message id literally.
* Unless you know what you are doing you should be using generateId() rather than this method,
* otherwise you may break compliancy with RFC 2822.
* @param string The message ID string.
*/
public function setId($id)
{
$this->headers->set("Message-ID", $id);
}
/**
* Create a RFC 2822 compliant message id, optionally based upon $idstring.
* The message ID includes information about the current time, the server and some random characters.
* @param string An optional string the base the ID on
* @return string The generated message ID, including the <> quotes.
* @author Cristian Rodriguez <judas.iscariote@flyspray.org>
*/
public function generateId($idstring=null)
{
$midparams = array(
"utctime" => gmstrftime("%Y%m%d%H%M%S"),
"pid" => getmypid(),
"randint" => mt_rand(),
"customstr" => (preg_match("/^(?<!\\.)[a-z0-9\\.]+(?!\\.)\$/iD", $idstring) ? $idstring : "swift") ,
"hostname" => (isset($_SERVER["SERVER_NAME"]) ? $_SERVER["SERVER_NAME"] : php_uname("n")),
);
$this->setId(vsprintf("<%s.%d.%d.%s@%s>", $midparams));
return $this->getId();
}
/**
* Get the generated message ID for this message, including the <> quotes.
* If generated automatically, or using generateId() this method returns a RFC2822 compliant Message-ID.
* @return string
* @author Cristian Rodriguez <judas.iscariote@flyspray.org>
*/
public function getId()
{
return $this->headers->has("Message-ID") ? $this->headers->get("Message-ID") : null;
}
/**
* Set the address in the Return-Path: header
* @param string The bounce-detect address
*/
public function setReturnPath($address)
{
if ($address instanceof Swift_Address) $address = $address->build(true);
$this->headers->set("Return-Path", $address);
}
/**
* Return the address used in the Return-Path: header
* @return string
* @param boolean Return the address for SMTP command
*/
public function getReturnPath($smtp=false)
{
if ($this->headers->has("Return-Path"))
{
if (!$smtp) return $this->headers->get("Return-Path");
else
{
$path = $this->headers->get("Return-Path");
if (strpos($path, ">") > strpos($path, "<")) return substr($path, ($start = strpos($path, "<")), ($start + strrpos($path, ">") + 1));
else return "<" . $path . ">";
}
}
}
/**
* Set the address in the From: header
* @param string The address to set as From
*/
public function setFrom($from)
{
if ($from instanceof Swift_Address) $from = $from->build();
$this->headers->set("From", $from);
}
/**
* Get the address used in the From: header
* @return string
*/
public function getFrom()
{
if ($this->headers->has("From")) return $this->headers->get("From");
}
/**
* Set the list of recipients in the To: header
* @param mixed An array or a string
*/
public function setTo($to)
{
if ($to)
{
if (!is_array($to)) $to = array($to);
foreach ($to as $key => $value)
{
if ($value instanceof Swift_Address) $to[$key] = $value->build();
}
}
$this->headers->set("To", $to);
}
/**
* Return the list of recipients in the To: header
* @return array
*/
public function getTo()
{
if ($this->headers->has("To"))
{
$to = $this->headers->get("To");
if ($to == "") return array();
else return (array) $to;
}
}
/**
* Set the list of recipients in the Reply-To: header
* @param mixed An array or a string
*/
public function setReplyTo($replyto)
{
if ($replyto)
{
if (!is_array($replyto)) $replyto = array($replyto);
foreach ($replyto as $key => $value)
{
if ($value instanceof Swift_Address) $replyto[$key] = $value->build();
}
}
$this->headers->set("Reply-To", $replyto);
}
/**
* Return the list of recipients in the Reply-To: header
* @return array
*/
public function getReplyTo()
{
if ($this->headers->has("Reply-To"))
{
$reply_to = $this->headers->get("Reply-To");
if ($reply_to == "") return array();
else return (array) $reply_to;
}
}
/**
* Set the list of recipients in the Cc: header
* @param mixed An array or a string
*/
public function setCc($cc)
{
if ($cc)
{
if (!is_array($cc)) $cc = array($cc);
foreach ($cc as $key => $value)
{
if ($value instanceof Swift_Address) $cc[$key] = $value->build();
}
}
$this->headers->set("Cc", $cc);
}
/**
* Return the list of recipients in the Cc: header
* @return array
*/
public function getCc()
{
if ($this->headers->has("Cc"))
{
$cc = $this->headers->get("Cc");
if ($cc == "") return array();
else return (array) $cc;
}
}
/**
* Set the list of recipients in the Bcc: header
* @param mixed An array or a string
*/
public function setBcc($bcc)
{
if ($bcc)
{
if (!is_array($bcc)) $bcc = array($bcc);
foreach ($bcc as $key => $value)
{
if ($value instanceof Swift_Address) $bcc[$key] = $value->build();
}
}
$this->headers->set("Bcc", $bcc);
}
/**
* Return the list of recipients in the Bcc: header
* @return array
*/
public function getBcc()
{
if ($this->headers->has("Bcc"))
{
$bcc = $this->headers->get("Bcc");
if ($bcc == "") return array();
else return (array) $bcc;
}
}
/**
* Set the subject in the headers
* @param string The subject of the email
*/
public function setSubject($subject)
{
$this->headers->set("Subject", $subject);
}
/**
* Get the current subject used in the headers
* @return string
*/
public function getSubject()
{
return $this->headers->get("Subject");
}
/**
* Set the date in the headers in RFC 2822 format
* @param int The time as a UNIX timestamp
*/
public function setDate($date)
{
$this->headers->set("Date", date("r", $date));
}
/**
* Get the date as it looks in the headers
* @return string
*/
public function getDate()
{
return strtotime($this->headers->get("Date"));
}
/**
* Set the charset of the document
* @param string The charset used
*/
public function setCharset($charset)
{
$this->headers->setAttribute("Content-Type", "charset", $charset);
if (($this->getEncoding() == "7bit") && (strtolower($charset) == "utf-8" || strtolower($charset) == "utf8")) $this->setEncoding("8bit");
}
/**
* Get the charset used in the document
* Returns null if none is set
* @return string
*/
public function getCharset()
{
if ($this->headers->hasAttribute("Content-Type", "charset"))
{
return $this->headers->getAttribute("Content-Type", "charset");
}
else
{
return null;
}
}
/**
* Set the "format" attribute to flowed
* @param boolean On or Off
*/
public function setFlowed($flowed=true)
{
$value = null;
if ($flowed) $value = "flowed";
$this->headers->setAttribute("Content-Type", "format", $value);
}
/**
* Check if the message format is set as flowed
* @return boolean
*/
public function isFlowed()
{
if ($this->headers->hasAttribute("Content-Type", "format")
&& $this->headers->getAttribute("Content-Type", "format") == "flowed")
{
return true;
}
else return false;
}
/**
* Set the message prioirty in the mail client (don't rely on this)
* @param int The priority as a value between 1 (high) and 5 (low)
*/
public function setPriority($priority)
{
$priority = (int) $priority;
if ($priority > self::PRIORITY_LOW) $priority = self::PRIORITY_LOW;
if ($priority < self::PRIORITY_HIGH) $priority = self::PRIORITY_HIGH;
$label = array(1 => "High", 2 => "High", 3 => "Normal", 4 => "Low", 5 => "Low");
$this->headers->set("X-Priority", $priority);
$this->headers->set("X-MSMail-Priority", $label[$priority]);
$this->headers->set("X-MimeOLE", "Produced by SwiftMailer " . $this->libVersion);
}
/**
* Request that the client send back a read-receipt (don't rely on this!)
* @param string Request address
*/
public function requestReadReceipt($request)
{
if ($request instanceof Swift_Address) $request = $request->build();
if (!$request)
{
$this->headers->set("Disposition-Notification-To", null);
$this->headers->set("X-Confirm-Reading-To", null);
$this->headers->set("Return-Receipt-To", null);
}
else
{
$this->headers->set("Disposition-Notification-To", $request);
$this->headers->set("X-Confirm-Reading-To", $request);
$this->headers->set("Return-Receipt-To", $request);
}
}
/**
* Check if a read receipt has been requested for this message
* @return boolean
*/
public function wantsReadReceipt()
{
return $this->headers->has("Disposition-Notification-To");
}
/**
* Get the current message priority
* Returns NULL if none set
* @return int
*/
public function getPriority()
{
if ($this->headers->has("X-Priority")) return $this->headers->get("X-Priority");
else return null;
}
/**
* Alias for setData()
* @param mixed Body
*/
public function setBody($body)
{
$this->setData($body);
}
/**
* Alias for getData()
* @return mixed The document body
*/
public function getBody()
{
return $this->getData();
}
/**
* Set the MIME warning message which is displayed to old clients
* @var string The full warning message (in 7bit ascii)
*/
public function setMimeWarning($text)
{
$this->mimeWarning = (string) $text;
}
/**
* Get the MIME warning which is displayed to old clients
* @return string
*/
public function getMimeWarning()
{
return $this->mimeWarning;
}
/**
* Attach a mime part or an attachment of some sort
* Any descendant of Swift_Message_Mime can be added safely (including other Swift_Message objects for mail forwarding!!)
* @param Swift_Message_Mime The document to attach
* @param string An identifier to use (one is returned otherwise)
* @return string The identifier for the part
*/
public function attach(Swift_Message_Mime $child, $id=null)
{
try {
switch ($child->getLevel())
{
case Swift_Message_Mime::LEVEL_ALTERNATIVE:
$sign = (strtolower($child->getContentType()) == "text/plain") ? -1 : 1;
$id = $this->getReference("parent", "alternative")->addChild($child, $id, $sign);
$this->setReference("alternative", $id, $child);
break;
case Swift_Message_Mime::LEVEL_RELATED:
$id = "cid:" . $child->getContentId();
$id = $this->getReference("parent", "related")->addChild($child, $id, 1);
$this->setReference("related", $id, $child);
break;
case Swift_Message_Mime::LEVEL_MIXED: default:
$id = $this->getReference("parent", "mixed")->addChild($child, $id, 1);
$this->setReference("mixed", $id, $child);
break;
}
$this->postAttachFixStructure();
$this->fixContentType();
return $id;
} catch (Swift_Message_MimeException $e) {
throw new Swift_Message_MimeException("Something went wrong whilst trying to move some MIME parts during an attach(). " .
"The MIME component threw an exception:<br />" . $e->getMessage());
}
}
/**
* Remove a nested MIME part
* @param string The ID of the attached part
* @throws Swift_Message_MimeException If no such part exists
*/
public function detach($id)
{
try {
switch (true)
{
case array_key_exists($id, $this->references["alternative"]):
$this->getReference("parent", "alternative")->removeChild($id);
unset($this->references["alternative"][$id]);
break;
case array_key_exists($id, $this->references["related"]):
$this->getReference("parent", "related")->removeChild($id);
unset($this->references["related"][$id]);
break;
case array_key_exists($id, $this->references["mixed"]):
$this->getReference("parent", "mixed")->removeChild($id);
unset($this->references["mixed"][$id]);
break;
default:
throw new Swift_Message_MimeException("Unable to detach part identified by ID '" . $id . "' since it's not registered.");
break;
}
$this->postDetachFixStructure();
$this->fixContentType();
} catch (Swift_Message_MimeException $e) {
throw new Swift_Message_MimeException("Something went wrong whilst trying to move some MIME parts during a detach(). " .
"The MIME component threw an exception:<br />" . $e->getMessage());
}
}
/**
* Sets the correct content type header by looking at what types of data we have set
*/
protected function fixContentType()
{
if (!empty($this->references["mixed"])) $this->setContentType("multipart/mixed");
elseif (!empty($this->references["related"])) $this->setContentType("multipart/related");
elseif (!empty($this->references["alternative"])) $this->setContentType("multipart/alternative");
}
/**
* Move a branch of the tree, containing all it's MIME parts onto another branch
* @param string The content type on the branch itself
* @param string The content type which may exist in the branch's parent
* @param array The array containing all the nodes presently
* @param string The location of the branch now
* @param string The location of the branch after moving
* @param string The key to identify the branch by in it's new location
*/
protected function moveBranchIn($type, $nested_type, $from, $old_branch, $new_branch, $tag)
{
$new = new Swift_Message_Part();
$new->setContentType($type);
$this->getReference("parent", $new_branch)->addChild($new, $tag, -1);
switch ($new_branch)
{
case "related": $this->setReference("related", $tag, $new);//relatedRefs[$tag] = $new;
break;
case "mixed": $this->setReference("mixed", $tag, $new);//mixedRefs[$tag] = $new;
break;
}
foreach ($from as $id => $ref)
{
if (!$ref) $ref = $this;
$sign = (strtolower($ref->getContentType()) == "text/plain"
|| strtolower($ref->getContentType()) == $nested_type) ? -1 : 1;
switch ($new_branch)
{
case "related": $this->getReference("related", $tag)->addChild($ref, $id, $sign);
break;
case "mixed": $this->getReference("mixed", $tag)->addChild($ref, $id, $sign);
break;
}
$this->getReference("parent", $old_branch)->removeChild($id);
}
$this->setReference("parent", $old_branch, $new); //parentRefs[$old_branch] = $new;
}
/**
* Analyzes the mixing of MIME types in a mulitpart message an re-arranges if needed
* It looks complicated and long winded but the concept is pretty simple, even if putting it
* in code does me make want to cry!
*/
protected function postAttachFixStructure()
{
switch (true)
{
case (!empty($this->references["mixed"]) && !empty($this->references["related"]) && !empty($this->references["alternative"])):
if (!isset($this->references["related"]["_alternative"]))
{
$this->moveBranchIn(
"multipart/alternative", "multipart/alternative", $this->references["alternative"], "alternative", "related", "_alternative");
}
if (!isset($this->references["mixed"]["_related"]))
{
$this->moveBranchIn(
"multipart/related", "multipart/alternative", $this->references["related"], "related", "mixed", "_related");
}
break;
case (!empty($this->references["mixed"]) && !empty($this->references["related"])):
if (!isset($this->references["mixed"]["_related"]))
{
$this->moveBranchIn(
"multipart/related", "multipart/related", $this->references["related"], "related", "mixed", "_related");
}
break;
case (!empty($this->references["mixed"]) && !empty($this->references["alternative"])):
if (!isset($this->references["mixed"]["_alternative"]))
{
$this->moveBranchIn(
"multipart/alternative", null, $this->references["alternative"], "alternative", "mixed", "_alternative");
}
break;
case (!empty($this->references["related"]) && !empty($this->references["alternative"])):
if (!isset($this->references["related"]["_alternative"]))
{
$this->moveBranchIn(
"multipart/alternative", "multipart/alternative", $this->references["alternative"], "alternative", "related", "_alternative");
}
break;
}
}
/**
* Move a branch further toward the top of the tree
* @param array The array containing MIME parts from the old branch
* @param string The name of the old branch
* @param string The name of the new branch
* @param string The key of the branch being moved
*/
protected function moveBranchOut($from, $old_branch, $new_branch, $tag)
{
foreach ($from as $id => $ref)
{
if (!$ref) $ref = $this;
$sign = (strtolower($ref->getContentType()) == "text/html"
|| strtolower($ref->getContentType()) == "multipart/alternative") ? -1 : 1;
$this->getReference("parent", $new_branch)->addChild($ref, $id, $sign);
switch ($new_branch)
{
case "related": $this->getReference("related", $tag)->removeChild($id);
break;
case "mixed": $this->getReference("parent", $old_branch)->removeChild($id);
break;
}
}
$this->getReference("parent", $new_branch)->removeChild($tag);
$mixed = $this->getReference("parent", $new_branch);//parentRefs[$new_branch];
$this->setReference("parent", $old_branch, $mixed);//parentRefs[$old_branch] = $mixed;
switch ($new_branch)
{
case "related": unset($this->references["related"][$tag]);
break;
case "mixed": unset($this->references["mixed"][$tag]);
break;
}
}
/**
* Analyzes the mixing of MIME types in a mulitpart message an re-arranges if needed
* It looks complicated and long winded but the concept is pretty simple, even if putting it
* in code does me make want to cry!
*/
protected function postDetachFixStructure()
{
switch (true)
{
case (!empty($this->references["mixed"]) && !empty($this->references["related"]) && !empty($this->references["alternative"])):
if (array_keys($this->references["related"]) == array("_alternative"))
{
$alt = $this->getReference("parent", "related")->getChild("_alternative");
$this->getReference("parent", "mixed")->addChild($alt, "_alternative", -1);
$this->setReference("mixed", "_alternative", $alt);//mixedRefs["_alternative"] = $alt;
$this->getReference("parent", "related")->removeChild("_alternative");
unset($this->references["related"]["_alternative"]);
$this->getReference("parent", "mixed")->removeChild("_related");
unset($this->references["mixed"]["_related"]);
}
if (array_keys($this->references["mixed"]) == array("_related"))
{
$this->moveBranchOut($this->references["related"], "related", "mixed", "_related");
}
break;
case (!empty($this->references["mixed"]) && !empty($this->references["related"])):
if (array_keys($this->references["mixed"]) == array("_related"))
{
$this->moveBranchOut($this->references["related"], "related", "mixed", "_related");
}
if (isset($this->references["related"]["_alternative"]))
{
$this->detach("_alternative");
}
break;
case (!empty($this->references["mixed"]) && !empty($this->references["alternative"])):
if (array_keys($this->references["mixed"]) == array("_alternative"))
{
$this->moveBranchOut($this->references["alternative"], "alternative", "mixed", "_alternative");
}
break;
case (!empty($this->references["related"]) && !empty($this->references["alternative"])):
if (array_keys($this->references["related"]) == array("_alternative"))
{
$this->moveBranchOut($this->references["alternative"], "alternative", "related", "_alternative");
}
break;
case (!empty($this->references["mixed"])):
if (isset($this->references["mixed"]["_related"])) $this->detach("_related");
case (!empty($this->references["related"])):
if (isset($this->references["related"]["_alternative"]) || isset($this->references["mixed"]["_alternative"]))
$this->detach("_alternative");
break;
}
}
/**
* Execute needed logic prior to compilation
*/
public function preBuild()
{
$data = $this->getData();
if (!($enc = $this->getEncoding()))
{
$this->setEncoding("8bit");
}
if ($this->getCharset() === null && !$this->numChildren())
{
Swift_ClassLoader::load("Swift_Message_Encoder");
if (is_string($data) && Swift_Message_Encoder::instance()->isUTF8($data))
{
$this->setCharset("utf-8");
}
elseif(is_string($data) && Swift_Message_Encoder::instance()->is7BitAscii($data))
{
$this->setCharset("us-ascii");
if (!$enc) $this->setEncoding("7bit");
}
else $this->setCharset("iso-8859-1");
}
elseif ($this->numChildren())
{
if (!$this->getData())
{
$this->setData($this->getMimeWarning());
$this->setLineWrap(76);
}
if ($this->getCharset() !== null) $this->setCharset(null);
if ($this->isFlowed()) $this->setFlowed(false);
$this->setEncoding("7bit");
}
}
}
+12 -6
View File
@@ -59,17 +59,23 @@ class AdminMondialRelay extends AdminTab
$errorListTicket = $MRCreateTicket->checkPreValidation(); $errorListTicket = $MRCreateTicket->checkPreValidation();
if (count($errorListTicket)) $titleType = array(
{ 'error' => $this->l('Thanks to kindly correct the following errors on ').
$html .= '<div class="error">'.
$this->l('Thanks to kindly correct the following errors on ').
' <a href="index.php?tab=AdminContact&token='.Tools::getAdminToken('AdminContact'. ' <a href="index.php?tab=AdminContact&token='.Tools::getAdminToken('AdminContact'.
(int)Tab::getIdFromClassName('AdminContact').(int)$this->context->id_employee).'" style="color:#f00;">&nbsp;'. (int)Tab::getIdFromClassName('AdminContact').(int)$this->context->id_employee).'" style="color:#f00;">&nbsp;'.
$this->l('the contact page').'</a>:<ul>'; $this->l('the contact page').'</a>:<ul>',
foreach($errorListTicket as $type => $error) 'warn' => $this->l('Please take a look to this following warning, maybe the ticket won\'t be generated'));
foreach($errorListTicket as $errorType => $errorList)
{
if (count($errorList))
{
$html .= '<div class="MR_'.$errorType.'">'.$titleType[$errorType];
foreach($errorList as $type => $error)
$html .= '<li>'.$type.': '.$error.'</li>'; $html .= '<li>'.$type.': '.$error.'</li>';
$html .= '</ul></div>'; $html .= '</ul></div>';
} }
}
$html .= '<p>'.$this->l('All orders which have the state').' "<b>'.$order_state->name.'</b>" '. $html .= '<p>'.$this->l('All orders which have the state').' "<b>'.$order_state->name.'</b>" '.
$this->l('will be available for sticker creation'); $this->l('will be available for sticker creation');
@@ -274,7 +274,7 @@ class MRCreateTickets implements IMondialRelayWSMethod
{ {
$this->_fields['list']['Enseigne']['value'] = Configuration::get('MR_ENSEIGNE_WEBSERVICE'); $this->_fields['list']['Enseigne']['value'] = Configuration::get('MR_ENSEIGNE_WEBSERVICE');
$this->_fields['list']['Expe_Langage']['value'] = Configuration::get('MR_LANGUAGE'); $this->_fields['list']['Expe_Langage']['value'] = Configuration::get('MR_LANGUAGE');
$this->_fields['list']['Expe_Ad1']['value'] = Configuration::get('PS_MR_SHOP_NAME'); $this->_fields['list']['Expe_Ad1']['value'] = Configuration::get('PS_SHOP_NAME');
$this->_fields['list']['Expe_Ad3']['value'] = Configuration::get('PS_SHOP_ADDR1'); $this->_fields['list']['Expe_Ad3']['value'] = Configuration::get('PS_SHOP_ADDR1');
// Deleted, cause to many failed for the process // Deleted, cause to many failed for the process
// $this->_fields['list']['Expe_Ad4']['value'] = Configuration::get('PS_SHOP_ADDR2'); // $this->_fields['list']['Expe_Ad4']['value'] = Configuration::get('PS_SHOP_ADDR2');
@@ -331,7 +331,7 @@ class MRCreateTickets implements IMondialRelayWSMethod
$tmp['NDossier']['value'] = $orderDetail['id_order']; $tmp['NDossier']['value'] = $orderDetail['id_order'];
$tmp['NClient']['value'] = $orderDetail['id_customer']; $tmp['NClient']['value'] = $orderDetail['id_customer'];
$tmp['Dest_Langage']['value'] = 'FR'; //Language::getIsoById($orderDetail['id_lang']); $tmp['Dest_Langage']['value'] = 'FR'; //Language::getIsoById($orderDetail['id_lang']);
$tmp['Dest_Ad1']['value'] = $deliveriesAddress->lastname; $tmp['Dest_Ad1']['value'] = $deliveriesAddress->firstname.' '.$deliveriesAddress->lastname;
$tmp['Dest_Ad2']['value'] = $deliveriesAddress->address2; $tmp['Dest_Ad2']['value'] = $deliveriesAddress->address2;
$tmp['Dest_Ad3']['value'] = $deliveriesAddress->address1; $tmp['Dest_Ad3']['value'] = $deliveriesAddress->address1;
$tmp['Dest_Ville']['value'] = $deliveriesAddress->city; $tmp['Dest_Ville']['value'] = $deliveriesAddress->city;
@@ -342,7 +342,6 @@ class MRCreateTickets implements IMondialRelayWSMethod
$tmp['Dest_Tel2']['value'] = $deliveriesAddress->phone_mobile; $tmp['Dest_Tel2']['value'] = $deliveriesAddress->phone_mobile;
$tmp['Dest_Mail']['value'] = $customer->email; $tmp['Dest_Mail']['value'] = $customer->email;
$tmp['Assurance']['value'] = $orderDetail['mr_ModeAss']; $tmp['Assurance']['value'] = $orderDetail['mr_ModeAss'];
if ($orderDetail['MR_Selected_Num'] != 'LD1' && $orderDetail['MR_Selected_Num'] != 'LDS') if ($orderDetail['MR_Selected_Num'] != 'LD1' && $orderDetail['MR_Selected_Num'] != 'LDS')
{ {
$tmp['LIV_Rel_Pays']['value'] = $orderDetail['MR_Selected_Pays']; $tmp['LIV_Rel_Pays']['value'] = $orderDetail['MR_Selected_Pays'];
@@ -511,7 +510,7 @@ class MRCreateTickets implements IMondialRelayWSMethod
*/ */
public function checkPreValidation() public function checkPreValidation()
{ {
$errorList = array(); $errorList = array('error' => array(), 'warn' => array());
if (!$this->_mondialRelay) if (!$this->_mondialRelay)
$this->_mondialRelay = new MondialRelay(); $this->_mondialRelay = new MondialRelay();
@@ -521,7 +520,7 @@ class MRCreateTickets implements IMondialRelayWSMethod
'value' => Configuration::get('MR_LANGUAGE'), 'value' => Configuration::get('MR_LANGUAGE'),
'error' => $this->_mondialRelay->l('Please check your language configuration')), 'error' => $this->_mondialRelay->l('Please check your language configuration')),
'Expe_Ad1' => array( 'Expe_Ad1' => array(
'value' => Configuration::get('PS_MR_SHOP_NAME'), 'value' => Configuration::get('PS_SHOP_NAME'),
'error' => $this->_mondialRelay->l('Please check your shop name configuration')), 'error' => $this->_mondialRelay->l('Please check your shop name configuration')),
'Expe_Ad3' => array( 'Expe_Ad3' => array(
'value' => Configuration::get('PS_SHOP_ADDR1'), 'value' => Configuration::get('PS_SHOP_ADDR1'),
@@ -531,7 +530,8 @@ class MRCreateTickets implements IMondialRelayWSMethod
'error' => $this->_mondialRelay->l('Please check your city configuration')), 'error' => $this->_mondialRelay->l('Please check your city configuration')),
'Expe_CP' => array( 'Expe_CP' => array(
'value' => Configuration::get('PS_SHOP_CODE'), 'value' => Configuration::get('PS_SHOP_CODE'),
'error' => $this->_mondialRelay->l('Please check your zipcode configuration')), 'error' => $this->_mondialRelay->l('Please check your zipcode configuration'),
'warn' => $this->_mondialRelay->l('It seems the layout of your zipcode country is not configured or you didn\'t set a right zipcode')),
'Expe_Pays' => array( 'Expe_Pays' => array(
'value' => ((_PS_VERSION_ >= '1.4') ? 'value' => ((_PS_VERSION_ >= '1.4') ?
Country::getIsoById(Configuration::get('PS_SHOP_COUNTRY_ID')) : Country::getIsoById(Configuration::get('PS_SHOP_COUNTRY_ID')) :
@@ -546,16 +546,22 @@ class MRCreateTickets implements IMondialRelayWSMethod
foreach($list as $name => $tab) foreach($list as $name => $tab)
{ {
$tab['value'] = strtoupper($tab['value']); // Mac server make an empty string instead of a cleaned string
// TODO : test on windows and linux server
$cleanedString = MRTools::replaceAccentedCharacters($tab['value']);
$tab['value'] = !empty($cleanedString) ? strtoupper($cleanedString) : strtoupper($tab['value']);
if ($name == 'Expe_CP') if ($name == 'Expe_CP')
{ {
if (!MRTools::checkZipcodeByCountry($tab['value'], array( if (!($zipcodeError = MRTools::checkZipcodeByCountry($tab['value'], array(
'id_country' => Configuration::get('PS_COUNTRY_DEFAULT')))) 'id_country' => Configuration::get('PS_COUNTRY_DEFAULT')))))
$errorList[$name] = $tab['error']; $errorList['error'][$name] = $tab['error'];
else if ($zipcodeError < 0)
$errorList['warn'][$name] = $tab['warn'];
} }
else if (isset($this->_fields['list'][$name]['regexValidation']) && else if (isset($this->_fields['list'][$name]['regexValidation']) &&
(!preg_match($this->_fields['list'][$name]['regexValidation'], $tab['value'], $matches))) (!preg_match($this->_fields['list'][$name]['regexValidation'], $tab['value'], $matches)))
$errorList[$name] = $tab['error']; $errorList['error'][$name] = $tab['error'];
} }
return $errorList; return $errorList;
} }
+3 -3
View File
@@ -64,14 +64,14 @@ class MRTools
{ {
$id_country = $params['id_country']; $id_country = $params['id_country'];
$zipcodeFormat = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue(' $zipcodeFormat = Db::getInstance()->getValue('
SELECT `zip_code_format` SELECT `zip_code_format`
FROM `'._DB_PREFIX_.'country` FROM `'._DB_PREFIX_.'country`
WHERE `id_country` = '.(int)$id_country); WHERE `id_country` = '.(int)$id_country);
// Skip the cheking format if doesn't exist // -1 to warn user that no layout exist
if (!$zipcodeFormat) if (!$zipcodeFormat)
return true; return -1;
$regxMask = str_replace( $regxMask = str_replace(
array('N', 'C', 'L'), array('N', 'C', 'L'),
+1 -1
View File
@@ -2,7 +2,7 @@
<module> <module>
<name>mondialrelay</name> <name>mondialrelay</name>
<displayName><![CDATA[Mondial Relay]]></displayName> <displayName><![CDATA[Mondial Relay]]></displayName>
<version><![CDATA[1.7.8]]></version> <version><![CDATA[1.7.9]]></version>
<description><![CDATA[Deliver in Relay points]]></description> <description><![CDATA[Deliver in Relay points]]></description>
<author><![CDATA[]]></author> <author><![CDATA[]]></author>
<tab><![CDATA[shipping_logistics]]></tab> <tab><![CDATA[shipping_logistics]]></tab>

Some files were not shown because too many files have changed in this diff Show More