diff --git a/README.md b/README.md index 0d1f0df50..f11b82139 100644 --- a/README.md +++ b/README.md @@ -2,47 +2,48 @@ README ====== ![PrestaShop](http://www.prestashop.com/images/banners/general/prestashop_728x90.png "PrestaShop") -PREPARATION +ABOUT -------- -To install PrestaShop, you need a remote web server or on your computer (MAMP), with access to a database like MySQL. -You'll need access to phpMyAdmin to create a database and to indicate the information in the database in the installer. +PrestaShop is a free and open-source e-commerce web application, committed to providing the best shopping cart experience for both merchants and consumers. + + +SERVER CONFIGURATION +-------- + +To install PrestaShop, you need a web server running PHP5 and any flavor of MySQL5 (MySQL, MariaDB, Percona Server...). +You will also need a database administration tool, such as phpMyAdmin, in order to create a database for PrestaShop. +We recommend the Apache or Nginx web servers. + +If your host does not offer PHP5 by default, here are a few [explanations][2] about PHP5 or the .htaccess file for certain hosting services (1&1, Free, Lycos, OVH, Infomaniak, Amen, GoDaddy, etc). + +If you want your online store ready to go, visit [http://www.prestabox.com][1]: it lets you create your online store in less than 10 minutes without any technical knowledge. -If you do not host and unable to create your store, we offer a turnkey store, which lets you create your online store in less than 10 minutes without any technical knowledge. -We invite you to visit: [http://www.prestabox.com][1] INSTALLATION -------- -Simply go to your PrestaShop web directory and use installer :-) +With your web browser, go to the root of your PrestaShop directory, and the installer will start. Follow the instructions until PrestaShop is installed. -If you have any PHP error, perhaps you don't have PHP5 or you need to activate it on your web host. -Please go to our forum to find pre-installation settings (PHP 5, htaccess) for certain hosting services (1&1, Free, Lycos, OVH, Infomaniak, Amen, GoDaddy, etc). +If you have any PHP error, perhaps you don't have PHP5 or you need to activate it on your web host. See the page linked above. +If you don't find any solution to start the installer, please post on [the PrestaShop forums][3]. -English webhost [specifics settings][2] - - -If you don't find any solution to launch installer, please post on [our forum][3] - - -There are always solutions for your issues ;-) DOCUMENTATION -------- -For any extra documentation (how-to), please read our [Online documentation][4] +The official PrestaShop documentation is available online [on its own website][4]. FORUMS -------- -You can also discuss, help and contribute with PrestaShop community on [our forums][5] +You can discuss, help and contribute with PrestaShop community on [the PrestaShop forums][5]. - -Thanks for downloading and using PrestaShop e-commerce Open-source solution! +Thank you for downloading and using PrestaShop e-commerce Open-source solution! [1]: http://www.prestabox.com [2]: http://www.prestashop.com/forums/topic/2946-pre-installation-settings-php-5-htaccess-for-certain-hosting-services/ [3]: http://www.prestashop.com/forums/forum/7-installing-prestashop/ [4]: http://doc.prestashop.com -[5]: http://www.prestashop.com/forums/ \ No newline at end of file +[5]: http://www.prestashop.com/forums/ diff --git a/admin-dev/themes/default/template/controllers/groups/helpers/view/view.tpl b/admin-dev/themes/default/template/controllers/groups/helpers/view/view.tpl index eceafdb0c..e2503c9a6 100755 --- a/admin-dev/themes/default/template/controllers/groups/helpers/view/view.tpl +++ b/admin-dev/themes/default/template/controllers/groups/helpers/view/view.tpl @@ -58,6 +58,7 @@

{l s='Members of this customer group'}

+

{l s='Limited to the 100th first customers.'} {l s='Please use filters to narrow your search.'}

{$customerList} {/block} \ No newline at end of file diff --git a/admin-dev/themes/default/template/controllers/import/helpers/form/form.tpl b/admin-dev/themes/default/template/controllers/import/helpers/form/form.tpl index 059ccfdd2..c1949da21 100644 --- a/admin-dev/themes/default/template/controllers/import/helpers/form/form.tpl +++ b/admin-dev/themes/default/template/controllers/import/helpers/form/form.tpl @@ -112,7 +112,6 @@
{l s='Import '} -
{if count($files_to_import)} @@ -146,7 +145,7 @@
+ @@ -66,7 +66,7 @@
{if $page > 1} -   - +   + {/if} {l s='Page'} {$page} / {$total_pages} {if $page < $total_pages} -   - +   + {/if} | {l s='Display'} - {* Choose number of results per page *} {foreach $pagination AS $value} @@ -57,7 +57,7 @@ / {$list_total} {l s='result(s)'} - + @@ -84,7 +84,7 @@ {foreach $fields_display AS $key => $params} diff --git a/admin-dev/themes/default/template/helpers/form/form.tpl b/admin-dev/themes/default/template/helpers/form/form.tpl index ee9ee638a..ed77b5c40 100644 --- a/admin-dev/themes/default/template/helpers/form/form.tpl +++ b/admin-dev/themes/default/template/helpers/form/form.tpl @@ -30,7 +30,7 @@ {if isset($fields.title)}

{$fields.title}

{/if} {block name="defaultForm"} - + {if $form_id} {/if} diff --git a/admin-dev/themes/default/template/helpers/options/options.tpl b/admin-dev/themes/default/template/helpers/options/options.tpl index ea9bb26c2..3c1309690 100644 --- a/admin-dev/themes/default/template/helpers/options/options.tpl +++ b/admin-dev/themes/default/template/helpers/options/options.tpl @@ -34,7 +34,7 @@ {block name="defaultOptions"}
- X + X
diff --git a/classes/Autoload.php b/classes/Autoload.php index 585ad858e..bd1a6715c 100644 --- a/classes/Autoload.php +++ b/classes/Autoload.php @@ -54,6 +54,8 @@ class Autoload $this->root_dir = dirname(dirname(__FILE__)).'/'; if (file_exists($this->root_dir.Autoload::INDEX_FILE)) $this->index = include($this->root_dir.Autoload::INDEX_FILE); + else + $this->generateIndex(); } /** @@ -80,9 +82,8 @@ class Autoload if (strpos(strtolower($classname), 'smarty_') === 0) return; - // regenerate the class index if the requested class is not found in the index or if the requested file doesn't exists - if (!isset($this->index[$classname]) - || ($this->index[$classname] && !is_file($this->root_dir.$this->index[$classname])) + // regenerate the class index if the requested file doesn't exists + if ((isset($this->index[$classname]) && $this->index[$classname] && !is_file($this->root_dir.$this->index[$classname])) || (isset($this->index[$classname.'Core']) && $this->index[$classname.'Core'] && !is_file($this->root_dir.$this->index[$classname.'Core']))) $this->generateIndex(); @@ -138,18 +139,14 @@ class Autoload { $filename_tmp = tempnam(dirname($filename), basename($filename.'.')); if($filename_tmp !== FALSE and file_put_contents($filename_tmp, $content, LOCK_EX) !== FALSE) - { + { @rename($filename_tmp, $filename); - @chmod($filename, 0664); + @chmod($filename, 0666); } - else - { - // $filename_tmp couldn't be written. $filename should be there anyway (even if outdated), - // no need to die. + else + // $filename_tmp couldn't be written. $filename should be there anyway (even if outdated), no need to die. error_log('Cannot write temporary file '.$filename_tmp); - } } - $this->index = $classes; } @@ -192,4 +189,3 @@ class Autoload return isset($this->index[$classname]) ? $this->index[$classname] : null; } } - diff --git a/classes/Cart.php b/classes/Cart.php index e57509cc3..d19fb0ab0 100644 --- a/classes/Cart.php +++ b/classes/Cart.php @@ -762,10 +762,11 @@ class CartCore extends ObjectModel { // You can't add a cart rule that does not exist $cartRule = new CartRule($id_cart_rule, Context::getContext()->language->id); + if (!Validate::isLoadedObject($cartRule)) return false; - if (Db::getInstance()->getValue('SELECT id_cart_rule FROM '._DB_PREFIX_.'cart_cart_rule WHERE id_cart = '.(int)$this->id)) + if (Db::getInstance()->getValue('SELECT id_cart_rule FROM '._DB_PREFIX_.'cart_cart_rule WHERE id_cart_rule = '.(int)$id_cart_rule.' AND id_cart = '.(int)$this->id)) return false; // Add the cart rule to the cart @@ -3415,6 +3416,7 @@ class CartCore extends ObjectModel */ public function setNoMultishipping() { + $emptyCache = $result = false; if (Configuration::get('PS_ALLOW_MULTISHIPPING')) { // Upgrading quantities @@ -3433,7 +3435,9 @@ class CartCore extends ObjectModel AND `id_shop` = '.(int)$this->id_shop.' AND id_product = '.$product['id_product'].' AND id_product_attribute = '.$product['id_product_attribute']; - Db::getInstance()->execute($sql); + $result = Db::getInstance()->execute($sql); + if ($result) + $emptyCache = true; } // Merging multiple lines @@ -3451,15 +3455,18 @@ class CartCore extends ObjectModel } // Update delivery address for each product line - Db::getInstance()->execute(' - UPDATE `'._DB_PREFIX_.'cart_product` + $sql = 'UPDATE `'._DB_PREFIX_.'cart_product` SET `id_address_delivery` = ( SELECT `id_address_delivery` FROM `'._DB_PREFIX_.'cart` WHERE `id_cart` = '.(int)$this->id.' AND `id_shop` = '.(int)$this->id_shop.' ) WHERE `id_cart` = '.(int)$this->id.' - '.(Configuration::get('PS_ALLOW_MULTISHIPPING') ? ' AND `id_shop` = '.(int)$this->id_shop : '')); - + '.(Configuration::get('PS_ALLOW_MULTISHIPPING') ? ' AND `id_shop` = '.(int)$this->id_shop : ''); + + $result = Db::getInstance()->execute($sql); + if ($result) + $emptyCache = true; + if (Customization::isFeatureActive()) Db::getInstance()->execute(' UPDATE `'._DB_PREFIX_.'customization` @@ -3468,6 +3475,9 @@ class CartCore extends ObjectModel WHERE `id_cart` = '.(int)$this->id.' ) WHERE `id_cart` = '.(int)$this->id); + + if ($emptyCache) + $this->_products = null; } /** diff --git a/classes/CartRule.php b/classes/CartRule.php index 10ab17616..ea87a4174 100644 --- a/classes/CartRule.php +++ b/classes/CartRule.php @@ -1190,7 +1190,7 @@ class CartRuleCore extends ObjectModel SELECT cr.*, crl.* FROM '._DB_PREFIX_.'cart_rule cr LEFT JOIN '._DB_PREFIX_.'cart_rule_lang crl ON (cr.id_cart_rule = crl.id_cart_rule AND crl.id_lang = '.(int)$id_lang.') - WHERE code LIKE \'%'.pSQL($name).'%\' + WHERE code LIKE \'%'.pSQL($name).'%\' OR name LIKE \'%'.pSQL($name).'%\' '); } } diff --git a/classes/Connection.php b/classes/Connection.php index 4b171b1f0..7375841c9 100644 --- a/classes/Connection.php +++ b/classes/Connection.php @@ -97,7 +97,7 @@ class ConnectionCore extends ObjectModel 'id_connections' => (int)$cookie->id_connections, 'id_page' => (int)$id_page, 'time_start' => $time_start - )); + ), false, true, Db::INSERT_IGNORE); // This array is serialized and used by the ajax request to identify the page return array( @@ -114,7 +114,7 @@ class ConnectionCore extends ObjectModel // This is a bot and we have to retrieve its connection ID $sql = 'SELECT `id_connections` FROM `'._DB_PREFIX_.'connections` WHERE ip_address = '.ip2long(Tools::getRemoteAddr()).' - AND DATE_ADD(`date_add`, INTERVAL 30 MINUTE) > \''.pSQL(date('Y-m-d H:i:00')).'\' + AND `date_add` > \''.pSQL(date('Y-m-d H:i:00', time() - 1800)).'\' '.Shop::addSqlRestriction(Shop::SHARE_CUSTOMER).' ORDER BY `date_add` DESC'; if ($id_connections = Db::getInstance()->getValue($sql)) @@ -128,7 +128,7 @@ class ConnectionCore extends ObjectModel $sql = 'SELECT `id_guest` FROM `'._DB_PREFIX_.'connections` WHERE `id_guest` = '.(int)$cookie->id_guest.' - AND DATE_ADD(`date_add`, INTERVAL 30 MINUTE) > \''.pSQL(date('Y-m-d H:i:00')).'\' + AND `date_add` > \''.pSQL(date('Y-m-d H:i:00', time() - 1800)).'\' '.Shop::addSqlRestriction(Shop::SHARE_CUSTOMER).' ORDER BY `date_add` DESC'; $result = Db::getInstance()->getRow($sql); diff --git a/classes/Dispatcher.php b/classes/Dispatcher.php index c96926263..7bfaa54ca 100644 --- a/classes/Dispatcher.php +++ b/classes/Dispatcher.php @@ -369,7 +369,7 @@ class DispatcherCore // If there are several languages, get language from uri if ($this->use_routes && Language::isMultiLanguageActivated()) - if (preg_match('#^/([a-z]{2})/#', $this->request_uri, $m)) + if (preg_match('#^/([a-z]{2})/?#', $this->request_uri, $m)) { $_GET['isolang'] = $m[1]; $this->request_uri = substr($this->request_uri, 3); @@ -549,7 +549,7 @@ class DispatcherCore if ($id_shop === null) $id_shop = (int)Context::getContext()->shop->id; - if ($this->use_routes && !isset($this->routes[$id_shop])) + if (!isset($this->routes[$id_shop])) $this->loadRoutes($id_shop); if (!isset($this->routes[$id_shop]) || !isset($this->routes[$id_shop][$id_lang]) || !isset($this->routes[$id_shop][$id_lang][$route_id])) @@ -594,9 +594,9 @@ class DispatcherCore if ($id_shop === null) $id_shop = (int)Context::getContext()->shop->id; - if ($this->use_routes && !isset($this->routes[$id_shop])) + if (!isset($this->routes[$id_shop])) $this->loadRoutes($id_shop); - + if (!isset($this->routes[$id_shop][$id_lang][$route_id])) { $query = http_build_query($params, '', '&'); diff --git a/classes/Link.php b/classes/Link.php index 21e6201ea..cb207e6db 100644 --- a/classes/Link.php +++ b/classes/Link.php @@ -91,12 +91,8 @@ class LinkCore if (!$id_lang) $id_lang = Context::getContext()->language->id; - if (Configuration::get('PS_MULTISHOP_FEATURE_ACTIVE') && $id_shop !== null) - $shop = new Shop($id_shop); - else - $shop = Context::getContext()->shop; - - $url = 'http://'.$shop->domain.$shop->getBaseURI().$this->getLangLink($id_lang, null, $id_shop); + + $url = $this->getBaseLink($id_shop).$this->getLangLink($id_lang, null, $id_shop); if (!is_object($product)) { @@ -163,11 +159,7 @@ class LinkCore if (!$id_lang) $id_lang = Context::getContext()->language->id; - if ($id_shop === null) - $shop = Context::getContext()->shop; - else - $shop = new Shop($id_shop); - $url = 'http://'.$shop->domain.$shop->getBaseURI().$this->getLangLink($id_lang, null, $id_shop); + $url = $this->getBaseLink($id_shop).$this->getLangLink($id_lang, null, $id_shop); if (!is_object($category)) $category = new Category($category, $id_lang); @@ -206,11 +198,7 @@ class LinkCore if (!$id_lang) $id_lang = Context::getContext()->language->id; - if ($id_shop === null) - $shop = Context::getContext()->shop; - else - $shop = new Shop($id_shop); - $url = 'http://'.$shop->domain.$shop->getBaseURI().$this->getLangLink($id_lang, null, $id_shop); + $url = $this->getBaseLink($id_shop).$this->getLangLink($id_lang, null, $id_shop); $dispatcher = Dispatcher::getInstance(); if (!is_object($cms_category)) @@ -239,19 +227,12 @@ class LinkCore * @param int $id_lang * @return string */ - public function getCMSLink($cms, $alias = null, $ssl = false, $id_lang = null, $id_shop = null) + public function getCMSLink($cms, $alias = null, $ssl = null, $id_lang = null, $id_shop = null) { - $base = (($ssl && $this->ssl_enable) ? 'https://' : 'http://'); - if (!$id_lang) $id_lang = Context::getContext()->language->id; - - if ($id_shop === null) - $shop = Context::getContext()->shop; - else - $shop = new Shop($id_shop); - $url = $base.$shop->domain.$shop->getBaseURI().$this->getLangLink($id_lang, null, $id_shop); + $url = $this->getBaseLink($id_shop, $ssl).$this->getLangLink($id_lang, null, $id_shop); $dispatcher = Dispatcher::getInstance(); if (!is_object($cms)) @@ -290,11 +271,8 @@ class LinkCore if (!$id_lang) $id_lang = Context::getContext()->language->id; - if ($id_shop === null) - $shop = Context::getContext()->shop; - else - $shop = new Shop($id_shop); - $url = 'http://'.$shop->domain.$shop->getBaseURI().$this->getLangLink($id_lang, null, $id_shop); + + $url = $this->getBaseLink($id_shop).$this->getLangLink($id_lang, null, $id_shop); $dispatcher = Dispatcher::getInstance(); if (!is_object($supplier)) @@ -327,11 +305,7 @@ class LinkCore if (!$id_lang) $id_lang = Context::getContext()->language->id; - if ($id_shop === null) - $shop = Context::getContext()->shop; - else - $shop = new Shop($id_shop); - $url = 'http://'.$shop->domain.$shop->getBaseURI().$this->getLangLink($id_lang, null, $id_shop); + $url = $this->getBaseLink($id_shop).$this->getLangLink($id_lang, null, $id_shop); $dispatcher = Dispatcher::getInstance(); if (!is_object($manufacturer)) @@ -360,18 +334,12 @@ class LinkCore * @param int $id_lang * @return string */ - public function getModuleLink($module, $controller = 'default', array $params = array(), $ssl = false, $id_lang = null, $id_shop = null) + public function getModuleLink($module, $controller = 'default', array $params = array(), $ssl = null, $id_lang = null, $id_shop = null) { - $base = (($ssl && $this->ssl_enable) ? 'https://' : 'http://'); - if (!$id_lang) $id_lang = Context::getContext()->language->id; - if ($id_shop === null) - $shop = Context::getContext()->shop; - else - $shop = new Shop($id_shop); - $url = $base.$shop->domain.$shop->getBaseURI().$this->getLangLink($id_lang, null, $id_shop); + $url = $this->getBaseLink($id_shop, $ssl).$this->getLangLink($id_lang, null, $id_shop); // If the module has its own route ... just use it ! if (Dispatcher::getInstance()->hasRoute('module-'.$module.'-'.$controller, $id_lang, $id_shop)) @@ -453,10 +421,9 @@ class LinkCore * * @return string Page link */ - public function getPageLink($controller, $ssl = false, $id_lang = null, $request = null, $request_url_encode = false, $id_shop = null) + public function getPageLink($controller, $ssl = null, $id_lang = null, $request = null, $request_url_encode = false, $id_shop = null) { $controller = Tools::strReplaceFirst('.php', '', $controller); - if (!$id_lang) $id_lang = (int)Context::getContext()->language->id; @@ -469,16 +436,9 @@ class LinkCore parse_str($request, $request); } - if ($id_shop === null) - $shop = Context::getContext()->shop; - else - $shop = new Shop($id_shop); - $uri_path = Dispatcher::getInstance()->createUrl($controller, $id_lang, $request, false, '', $id_shop); - $url = ($ssl && $this->ssl_enable) ? 'https://' : 'http://'; - $url .= $shop->domain.$shop->getBaseURI().$this->getLangLink($id_lang, null, $id_shop).ltrim($uri_path, '/'); - return $url; + return $this->getBaseLink($id_shop, $ssl).$this->getLangLink($id_lang, null, $id_shop).ltrim($uri_path, '/'); } public function getCatImageLink($name, $id_category, $type = null) @@ -642,5 +602,26 @@ class LinkCore return Language::getIsoById($id_lang).'/'; } + + protected function getBaseLink($id_shop = null, $ssl = null) + { + static $force_ssl = null; + + if ($ssl === null) + { + if ($force_ssl === null) + $force_ssl = (Configuration::get('PS_SSL_ENABLED') && Configuration::get('PS_SSL_ENABLED_EVERYWHERE')); + $ssl = $force_ssl; + } + + if (Configuration::get('PS_MULTISHOP_FEATURE_ACTIVE') && $id_shop !== null) + $shop = new Shop($id_shop); + else + $shop = Context::getContext()->shop; + + $base = (($ssl && $this->ssl_enable) ? 'https://'.$shop->domain_ssl : 'http://'.$shop->domain); + + return $base.$shop->getBaseURI(); + } } diff --git a/classes/Mail.php b/classes/Mail.php index d53498b32..c4367878a 100644 --- a/classes/Mail.php +++ b/classes/Mail.php @@ -50,10 +50,11 @@ class MailCore * @param bool $modeSMTP * @param string $template_path * @param bool $die + * @param string $bcc Bcc recipient */ public static function Send($id_lang, $template, $subject, $template_vars, $to, $to_name = null, $from = null, $from_name = null, $file_attachment = null, $mode_smtp = null, - $template_path = _PS_MAIL_DIR_, $die = false, $id_shop = null) + $template_path = _PS_MAIL_DIR_, $die = false, $id_shop = null, $bcc = null) { $configuration = Configuration::getMultiple(array( 'PS_SHOP_EMAIL', @@ -127,9 +128,9 @@ class MailCore } /* Construct multiple recipients list if needed */ + $to_list = new Swift_RecipientList(); if (is_array($to) && isset($to)) { - $to_list = new Swift_RecipientList(); foreach ($to as $key => $addr) { $to_name = null; @@ -153,17 +154,20 @@ class MailCore $to_list->addTo($addr, self::mimeEncode($to_name)); } $to_plugin = $to[0]; - $to = $to_list; } else { /* Simple recipient, one address */ $to_plugin = $to; if ($to_name == null) $to_name = $to; if (function_exists('mb_encode_mimeheader')) - $to = new Swift_Address($to, mb_encode_mimeheader($to_name, 'utf-8')); + $to_list->addTo($to, mb_encode_mimeheader($to_name, 'utf-8')); else - $to = new Swift_Address($to, self::mimeEncode($to_name)); + $to_list->addTo($to, self::mimeEncode($to_name)); } + if(isset($bcc)) { + $to_list->addBcc($bcc); + } + $to = $to_list; try { /* Connect with the appropriate configuration */ if ($configuration['PS_MAIL_METHOD'] == 2) @@ -445,4 +449,4 @@ class MailCore return $start . $string . $end; } -} \ No newline at end of file +} diff --git a/classes/Media.php b/classes/Media.php index 86b51e5ff..7ce172f56 100755 --- a/classes/Media.php +++ b/classes/Media.php @@ -39,7 +39,7 @@ class MediaCore 'ui.accordion' => array('fileName' => 'jquery.ui.accordion.min.js', 'dependencies' => array('ui.core', 'ui.widget'), 'theme' => true), 'ui.autocomplete' => array('fileName' => 'jquery.ui.autocomplete.min.js', 'dependencies' => array('ui.core', 'ui.widget', 'ui.position'), 'theme' => true), 'ui.button' => array('fileName' => 'jquery.ui.button.min.js', 'dependencies' => array('ui.core', 'ui.widget'), 'theme' => true), - 'ui.dialog' => array('fileName' => 'jquery.ui.dialog.min.js', 'dependencies' => array('ui.core', 'ui.widget', 'ui.position'), 'theme' => true), + 'ui.dialog' => array('fileName' => 'jquery.ui.dialog.min.js', 'dependencies' => array('ui.core', 'ui.widget', 'ui.position','ui.button'), 'theme' => true), 'ui.slider' => array('fileName' => 'jquery.ui.slider.min.js', 'dependencies' => array('ui.core', 'ui.widget', 'ui.mouse'), 'theme' => true), 'ui.tabs' => array('fileName' => 'jquery.ui.tabs.min.js', 'dependencies' => array('ui.core', 'ui.widget'), 'theme' => true), 'ui.datepicker' => array('fileName' => 'jquery.ui.datepicker.min.js', 'dependencies' => array('ui.core'), 'theme' => true), diff --git a/classes/Meta.php b/classes/Meta.php index e4c3b3147..76933c88b 100644 --- a/classes/Meta.php +++ b/classes/Meta.php @@ -68,8 +68,11 @@ class MetaCore extends ObjectModel { if ($file != 'index.php' && !in_array(strtolower(str_replace('Controller.php', '', $file)), $exlude_pages)) { - $reflection = new ReflectionClass(str_replace('.php', '', $file)); - $properties = $reflection->getDefaultProperties(); + $class_name = str_replace('.php', '', $file); + if (class_exists($class_name)) + $reflection = new ReflectionClass(str_replace('.php', '', $file)); + if (isset($reflection) && $reflection) + $properties = $reflection->getDefaultProperties(); if (isset($properties['php_self'])) $selected_pages[$properties['php_self']] = $properties['php_self']; else if (preg_match('/^[a-z0-9_.-]*\.php$/i', $file)) diff --git a/classes/Product.php b/classes/Product.php index 188ce4a05..19e5917af 100644 --- a/classes/Product.php +++ b/classes/Product.php @@ -3055,18 +3055,18 @@ class ProductCore extends ObjectModel if (!Combination::isFeatureActive()) return array(); $sql = 'SELECT ag.`id_attribute_group`, ag.`is_color_group`, agl.`name` AS group_name, agl.`public_name` AS public_group_name, - a.`id_attribute`, al.`name` AS attribute_name, a.`color` AS attribute_color, pa.`id_product_attribute`, - IFNULL(stock.quantity, 0) as quantity, product_attribute_shop.`price`, product_attribute_shop.`ecotax`, pa.`weight`, + a.`id_attribute`, al.`name` AS attribute_name, a.`color` AS attribute_color, product_attribute_shop.`id_product_attribute`, + IFNULL(stock.quantity, 0) as quantity, product_attribute_shop.`price`, product_attribute_shop.`ecotax`, product_attribute_shop.`weight`, product_attribute_shop.`default_on`, pa.`reference`, product_attribute_shop.`unit_price_impact`, - pa.`minimal_quantity`, pa.`available_date`, ag.`group_type` + product_attribute_shop.`minimal_quantity`, product_attribute_shop.`available_date`, ag.`group_type` FROM `'._DB_PREFIX_.'product_attribute` pa '.Shop::addSqlAssociation('product_attribute', 'pa').' '.Product::sqlStock('pa', 'pa').' - LEFT JOIN `'._DB_PREFIX_.'product_attribute_combination` pac ON pac.`id_product_attribute` = pa.`id_product_attribute` - LEFT JOIN `'._DB_PREFIX_.'attribute` a ON a.`id_attribute` = pac.`id_attribute` - LEFT JOIN `'._DB_PREFIX_.'attribute_group` ag ON ag.`id_attribute_group` = a.`id_attribute_group` - LEFT JOIN `'._DB_PREFIX_.'attribute_lang` al ON a.`id_attribute` = al.`id_attribute` - LEFT JOIN `'._DB_PREFIX_.'attribute_group_lang` agl ON ag.`id_attribute_group` = agl.`id_attribute_group` + LEFT JOIN `'._DB_PREFIX_.'product_attribute_combination` pac ON (pac.`id_product_attribute` = pa.`id_product_attribute`) + LEFT JOIN `'._DB_PREFIX_.'attribute` a ON (a.`id_attribute` = pac.`id_attribute`) + LEFT JOIN `'._DB_PREFIX_.'attribute_group` ag ON (ag.`id_attribute_group` = a.`id_attribute_group`) + LEFT JOIN `'._DB_PREFIX_.'attribute_lang` al ON (a.`id_attribute` = al.`id_attribute`) + LEFT JOIN `'._DB_PREFIX_.'attribute_group_lang` agl ON (ag.`id_attribute_group` = agl.`id_attribute_group`) '.Shop::addSqlAssociation('attribute', 'a').' WHERE pa.`id_product` = '.(int)$this->id.' AND al.`id_lang` = '.(int)$id_lang.' diff --git a/classes/Tools.php b/classes/Tools.php index d8ead1538..38aee11b6 100644 --- a/classes/Tools.php +++ b/classes/Tools.php @@ -1260,6 +1260,13 @@ class ToolsCore return Tools::strtoupper(Tools::substr($str, 0, 1)).Tools::substr($str, 1); } + public static function ucwords($str) + { + if (function_exists('mb_convert_case')) + return mb_convert_case($str, MB_CASE_TITLE); + return ucwords(strtolower($str)); + } + public static function orderbyPrice(&$array, $order_way) { foreach ($array as &$row) @@ -1401,26 +1408,9 @@ class ToolsCore public static function copy($source, $destination, $stream_context = null) { - if ($stream_context == null && preg_match('/^https?:\/\//', $source)) - $stream_context = @stream_context_create(array('http' => array('timeout' => 10))); - - if (in_array(@ini_get('allow_url_fopen'), array('On', 'on', '1')) || !preg_match('/^https?:\/\//', $source)) - return @copy($source, $destination, $stream_context); - elseif (function_exists('curl_init')) - { - $curl = curl_init(); - curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($curl, CURLOPT_URL, $source); - curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5); - curl_setopt($curl, CURLOPT_TIMEOUT, 10); - curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); - $opts = stream_context_get_options($stream_context); - $content = curl_exec($curl); - curl_close($curl); - return file_put_contents($destination, $content); - } - else - return false; + if (is_null($stream_context) && !preg_match('/^https?:\/\//', $source)) + return @copy($source, $destination); + return @file_put_contents($destination, Tools::file_get_contents($source, false, $stream_context)); } /** @@ -1596,7 +1586,8 @@ class ToolsCore if (self::$_cache_nb_media_servers && ($id_media_server = (abs(crc32($filename)) % self::$_cache_nb_media_servers + 1))) return constant('_MEDIA_SERVER_'.$id_media_server.'_'); - return Tools::getShopDomain(); + + return Tools::usingSecureMode() ? Tools::getShopDomainSSL() : Tools::getShopDomain(); } public static function generateHtaccess($path = null, $rewrite_settings = null, $cache_control = null, $specific = '', $disable_multiviews = null, $medias = false, $disable_modsec = null) diff --git a/classes/controller/AdminController.php b/classes/controller/AdminController.php index 82465abf0..84feddee9 100644 --- a/classes/controller/AdminController.php +++ b/classes/controller/AdminController.php @@ -45,7 +45,7 @@ class AdminControllerCore extends Controller public $template = 'content.tpl'; /** @var string Associated table name */ - public $table; + public $table = 'configuration'; public $list_id; @@ -2159,8 +2159,11 @@ class AdminControllerCore extends Controller || !Validate::isUnsignedId($id_lang)) throw new PrestaShopException('get list params is not valid'); - if (isset($this->fields_list[$order_by]) && isset($this->fields_list[$order_by]['filter_key'])) - $order_by = $this->fields_list[$order_by]['filter_key']; + if (!isset($this->fields_list[$order_by]['order_key']) && isset($this->fields_list[$order_by]['filter_key'])) + $this->fields_list[$order_by]['order_key'] = $this->fields_list[$order_by]['filter_key']; + + if (isset($this->fields_list[$order_by]) && isset($this->fields_list[$order_by]['order_key'])) + $order_by = $this->fields_list[$order_by]['order_key']; /* Determine offset from current page */ if ((isset($_POST['submitFilter'.$this->list_id]) || diff --git a/classes/controller/FrontController.php b/classes/controller/FrontController.php index 9725e99f1..cdbbbc696 100644 --- a/classes/controller/FrontController.php +++ b/classes/controller/FrontController.php @@ -65,6 +65,9 @@ class FrontControllerCore extends Controller parent::__construct(); + if (Configuration::get('PS_SSL_ENABLED') && Configuration::get('PS_SSL_ENABLED_EVERYWHERE')) + $this->ssl = true; + if (isset($useSSL)) $this->ssl = $useSSL; else @@ -144,8 +147,6 @@ class FrontControllerCore extends Controller // Init cookie language // @TODO This method must be moved into switchLanguage Tools::setCookieLanguage($this->context->cookie); - - $currency = Tools::setCurrency($this->context->cookie); $protocol_link = (Configuration::get('PS_SSL_ENABLED') || Tools::usingSecureMode()) ? 'https://' : 'http://'; $useSSL = ((isset($this->ssl) && $this->ssl && Configuration::get('PS_SSL_ENABLED')) || Tools::usingSecureMode()) ? true : false; @@ -167,6 +168,8 @@ class FrontControllerCore extends Controller if (($newDefault = $this->geolocationManagement($this->context->country)) && Validate::isLoadedObject($newDefault)) $this->context->country = $newDefault; + $currency = Tools::setCurrency($this->context->cookie); + if (isset($_GET['logout']) || ($this->context->customer->logged && Customer::isBanned($this->context->customer->id))) { $this->context->customer->logout(); @@ -597,7 +600,7 @@ class FrontControllerCore extends Controller if (!$canonical_url || !Configuration::get('PS_CANONICAL_REDIRECT') || strtoupper($_SERVER['REQUEST_METHOD']) != 'GET' || Tools::getValue('live_edit')) return; - $match_url = (($this->ssl && Configuration::get('PS_SSL_ENABLED')) ? 'https://' : 'http://').$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; + $match_url = (($this->ssl) ? 'https://' : 'http://').$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; $match_url = rawurldecode($match_url); if (!preg_match('/^'.Tools::pRegexp(rawurldecode($canonical_url), '/').'([&?].*)?$/', $match_url)) { @@ -667,6 +670,7 @@ class FrontControllerCore extends Controller } } } + if (isset($this->context->cookie->iso_code_country) && $this->context->cookie->iso_code_country && !Validate::isLanguageIsoCode($this->context->cookie->iso_code_country)) $this->context->cookie->iso_code_country = Country::getIsoById(Configuration::get('PS_COUNTRY_DEFAULT')); if (isset($this->context->cookie->iso_code_country) && ($id_country = Country::getByIso(strtoupper($this->context->cookie->iso_code_country)))) diff --git a/classes/helper/HelperForm.php b/classes/helper/HelperForm.php index ff9810baf..3aa90447f 100644 --- a/classes/helper/HelperForm.php +++ b/classes/helper/HelperForm.php @@ -35,10 +35,10 @@ class HelperFormCore extends Helper /** @var array of forms fields */ protected $fields_form = array(); - /** @var array values ​​of form fields */ + /** @var array values of form fields */ public $fields_value = array(); - public $table; + public $table = 'configuration'; public $name_controller = ''; /** @var string if not null, a title will be added on that list */ diff --git a/classes/helper/HelperList.php b/classes/helper/HelperList.php index 69a6127c2..eeb161535 100644 --- a/classes/helper/HelperList.php +++ b/classes/helper/HelperList.php @@ -136,6 +136,9 @@ class HelperListCore extends Helper $this->_list = $list; $this->fields_list = $fields_display; + $this->orderBy = preg_replace('/^([a-z _]*!)/Ui', '', $this->orderBy); + $this->orderWay = preg_replace('/^([a-z _]*!)/Ui', '', $this->orderWay); + // Display list header (filtering, pagination and column names) $tpl_vars['header'] = $this->displayListHeader(); @@ -456,7 +459,7 @@ class HelperListCore extends Helper ); if ($this->specificConfirmDelete !== false) - $data['confirm'] = !is_null($this->specificConfirmDelete) ? '\r'.$this->specificConfirmDelete : addcslashes(Tools::htmlentitiesDecodeUTF8(self::$cache_lang['DeleteItem'].$name), '\''); + $data['confirm'] = !is_null($this->specificConfirmDelete) ? '\r'.$this->specificConfirmDelete : Tools::safeOutput(addcslashes(self::$cache_lang['DeleteItem'].$name, '\'')); $tpl->assign(array_merge($this->tpl_delete_link_vars, $data)); @@ -522,9 +525,6 @@ class HelperListCore extends Helper isset($this->context->cookie->{$this->list_id.'_pagination'}) ? $this->context->cookie->{$this->list_id.'_pagination'} : null ); - // Cleaning links - if (Tools::getValue($this->table.'Orderby') && Tools::getValue($this->table.'Orderway')) - $this->currentIndex = preg_replace('/&'.$this->table.'Orderby=([a-z _]*)&'.$this->table.'Orderway=([a-z]*)/i', '', $this->currentIndex); if ($this->position_identifier && (int)Tools::getValue($this->position_identifier, 1)) $table_id = substr($this->identifier, 3, strlen($this->identifier)); diff --git a/classes/module/Module.php b/classes/module/Module.php index d6a9c1142..f04a72a6a 100644 --- a/classes/module/Module.php +++ b/classes/module/Module.php @@ -118,6 +118,9 @@ abstract class ModuleCore /** @var Smarty_Data */ protected $smarty; + + /** @var currentSmartySubTemplate */ + protected $current_subtemplate = null; const CACHE_FILE_MODULES_LIST = '/config/xml/modules_list.xml'; @@ -1653,20 +1656,35 @@ abstract class ModuleCore if ($cacheId !== null) Tools::enableCache(); - $smarty_subtemplate = $this->context->smarty->createTemplate( - $this->getTemplatePath($template), - $cacheId, - $compileId, - $this->smarty - ); - $result = $smarty_subtemplate->fetch(); + $result = $this->getCurrentSubTemplate($template, $cacheId, $compileId)->fetch(); if ($cacheId !== null) Tools::restoreCacheSettings(); + $this->resetCurrentSubTemplate($template, $cacheId, $compileId); + return $result; } } + + protected function getCurrentSubTemplate($template, $cache_id = null, $compile_id = null) + { + if (!isset($this->current_subtemplate[$template.'_'.$cache_id.'_'.$compile_id])) + { + $this->current_subtemplate[$template.'_'.$cache_id.'_'.$compile_id] = $this->context->smarty->createTemplate( + $this->getTemplatePath($template), + $cache_id, + $compile_id, + $this->smarty + ); + } + return $this->current_subtemplate[$template.'_'.$cache_id.'_'.$compile_id]; + } + + protected function resetCurrentSubTemplate($template, $cache_id, $compile_id) + { + $this->current_subtemplate[$template.'_'.$cache_id.'_'.$compile_id] = null; + } /** * Get realpath of a template of current module (check if template is overriden too) @@ -1696,10 +1714,8 @@ abstract class ModuleCore public function isCached($template, $cacheId = null, $compileId = null) { - $context = Context::getContext(); - Tools::enableCache(); - $is_cached = $context->smarty->isCached($this->getTemplatePath($template), $cacheId, $compileId); + $is_cached = $this->getCurrentSubTemplate($this->getTemplatePath($template), $cacheId, $compileId)->isCached($this->getTemplatePath($template), $cacheId, $compileId); Tools::restoreCacheSettings(); return $is_cached; diff --git a/classes/shop/Shop.php b/classes/shop/Shop.php index 4ca5cf8f4..2b1320c27 100644 --- a/classes/shop/Shop.php +++ b/classes/shop/Shop.php @@ -363,10 +363,12 @@ class ShopCore extends ObjectModel // Define some $_SERVER variables like HTTP_HOST if PHP is launched with php-cli if (Tools::isPHPCLI()) { - if(!isset($_SERVER['HTTP_HOST']) || empty($_SERVER['HTTP_HOST'])) + if (!isset($_SERVER['HTTP_HOST']) || empty($_SERVER['HTTP_HOST'])) $_SERVER['HTTP_HOST'] = $shop->domain; - if(!isset($_SERVER['SERVER_NAME']) || empty($_SERVER['SERVER_NAME'])) + if (!isset($_SERVER['SERVER_NAME']) || empty($_SERVER['SERVER_NAME'])) $_SERVER['SERVER_NAME'] = $shop->domain; + if (!isset($_SERVER['REMOTE_ADDR']) || empty($_SERVER['REMOTE_ADDR'])) + $_SERVER['REMOTE_ADDR'] = '127.0.0.1'; } } else diff --git a/classes/stock/StockAvailable.php b/classes/stock/StockAvailable.php index 12e23cd39..2e47abb49 100644 --- a/classes/stock/StockAvailable.php +++ b/classes/stock/StockAvailable.php @@ -305,11 +305,7 @@ class StockAvailableCore extends ObjectModel if (!Validate::isUnsignedId($id_product)) return false; - if ($id_shop === null) - $id_shop = Context::getContext()->shop->id; - $existing_id = StockAvailable::getStockAvailableIdByProductId((int)$id_product, (int)$id_product_attribute, (int)$id_shop); - if ($existing_id > 0) { Db::getInstance()->update( diff --git a/classes/tax/TaxRulesTaxManager.php b/classes/tax/TaxRulesTaxManager.php index dcb78419e..99cbea94d 100644 --- a/classes/tax/TaxRulesTaxManager.php +++ b/classes/tax/TaxRulesTaxManager.php @@ -80,7 +80,7 @@ class TaxRulesTaxManagerCore implements TaxManagerInterface if (!empty($this->address->postcode)) $postcode = $this->address->postcode; - if (!isset(self::$cache_tax_calculator[$postcode.'-'.$this->type])) + if (!isset(self::$cache_tax_calculator[(int)$this->address->id_country.'-'.$postcode.'-'.$this->type])) { $rows = Db::getInstance()->executeS(' SELECT * diff --git a/classes/webservice/WebserviceRequest.php b/classes/webservice/WebserviceRequest.php index 546370998..2dca1bdb3 100644 --- a/classes/webservice/WebserviceRequest.php +++ b/classes/webservice/WebserviceRequest.php @@ -1289,9 +1289,8 @@ class WebserviceRequestCore $check = ' WHERE ('.implode('OR', $OR).') AND `'.bqSQL($this->resourceConfiguration['fields']['id']['sqlId']).'` = '.(int)$this->urlSegment[1]; if (!Db::getInstance()->getValue($sql.$check)) $this->setError(404, 'This '.$this->resourceConfiguration['retrieveData']['className'].' ('.(int)$this->urlSegment[1].') does not exists on this shop', 131); - else - return $objects; } + return $objects; } if (!count($this->errors)) { diff --git a/controllers/admin/AdminAddressesController.php b/controllers/admin/AdminAddressesController.php index cc411b8eb..7d0e0c6be 100644 --- a/controllers/admin/AdminAddressesController.php +++ b/controllers/admin/AdminAddressesController.php @@ -77,7 +77,7 @@ class AdminAddressesControllerCore extends AdminController parent::initToolbar(); if (!$this->display) $this->toolbar_btn['import'] = array( - 'href' => $this->context->link->getAdminLink('AdminImport', true).'&import_type='.$this->table, + 'href' => $this->context->link->getAdminLink('AdminImport', true).'&import_type=addresses', 'desc' => $this->l('Import') ); } diff --git a/controllers/admin/AdminCategoriesController.php b/controllers/admin/AdminCategoriesController.php index 69db3dc17..e605472ff 100644 --- a/controllers/admin/AdminCategoriesController.php +++ b/controllers/admin/AdminCategoriesController.php @@ -246,7 +246,7 @@ class AdminCategoriesControllerCore extends AdminController 'desc' => $this->l('Add New') ); $this->toolbar_btn['import'] = array( - 'href' => $this->context->link->getAdminLink('AdminImport', true).'&import_type='.$this->table, + 'href' => $this->context->link->getAdminLink('AdminImport', true).'&import_type=categories', 'desc' => $this->l('Import') ); } diff --git a/controllers/admin/AdminCmsController.php b/controllers/admin/AdminCmsController.php index c46c61b88..8d77909e4 100644 --- a/controllers/admin/AdminCmsController.php +++ b/controllers/admin/AdminCmsController.php @@ -110,10 +110,10 @@ class AdminCmsControllerCore extends AdminController 'type' => 'text', 'label' => $this->l('Meta title:'), 'name' => 'meta_title', - 'id' => 'name', // for copy2friendlyUrl compatibility + 'id' => 'name', // for copyMeta2friendlyURL compatibility 'lang' => true, 'required' => true, - 'class' => 'copy2friendlyUrl', + 'class' => 'copyMeta2friendlyURL', 'hint' => $this->l('Invalid characters:').' <>;=#{}', 'size' => 50 ), diff --git a/controllers/admin/AdminCustomerThreadsController.php b/controllers/admin/AdminCustomerThreadsController.php index 3714a0a17..c53945a5b 100644 --- a/controllers/admin/AdminCustomerThreadsController.php +++ b/controllers/admin/AdminCustomerThreadsController.php @@ -380,7 +380,7 @@ class AdminCustomerThreadsControllerCore extends AdminController $cm->id_employee = (int)$this->context->employee->id; $cm->id_customer_thread = $ct->id; - $cm->message = Tools::htmlentitiesutf8(Tools::getValue('reply_message')); + $cm->message = Tools::getValue('reply_message'); $cm->ip_address = ip2long($_SERVER['REMOTE_ADDR']); if (isset($_FILES) && !empty($_FILES['joinFile']['name']) && $_FILES['joinFile']['error'] != 0) $this->errors[] = Tools::displayError('An error occurred during the file upload process.'); @@ -597,11 +597,12 @@ class AdminCustomerThreadsControllerCore extends AdminController } $message['date_add'] = Tools::displayDate($message['date_add'], null, true); $message['user_agent'] = strip_tags($message['user_agent']); + $message['message'] = preg_replace( '/(https?:\/\/[a-z0-9#%&_=\(\)\.\? \+\-@\/]{6,1000})([\s\n<])/Uui', '\1\2', html_entity_decode($message['message'], - ENT_NOQUOTES, 'UTF-8') + ENT_QUOTES, 'UTF-8') ); $tpl->assign(array( diff --git a/controllers/admin/AdminCustomersController.php b/controllers/admin/AdminCustomersController.php index d4edc5926..98194a0f5 100644 --- a/controllers/admin/AdminCustomersController.php +++ b/controllers/admin/AdminCustomersController.php @@ -190,7 +190,7 @@ class AdminCustomersControllerCore extends AdminController else if (!$this->display) //display import button only on listing { $this->toolbar_btn['import'] = array( - 'href' => $this->context->link->getAdminLink('AdminImport', true).'&import_type='.$this->table, + 'href' => $this->context->link->getAdminLink('AdminImport', true).'&import_type=customers', 'desc' => $this->l('Import') ); } diff --git a/controllers/admin/AdminGroupsController.php b/controllers/admin/AdminGroupsController.php index 3c8f26a79..007bd38b0 100644 --- a/controllers/admin/AdminGroupsController.php +++ b/controllers/admin/AdminGroupsController.php @@ -193,7 +193,7 @@ class AdminGroupsControllerCore extends AdminController 'active' => array('title' => $this->l('Enabled'),'align' => 'center','width' => 20, 'active' => 'status','type' => 'bool') )); - $customer_list = $group->getCustomers(false, 0, 0, true); + $customer_list = $group->getCustomers(false, 0, 100, true); $helper = new HelperList(); $helper->currentIndex = Context::getContext()->link->getAdminLink('AdminCustomers', false); diff --git a/controllers/admin/AdminHomeController.php b/controllers/admin/AdminHomeController.php index 96d37e035..45797273e 100644 --- a/controllers/admin/AdminHomeController.php +++ b/controllers/admin/AdminHomeController.php @@ -503,7 +503,7 @@ class AdminHomeControllerCore extends AdminController // SHOW TIPS OF THE DAY $content = Tools::file_get_contents($protocol.'api.prestashop.com/partner/tipsoftheday/?iso_country='.$isoCountry.'&iso_lang='.Tools::strtolower($isoUser), false, $stream_context); - $content = explode('|', utf8_encode($content)); + $content = explode('|', $content); if ($content[0] == 'OK' && Validate::isCleanHtml($content[1])) $result['discover_prestashop'] .= '
'.$content[1].'
'; diff --git a/controllers/admin/AdminImagesController.php b/controllers/admin/AdminImagesController.php index 13b505f0f..922fcf050 100644 --- a/controllers/admin/AdminImagesController.php +++ b/controllers/admin/AdminImagesController.php @@ -52,8 +52,17 @@ class AdminImagesControllerCore extends AdminController 'stores' => array('title' => $this->l('Stores'), 'width' => 50, 'align' => 'center', 'type' => 'bool', 'callback' => 'printEntityActiveIcon', 'orderby' => false) ); - // No need to display the old image system if the install has been made later than 2013-03-26 - $this->display_move = (!Configuration::get('PS_LEGACY_IMAGES') && defined('_PS_CREATION_DATE_') && strtotime(_PS_CREATION_DATE_) > strtotime('2013-03-26')) ? false : true; + // No need to display the old image system migration tool except if product images are in _PS_PROD_IMG_DIR_ + $this->display_move = false; + $dir = _PS_PROD_IMG_DIR_; + if (is_dir($dir)) + if ($dh = opendir($dir)) + { + while (($file = readdir($dh)) !== false && $this->display_move == false) + if (!is_dir($dir.DIRECTORY_SEPARATOR.$file) && $file[0] != '.' && is_numeric($file[0])) + $this->display_move = true; + closedir($dh); + } $this->fields_options = array( 'images' => array( diff --git a/controllers/admin/AdminImportController.php b/controllers/admin/AdminImportController.php index b0bef57b6..ca3c3050d 100644 --- a/controllers/admin/AdminImportController.php +++ b/controllers/admin/AdminImportController.php @@ -465,11 +465,20 @@ class AdminImportControllerCore extends AdminController $this->addCSS(_PS_CSS_DIR_.'jquery.fancybox-1.3.4.css', 'screen'); $this->addJqueryPlugin(array('fancybox')); + $entity_selected = 0; + if (isset($this->entities[$this->l(Tools::ucfirst(Tools::getValue('import_type')))])) + { + $entity_selected = $this->entities[$this->l(Tools::ucfirst(Tools::getValue('import_type')))]; + $this->context->cookie->entity_selected = $entity_selected; + } + elseif(isset($this->context->cookie->entity_selected)) + $entity_selected = (int)$this->context->cookie->entity_selected; + $this->tpl_form_vars = array( 'module_confirmation' => (Tools::getValue('import')) && (isset($this->warnings) && !count($this->warnings)), 'path_import' => _PS_ADMIN_DIR_.'/import/', 'entities' => $this->entities, - 'entity' => Tools::getValue('entity'), + 'entity_selected' => $entity_selected, 'files_to_import' => $files_to_import, 'languages' => Language::getLanguages(false), 'id_language' => $this->context->language->id, @@ -497,6 +506,9 @@ class AdminImportControllerCore extends AdminController for ($i = 0; $i < $nb_table; $i++) $data[$i] = $this->generateContentTable($i, $nb_column, $handle, $this->separator); + if ($entity_selected = (int)Tools::getValue('entity')) + $this->context->cookie->entity_selected = $entity_selected; + $this->tpl_view_vars = array( 'import_matchs' => Db::getInstance()->executeS('SELECT * FROM '._DB_PREFIX_.'import_match'), 'fields_value' => array( @@ -874,1951 +886,4 @@ class AdminImportControllerCore extends AdminController if (isset($category->parent) && is_numeric($category->parent)) { - if (isset($cat_moved[$category->parent])) - $category->parent = $cat_moved[$category->parent]; - $category->id_parent = $category->parent; - } - elseif (isset($category->parent) && is_string($category->parent)) - { - $category_parent = Category::searchByName($default_language_id, $category->parent, true); - if ($category_parent['id_category']) - { - $category->id_parent = (int)$category_parent['id_category']; - $category->level_depth = (int)$category_parent['level_depth'] + 1; - } - else - { - $category_to_create = new Category(); - $category_to_create->name = AdminImportController::createMultiLangField($category->parent); - $category_to_create->active = 1; - $category_link_rewrite = Tools::link_rewrite($category_to_create->name[$default_language_id]); - $category_to_create->link_rewrite = $category_link_rewrite; - $category_to_create->id_parent = Configuration::get('PS_HOME_CATEGORY'); // Default parent is home for unknown category to create - if (($field_error = $category_to_create->validateFields(UNFRIENDLY_ERROR, true)) === true && - ($lang_field_error = $category_to_create->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && $category_to_create->add()) - $category->id_parent = $category_to_create->id; - else - { - $this->errors[] = sprintf( - Tools::displayError('%1$s (ID: %2$s) cannot be saved'), - $category_to_create->name[$default_language_id], - (isset($category_to_create->id) ? $category_to_create->id : 'null') - ); - $this->errors[] = ($field_error !== true ? $field_error : '').(isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : ''). - Db::getInstance()->getMsgError(); - } - } - } - if (isset($category->link_rewrite) && !empty($category->link_rewrite[$default_language_id])) - $valid_link = Validate::isLinkRewrite($category->link_rewrite[$default_language_id]); - else - $valid_link = false; - - if (!Shop::isFeatureActive()) - $category->id_shop_default = 1; - else - $category->id_shop_default = (int)Context::getContext()->shop->id; - - $bak = $category->link_rewrite[$default_language_id]; - if ((isset($category->link_rewrite) && empty($category->link_rewrite[$default_language_id])) || !$valid_link) - { - $category->link_rewrite = Tools::link_rewrite($category->name[$default_language_id]); - if ($category->link_rewrite == '') - { - $category->link_rewrite = 'friendly-url-autogeneration-failed'; - $this->warnings[] = sprintf(Tools::displayError('URL rewriting failed to auto-generate a friendly URL for: %s'), $category->name[$default_language_id]); - } - $category->link_rewrite = AdminImportController::createMultiLangField($category->link_rewrite); - } - - if (!$valid_link) - $this->warnings[] = sprintf( - Tools::displayError('Rewrite link for %1$s (ID: %2$s) was re-written as %3$s.'), - $bak, - (isset($info['id']) ? $info['id'] : 'null'), - $category->link_rewrite[$default_language_id] - ); - $res = false; - if (($field_error = $category->validateFields(UNFRIENDLY_ERROR, true)) === true && - ($lang_field_error = $category->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && empty($this->errors)) - { - $category_already_created = Category::searchByNameAndParentCategoryId( - $default_language_id, - $category->name[$default_language_id], - $category->id_parent - ); - - // If category already in base, get id category back - if ($category_already_created['id_category']) - { - $cat_moved[$category->id] = (int)$category_already_created['id_category']; - $category->id = (int)$category_already_created['id_category']; - } - - if ($category->id && $category->id == $category->id_parent) - { - $this->errors[] = Tools::displayError('a category cannot be its own parent'); - continue; - } - - /* No automatic nTree regeneration for import */ - $category->doNotRegenerateNTree = true; - - // If id category AND id category already in base, trying to update - $categories_home_root = array(Configuration::get('PS_ROOT_CATEGORY'), Configuration::get('PS_HOME_CATEGORY')); - if ($category->id && $category->categoryExists($category->id) && !in_array($category->id, $categories_home_root)) - $res = $category->update(); - if ($category->id == Configuration::get('PS_ROOT_CATEGORY')) - $this->errors[] = Tools::displayError('The root category cannot be modified.'); - // If no id_category or update failed - if (!$res) - $res = $category->add(); - } - //copying images of categories - if (isset($category->image) && !empty($category->image)) - if (!(AdminImportController::copyImg($category->id, null, $category->image, 'categories'))) - $this->warnings[] = $category->image.' '.Tools::displayError('cannot be copied.'); - // If both failed, mysql error - if (!$res) - { - $this->errors[] = sprintf( - Tools::displayError('%1$s (ID: %2$s) cannot be saved'), - (isset($info['name']) ? Tools::safeOutput($info['name']) : 'No Name'), - (isset($info['id']) ? Tools::safeOutput($info['id']) : 'No ID') - ); - $error_tmp = ($field_error !== true ? $field_error : '').(isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '').Db::getInstance()->getMsgError(); - if ($error_tmp != '') - $this->errors[] = $error_tmp; - } - else - { - // Associate category to shop - if (Shop::isFeatureActive()) - { - Db::getInstance()->execute(' - DELETE FROM '._DB_PREFIX_.'category_shop - WHERE id_category = '.(int)$category->id - ); - - if (!Shop::isFeatureActive()) - $info['shop'] = 1; - elseif (!isset($info['shop']) || empty($info['shop'])) - $info['shop'] = implode($this->multiple_value_separator, Shop::getContextListShopID()); - - // Get shops for each attributes - $info['shop'] = explode($this->multiple_value_separator, $info['shop']); - - foreach ($info['shop'] as $shop) - if (!is_numeric($shop)) - $category->addShop(Shop::getIdByName($shop)); - else - $category->addShop($shop); - } - } - } - - /* Import has finished, we can regenerate the categories nested tree */ - Category::regenerateEntireNtree(); - - $this->closeCsvFile($handle); - } - - public function productImport() - { - $this->receiveTab(); - $handle = $this->openCsvFile(); - $default_language_id = (int)Configuration::get('PS_LANG_DEFAULT'); - AdminImportController::setLocale(); - $shop_ids = Shop::getCompleteListOfShopsID(); - for ($current_line = 0; $line = fgetcsv($handle, MAX_LINE_SIZE, $this->separator); $current_line++) - { - if (Tools::getValue('convert')) - $line = $this->utf8EncodeArray($line); - $info = AdminImportController::getMaskedRow($line); - - if (Tools::getValue('forceIDs') && isset($info['id']) && (int)$info['id']) - $product = new Product((int)$info['id']); - else - { - if (array_key_exists('id', $info) && (int)$info['id'] && Product::existsInDatabase((int)$info['id'], 'product')) - $product = new Product((int)$info['id']); - else - $product = new Product(); - } - - if (array_key_exists('id', $info) && (int)$info['id'] && Product::existsInDatabase((int)$info['id'], 'product')) - { - $product->loadStockData(); - $category_data = Product::getProductCategories((int)$product->id); - foreach ($category_data as $tmp) - $product->category[] = $tmp; - } - - AdminImportController::setEntityDefaultValues($product); - AdminImportController::arrayWalk($info, array('AdminImportController', 'fillInfo'), $product); - - if (!Shop::isFeatureActive()) - $product->shop = 1; - elseif (!isset($product->shop) || empty($product->shop)) - $product->shop = implode($this->multiple_value_separator, Shop::getContextListShopID()); - - if (!Shop::isFeatureActive()) - $product->id_shop_default = 1; - else - $product->id_shop_default = (int)Context::getContext()->shop->id; - - // link product to shops - $product->id_shop_list = array(); - foreach (explode($this->multiple_value_separator, $product->shop) as $shop) - if (!is_numeric($shop)) - $product->id_shop_list[] = Shop::getIdByName($shop); - else - $product->id_shop_list[] = $shop; - - if ((int)$product->id_tax_rules_group != 0) - { - if (Validate::isLoadedObject(new TaxRulesGroup($product->id_tax_rules_group))) - { - $address = $this->context->shop->getAddress(); - $tax_manager = TaxManagerFactory::getManager($address, $product->id_tax_rules_group); - $product_tax_calculator = $tax_manager->getTaxCalculator(); - $product->tax_rate = $product_tax_calculator->getTotalRate(); - } - else - $this->addProductWarning( - 'id_tax_rules_group', - $product->id_tax_rules_group, - Tools::displayError('Invalid tax rule group ID. You first need to create a group with this ID.') - ); - } - if (isset($product->manufacturer) && is_numeric($product->manufacturer) && Manufacturer::manufacturerExists((int)$product->manufacturer)) - $product->id_manufacturer = (int)$product->manufacturer; - else if (isset($product->manufacturer) && is_string($product->manufacturer) && !empty($product->manufacturer)) - { - if ($manufacturer = Manufacturer::getIdByName($product->manufacturer)) - $product->id_manufacturer = (int)$manufacturer; - else - { - $manufacturer = new Manufacturer(); - $manufacturer->name = $product->manufacturer; - if (($field_error = $manufacturer->validateFields(UNFRIENDLY_ERROR, true)) === true && - ($lang_field_error = $manufacturer->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && $manufacturer->add()) - $product->id_manufacturer = (int)$manufacturer->id; - else - { - $this->errors[] = sprintf( - Tools::displayError('%1$s (ID: %2$s) cannot be saved'), - $manufacturer->name, - (isset($manufacturer->id) ? $manufacturer->id : 'null') - ); - $this->errors[] = ($field_error !== true ? $field_error : '').(isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : ''). - Db::getInstance()->getMsgError(); - } - } - } - - if (isset($product->supplier) && is_numeric($product->supplier) && Supplier::supplierExists((int)$product->supplier)) - $product->id_supplier = (int)$product->supplier; - else if (isset($product->supplier) && is_string($product->supplier) && !empty($product->supplier)) - { - if ($supplier = Supplier::getIdByName($product->supplier)) - $product->id_supplier = (int)$supplier; - else - { - $supplier = new Supplier(); - $supplier->name = $product->supplier; - $supplier->active = true; - - if (($field_error = $supplier->validateFields(UNFRIENDLY_ERROR, true)) === true && - ($lang_field_error = $supplier->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && $supplier->add()) - { - $product->id_supplier = (int)$supplier->id; - $supplier->associateTo($product->id_shop_list); - } - else - { - $this->errors[] = sprintf( - Tools::displayError('%1$s (ID: %2$s) cannot be saved'), - $supplier->name, - (isset($supplier->id) ? $supplier->id : 'null') - ); - $this->errors[] = ($field_error !== true ? $field_error : '').(isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : ''). - Db::getInstance()->getMsgError(); - } - } - } - - if (isset($product->price_tex) && !isset($product->price_tin)) - $product->price = $product->price_tex; - else if (isset($product->price_tin) && !isset($product->price_tex)) - { - $product->price = $product->price_tin; - // If a tax is already included in price, withdraw it from price - if ($product->tax_rate) - $product->price = (float)number_format($product->price / (1 + $product->tax_rate / 100), 6, '.', ''); - } - else if (isset($product->price_tin) && isset($product->price_tex)) - $product->price = $product->price_tex; - - if (isset($product->category) && is_array($product->category) && count($product->category)) - { - $product->id_category = array(); // Reset default values array - foreach ($product->category as $value) - { - if (is_numeric($value)) - { - if (Category::categoryExists((int)$value)) - $product->id_category[] = (int)$value; - else - { - $category_to_create = new Category(); - $category_to_create->id = (int)$value; - $category_to_create->name = AdminImportController::createMultiLangField($value); - $category_to_create->active = 1; - $category_to_create->id_parent = Configuration::get('PS_HOME_CATEGORY'); // Default parent is home for unknown category to create - $category_link_rewrite = Tools::link_rewrite($category_to_create->name[$default_language_id]); - $category_to_create->link_rewrite = AdminImportController::createMultiLangField($category_link_rewrite); - if (($field_error = $category_to_create->validateFields(UNFRIENDLY_ERROR, true)) === true && - ($lang_field_error = $category_to_create->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && $category_to_create->add()) - $product->id_category[] = (int)$category_to_create->id; - else - { - $this->errors[] = sprintf( - Tools::displayError('%1$s (ID: %2$s) cannot be saved'), - $category_to_create->name[$default_language_id], - (isset($category_to_create->id) ? $category_to_create->id : 'null') - ); - $this->errors[] = ($field_error !== true ? $field_error : '').(isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : ''). - Db::getInstance()->getMsgError(); - } - } - } - else if (is_string($value) && !empty($value)) - { - $category = Category::searchByName($default_language_id, trim($value), true); - if ($category['id_category']) - $product->id_category[] = (int)$category['id_category']; - else - { - $category_to_create = new Category(); - if (!Shop::isFeatureActive()) - $category_to_create->id_shop_default = 1; - else - $category_to_create->id_shop_default = (int)Context::getContext()->shop->id; - $category_to_create->name = AdminImportController::createMultiLangField(trim($value)); - $category_to_create->active = 1; - $category_to_create->id_parent = (int)Configuration::get('PS_HOME_CATEGORY'); // Default parent is home for unknown category to create - $category_link_rewrite = Tools::link_rewrite($category_to_create->name[$default_language_id]); - $category_to_create->link_rewrite = AdminImportController::createMultiLangField($category_link_rewrite); - if (($field_error = $category_to_create->validateFields(UNFRIENDLY_ERROR, true)) === true && - ($lang_field_error = $category_to_create->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && $category_to_create->add()) - $product->id_category[] = (int)$category_to_create->id; - else - { - $this->errors[] = sprintf( - Tools::displayError('%1$s (ID: %2$s) cannot be saved'), - $category_to_create->name[$default_language_id], - (isset($category_to_create->id) ? $category_to_create->id : 'null') - ); - $this->errors[] = ($field_error !== true ? $field_error : '').(isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : ''). - Db::getInstance()->getMsgError(); - } - } - } - } - } - - $product->id_category_default = isset($product->id_category[0]) ? (int)$product->id_category[0] : ''; - - $link_rewrite = (is_array($product->link_rewrite) && count($product->link_rewrite)) ? trim($product->link_rewrite[$default_language_id]) : ''; - - $valid_link = Validate::isLinkRewrite($link_rewrite); - - if ((isset($product->link_rewrite[$default_language_id]) && empty($product->link_rewrite[$default_language_id])) || !$valid_link) - { - $link_rewrite = Tools::link_rewrite($product->name[$default_language_id]); - if ($link_rewrite == '') - $link_rewrite = 'friendly-url-autogeneration-failed'; - } - - if (!$valid_link) - $this->warnings[] = sprintf( - Tools::displayError('Rewrite link for %1$s (ID: %2$s) was re-written as %3$s.'), - $product->name[$default_language_id], - (isset($info['id']) ? $info['id'] : 'null'), - $link_rewrite - ); - - $product->link_rewrite = AdminImportController::createMultiLangField($link_rewrite); - - // replace the value of separator by coma - if ($this->multiple_value_separator != ',') - foreach ($product->meta_keywords as &$meta_keyword) - if (!empty($meta_keyword)) - $meta_keyword = str_replace($this->multiple_value_separator, ',', $meta_keyword); - - // Convert comma into dot for all floating values - foreach (Product::$definition['fields'] as $key => $array) - if ($array['type'] == Product::TYPE_FLOAT) - $product->{$key} = str_replace(',', '.', $product->{$key}); - - // Indexation is already 0 if it's a new product, but not if it's an update - $product->indexed = 0; - - $res = false; - $field_error = $product->validateFields(UNFRIENDLY_ERROR, true); - $lang_field_error = $product->validateFieldsLang(UNFRIENDLY_ERROR, true); - if ($field_error === true && $lang_field_error === true) - { - // check quantity - if ($product->quantity == null) - $product->quantity = 0; - - // If match ref is specified && ref product && ref product already in base, trying to update - if (Tools::getValue('match_ref') == 1 && $product->reference && $product->existsRefInDatabase($product->reference)) - { - $datas = Db::getInstance()->getRow(' - SELECT product_shop.`date_add`, p.`id_product` - FROM `'._DB_PREFIX_.'product` p - '.Shop::addSqlAssociation('product', 'p').' - WHERE p.`reference` = "'.$product->reference.'" - '); - $product->id = (int)$datas['id_product']; - $product->date_add = pSQL($datas['date_add']); - $res = $product->update(); - } // Else If id product && id product already in base, trying to update - else if ($product->id && Product::existsInDatabase((int)$product->id, 'product')) - { - $datas = Db::getInstance()->getRow(' - SELECT product_shop.`date_add` - FROM `'._DB_PREFIX_.'product` p - '.Shop::addSqlAssociation('product', 'p').' - WHERE p.`id_product` = '.(int)$product->id); - $product->date_add = pSQL($datas['date_add']); - $res = $product->update(); - } - // If no id_product or update failed - if (!$res) - { - if (isset($product->date_add) && $product->date_add != '') - $res = $product->add(false); - else - $res = $product->add(); - } - } - - $shops = array(); - $product_shop = explode($this->multiple_value_separator, $product->shop); - foreach ($product_shop as $shop) - { - $shop = trim($shop); - if (!is_numeric($shop)) - $shop = Shop::getIdByName($shop); - - if (in_array($shop, $shop_ids)) - $shops[] = $shop; - else - $this->addProductWarning(Tools::safeOutput($info['name']), $product->id, $this->l('Shop is not valid')); - } - if (empty($shops)) - $shops = Shop::getContextListShopID(); - // If both failed, mysql error - if (!$res) - { - $this->errors[] = sprintf( - Tools::displayError('%1$s (ID: %2$s) cannot be saved'), - (isset($info['name']) ? Tools::safeOutput($info['name']) : 'No Name'), - (isset($info['id']) ? Tools::safeOutput($info['id']) : 'No ID') - ); - $this->errors[] = ($field_error !== true ? $field_error : '').(isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : ''). - Db::getInstance()->getMsgError(); - - } - else - { - // Product supplier - if (isset($product->id_supplier) && isset($product->supplier_reference)) - { - $id_product_supplier = ProductSupplier::getIdByProductAndSupplier((int)$product->id, 0, (int)$product->id_supplier); - if ($id_product_supplier) - $product_supplier = new ProductSupplier((int)$id_product_supplier); - else - $product_supplier = new ProductSupplier(); - - $product_supplier->id_product = $product->id; - $product_supplier->id_product_attribute = 0; - $product_supplier->id_supplier = $product->id_supplier; - $product_supplier->product_supplier_price_te = $product->wholesale_price; - $product_supplier->product_supplier_reference = $product->supplier_reference; - $product_supplier->save(); - } - - // SpecificPrice (only the basic reduction feature is supported by the import) - if ((isset($info['reduction_price']) && $info['reduction_price'] > 0) || (isset($info['reduction_percent']) && $info['reduction_percent'] > 0)) - { - $specific_price = new SpecificPrice(); - $specific_price->id_product = (int)$product->id; - // @todo multishop specific price import - $specific_price->id_shop = $this->context->shop->id; - $specific_price->id_currency = 0; - $specific_price->id_country = 0; - $specific_price->id_group = 0; - $specific_price->price = -1; - $specific_price->id_customer = 0; - $specific_price->from_quantity = 1; - $specific_price->reduction = (isset($info['reduction_price']) && $info['reduction_price']) ? $info['reduction_price'] : $info['reduction_percent'] / 100; - $specific_price->reduction_type = (isset($info['reduction_price']) && $info['reduction_price']) ? 'amount' : 'percentage'; - $specific_price->from = (isset($info['reduction_from']) && Validate::isDate($info['reduction_from'])) ? $info['reduction_from'] : '0000-00-00 00:00:00'; - $specific_price->to = (isset($info['reduction_to']) && Validate::isDate($info['reduction_to'])) ? $info['reduction_to'] : '0000-00-00 00:00:00'; - if (!$specific_price->add()) - $this->addProductWarning(Tools::safeOutput($info['name']), $product->id, $this->l('Discount is invalid')); - } - - if (isset($product->tags) && !empty($product->tags)) - { - // Delete tags for this id product, for no duplicating error - Tag::deleteTagsForProduct($product->id); - - if (!is_array($product->tags)) - { - $product->tags = AdminImportController::createMultiLangField($product->tags); - foreach ($product->tags as $key => $tags) - { - $is_tag_added = Tag::addTags($key, $product->id, $tags, $this->multiple_value_separator); - if (!$is_tag_added) - { - $this->addProductWarning(Tools::safeOutput($info['name']), $product->id, $this->l('Tags list is invalid')); - break; - } - } - } - else - { - foreach ($product->tags as $key => $tags) - { - $str = ''; - foreach ($tags as $one_tag) - $str .= $one_tag.$this->multiple_value_separator; - $str = rtrim($str, $this->multiple_value_separator); - - $is_tag_added = Tag::addTags($key, $product->id, $str, $this->multiple_value_separator); - if (!$is_tag_added) - { - $this->addProductWarning(Tools::safeOutput($info['name']), (int)$product->id, 'Invalid tag(s) ('.$str.')'); - break; - } - } - } - } - //delete existing images if "delete_existing_images" is set to 1 - if (isset($product->delete_existing_images)) - if ((bool)$product->delete_existing_images) - $product->deleteImages(); - else if (isset($product->image) && is_array($product->image) && count($product->image)) - $product->deleteImages(); - - if (isset($product->image) && is_array($product->image) && count($product->image)) - { - $product_has_images = (bool)Image::getImages($this->context->language->id, (int)$product->id); - foreach ($product->image as $key => $url) - { - $url = trim($url); - $error = false; - if (!empty($url)) - { - $url = str_replace(' ', '%20', $url); - - $image = new Image(); - $image->id_product = (int)$product->id; - $image->position = Image::getHighestPosition($product->id) + 1; - $image->cover = (!$key && !$product_has_images) ? true : false; - // file_exists doesn't work with HTTP protocol - if (($field_error = $image->validateFields(UNFRIENDLY_ERROR, true)) === true && - ($lang_field_error = $image->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && $image->add()) - { - // associate image to selected shops - $image->associateTo($shops); - if (!AdminImportController::copyImg($product->id, $image->id, $url)) - { - $image->delete(); - $this->warnings[] = sprintf(Tools::displayError('Error copying image: %s'), $url); - } - } - else - $error = true; - } - else - $error = true; - - if ($error) - $this->warnings[] = sprintf(Tools::displayError('Product n°%1$d: the picture cannot be saved: %2$s'), $image->id_product, $url); - } - } - if (isset($product->id_category)) - $product->updateCategories(array_map('intval', $product->id_category)); - - // Features import - $features = get_object_vars($product); - - if (isset($features['features']) && !empty($features['features'])) - foreach (explode($this->multiple_value_separator, $features['features']) as $single_feature) - { - $tab_feature = explode(':', $single_feature); - $feature_name = trim($tab_feature[0]); - $feature_value = trim($tab_feature[1]); - $position = isset($tab_feature[2]) ? $tab_feature[2]: false; - if(!empty($feature_name) && !empty($feature_value)) - { - $id_feature = Feature::addFeatureImport($feature_name, $position); - $id_feature_value = FeatureValue::addFeatureValueImport($id_feature, $feature_value); - Product::addFeatureProductImport($product->id, $id_feature, $id_feature_value); - } - } - // clean feature positions to avoid conflict - Feature::cleanPositions(); - } - - // stock available - if (Shop::isFeatureActive()) - { - foreach ($shops as $shop) - StockAvailable::setQuantity((int)$product->id, 0, $product->quantity, (int)$shop); - } - else - StockAvailable::setQuantity((int)$product->id, 0, $product->quantity, $this->context->shop->id); - - } - - $this->closeCsvFile($handle); - } - - public function attributeImport() - { - $default_language = Configuration::get('PS_LANG_DEFAULT'); - - $groups = array(); - foreach (AttributeGroup::getAttributesGroups($default_language) as $group) - $groups[$group['name']] = (int)$group['id_attribute_group']; - - $attributes = array(); - foreach (Attribute::getAttributes($default_language) as $attribute) - $attributes[$attribute['attribute_group'].'_'.$attribute['name']] = (int)$attribute['id_attribute']; - - $this->receiveTab(); - $handle = $this->openCsvFile(); - AdminImportController::setLocale(); - for ($current_line = 0; $line = fgetcsv($handle, MAX_LINE_SIZE, $this->separator); $current_line++) - { - if (count($line) == 1 && empty($line[0])) - continue; - - if (Tools::getValue('convert')) - $line = $this->utf8EncodeArray($line); - $info = AdminImportController::getMaskedRow($line); - $info = array_map('trim', $info); - - AdminImportController::setDefaultValues($info); - - if (!Shop::isFeatureActive()) - $info['shop'] = 1; - elseif (!isset($info['shop']) || empty($info['shop'])) - $info['shop'] = implode($this->multiple_value_separator, Shop::getContextListShopID()); - - // Get shops for each attributes - $info['shop'] = explode($this->multiple_value_separator, $info['shop']); - - $id_shop_list = array(); - foreach ($info['shop'] as $shop) - if (!is_numeric($shop)) - $id_shop_list[] = Shop::getIdByName($shop); - else - $id_shop_list[] = $shop; - - if(isset($info['id_product'])) - $product = new Product((int)$info['id_product'], false, $default_language); - else - continue; - - $id_image = null; - - //delete existing images if "delete_existing_images" is set to 1 - if (array_key_exists('delete_existing_images', $info) && $info['delete_existing_images'] && !isset($this->cache_image_deleted[(int)$product->id])) - { - $product->deleteImages(); - $this->cache_image_deleted[(int)$product->id] = true; - } - - if (isset($info['image_url']) && $info['image_url']) - { - $product_has_images = (bool)Image::getImages($this->context->language->id, $product->id); - - $url = $info['image_url']; - $image = new Image(); - $image->id_product = (int)$product->id; - $image->position = Image::getHighestPosition($product->id) + 1; - $image->cover = (!$product_has_images) ? true : false; - - $field_error = $image->validateFields(UNFRIENDLY_ERROR, true); - $lang_field_error = $image->validateFieldsLang(UNFRIENDLY_ERROR, true); - - if ($field_error === true && $lang_field_error === true && $image->add()) - { - $image->associateTo($id_shop_list); - if (!AdminImportController::copyImg($product->id, $image->id, $url)) - { - $this->warnings[] = sprintf(Tools::displayError('Error copying image: %s'), $url); - $image->delete(); - } - else - $id_image = array($image->id); - } - else - { - $this->warnings[] = sprintf( - Tools::displayError('%s cannot be saved'), - (isset($image->id_product) ? ' ('.$image->id_product.')' : '') - ); - $this->errors[] = ($field_error !== true ? $field_error : '').(isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : '').mysql_error(); - } - } - elseif (isset($info['image_position']) && $info['image_position']) - { - $images = $product->getImages($default_language); - - if ($images) - foreach ($images as $row) - if ($row['position'] == (int)$info['image_position']) - { - $id_image = array($row['id_image']); - break; - } - if (!$id_image) - $this->warnings[] = sprintf( - Tools::displayError('No image was found for combination with id_product = %s and image position = %s.'), - $product->id, - (int)$info['image_position'] - ); - } - - $id_attribute_group = 0; - // groups - $groups_attributes = array(); - if(isset($info['group'])) - foreach (explode($this->multiple_value_separator, $info['group']) as $key => $group) - { - $tab_group = explode(':', $group); - $group = trim($tab_group[0]); - if (!isset($tab_group[1])) - $type = 'select'; - else - $type = trim($tab_group[1]); - - // sets group - $groups_attributes[$key]['group'] = $group; - - // if position is filled - if (isset($tab_group[2])) - $position = trim($tab_group[2]); - else - $position = false; - - if (!isset($groups[$group])) - { - $obj = new AttributeGroup(); - $obj->is_color_group = false; - $obj->group_type = pSQL($type); - $obj->name[$default_language] = $group; - $obj->public_name[$default_language] = $group; - $obj->position = (!$position) ? AttributeGroup::getHigherPosition() + 1 : $position; - - if (($field_error = $obj->validateFields(UNFRIENDLY_ERROR, true)) === true && - ($lang_field_error = $obj->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true) - { - $obj->add(); - $obj->associateTo($id_shop_list); - $groups[$group] = $obj->id; - } - else - $this->errors[] = ($field_error !== true ? $field_error : '').(isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : ''); - - // fils groups attributes - $id_attribute_group = $obj->id; - $groups_attributes[$key]['id'] = $id_attribute_group; - } - else // alreay exists - { - $id_attribute_group = $groups[$group]; - $groups_attributes[$key]['id'] = $id_attribute_group; - } - } - - // inits attribute - $id_product_attribute = 0; - $id_product_attribute_update = false; - $attributes_to_add = array(); - - // for each attribute - if(isset($info['attribute'])) - foreach (explode($this->multiple_value_separator, $info['attribute']) as $key => $attribute) - { - $tab_attribute = explode(':', $attribute); - $attribute = trim($tab_attribute[0]); - // if position is filled - if (isset($tab_attribute[1])) - $position = trim($tab_attribute[1]); - else - $position = false; - - if (isset($groups_attributes[$key])) - { - $group = $groups_attributes[$key]['group']; - if (!isset($attributes[$group.'_'.$attribute]) && count($groups_attributes[$key]) == 2) - { - $id_attribute_group = $groups_attributes[$key]['id']; - $obj = new Attribute(); - // sets the proper id (corresponding to the right key) - $obj->id_attribute_group = $groups_attributes[$key]['id']; - $obj->name[$default_language] = str_replace('\n', '', str_replace('\r', '', $attribute)); - $obj->position = (!$position && isset($groups[$group])) ? Attribute::getHigherPosition($groups[$group]) + 1 : $position; - - if (($field_error = $obj->validateFields(UNFRIENDLY_ERROR, true)) === true && - ($lang_field_error = $obj->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true) - { - $obj->add(); - $obj->associateTo($id_shop_list); - $attributes[$group.'_'.$attribute] = $obj->id; - } - else - $this->errors[] = ($field_error !== true ? $field_error : '').(isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : ''); - } - - $info['minimal_quantity'] = isset($info['minimal_quantity']) && $info['minimal_quantity'] ? (int)$info['minimal_quantity'] : 1; - - $info['wholesale_price'] = str_replace(',', '.', $info['wholesale_price']); - $info['price'] = str_replace(',', '.', $info['price']); - $info['ecotax'] = str_replace(',', '.', $info['ecotax']); - $info['weight'] = str_replace(',', '.', $info['weight']); - - // if a reference is specified for this product, get the associate id_product_attribute to UPDATE - if (isset($info['reference']) && !empty($info['reference'])) - { - $id_product_attribute = Combination::getIdByReference($product->id, strval($info['reference'])); - - // updates the attribute - if ($id_product_attribute) - { - // gets all the combinations of this product - $attribute_combinations = $product->getAttributeCombinations($default_language); - foreach ($attribute_combinations as $attribute_combination) - { - if ($id_product_attribute && in_array($id_product_attribute, $attribute_combination)) - { - $product->updateAttribute( - $id_product_attribute, - (float)$info['wholesale_price'], - (float)$info['price'], - (float)$info['weight'], - 0, - (float)$info['ecotax'], - $id_image, - strval($info['reference']), - strval($info['ean13']), - (int)$info['default_on'], - 0, - strval($info['upc']), - (int)$info['minimal_quantity'], - 0, - null, - $id_shop_list - ); - - $id_product_attribute_update = true; - } - } - } - } - - // if no attribute reference is specified, creates a new one - if (!$id_product_attribute) - { - $id_product_attribute = $product->addCombinationEntity( - (float)$info['wholesale_price'], - (float)$info['price'], - (float)$info['weight'], - 0, - (float)$info['ecotax'], - (int)$info['quantity'], - $id_image, - strval($info['reference']), - 0, - strval($info['ean13']), - (int)$info['default_on'], - 0, - strval($info['upc']), - (int)$info['minimal_quantity'], - $id_shop_list - ); - } - - // fills our attributes array, in order to add the attributes to the product_attribute afterwards - if(isset($attributes[$group.'_'.$attribute])) - $attributes_to_add[] = (int)$attributes[$group.'_'.$attribute]; - - // after insertion, we clean attribute position and group attribute position - $obj = new Attribute(); - $obj->cleanPositions((int)$id_attribute_group, false); - AttributeGroup::cleanPositions(); - } - } - - $product->checkDefaultAttributes(); - if (!$product->cache_default_attribute) - Product::updateDefaultAttribute($product->id); - if ($id_product_attribute) - { - // now adds the attributes in the attribute_combination table - if ($id_product_attribute_update) - { - Db::getInstance()->execute(' - DELETE FROM '._DB_PREFIX_.'product_attribute_combination - WHERE id_product_attribute = '.(int)$id_product_attribute); - } - - foreach ($attributes_to_add as $attribute_to_add) - { - Db::getInstance()->execute(' - INSERT IGNORE INTO '._DB_PREFIX_.'product_attribute_combination (id_attribute, id_product_attribute) - VALUES ('.(int)$attribute_to_add.','.(int)$id_product_attribute.')'); - } - - StockAvailable::setQuantity($product->id, $id_product_attribute, (int)$info['quantity']); - } - } - - $this->closeCsvFile($handle); - } - - public function customerImport() - { - $customer_exist = false; - $this->receiveTab(); - $handle = $this->openCsvFile(); - AdminImportController::setLocale(); - for ($current_line = 0; $line = fgetcsv($handle, MAX_LINE_SIZE, $this->separator); $current_line++) - { - if (Tools::getValue('convert')) - $line = $this->utf8EncodeArray($line); - $info = AdminImportController::getMaskedRow($line); - - AdminImportController::setDefaultValues($info); - - if (Tools::getValue('forceIDs') && isset($info['id']) && (int)$info['id']) - $customer = new Customer((int)$info['id']); - else - { - if (array_key_exists('id', $info) && (int)$info['id'] && Customer::customerIdExistsStatic((int)$info['id'])) - $customer = new Customer((int)$info['id']); - else - $customer = new Customer(); - } - - if (array_key_exists('id', $info) && (int)$info['id'] && Customer::customerIdExistsStatic((int)$info['id'])) - { - $current_id_customer = $customer->id; - $current_id_shop = $customer->id_shop; - $current_id_shop_group = $customer->id_shop_group; - $customer_exist = true; - $customer_groups = $customer->getGroups(); - $addresses = $customer->getAddresses((int)Configuration::get('PS_LANG_DEFAULT')); - foreach ($customer_groups as $key => $group) - if ($group == $customer->id_default_group) - unset($customer_groups[$key]); - } - - AdminImportController::arrayWalk($info, array('AdminImportController', 'fillInfo'), $customer); - - if ($customer->passwd) - $customer->passwd = Tools::encrypt($customer->passwd); - - $id_shop_list = explode($this->multiple_value_separator, $customer->id_shop); - $customers_shop = array(); - $customers_shop['shared'] = array(); - $default_shop = new Shop((int)Configuration::get('PS_SHOP_DEFAULT')); - if (Shop::isFeatureActive() && $id_shop_list) - { - foreach ($id_shop_list as $id_shop) - { - $shop = new Shop((int)$id_shop); - $group_shop = $shop->getGroup(); - if ($group_shop->share_customer) - { - if (!in_array($group_shop->id, $customers_shop['shared'])) - $customers_shop['shared'][(int)$id_shop] = $group_shop->id; - } - else - $customers_shop[(int)$id_shop] = $group_shop->id; - } - } - else - { - $default_shop = new Shop((int)Configuration::get('PS_SHOP_DEFAULT')); - $default_shop->getGroup(); - $customers_shop[$default_shop->id] = $default_shop->getGroup()->id; - } - - //set temporally for validate field - $customer->id_shop = $default_shop->id; - $customer->id_shop_group = $default_shop->getGroup()->id; - - $res = true; - if (($field_error = $customer->validateFields(UNFRIENDLY_ERROR, true)) === true && - ($lang_field_error = $customer->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true) - { - foreach ($customers_shop as $id_shop => $id_group) - { - if ($id_shop == 'shared') - { - foreach ($id_group as $key => $id) - { - $customer->id_shop = (int)$key; - $customer->id_shop_group = (int)$id; - if ($customer_exist && ($current_id_shop_group == $id || in_array($current_id_shop, ShopGroup::getShopsFromGroup($id)))) - { - $customer->id = $current_id_customer; - $res &= $customer->update(); - } - - else - { - $res &= $customer->add(); - if (isset($customer_groups)) - $customer->addGroups($customer_groups); - if (isset($addresses)) - foreach ($addresses as $address) - { - $address['id_customer'] = $customer->id; - unset($address['country'], $address['state'], $address['state_iso'], $address['id_address'] ); - Db::getInstance()->insert('address', $address); - } - } - } - } - else - { - $customer->id_shop = $id_shop; - $customer->id_shop_group = $id_group; - if ($customer_exist && $id_shop == $current_id_shop) - { - $customer->id = $current_id_customer; - $res &= $customer->update(); - } - else - { - $res &= $customer->add(); - if (isset($customer_groups)) - $customer->addGroups($customer_groups); - if (isset($addresses)) - foreach ($addresses as $address) - { - $address['id_customer'] = $customer->id; - unset($address['country'], $address['state'], $address['state_iso'], $address['id_address']); - Db::getInstance()->insert('address', $address); - } - } - } - } - } - $customer_exist = false; - if (!$res) - { - $this->errors[] = sprintf( - Tools::displayError('%1$s (ID: %2$s) cannot be saved'), - $info['email'], - (isset($info['id']) ? $info['id'] : 'null') - ); - $this->errors[] = ($field_error !== true ? $field_error : '').(isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : ''). - Db::getInstance()->getMsgError(); - } - } - $this->closeCsvFile($handle); - } - - public function addressImport() - { - $this->receiveTab(); - $default_language_id = (int)Configuration::get('PS_LANG_DEFAULT'); - $handle = $this->openCsvFile(); - AdminImportController::setLocale(); - for ($current_line = 0; $line = fgetcsv($handle, MAX_LINE_SIZE, $this->separator); $current_line++) - { - if (Tools::getValue('convert')) - $line = $this->utf8EncodeArray($line); - $info = AdminImportController::getMaskedRow($line); - - AdminImportController::setDefaultValues($info); - $address = new Address(); - AdminImportController::arrayWalk($info, array('AdminImportController', 'fillInfo'), $address); - - if (isset($address->country) && is_numeric($address->country)) - { - if (Country::getNameById(Configuration::get('PS_LANG_DEFAULT'), (int)$address->country)) - $address->id_country = (int)$address->country; - } - else if (isset($address->country) && is_string($address->country) && !empty($address->country)) - { - if ($id_country = Country::getIdByName(null, $address->country)) - $address->id_country = (int)$id_country; - else - { - $country = new Country(); - $country->active = 1; - $country->name = AdminImportController::createMultiLangField($address->country); - $country->id_zone = 0; // Default zone for country to create - $country->iso_code = strtoupper(substr($address->country, 0, 2)); // Default iso for country to create - $country->contains_states = 0; // Default value for country to create - $lang_field_error = $country->validateFieldsLang(UNFRIENDLY_ERROR, true); - if (($field_error = $country->validateFields(UNFRIENDLY_ERROR, true)) === true && - ($lang_field_error = $country->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && $country->add()) - $address->id_country = (int)$country->id; - else - { - $this->errors[] = sprintf(Tools::displayError('%s cannot be saved'), $country->name[$default_language_id]); - $this->errors[] = ($field_error !== true ? $field_error : '').(isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : ''). - Db::getInstance()->getMsgError(); - } - } - } - - if (isset($address->state) && is_numeric($address->state)) - { - if (State::getNameById((int)$address->state)) - $address->id_state = (int)$address->state; - } - else if (isset($address->state) && is_string($address->state) && !empty($address->state)) - { - if ($id_state = State::getIdByName($address->state)) - $address->id_state = (int)$id_state; - else - { - $state = new State(); - $state->active = 1; - $state->name = $address->state; - $state->id_country = isset($country->id) ? (int)$country->id : 0; - $state->id_zone = 0; // Default zone for state to create - $state->iso_code = strtoupper(substr($address->state, 0, 2)); // Default iso for state to create - $state->tax_behavior = 0; - if (($field_error = $state->validateFields(UNFRIENDLY_ERROR, true)) === true && - ($lang_field_error = $state->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && $state->add()) - $address->id_state = (int)$state->id; - else - { - $this->errors[] = sprintf(Tools::displayError('%s cannot be saved'), $state->name); - $this->errors[] = ($field_error !== true ? $field_error : '').(isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : ''). - Db::getInstance()->getMsgError(); - } - } - } - - if (isset($address->customer_email) && !empty($address->customer_email)) - { - if (Validate::isEmail($address->customer_email)) - { - // a customer could exists in different shop - $customer_list = Customer::getCustomersByEmail($address->customer_email); - - if (count($customer_list) == 0) - $this->errors[] = sprintf( - Tools::displayError('%1$s does not exist in database %2$s (ID: %3$s) cannot be saved'), - Db::getInstance()->getMsgError(), - $address->customer_email, - (isset($info['id']) ? $info['id'] : 'null') - ); - } - else - { - $this->errors[] = sprintf(Tools::displayError('"%s": Is not a valid email address'), $address->customer_email); - continue; - } - } - elseif (isset($address->id_customer) && !empty($address->id_customer)) - { - if (Customer::customerIdExistsStatic((int)$address->id_customer)) - { - $customer = new Customer((int)$address->id_customer); - - // a customer could exists in different shop - $customer_list = Customer::getCustomersByEmail($customer->email); - - if (count($customer_list) == 0) - $this->errors[] = sprintf( - Tools::displayError('%1$s does not exist in database %2$s (ID: %3$s) cannot be saved'), - Db::getInstance()->getMsgError(), - $customer->email, - (int)$address->id_customer - ); - } - else - $this->errors[] = sprintf(Tools::displayError('The customer ID n.%d does not exist in the database (ID: %d) cannot be saved'), $address->id_customer); - } - else - { - $customer_list = array(); - $address->id_customer = 0; - } - - if (isset($address->manufacturer) && is_numeric($address->manufacturer) && Manufacturer::manufacturerExists((int)$address->manufacturer)) - $address->id_manufacturer = (int)$address->manufacturer; - else if (isset($address->manufacturer) && is_string($address->manufacturer) && !empty($address->manufacturer)) - { - $manufacturer = new Manufacturer(); - $manufacturer->name = $address->manufacturer; - if (($field_error = $manufacturer->validateFields(UNFRIENDLY_ERROR, true)) === true && - ($lang_field_error = $manufacturer->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && $manufacturer->add()) - $address->id_manufacturer = (int)$manufacturer->id; - else - { - $this->errors[] = Db::getInstance()->getMsgError().' '.sprintf( - Tools::displayError('%1$s (ID: %2$s) cannot be saved'), - $manufacturer->name, - (isset($manufacturer->id) ? $manufacturer->id : 'null') - ); - $this->errors[] = ($field_error !== true ? $field_error : '').(isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : ''). - Db::getInstance()->getMsgError(); - } - } - - if (isset($address->supplier) && is_numeric($address->supplier) && Supplier::supplierExists((int)$address->supplier)) - $address->id_supplier = (int)$address->supplier; - else if (isset($address->supplier) && is_string($address->supplier) && !empty($address->supplier)) - { - $supplier = new Supplier(); - $supplier->name = $address->supplier; - if (($field_error = $supplier->validateFields(UNFRIENDLY_ERROR, true)) === true && - ($lang_field_error = $supplier->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true && $supplier->add()) - $address->id_supplier = (int)$supplier->id; - else - { - $this->errors[] = Db::getInstance()->getMsgError().' '.sprintf( - Tools::displayError('%1$s (ID: %2$s) cannot be saved'), - $supplier->name, - (isset($supplier->id) ? $supplier->id : 'null') - ); - $this->errors[] = ($field_error !== true ? $field_error : '').(isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : ''). - Db::getInstance()->getMsgError(); - } - } - - $res = false; - if (($field_error = $address->validateFields(UNFRIENDLY_ERROR, true)) === true && - ($lang_field_error = $address->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true) - { - if (isset($customer_list) && count($customer_list) > 0) - { - $filter_list = array(); - foreach ($customer_list as $customer) - { - if (in_array($customer['id_customer'], $filter_list)) - continue; - - $filter_list[] = $customer['id_customer']; - - unset($address->id); - $address->id_customer = $customer['id_customer']; - $res = $address->add(); - - if (!$res) - $this->errors[] = sprintf( - Tools::displayError('%1$s (ID: %2$s) cannot be saved'), - $info['alias'], - (isset($info['id']) ? $info['id'] : 'null') - ); - } - } - else - { - if ($address->id && $address->addressExists($address->id)) - $res = $address->update(); - if (!$res) - $res = $address->add(); - } - } - if (!$res) - { - $this->errors[] = sprintf( - Tools::displayError('%1$s (ID: %2$s) cannot be saved'), - $info['alias'], - (isset($info['id']) ? $info['id'] : 'null') - ); - $this->errors[] = ($field_error !== true ? $field_error : '').(isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : ''). - Db::getInstance()->getMsgError(); - } - } - $this->closeCsvFile($handle); - } - - public function manufacturerImport() - { - $this->receiveTab(); - $handle = $this->openCsvFile(); - AdminImportController::setLocale(); - for ($current_line = 0; $line = fgetcsv($handle, MAX_LINE_SIZE, $this->separator); $current_line++) - { - if (Tools::getValue('convert')) - $line = $this->utf8EncodeArray($line); - $info = AdminImportController::getMaskedRow($line); - - AdminImportController::setDefaultValues($info); - - if (Tools::getValue('forceIDs') && isset($info['id']) && (int)$info['id']) - $manufacturer = new Manufacturer((int)$info['id']); - else - { - if (array_key_exists('id', $info) && (int)$info['id'] && Manufacturer::existsInDatabase((int)$info['id'], 'manufacturer')) - $manufacturer = new Manufacturer((int)$info['id']); - else - $manufacturer = new Manufacturer(); - } - - AdminImportController::arrayWalk($info, array('AdminImportController', 'fillInfo'), $manufacturer); - - $res = false; - if (($field_error = $manufacturer->validateFields(UNFRIENDLY_ERROR, true)) === true && - ($lang_field_error = $manufacturer->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true) - { - if ($manufacturer->id && $manufacturer->manufacturerExists($manufacturer->id)) - $res = $manufacturer->update(); - if (!$res) - $res = $manufacturer->add(); - - if ($res) - { - // Associate supplier to group shop - if (Shop::isFeatureActive() && $manufacturer->shop) - { - Db::getInstance()->execute(' - DELETE FROM '._DB_PREFIX_.'manufacturer_shop - WHERE id_manufacturer = '.(int)$manufacturer->id - ); - $manufacturer->shop = explode($this->multiple_value_separator, $manufacturer->shop); - $shops = array(); - foreach ($manufacturer->shop as $shop) - { - $shop = trim($shop); - if (!is_numeric($shop)) - $shop = ShopGroup::getIdByName($shop); - $shops[] = $shop; - } - $manufacturer->associateTo($shops); - } - } - } - - if (!$res) - { - $this->errors[] = Db::getInstance()->getMsgError().' '.sprintf( - Tools::displayError('%1$s (ID: %2$s) cannot be saved'), - (isset($info['name']) ? Tools::safeOutput($info['name']) : 'No Name'), - (isset($info['id']) ? Tools::safeOutput($info['id']) : 'No ID') - ); - $this->errors[] = ($field_error !== true ? $field_error : '').(isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : ''). - Db::getInstance()->getMsgError(); - } - } - $this->closeCsvFile($handle); - } - - public function supplierImport() - { - $this->receiveTab(); - $handle = $this->openCsvFile(); - AdminImportController::setLocale(); - for ($current_line = 0; $line = fgetcsv($handle, MAX_LINE_SIZE, $this->separator); $current_line++) - { - if (Tools::getValue('convert')) - $line = $this->utf8EncodeArray($line); - $info = AdminImportController::getMaskedRow($line); - - AdminImportController::setDefaultValues($info); - - if (Tools::getValue('forceIDs') && isset($info['id']) && (int)$info['id']) - $supplier = new Supplier((int)$info['id']); - else - { - if (array_key_exists('id', $info) && (int)$info['id'] && Supplier::existsInDatabase((int)$info['id'], 'supplier')) - $supplier = new Supplier((int)$info['id']); - else - $supplier = new Supplier(); - } - - - AdminImportController::arrayWalk($info, array('AdminImportController', 'fillInfo'), $supplier); - if (($field_error = $supplier->validateFields(UNFRIENDLY_ERROR, true)) === true && - ($lang_field_error = $supplier->validateFieldsLang(UNFRIENDLY_ERROR, true)) === true) - { - $res = false; - if ($supplier->id && $supplier->supplierExists($supplier->id)) - $res = $supplier->update(); - if (!$res) - $res = $supplier->add(); - - if (!$res) - $this->errors[] = Db::getInstance()->getMsgError().' '.sprintf( - Tools::displayError('%1$s (ID: %2$s) cannot be saved'), - (isset($info['name']) ? Tools::safeOutput($info['name']) : 'No Name'), - (isset($info['id']) ? Tools::safeOutput($info['id']) : 'No ID') - ); - else - { - // Associate supplier to group shop - if (Shop::isFeatureActive() && $supplier->shop) - { - Db::getInstance()->execute(' - DELETE FROM '._DB_PREFIX_.'supplier_shop - WHERE id_supplier = '.(int)$supplier->id - ); - $supplier->shop = explode($this->multiple_value_separator, $supplier->shop); - $shops = array(); - foreach ($supplier->shop as $shop) - { - $shop = trim($shop); - if (!is_numeric($shop)) - $shop = ShopGroup::getIdByName($shop); - $shops[] = $shop; - } - $supplier->associateTo($shops); - } - } - } - else - { - $this->errors[] = $this->l('Supplier is invalid').' ('.$supplier->name.')'; - $this->errors[] = ($field_error !== true ? $field_error : '').(isset($lang_field_error) && $lang_field_error !== true ? $lang_field_error : ''); - } - } - $this->closeCsvFile($handle); - } - - /** - * @since 1.5.0 - */ - public function supplyOrdersImport() - { - // opens CSV & sets locale - $this->receiveTab(); - $handle = $this->openCsvFile(); - AdminImportController::setLocale(); - - // main loop, for each supply orders to import - for ($current_line = 0; $line = fgetcsv($handle, MAX_LINE_SIZE, $this->separator); ++$current_line) - { - // if convert requested - if (Tools::getValue('convert')) - $line = $this->utf8EncodeArray($line); - $info = AdminImportController::getMaskedRow($line); - - // sets default values if needed - AdminImportController::setDefaultValues($info); - - // if an id is set, instanciates a supply order with this id if possible - if (array_key_exists('id', $info) && (int)$info['id'] && SupplyOrder::exists((int)$info['id'])) - $supply_order = new SupplyOrder((int)$info['id']); - // if a reference is set, instanciates a supply order with this reference if possible - else if (array_key_exists('reference', $info) && $info['reference'] && SupplyOrder::exists(pSQL($info['reference']))) - $supply_order = SupplyOrder::getSupplyOrderByReference(pSQL($info['reference'])); - else // new supply order - $supply_order = new SupplyOrder(); - - // gets parameters - $id_supplier = (int)$info['id_supplier']; - $id_lang = (int)$info['id_lang']; - $id_warehouse = (int)$info['id_warehouse']; - $id_currency = (int)$info['id_currency']; - $reference = pSQL($info['reference']); - $date_delivery_expected = pSQL($info['date_delivery_expected']); - $discount_rate = (float)$info['discount_rate']; - $is_template = (bool)$info['is_template']; - - // checks parameters - if (!Supplier::supplierExists($id_supplier)) - $this->errors[] = sprintf($this->l('Supplier ID (%d) is not valid (at line %d).'), $id_supplier, $current_line + 1); - if (!Language::getLanguage($id_lang)) - $this->errors[] = sprintf($this->l('Lang ID (%d) is not valid (at line %d).'), $id_lang, $current_line + 1); - if (!Warehouse::exists($id_warehouse)) - $this->errors[] = sprintf($this->l('Warehouse ID (%d) is not valid (at line %d).'), $id_warehouse, $current_line + 1); - if (!Currency::getCurrency($id_currency)) - $this->errors[] = sprintf($this->l('Currency ID (%d) is not valid (at line %d).'), $id_currency, $current_line + 1); - if (empty($supply_order->reference) && SupplyOrder::exists($reference)) - $this->errors[] = sprintf($this->l('Reference (%s) already exists (at line %d).'), $reference, $current_line + 1); - if (!empty($supply_order->reference) && ($supply_order->reference != $reference && SupplyOrder::exists($reference))) - $this->errors[] = sprintf($this->l('Reference (%s) already exists (at line %d).'), $reference, $current_line + 1); - if (!Validate::isDateFormat($date_delivery_expected)) - $this->errors[] = sprintf($this->l('Date (%s) is not valid (at line %d). Format: %s.'), $date_delivery_expected, - $current_line + 1, $this->l('YYYY-MM-DD')); - else if (new DateTime($date_delivery_expected) <= new DateTime('yesterday')) - $this->errors[] = sprintf($this->l('Date (%s) cannot be in the past (at line %d). Format: %s.'), $date_delivery_expected, - $current_line + 1, $this->l('YYYY-MM-DD')); - if ($discount_rate < 0 || $discount_rate > 100) - $this->errors[] = sprintf($this->l('Discount rate (%d) is not valid (at line %d). %s.'), $discount_rate, - $current_line + 1, $this->l('Format: Between 0 and 100')); - if ($supply_order->id > 0 && !$supply_order->isEditable()) - $this->errors[] = sprintf($this->l('Supply Order (%d) is not editable (at line %d).'), $supply_order->id, $current_line + 1); - - // if no errors, sets supply order - if (empty($this->errors)) - { - // adds parameters - $info['id_ref_currency'] = (int)Currency::getDefaultCurrency()->id; - $info['supplier_name'] = pSQL(Supplier::getNameById($id_supplier)); - if ($supply_order->id > 0) - { - $info['id_supply_order_state'] = (int)$supply_order->id_supply_order_state; - $info['id'] = (int)$supply_order->id; - } - else - $info['id_supply_order_state'] = 1; - - // sets parameters - AdminImportController::arrayWalk($info, array('AdminImportController', 'fillInfo'), $supply_order); - - // updatesd($supply_order); - $res = true; - if ($supply_order->id > 0) - $res &= $supply_order->update(); - else - $res &= $supply_order->add(); - - // errors - if (!$res) - $this->errors[] = sprintf($this->l('Supply Order could not be saved (at line %d).'), $current_line + 1); - } - } - - // closes - $this->closeCsvFile($handle); - } - - public function supplyOrdersDetailsImport() - { - // opens CSV & sets locale - $this->receiveTab(); - $handle = $this->openCsvFile(); - AdminImportController::setLocale(); - - $products = array(); - $reset = true; - // main loop, for each supply orders details to import - for ($current_line = 0; $line = fgetcsv($handle, MAX_LINE_SIZE, $this->separator); ++$current_line) - { - // if convert requested - if (Tools::getValue('convert')) - $line = $this->utf8EncodeArray($line); - $info = AdminImportController::getMaskedRow($line); - - // sets default values if needed - AdminImportController::setDefaultValues($info); - - // gets the supply order - if (array_key_exists('supply_order_reference', $info) && pSQL($info['supply_order_reference']) && SupplyOrder::exists(pSQL($info['supply_order_reference']))) - $supply_order = SupplyOrder::getSupplyOrderByReference(pSQL($info['supply_order_reference'])); - else - $this->errors[] = sprintf($this->l('Supply Order (%s) could not be loaded (at line %d).'), (int)$info['supply_order_reference'], $current_line + 1); - - if (empty($this->errors)) - { - // sets parameters - $id_product = (int)$info['id_product']; - if (!$info['id_product_attribute']) - $info['id_product_attribute'] = 0; - $id_product_attribute = (int)$info['id_product_attribute']; - $unit_price_te = (float)$info['unit_price_te']; - $quantity_expected = (int)$info['quantity_expected']; - $discount_rate = (float)$info['discount_rate']; - $tax_rate = (float)$info['tax_rate']; - - // checks if one product/attribute is there only once - if (isset($products[$id_product][$id_product_attribute])) - $this->errors[] = sprintf($this->l('Product/Attribute (%d/%d) cannot be added twice (at line %d).'), $id_product, - $id_product_attribute, $current_line + 1); - else - $products[$id_product][$id_product_attribute] = $quantity_expected; - - // checks parameters - if (false === ($supplier_reference = ProductSupplier::getProductSupplierReference($id_product, $id_product_attribute, $supply_order->id_supplier))) - $this->errors[] = sprintf($this->l('Product (%d/%d) is not available for this order (at line %d).'), $id_product, - $id_product_attribute, $current_line + 1); - if ($unit_price_te < 0) - $this->errors[] = sprintf($this->l('Unit Price (tax excl.) (%d) is not valid (at line %d).'), $unit_price_te, $current_line + 1); - if ($quantity_expected < 0) - $this->errors[] = sprintf($this->l('Quantity Expected (%d) is not valid (at line %d).'), $quantity_expected, $current_line + 1); - if ($discount_rate < 0 || $discount_rate > 100) - $this->errors[] = sprintf($this->l('Discount rate (%d) is not valid (at line %d). %s.'), $discount_rate, - $current_line + 1, $this->l('Format: Between 0 and 100')); - if ($tax_rate < 0 || $tax_rate > 100) - $this->errors[] = sprintf($this->l('Quantity Expected (%d) is not valid (at line %d).'), $tax_rate, - $current_line + 1, $this->l('Format: Between 0 and 100')); - - // if no errors, sets supply order details - if (empty($this->errors)) - { - // resets order if needed - if ($reset) - { - $supply_order->resetProducts(); - $reset = false; - } - - // creates new product - $supply_order_detail = new SupplyOrderDetail(); - AdminImportController::arrayWalk($info, array('AdminImportController', 'fillInfo'), $supply_order_detail); - - // sets parameters - $supply_order_detail->id_supply_order = $supply_order->id; - $currency = new Currency($supply_order->id_ref_currency); - $supply_order_detail->id_currency = $currency->id; - $supply_order_detail->exchange_rate = $currency->conversion_rate; - $supply_order_detail->supplier_reference = $supplier_reference; - $supply_order_detail->name = Product::getProductName($id_product, $id_product_attribute, $supply_order->id_lang); - - // gets ean13 / ref / upc - $query = new DbQuery(); - $query->select(' - IFNULL(pa.reference, IFNULL(p.reference, \'\')) as reference, - IFNULL(pa.ean13, IFNULL(p.ean13, \'\')) as ean13, - IFNULL(pa.upc, IFNULL(p.upc, \'\')) as upc - '); - $query->from('product', 'p'); - $query->leftJoin('product_attribute', 'pa', 'pa.id_product = p.id_product AND id_product_attribute = '.(int)$id_product_attribute); - $query->where('p.id_product = '.(int)$id_product); - $query->where('p.is_virtual = 0 AND p.cache_is_pack = 0'); - $res = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($query); - $product_infos = $res['0']; - - $supply_order_detail->reference = $product_infos['reference']; - $supply_order_detail->ean13 = $product_infos['ean13']; - $supply_order_detail->upc = $product_infos['upc']; - - $supply_order_detail->add(); - $supply_order->update(); - unset($supply_order_detail); - - } - } - } - - // closes - $this->closeCsvFile($handle); - } - - public function utf8EncodeArray($array) - { - return (is_array($array) ? array_map('utf8_encode', $array) : utf8_encode($array)); - } - - protected function getNbrColumn($handle, $glue) - { - $tmp = fgetcsv($handle, MAX_LINE_SIZE, $glue); - AdminImportController::rewindBomAware($handle); - return count($tmp); - } - - protected static function usortFiles($a, $b) - { - $a = strrev(substr(strrev($a), 0, 14)); - $b = strrev(substr(strrev($b), 0, 14)); - - if ($a == $b) - return 0; - - return ($a < $b) ? 1 : -1; - } - - protected function openCsvFile() - { - $handle = fopen(_PS_ADMIN_DIR_.'/import/'.strval(preg_replace('/\.{2,}/', '.', Tools::getValue('csv'))), 'r'); - - if (!$handle) - $this->errors[] = Tools::displayError('Cannot read the .CSV file'); - - AdminImportController::rewindBomAware($handle); - - for ($i = 0; $i < (int)Tools::getValue('skip'); ++$i) - $line = fgetcsv($handle, MAX_LINE_SIZE, $this->separator); - return $handle; - } - - protected function closeCsvFile($handle) - { - fclose($handle); - } - - protected function truncateTables($case) - { - switch ((int)$case) - { - case $this->entities[$this->l('Categories')]: - Db::getInstance()->execute(' - DELETE FROM `'._DB_PREFIX_.'category` - WHERE id_category NOT IN ('.(int)Configuration::get('PS_HOME_CATEGORY'). - ', '.(int)Configuration::get('PS_ROOT_CATEGORY').')'); - Db::getInstance()->execute(' - DELETE FROM `'._DB_PREFIX_.'category_lang` - WHERE id_category NOT IN ('.(int)Configuration::get('PS_HOME_CATEGORY'). - ', '.(int)Configuration::get('PS_ROOT_CATEGORY').')'); - Db::getInstance()->execute(' - DELETE FROM `'._DB_PREFIX_.'category_shop` - WHERE `id_category` NOT IN ('.(int)Configuration::get('PS_HOME_CATEGORY'). - ', '.(int)Configuration::get('PS_ROOT_CATEGORY').')'); - Db::getInstance()->execute('ALTER TABLE `'._DB_PREFIX_.'category` AUTO_INCREMENT = 3'); - foreach (scandir(_PS_CAT_IMG_DIR_) as $d) - if (preg_match('/^[0-9]+(\-(.*))?\.jpg$/', $d)) - unlink(_PS_CAT_IMG_DIR_.$d); - break; - case $this->entities[$this->l('Products')]: - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'product'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'product_shop'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'feature_product'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'product_lang'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'category_product'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'product_tag'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'image'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'image_lang'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'image_shop'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'specific_price'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'specific_price_priority'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'product_carrier'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'cart_product'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'compare_product'); - if (count(Db::getInstance()->executeS('SHOW TABLES LIKE \''._DB_PREFIX_.'favorite_product\' '))) //check if table exist - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'favorite_product'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'product_attachment'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'product_country_tax'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'product_download'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'product_group_reduction_cache'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'product_sale'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'product_supplier'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'scene_products'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'warehouse_product_location'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'stock'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'stock_available'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'stock_mvt'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'customization'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'customization_field'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'supply_order_detail'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'attribute_impact'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'product_attribute`'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'product_attribute_shop`'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'product_attribute_combination`'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'product_attribute_image`'); - Image::deleteAllImages(_PS_PROD_IMG_DIR_); - if (!file_exists(_PS_PROD_IMG_DIR_)) - mkdir(_PS_PROD_IMG_DIR_); - break; - case $this->entities[$this->l('Combinations')]: - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'attribute`'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'attribute_impact'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'attribute_lang`'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'attribute_group`'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'attribute_group_lang`'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'attribute_group_shop`'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'attribute_shop`'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'product_attribute`'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'product_attribute_shop`'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'product_attribute_combination`'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'product_attribute_image`'); - Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'stock_available` WHERE id_product_attribute !=0'); - break; - case $this->entities[$this->l('Customers')]: - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'customer'); - break; - case $this->entities[$this->l('Addresses')]: - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'address'); - break; - case $this->entities[$this->l('Manufacturers')]: - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'manufacturer'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'manufacturer_lang'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'manufacturer_shop'); - foreach (scandir(_PS_MANU_IMG_DIR_) as $d) - if (preg_match('/^[0-9]+(\-(.*))?\.jpg$/', $d)) - unlink(_PS_MANU_IMG_DIR_.$d); - break; - case $this->entities[$this->l('Suppliers')]: - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'supplier'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'supplier_lang'); - Db::getInstance()->execute('TRUNCATE TABLE `'._DB_PREFIX_.'supplier_shop'); - foreach (scandir(_PS_SUPP_IMG_DIR_) as $d) - if (preg_match('/^[0-9]+(\-(.*))?\.jpg$/', $d)) - unlink(_PS_SUPP_IMG_DIR_.$d); - break; - } - Image::clearTmpDir(); - return true; - } - - public function clearSmartyCache() - { - Tools::enableCache(); - Tools::clearCache($this->context->smarty); - Tools::restoreCacheSettings(); - } - - public function postProcess() - { - /* PrestaShop demo mode */ - if (_PS_MODE_DEMO_) - { - $this->errors[] = Tools::displayError('This functionality has been disabled.'); - return; - } - /* PrestaShop demo mode*/ - - if (Tools::isSubmit('submitFileUpload')) - { - if (isset($_FILES['file']) && !empty($_FILES['file']['error'])) - { - switch ($_FILES['file']['error']) - { - case UPLOAD_ERR_INI_SIZE: - $this->errors[] = Tools::displayError('The uploaded file exceeds the upload_max_filesize directive in php.ini. If your server configuration allows it, you may add a directive in your .htaccess.'); - break; - case UPLOAD_ERR_FORM_SIZE: - $this->errors[] = Tools::displayError('The uploaded file exceeds the post_max_size directive in php.ini. - If your server configuration allows it, you may add a directive in your .htaccess, for example:') - .'
- php_value post_max_size 20M '. - Tools::displayError('(click to open "Generators" page)').''; - break; - break; - case UPLOAD_ERR_PARTIAL: - $this->errors[] = Tools::displayError('The uploaded file was only partially uploaded.'); - break; - break; - case UPLOAD_ERR_NO_FILE: - $this->errors[] = Tools::displayError('No file was uploaded.'); - break; - break; - } - } - else if (!file_exists($_FILES['file']['tmp_name']) || - !@move_uploaded_file($_FILES['file']['tmp_name'], _PS_ADMIN_DIR_.'/import/'.date('Ymdhis').'-'.$_FILES['file']['name'])) - $this->errors[] = $this->l('An error occurred while uploading / copying the file.'); - else - Tools::redirectAdmin(self::$currentIndex.'&token='.Tools::getValue('token').'&conf=18'); - } - else if (Tools::getValue('import')) - { - // Check if the CSV file exist - if (Tools::getValue('csv')) - { - // If i am a superadmin, i can truncate table - if (((Shop::isFeatureActive() && $this->context->employee->isSuperAdmin()) || !Shop::isFeatureActive()) && Tools::getValue('truncate')) - $this->truncateTables((int)Tools::getValue('entity')); - $import_type = false; - switch ((int)Tools::getValue('entity')) - { - case $this->entities[$import_type = $this->l('Categories')]: - $this->categoryImport(); - $this->clearSmartyCache(); - break; - case $this->entities[$import_type = $this->l('Products')]: - $import_type = $this->l('Categories'); - $this->productImport(); - $this->clearSmartyCache(); - break; - case $this->entities[$import_type = $this->l('Customers')]: - $this->customerImport(); - break; - case $this->entities[$import_type = $this->l('Addresses')]: - $this->addressImport(); - break; - case $this->entities[$import_type = $this->l('Combinations')]: - $this->attributeImport(); - $this->clearSmartyCache(); - break; - case $this->entities[$import_type = $this->l('Manufacturers')]: - $this->manufacturerImport(); - $this->clearSmartyCache(); - break; - case $this->entities[$import_type = $this->l('Suppliers')]: - $this->supplierImport(); - $this->clearSmartyCache(); - break; - // @since 1.5.0 - case $this->entities[$import_type = $this->l('Supply Orders')]: - if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) - $this->supplyOrdersImport(); - break; - // @since 1.5.0 - case $this->entities[$import_type = $this->l('Supply Order Details')]: - if (Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) - $this->supplyOrdersDetailsImport(); - break; - default: - $this->errors[] = $this->l('Please select what you would like to import'); - } - if ($import_type !== false) - { - $log_message = sprintf($this->l('%s import'), $import_type); - if (Tools::getValue('truncate')) - $log_message .= ' '.$this->l('with truncate'); - Logger::addLog($log_message, 1, null, $import_type, null, true, (int)$this->context->employee->id); - } - } - else - $this->errors[] = $this->l('You must upload a file in order to proceed to the next step'); - } - - parent::postProcess(); - } - - public static function setLocale() - { - $iso_lang = trim(Tools::getValue('iso_lang')); - setlocale(LC_COLLATE, strtolower($iso_lang).'_'.strtoupper($iso_lang).'.UTF-8'); - setlocale(LC_CTYPE, strtolower($iso_lang).'_'.strtoupper($iso_lang).'.UTF-8'); - } - - protected function addProductWarning($product_name, $product_id = null, $message = '') - { - $this->warnings[] = $product_name.(isset($product_id) ? ' (ID '.$product_id.')' : '').' '.Tools::displayError($message); - } - - public function ajaxProcessSaveImportMatchs() - { - if ($this->tabAccess['edit'] === '1') - { - $match = implode('|', Tools::getValue('type_value')); - Db::getInstance()->execute('INSERT INTO `'._DB_PREFIX_.'import_match` ( - `id_import_match` , - `name` , - `match`, - `skip` - ) - VALUES ( - NULL , - \''.pSQL(Tools::getValue('newImportMatchs')).'\', - \''.pSQL($match).'\', - \''.pSQL(Tools::getValue('skip')).'\' - )'); - - die('{"id" : "'.Db::getInstance()->Insert_ID().'"}'); - } - } - - public function ajaxProcessLoadImportMatchs() - { - if ($this->tabAccess['edit'] === '1') - { - $return = Db::getInstance()->executeS('SELECT * FROM `'._DB_PREFIX_.'import_match` WHERE `id_import_match` = '.(int)Tools::getValue('idImportMatchs')); - die('{"id" : "'.$return[0]['id_import_match'].'", "matchs" : "'.$return[0]['match'].'", "skip" : "'.$return[0]['skip'].'"}'); - } - } - - public function ajaxProcessDeleteImportMatchs() - { - if ($this->tabAccess['edit'] === '1') - { - Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'import_match` WHERE `id_import_match` = '.(int)Tools::getValue('idImportMatchs')); - die; - } - } -} \ No newline at end of file + if (isset($cat_moved[$category->parent \ No newline at end of file diff --git a/controllers/admin/AdminManufacturersController.php b/controllers/admin/AdminManufacturersController.php index ebdb2ad1d..2ec73737a 100644 --- a/controllers/admin/AdminManufacturersController.php +++ b/controllers/admin/AdminManufacturersController.php @@ -140,7 +140,7 @@ class AdminManufacturersControllerCore extends AdminController 'lastname' => array( 'title' => $this->l('Last name'), 'width' => 100, - 'filter_key' => 'a!name' + 'filter_key' => 'a!lastname' ), 'postcode' => array( 'title' => $this->l('Zip Code/Postal Code'), @@ -570,7 +570,7 @@ class AdminManufacturersControllerCore extends AdminController default: parent::initToolbar(); $this->toolbar_btn['import'] = array( - 'href' => $this->context->link->getAdminLink('AdminImport', true).'&import_type='.$this->table, + 'href' => $this->context->link->getAdminLink('AdminImport', true).'&import_type=manufacturers', 'desc' => $this->l('Import') ); } diff --git a/controllers/admin/AdminOrdersController.php b/controllers/admin/AdminOrdersController.php index 0b9557f64..d15fd1323 100755 --- a/controllers/admin/AdminOrdersController.php +++ b/controllers/admin/AdminOrdersController.php @@ -110,7 +110,8 @@ class AdminOrdersControllerCore extends AdminController 'type' => 'select', 'list' => $statuses_array, 'filter_key' => 'os!id_order_state', - 'filter_type' => 'int' + 'filter_type' => 'int', + 'order_key' => 'osname' ), 'date_add' => array( 'title' => $this->l('Date'), @@ -506,7 +507,7 @@ class AdminOrdersControllerCore extends AdminController if (Tools::isSubmit('generateDiscountRefund') && !count($this->errors)) { $cart_rule = new CartRule(); - $cart_rule->description = sprintf($this->l('Credit card slip for order #%d'), $order->id); + $cart_rule->description = sprintf($this->l('Credit slip for order #%d'), $order->id); $languages = Language::getLanguages(false); foreach ($languages as $language) // Define a temporary name @@ -804,7 +805,7 @@ class AdminOrdersControllerCore extends AdminController if (!Validate::isLoadedObject($order)) $this->errors[] = Tools::displayError('The order cannot be found'); - elseif (!Validate::isNegativePrice($amount)) + elseif (!Validate::isNegativePrice($amount) || !(float)$amount) $this->errors[] = Tools::displayError('The amount is invalid.'); elseif (!Validate::isString(Tools::getValue('payment_method'))) $this->errors[] = Tools::displayError('The selected payment method is invalid.'); @@ -1341,11 +1342,14 @@ class AdminOrdersControllerCore extends AdminController $product['warehouse_name'] = '--'; } + $gender = new Gender((int)$customer->id_gender, $this->context->language->id); + // Smarty assign $this->tpl_view_vars = array( 'order' => $order, 'cart' => new Cart($order->id_cart), 'customer' => $customer, + 'gender' => $gender, 'customer_addresses' => $customer->getAddresses($this->context->language->id), 'addresses' => array( 'delivery' => $addressDelivery, diff --git a/controllers/admin/AdminPerformanceController.php b/controllers/admin/AdminPerformanceController.php index 798e1912d..acfbe4d20 100644 --- a/controllers/admin/AdminPerformanceController.php +++ b/controllers/admin/AdminPerformanceController.php @@ -796,6 +796,7 @@ class AdminPerformanceControllerCore extends AdminController { $redirectAdmin = true; Tools::clearSmartyCache(); + Autoload::getInstance()->generateIndex(); } if ($redirectAdmin && (!isset($this->errors) || !count($this->errors))) diff --git a/controllers/admin/AdminPreferencesController.php b/controllers/admin/AdminPreferencesController.php index f878f69fc..34a7e48e2 100644 --- a/controllers/admin/AdminPreferencesController.php +++ b/controllers/admin/AdminPreferencesController.php @@ -86,6 +86,19 @@ class AdminPreferencesControllerCore extends AdminController 'type' => 'bool', 'default' => '0' ), + ); + + if (Configuration::get('PS_SSL_ENABLED')) + $fields['PS_SSL_ENABLED_EVERYWHERE'] = array( + 'title' => $this->l('Force the SSL on all the pages'), + 'desc' => $this->l('Force all your store to use SSL'), + 'validation' => 'isBool', + 'cast' => 'intval', + 'type' => 'bool', + 'default' => '0' + ); + + $fields = array_merge($fields, array( 'PS_TOKEN_ENABLE' => array( 'title' => $this->l('Increase Front Office security'), 'desc' => $this->l('Enable or disable token in the Front Office to improve PrestaShop\'s security.'), @@ -135,7 +148,7 @@ class AdminPreferencesControllerCore extends AdminController 'list' => $activities2, 'identifier' => 'value' ), - ); + )); // No HTTPS activation if you haven't already. if (!Tools::usingSecureMode() && !Configuration::get('PS_SSL_ENABLED')) diff --git a/controllers/admin/AdminProductsController.php b/controllers/admin/AdminProductsController.php index b95d88942..03764fe67 100644 --- a/controllers/admin/AdminProductsController.php +++ b/controllers/admin/AdminProductsController.php @@ -1736,27 +1736,7 @@ class AdminProductsControllerCore extends AdminController // Save and preview if (Tools::isSubmit('submitAddProductAndPreview')) - { - $preview_url = $this->context->link->getProductLink( - $this->getFieldValue($this->object, 'id'), - $this->getFieldValue($this->object, 'link_rewrite', $this->context->language->id), - Category::getLinkRewrite($this->getFieldValue($this->object, 'id_category_default'), $this->context->language->id), - null, - null, - Context::getContext()->shop->id, - 0, - (bool)Configuration::get('PS_REWRITING_SETTINGS') - ); - - if (!$this->object->active) - { - $admin_dir = dirname($_SERVER['PHP_SELF']); - $admin_dir = substr($admin_dir, strrpos($admin_dir, '/') + 1); - $preview_url .= '&adtoken='.$this->token.'&ad='.$admin_dir.'&id_employee='.(int)$this->context->employee->id; - } - - $this->redirect_after = $preview_url; - } + $this->redirect_after = $this->getPreviewUrl($this->object); // Save and stay on same form if ($this->display == 'edit') @@ -1901,30 +1881,7 @@ class AdminProductsControllerCore extends AdminController // Save and preview if (Tools::isSubmit('submitAddProductAndPreview')) - { - $preview_url = $this->context->link->getProductLink( - $this->getFieldValue($object, 'id'), - $this->getFieldValue($object, 'link_rewrite', $this->context->language->id), - Category::getLinkRewrite($this->getFieldValue($object, 'id_category_default'), $this->context->language->id), - null, - null, - Context::getContext()->shop->id, - 0, - (bool)Configuration::get('PS_REWRITING_SETTINGS') - ); - - if (!$object->active) - { - $admin_dir = dirname($_SERVER['PHP_SELF']); - $admin_dir = substr($admin_dir, strrpos($admin_dir, '/') + 1); - if (strpos($preview_url, '?') === false) - $preview_url .= '?'; - else - $preview_url .= '&'; - $preview_url .= 'adtoken='.$this->token.'&ad='.$admin_dir.'&id_employee='.(int)$this->context->employee->id; - } - $this->redirect_after = $preview_url; - } + $this->redirect_after = $this->getPreviewUrl($object); else { // Save and stay on same form @@ -2480,7 +2437,7 @@ class AdminProductsControllerCore extends AdminController } else $this->toolbar_btn['import'] = array( - 'href' => $this->context->link->getAdminLink('AdminImport', true).'&import_type='.$this->table, + 'href' => $this->context->link->getAdminLink('AdminImport', true).'&import_type=products', 'desc' => $this->l('Import') ); @@ -2625,30 +2582,19 @@ class AdminProductsControllerCore extends AdminController $preview_url = $this->context->link->getProductLink( $product, $this->getFieldValue($product, 'link_rewrite', $this->context->language->id), - Category::getLinkRewrite($product->id_category_default, $this->context->language->id), + Category::getLinkRewrite($this->getFieldValue($product, 'id_category_default'), $this->context->language->id), null, $id_lang, - Context::getContext()->shop->id, + (int)Context::getContext()->shop->id, 0, $is_rewrite_active ); if (!$product->active) { - $preview_url = $this->context->link->getProductLink( - $product, - $this->getFieldValue($product, 'link_rewrite', $this->default_form_language), - Category::getLinkRewrite($this->getFieldValue($product, 'id_category_default'), $this->context->language->id), - null, - $id_lang, - Context::getContext()->shop->id, - 0, - $is_rewrite_active - ); $admin_dir = dirname($_SERVER['PHP_SELF']); $admin_dir = substr($admin_dir, strrpos($admin_dir, '/') + 1); $preview_url .= ((strpos($preview_url, '?') === false) ? '?' : '&').'adtoken='.$this->token.'&ad='.$admin_dir.'&id_employee='.(int)$this->context->employee->id; - } return $preview_url; diff --git a/controllers/admin/AdminStatusesController.php b/controllers/admin/AdminStatusesController.php index b046fe3ea..fe4e129e0 100644 --- a/controllers/admin/AdminStatusesController.php +++ b/controllers/admin/AdminStatusesController.php @@ -136,6 +136,7 @@ class AdminStatusesControllerCore extends AdminController { $this->table = 'order_return_state'; $this->_defaultOrderBy = $this->identifier = 'id_order_return_state'; + $this->list_id = 'order_return_state'; $this->deleted = false; $this->_orderBy = null; diff --git a/controllers/admin/AdminSuppliersController.php b/controllers/admin/AdminSuppliersController.php index bfe5618a3..d2eb52b8d 100644 --- a/controllers/admin/AdminSuppliersController.php +++ b/controllers/admin/AdminSuppliersController.php @@ -262,6 +262,24 @@ class AdminSuppliersControllerCore extends AdminController return parent::renderForm(); } + /** + * AdminController::initToolbar() override + * @see AdminController::initToolbar() + * + */ + public function initToolbar() + { + switch ($this->display) + { + default: + parent::initToolbar(); + $this->toolbar_btn['import'] = array( + 'href' => $this->context->link->getAdminLink('AdminImport', true).'&import_type=suppliers', + 'desc' => $this->l('Import') + ); + } + } + public function renderView() { $products = $this->object->getProductsLite($this->context->language->id); diff --git a/controllers/admin/AdminTaxRulesGroupController.php b/controllers/admin/AdminTaxRulesGroupController.php index c36597348..21045acfb 100644 --- a/controllers/admin/AdminTaxRulesGroupController.php +++ b/controllers/admin/AdminTaxRulesGroupController.php @@ -78,6 +78,7 @@ class AdminTaxRulesGroupControllerCore extends AdminController public function initRulesList($id_group) { $this->table = 'tax_rule'; + $this->list_id = 'tax_rule'; $this->identifier = 'id_tax_rule'; $this->className = 'TaxRule'; $this->lang = false; diff --git a/controllers/front/AuthController.php b/controllers/front/AuthController.php index 79b09cce6..505630aaa 100644 --- a/controllers/front/AuthController.php +++ b/controllers/front/AuthController.php @@ -425,6 +425,7 @@ class AuthControllerCore extends FrontController if (Tools::isSubmit('newsletter')) $this->processCustomerNewsletter($customer); + $customer->firstname = Tools::ucwords($customer->firstname); $customer->birthday = (empty($_POST['years']) ? '' : (int)$_POST['years'].'-'.(int)$_POST['months'].'-'.(int)$_POST['days']); if (!Validate::isBirthDate($customer->birthday)) $this->errors[] = Tools::displayError('Invalid date of birth.'); diff --git a/controllers/front/ContactController.php b/controllers/front/ContactController.php index 01941bf4d..8d3e5689e 100644 --- a/controllers/front/ContactController.php +++ b/controllers/front/ContactController.php @@ -144,7 +144,7 @@ class ContactControllerCore extends FrontController { $cm = new CustomerMessage(); $cm->id_customer_thread = $ct->id; - $cm->message = Tools::htmlentitiesUTF8($message); + $cm->message = $message; if (isset($fileAttachment['rename']) && !empty($fileAttachment['rename']) && rename($fileAttachment['tmp_name'], _PS_MODULE_DIR_.'../upload/'.basename($fileAttachment['rename']))) $cm->file_name = $fileAttachment['rename']; $cm->ip_address = ip2long($_SERVER['REMOTE_ADDR']); diff --git a/controllers/front/IdentityController.php b/controllers/front/IdentityController.php index 7f0eb50b4..109cf3bc8 100644 --- a/controllers/front/IdentityController.php +++ b/controllers/front/IdentityController.php @@ -79,7 +79,7 @@ class IdentityControllerCore extends FrontController if (!count($this->errors)) { $this->customer->id_default_group = (int)$prev_id_default_group; - $this->customer->firstname = Tools::ucfirst(Tools::strtolower($this->customer->firstname)); + $this->customer->firstname = Tools::ucwords($this->customer->firstname); if (!isset($_POST['newsletter'])) $this->customer->newsletter = 0; diff --git a/install-dev/upgrade/php/add_module_to_hook.php b/install-dev/upgrade/php/add_module_to_hook.php index c44e4eabd..fabd39cfa 100644 --- a/install-dev/upgrade/php/add_module_to_hook.php +++ b/install-dev/upgrade/php/add_module_to_hook.php @@ -35,9 +35,14 @@ function add_module_to_hook($module_name, $hook_name) if ((int)$id_module > 0) { - $id_hook = Db::getInstance()->getValue(' - SELECT `id_hook` FROM `'._DB_PREFIX_.'hook` WHERE `name` = "'.$hook_name.'" - '); + $id_hook = Db::getInstance()->getValue('SELECT `id_hook` FROM `'._DB_PREFIX_.'hook` WHERE `name` = "'.$hook_name.'"'); + if(!$id_hook) + { + $res &= Db::getInstance()->execute(' + INSERT IGNORE INTO `'._DB_PREFIX_.'hook` (`name`, `title`) + VALUES ("'.pSQL($hook_name).'", "'.pSQL($hook_name).'")'); + $id_hook = Db::getInstance()->Insert_ID(); + } if ((int)$id_hook > 0) { @@ -51,7 +56,5 @@ function add_module_to_hook($module_name, $hook_name) )'); } } - return $res; -} - +} \ No newline at end of file diff --git a/install-dev/upgrade/php/create_multistore.php b/install-dev/upgrade/php/create_multistore.php index c09b2916b..d0ecbf7b8 100755 --- a/install-dev/upgrade/php/create_multistore.php +++ b/install-dev/upgrade/php/create_multistore.php @@ -29,7 +29,8 @@ require_once(_PS_INSTALLER_PHP_UPGRADE_DIR_.'add_new_tab.php'); function create_multistore() { $res = true; - + if (!defined('_THEME_NAME_')) + define('_THEME_NAME_', 'default'); // @todo : use _PS_ROOT_DIR_ if (defined('__PS_BASE_URI__')) $INSTALLER__PS_BASE_URI = __PS_BASE_URI__; diff --git a/install-dev/upgrade/php/remove_tab.php b/install-dev/upgrade/php/remove_tab.php index 2a0c53902..9ade12ee5 100644 --- a/install-dev/upgrade/php/remove_tab.php +++ b/install-dev/upgrade/php/remove_tab.php @@ -29,6 +29,6 @@ function remove_tab($tabname) Db::getInstance()->execute(' DELETE t, l FROM `'._DB_PREFIX_.'tab` t LEFT JOIN `'._DB_PREFIX_.'tab_lang` l ON (t.id_tab = l.id_tab) - WHERE t.`class_name` = '.pSQL($tabname)); + WHERE t.`class_name` = "'.pSQL($tabname).'"'); } diff --git a/install-dev/upgrade/sql/1.5.6.0.sql b/install-dev/upgrade/sql/1.5.6.0.sql index 5f5521cff..3b03e96ed 100644 --- a/install-dev/upgrade/sql/1.5.6.0.sql +++ b/install-dev/upgrade/sql/1.5.6.0.sql @@ -1 +1,15 @@ -ALTER TABLE `PREFIX_manufacturer_lang` CHANGE `short_description` `short_description` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL; \ No newline at end of file +ALTER TABLE `PREFIX_manufacturer_lang` CHANGE `short_description` `short_description` TEXT CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL; + +/* PHP:add_module_to_hook(blockcart, actionCartListOverride); */; +/* PHP:add_module_to_hook(blockmanufacturer, actionObjectManufacturerDeleteAfter); */; +/* PHP:add_module_to_hook(blockmanufacturer, actionObjectManufacturerAddAfter); */; +/* PHP:add_module_to_hook(blockmanufacturer, actionObjectManufacturerUpdateAfter); */; +/* PHP:add_module_to_hook(blocksupplier, actionObjectSupplierDeleteAfter); */; +/* PHP:add_module_to_hook(blocksupplier, actionObjectSupplierAddAfter); */; +/* PHP:add_module_to_hook(blocksupplier, actionObjectSupplierUpdateAfter); */; +/* PHP:add_module_to_hook(blockmyaccount, actionModuleRegisterHookAfter); */; +/* PHP:add_module_to_hook(blockmyaccountfooter, actionModuleRegisterHookAfter); */; +/* PHP:add_module_to_hook(blockmyaccount, actionModuleUnRegisterHookAfter); */; +/* PHP:add_module_to_hook(blockmyaccountfooter, actionModuleUnRegisterHookAfter); */; +/* PHP:remove_tab(AdminRangePrice); */; +/* PHP:remove_tab(AdminRangeWeight); */; \ No newline at end of file diff --git a/js/admin.js b/js/admin.js index 7904d724b..f0d210359 100644 --- a/js/admin.js +++ b/js/admin.js @@ -119,7 +119,8 @@ function copy2friendlyURL() function copyMeta2friendlyURL() { - $('#input_link_rewrite_' + id_language).val(str2url($('#name_' + id_language).val().replace(/^[0-9]+\./, ''), 'UTF-8')); + if (!$('input[name="id_cms"]').length) + $('#link_rewrite_' + id_language).val(str2url($('#name_' + id_language).val().replace(/^[0-9]+\./, ''), 'UTF-8')); } function updateCurrentText() @@ -480,7 +481,7 @@ function askFeatureName(selected, selector) { var elem; - if (selected.value == 'feature') + if (selected.value == 'features') { $('#features_' + selector).show(); $('#feature_name_' + selector).attr('name', selected.name); @@ -750,6 +751,7 @@ function doAdminAjax(data, success_func, error_func) { url : 'index.php', data : data, + type : 'POST', success : function(data){ if (success_func) return success_func(data); diff --git a/js/admin_carrier_wizard.js b/js/admin_carrier_wizard.js index 1bb403720..d2bb9f401 100644 --- a/js/admin_carrier_wizard.js +++ b/js/admin_carrier_wizard.js @@ -153,12 +153,13 @@ function displaySummary() $('tr.range_inf td input').each( function() { - if (!isNaN(parseFloat($(this).val())) && (range_inf == summary_translation_undefined || range_inf > $(this).val())) + if (!isNaN(parseFloat($(this).val())) && (range_inf == summary_translation_undefined || parseFloat(range_inf) > parseFloat($(this).val()))) range_inf = $(this).val(); }); $('tr.range_sup td input').each( function(){ - if (!isNaN(parseFloat($(this).val())) && (range_sup == summary_translation_undefined || range_sup < $(this).val())) + + if (!isNaN(parseFloat($(this).val())) && (range_sup == summary_translation_undefined || parseFloat(range_sup) < parseFloat($(this).val()))) range_sup = $(this).val(); }); @@ -272,7 +273,6 @@ function bind_inputs() }); $('tr.fees td input:checkbox').off('change').on('change', function () { - if($(this).is(':checked')) { $(this).closest('tr').children('td').each( function () { @@ -389,7 +389,7 @@ function hideFees() function showFees() { $('tr.range_inf td, tr.range_sup td, tr.fees_all td, tr.fees td').each( function () { - if ($(this).index() >= 2) + if ($(this).index() > 2) { //enable only if zone is active tr = $(this).parent('tr'); diff --git a/modules/blocklayered/blocklayered.tpl b/modules/blocklayered/blocklayered.tpl index f2102440a..f514f7231 100644 --- a/modules/blocklayered/blocklayered.tpl +++ b/modules/blocklayered/blocklayered.tpl @@ -94,7 +94,7 @@ param_product_url = ''; {if $value.nbr || !$hide_0_values}
  • {if isset($filter.is_color_group) && $filter.is_color_group} - + {if isset($value.checked) && $value.checked}{/if} {else} @@ -115,7 +115,7 @@ param_product_url = ''; {if $value.nbr || !$hide_0_values}
  • {if isset($filter.is_color_group) && $filter.is_color_group} - + {if isset($value.checked) && $value.checked}{/if} {else} diff --git a/modules/blocknewproducts/blocknewproducts.php b/modules/blocknewproducts/blocknewproducts.php index ae04a77ee..f6b23a22d 100644 --- a/modules/blocknewproducts/blocknewproducts.php +++ b/modules/blocknewproducts/blocknewproducts.php @@ -134,6 +134,11 @@ class BlockNewProducts extends Module { return $this->hookRightColumn($params); } + + public function hookHome($params) + { + return $this->hookRightColumn($params); + } public function hookHeader($params) { diff --git a/modules/carriercompare/carriercompare.php b/modules/carriercompare/carriercompare.php index 910088a43..8b82e30a6 100755 --- a/modules/carriercompare/carriercompare.php +++ b/modules/carriercompare/carriercompare.php @@ -72,7 +72,7 @@ class CarrierCompare extends Module $this->postProcess(); $this->smarty->assign('refresh_method', Configuration::get('SE_RERESH_METHOD')); - return $this->smarty->fetch($this->template_directory .'configuration.tpl'); + return $this->display(__FILE__, 'template/configuration.tpl'); } public function postProcess() @@ -155,7 +155,7 @@ class CarrierCompare extends Module 'refresh_method' => ($refresh_method === false) ? 0 : $refresh_method )); - return $this->smarty->fetch($this->template_directory.'carriercompare.tpl'); + return $this->display(__FILE__, 'template/carriercompare.tpl'); } /* diff --git a/modules/editorial/editorial.php b/modules/editorial/editorial.php index 3df3fa570..c7ecf4414 100644 --- a/modules/editorial/editorial.php +++ b/modules/editorial/editorial.php @@ -218,9 +218,9 @@ class Editorial extends Module if ($input['name'] != 'body_homepage_logo') $helper->fields_value[$input['name']] = $editorial->{$input['name']}; - $helper->fields_value['image'] = (file_exists(dirname(__FILE__).'/homepage_logo_'.(int)$id_shop.'.jpg') ? '' : ''); - if ($helper->fields_value['image']) - $helper->fields_value['size'] = filesize(dirname(__FILE__).'/homepage_logo_'.(int)$id_shop.'.jpg') / 1000; + $helper->fields_value['body_homepage_logo']['image'] = (file_exists(dirname(__FILE__).'/homepage_logo_'.(int)$id_shop.'.jpg') ? '' : ''); + if ($helper->fields_value['body_homepage_logo']) + $helper->fields_value['body_homepage_logo']['size'] = filesize(dirname(__FILE__).'/homepage_logo_'.(int)$id_shop.'.jpg') / 1000; $this->_html .= $helper->generateForm($this->fields_form); return $this->_html; diff --git a/modules/mailalerts/MailAlert.php b/modules/mailalerts/MailAlert.php index a0124326d..5f089c58e 100644 --- a/modules/mailalerts/MailAlert.php +++ b/modules/mailalerts/MailAlert.php @@ -36,6 +36,8 @@ class MailAlert extends ObjectModel public $id_shop; + public $id_lang; + /** * @see ObjectModel::$definition */ @@ -47,15 +49,19 @@ class MailAlert extends ObjectModel 'customer_email' => array('type' => self::TYPE_STRING, 'validate' => 'isEmail', 'required' => true), 'id_product' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt', 'required' => true), 'id_product_attribute' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt', 'required' => true), - 'id_shop' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt', 'required' => true) + 'id_shop' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt', 'required' => true), + 'id_lang' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt', 'required' => true) ), ); - public static function customerHasNotification($id_customer, $id_product, $id_product_attribute, $id_shop = null) + public static function customerHasNotification($id_customer, $id_product, $id_product_attribute, $id_shop = null, $id_lang = null) { if ($id_shop == null) $id_shop = Context::getContext()->shop->id; + if ($id_lang == null) + $id_lang = Context::getContext()->language->id; + $customer = new Customer($id_customer); $customer_email = $customer->email; @@ -70,14 +76,15 @@ class MailAlert extends ObjectModel return count(Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($sql)); } - public static function deleteAlert($id_customer, $customer_email, $id_product, $id_product_attribute) + public static function deleteAlert($id_customer, $customer_email, $id_product, $id_product_attribute, $id_shop) { $sql = ' DELETE FROM `'._DB_PREFIX_.self::$definition['table'].'` WHERE '.(($id_customer > 0) ? '(`customer_email` = \''.pSQL($customer_email).'\' OR `id_customer` = '.(int)$id_customer.')' : '`customer_email` = \''.pSQL($customer_email).'\''). ' AND `id_product` = '.(int)$id_product.' - AND `id_product_attribute` = '.(int)$id_product_attribute; + AND `id_product_attribute` = '.(int)$id_product_attribute.' + AND `id_shop` = '.(int)$id_shop; return Db::getInstance()->execute($sql); } @@ -160,17 +167,23 @@ class MailAlert extends ObjectModel public static function sendCustomerAlert($id_product, $id_product_attribute) { $link = new Link(); - - $id_lang = (int)Context::getContext()->language->id; - $product = new Product((int)$id_product, false, $id_lang); - $templateVars = array( - '{product}' => (is_array($product->name) ? $product->name[$id_lang] : $product->name), - '{product_link}' => $link->getProductLink($product) - ); - + $context = Context::getContext()->cloneContext(); $customers = self::getCustomers($id_product, $id_product_attribute); + foreach ($customers as $customer) { + $id_shop = (int)$customer['id_shop']; + $id_lang = (int)$customer['id_lang']; + $context->shop->id = $id_shop; + $context->language->id = $id_lang; + + $product = new Product((int)$id_product, false, $id_lang, $id_shop); + $product_link = $link->getProductLink($product, $product->link_rewrite, null, null, $id_lang, $id_shop); + $templateVars = array( + '{product}' => (is_array($product->name) ? $product->name[$id_lang] : $product->name), + '{product_link}' => $product_link + ); + if ($customer['id_customer']) { $customer = new Customer((int)$customer['id_customer']); @@ -182,14 +195,30 @@ class MailAlert extends ObjectModel $customer_id = 0; $customer_email = $customer['customer_email']; } + $iso = Language::getIsoById($id_lang); - + if (file_exists(dirname(__FILE__).'/mails/'.$iso.'/customer_qty.txt') && file_exists(dirname(__FILE__).'/mails/'.$iso.'/customer_qty.html')) - Mail::Send((int)Configuration::get('PS_LANG_DEFAULT'), 'customer_qty', Mail::l('Product available', $id_lang), $templateVars, strval($customer_email), NULL, strval(Configuration::get('PS_SHOP_EMAIL')), strval(Configuration::get('PS_SHOP_NAME')), NULL, NULL, dirname(__FILE__).'/mails/'); + Mail::Send( + $id_lang, + 'customer_qty', + Mail::l('Product available', $id_lang), + $templateVars, + strval($customer_email), + NULL, + strval(Configuration::get('PS_SHOP_EMAIL', null, null, $id_shop)), + strval(Configuration::get('PS_SHOP_NAME', null, null, $id_shop)), + NULL, + NULL, + dirname(__FILE__).'/mails/', + false, + $id_shop + ); - Hook::exec('actionModuleMailAlertSendCustomer', array('product' => (is_array($product->name) ? $product->name[$id_lang] : $product->name), 'link' => $link->getProductLink($product), 'customer' => $customer, 'product_obj' => $product)); - self::deleteAlert((int)$customer_id, strval($customer_email), (int)$id_product, (int)$id_product_attribute); + Hook::exec('actionModuleMailAlertSendCustomer', array('product' => (is_array($product->name) ? $product->name[$id_lang] : $product->name), 'link' => $product_link, 'customer' => $customer, 'product_obj' => $product)); + + self::deleteAlert((int)$customer_id, strval($customer_email), (int)$id_product, (int)$id_product_attribute, $id_shop); } } @@ -244,7 +273,7 @@ class MailAlert extends ObjectModel public static function getCustomers($id_product, $id_product_attribute) { $sql = ' - SELECT id_customer, customer_email + SELECT id_customer, customer_email, id_shop, id_lang FROM `'._DB_PREFIX_.self::$definition['table'].'` WHERE `id_product` = '.(int)$id_product.' AND `id_product_attribute` = '.(int)$id_product_attribute; diff --git a/modules/mailalerts/controllers/front/actions.php b/modules/mailalerts/controllers/front/actions.php index a1ff41a55..51c654de3 100644 --- a/modules/mailalerts/controllers/front/actions.php +++ b/modules/mailalerts/controllers/front/actions.php @@ -64,8 +64,10 @@ class MailalertsActionsModuleFrontController extends ModuleFrontController if (!Validate::isLoadedObject($product)) die('0'); - if (MailAlert::deleteAlert((int)Context::getContext()->customer->id, (int)Context::getContext()->customer->email, (int)$product->id, (int)$this->id_product_attribute)) + $context = Context::getContext(); + if (MailAlert::deleteAlert((int)$context->customer->id, (int)$context->customer->email, (int)$product->id, (int)$this->id_product_attribute)) die('0'); + die(1); } @@ -74,29 +76,32 @@ class MailalertsActionsModuleFrontController extends ModuleFrontController */ public function processAdd() { - if (Context::getContext()->customer->isLogged()) + $context = Context::getContext(); + + if ($context->customer->isLogged()) { - $id_customer = (int)Context::getContext()->customer->id; + $id_customer = (int)$context->customer->id; $customer = new Customer($id_customer); $customer_email = strval($customer->email); } else { $customer_email = strval(Tools::getValue('customer_email')); - $customer = Context::getContext()->customer->getByEmail($customer_email); + $customer = $context->customer->getByEmail($customer_email); $id_customer = (isset($customer->id) && ($customer->id != null)) ? (int)$customer->id : null; } $id_product = (int)Tools::getValue('id_product'); $id_product_attribute = (int)Tools::getValue('id_product_attribute'); - $id_shop = (int)Context::getContext()->shop->id; - $product = new Product($id_product, null, null, $id_shop, Context::getContext()); + $id_shop = (int)$context->shop->id; + $id_lang = (int)$context->language->id; + $product = new Product($id_product, false, $id_lang, $id_shop, $context); $mailAlert = MailAlert::customerHasNotification($id_customer, $id_product, $id_product_attribute, $id_shop); if ($mailAlert) die('2'); - else if (!Validate::isLoadedObject($product)) + elseif (!Validate::isLoadedObject($product)) die('0'); $mailAlert = new MailAlert(); @@ -106,10 +111,11 @@ class MailalertsActionsModuleFrontController extends ModuleFrontController $mailAlert->id_product = (int)$id_product; $mailAlert->id_product_attribute = (int)$id_product_attribute; $mailAlert->id_shop = (int)$id_shop; + $mailAlert->id_lang = (int)$id_lang; if ($mailAlert->add() !== false) die('1'); - + die('0'); } @@ -122,15 +128,15 @@ class MailalertsActionsModuleFrontController extends ModuleFrontController die('0'); $id_customer = (int)$this->context->customer->id; - - if (!$id_product = (int)(Tools::getValue('id_product'))) - die ('0'); - $id_product_attribute = (int)(Tools::getValue('id_product_attribute')); - $id_shop = (int)Context::getContext()->shop->id; - if (MailAlert::customerHasNotification((int)$id_customer, (int)$id_product, (int)$id_product_attribute, (int)$id_shop)) - die ('1'); - + if (!$id_product = (int)(Tools::getValue('id_product'))) + die('0'); + + $id_product_attribute = (int)(Tools::getValue('id_product_attribute')); + + if (MailAlert::customerHasNotification((int)$id_customer, (int)$id_product, (int)$id_product_attribute, (int)$this->context->shop->id)) + die('1'); + die('0'); } } \ No newline at end of file diff --git a/modules/mailalerts/mailalerts.php b/modules/mailalerts/mailalerts.php index 417ae3fa9..fb8cd41e4 100644 --- a/modules/mailalerts/mailalerts.php +++ b/modules/mailalerts/mailalerts.php @@ -40,13 +40,13 @@ class MailAlerts extends Module private $_merchant_coverage; private $_product_coverage; - const __MA_MAIL_DELIMITOR__ = ','; + const __MA_MAIL_DELIMITOR__ = "\n"; public function __construct() { $this->name = 'mailalerts'; $this->tab = 'administration'; - $this->version = '2.4'; + $this->version = '2.5'; $this->author = 'PrestaShop'; $this->need_instance = 0; @@ -100,7 +100,8 @@ class MailAlerts extends Module `id_product` int(10) unsigned NOT NULL, `id_product_attribute` int(10) unsigned NOT NULL, `id_shop` int(10) unsigned NOT NULL, - PRIMARY KEY (`id_customer`,`customer_email`,`id_product`,`id_product_attribute`) + `id_lang` int(10) unsigned NOT NULL, + PRIMARY KEY (`id_customer`,`customer_email`,`id_product`,`id_product_attribute`,`id_shop`) ) ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=utf8 COLLATE=utf8_general_ci'; if (!Db::getInstance()->execute($sql)) @@ -161,7 +162,7 @@ class MailAlerts extends Module $errors[] = $this->l('Invalid e-mail:').' '.Tools::safeOutput($email); break; } - else if (!empty($email) && count($email) > 0) + elseif (!empty($email) && count($email) > 0) $emails[$k] = $email; else unset($emails[$k]); @@ -171,15 +172,15 @@ class MailAlerts extends Module if (!Configuration::updateValue('MA_MERCHANT_MAILS', strval($emails))) $errors[] = $this->l('Cannot update settings'); - else if (!Configuration::updateValue('MA_MERCHANT_ORDER', (int)Tools::getValue('mA_merchand_order'))) + elseif (!Configuration::updateValue('MA_MERCHANT_ORDER', (int)Tools::getValue('mA_merchand_order'))) $errors[] = $this->l('Cannot update settings'); - else if (!Configuration::updateValue('MA_MERCHANT_OOS', (int)Tools::getValue('mA_merchand_oos'))) + elseif (!Configuration::updateValue('MA_MERCHANT_OOS', (int)Tools::getValue('mA_merchand_oos'))) $errors[] = $this->l('Cannot update settings'); - else if (!Configuration::updateValue('MA_LAST_QTIES', (int)Tools::getValue('MA_LAST_QTIES'))) + elseif (!Configuration::updateValue('MA_LAST_QTIES', (int)Tools::getValue('MA_LAST_QTIES'))) $errors[] = $this->l('Cannot update settings'); - else if (!Configuration::updateGlobalValue('MA_MERCHANT_COVERAGE', (int)Tools::getValue('mA_merchant_coverage'))) + elseif (!Configuration::updateGlobalValue('MA_MERCHANT_COVERAGE', (int)Tools::getValue('mA_merchant_coverage'))) $errors[] = $this->l('Cannot update settings'); - else if (!Configuration::updateGlobalValue('MA_PRODUCT_COVERAGE', (int)Tools::getValue('MA_PRODUCT_COVERAGE'))) + elseif (!Configuration::updateGlobalValue('MA_PRODUCT_COVERAGE', (int)Tools::getValue('MA_PRODUCT_COVERAGE'))) $errors[] = $this->l('Cannot update settings'); } } @@ -262,14 +263,16 @@ class MailAlerts extends Module return; // Getting differents vars - $id_lang = (int)Context::getContext()->language->id; + $context = Context::getContext(); + $id_lang = (int)$context->language->id; + $id_shop = (int)$context->shop->id; $currency = $params['currency']; - $configuration = Configuration::getMultiple(array('PS_SHOP_EMAIL', 'PS_MAIL_METHOD', 'PS_MAIL_SERVER', 'PS_MAIL_USER', 'PS_MAIL_PASSWD', 'PS_SHOP_NAME')); $order = $params['order']; $customer = $params['customer']; + $configuration = Configuration::getMultiple(array('PS_SHOP_EMAIL', 'PS_MAIL_METHOD', 'PS_MAIL_SERVER', 'PS_MAIL_USER', 'PS_MAIL_PASSWD', 'PS_SHOP_NAME', 'PS_MAIL_COLOR'), $id_lang, null, $id_shop); $delivery = new Address((int)$order->id_address_delivery); $invoice = new Address((int)$order->id_address_invoice); - $order_date_text = Tools::displayDate($order->date_add); + $order_date_text = Tools::displayDate($order->date_add, (int)$id_lang); $carrier = new Carrier((int)$order->id_carrier); $message = $order->getFirstMessage(); @@ -288,8 +291,7 @@ class MailAlerts extends Module $customization_text = ''; if (isset($customized_datas[$product['product_id']][$product['product_attribute_id']])) { - - foreach ($customized_datas[$product['product_id']][$product['product_attribute_id']] as $customization) + foreach ($customized_datas[$product['product_id']][$product['product_attribute_id']][$order->id_address_delivery] as $customization) { if (isset($customization['datas'][_CUSTOMIZE_TEXTFIELD_])) foreach ($customization['datas'][_CUSTOMIZE_TEXTFIELD_] as $text) @@ -339,11 +341,11 @@ class MailAlerts extends Module '{delivery_block_txt}' => MailAlert::getFormatedAddress($delivery, "\n"), '{invoice_block_txt}' => MailAlert::getFormatedAddress($invoice, "\n"), '{delivery_block_html}' => MailAlert::getFormatedAddress($delivery, '
    ', array( - 'firstname' => '%s', - 'lastname' => '%s')), + 'firstname' => '%s', + 'lastname' => '%s')), '{invoice_block_html}' => MailAlert::getFormatedAddress($invoice, '
    ', array( - 'firstname' => '%s', - 'lastname' => '%s')), + 'firstname' => '%s', + 'lastname' => '%s')), '{delivery_company}' => $delivery->company, '{delivery_firstname}' => $delivery->firstname, '{delivery_lastname}' => $delivery->lastname, @@ -353,9 +355,7 @@ class MailAlerts extends Module '{delivery_postal_code}' => $delivery->postcode, '{delivery_country}' => $delivery->country, '{delivery_state}' => $delivery->id_state ? $delivery_state->name : '', - '{delivery_phone}' => $delivery->phone, - '{delivery_phone_mobile}' => $delivery->phone_mobile, - '{delivery_vat_number}' => $delivery->vat_number, + '{delivery_phone}' => $delivery->phone ? $delivery->phone : $delivery->phone_mobile, '{delivery_other}' => $delivery->other, '{invoice_company}' => $invoice->company, '{invoice_firstname}' => $invoice->firstname, @@ -366,21 +366,18 @@ class MailAlerts extends Module '{invoice_postal_code}' => $invoice->postcode, '{invoice_country}' => $invoice->country, '{invoice_state}' => $invoice->id_state ? $invoice_state->name : '', - '{invoice_phone}' => $invoice->phone, - '{invoice_phone_mobile}' => $invoice->phone_mobile, - '{invoice_vat_number}' => $invoice->vat_number, + '{invoice_phone}' => $invoice->phone ? $invoice->phone : $invoice->phone_mobile, '{invoice_other}' => $invoice->other, '{order_name}' => sprintf('%06d', $order->id), - '{shop_name}' => Configuration::get('PS_SHOP_NAME'), + '{shop_name}' => $configuration['PS_SHOP_NAME'], '{date}' => $order_date_text, - '{carrier}' => (($carrier->name == '0') ? Configuration::get('PS_SHOP_NAME') : $carrier->name), + '{carrier}' => (($carrier->name == '0') ? $configuration['PS_SHOP_NAME'] : $carrier->name), '{payment}' => Tools::substr($order->payment, 0, 32), '{items}' => $items_table, '{total_paid}' => Tools::displayPrice($order->total_paid, $currency), '{total_products}' => Tools::displayPrice($order->getTotalProductsWithTaxes(), $currency), '{total_discounts}' => Tools::displayPrice($order->total_discounts, $currency), '{total_shipping}' => Tools::displayPrice($order->total_shipping, $currency), - '{total_tax_paid}' => Tools::displayPrice(($order->total_products_wt - $order->total_products) + ($order->total_shipping_tax_incl - $order->total_shipping_tax_excl), $currency, false), '{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $currency), '{currency}' => $currency->sign, '{message}' => $message @@ -390,19 +387,28 @@ class MailAlerts extends Module if (file_exists(dirname(__FILE__).'/mails/'.$iso.'/'.$template.'.txt') && file_exists(dirname(__FILE__).'/mails/'.$iso.'/'.$template.'.html')) - Mail::Send( - $id_lang, - $template, - sprintf(Mail::l('New order - #%06d', $id_lang), $order->id), - $template_vars, - explode(self::__MA_MAIL_DELIMITOR__, $this->_merchant_mails), - null, - $configuration['PS_SHOP_EMAIL'], - $configuration['PS_SHOP_NAME'], - null, - null, - dirname(__FILE__).'/mails/' - ); + { + // Send 1 email by merchant mail, because Mail::Send doesn't work with an array of recipients + $merchant_mails = explode(self::__MA_MAIL_DELIMITOR__, $this->_merchant_mails); + foreach ($merchant_mails as $merchant_mail) + { + Mail::Send( + $id_lang, + $template, + sprintf(Mail::l('New order - #%06d', $id_lang), $order->id), + $template_vars, + $merchant_mail, + null, + $configuration['PS_SHOP_EMAIL'], + $configuration['PS_SHOP_NAME'], + null, + null, + dirname(__FILE__).'/mails/', + null, + $id_shop + ); + } + } } public function hookActionProductOutOfStock($params) @@ -410,18 +416,20 @@ class MailAlerts extends Module if (!$this->_customer_qty || !Configuration::get('PS_STOCK_MANAGEMENT') || Product::isAvailableWhenOutOfStock($params['product']->out_of_stock)) return; + $context = Context::getContext(); $id_product = (int)$params['product']->id; $id_product_attribute = 0; - $id_customer = (int)Context::getContext()->customer->id; + $id_customer = (int)$context->customer->id; - if (!(int)Context::getContext()->customer->isLogged()) + if ((int)$context->customer->id <= 0) $this->context->smarty->assign('email', 1); - else if (MailAlert::customerHasNotification($id_customer, $id_product, $id_product_attribute)) + elseif (MailAlert::customerHasNotification($id_customer, $id_product, $id_product_attribute, (int)$context->shop->id)) return; $this->context->smarty->assign(array( - 'id_product' => $id_product, - 'id_product_attribute' => $id_product_attribute)); + 'id_product' => $id_product, + 'id_product_attribute' => $id_product_attribute + )); return $this->display(__FILE__, 'product.tpl'); } @@ -431,33 +439,47 @@ class MailAlerts extends Module $id_product = (int)$params['id_product']; $id_product_attribute = (int)$params['id_product_attribute']; $quantity = (int)$params['quantity']; - $id_shop = (int)Context::getContext()->shop->id; - $id_lang = (int)Context::getContext()->language->id; - $product = new Product($id_product, true, $id_lang, $id_shop, Context::getContext()); - $ma_last_qties = (int)Configuration::get('MA_LAST_QTIES'); + $context = Context::getContext(); + $id_shop = (int)$context->shop->id; + $id_lang = (int)$context->language->id; + $product = new Product($id_product, true, $id_lang, $id_shop, $context); + $configuration = Configuration::getMultiple(array('MA_LAST_QTIES', 'PS_STOCK_MANAGEMENT', 'PS_SHOP_EMAIL', 'PS_SHOP_NAME'), $id_lang, null, $id_shop); + $ma_last_qties = (int)$configuration['MA_LAST_QTIES']; - if ($product->active == 1 && (int)$quantity <= $ma_last_qties && !(!$this->_merchant_oos || empty($this->_merchant_mails)) && Configuration::get('PS_STOCK_MANAGEMENT')) + if ($product->active == 1 && (int)$quantity <= $ma_last_qties && !(!$this->_merchant_oos || empty($this->_merchant_mails)) && $configuration['PS_STOCK_MANAGEMENT']) { $iso = Language::getIsoById($id_lang); $product_name = Product::getProductName($id_product, $id_product_attribute, $id_lang); $template_vars = array( - '{qty}' => $quantity, - '{last_qty}' => $ma_last_qties, - '{product}' => $product_name); + '{qty}' => $quantity, + '{last_qty}' => $ma_last_qties, + '{product}' => $product_name + ); if (file_exists(dirname(__FILE__).'/mails/'.$iso.'/productoutofstock.txt') && file_exists(dirname(__FILE__).'/mails/'.$iso.'/productoutofstock.html')) - Mail::Send($id_lang, - 'productoutofstock', - Mail::l('Product out of stock', $id_lang), - $template_vars, - explode(self::__MA_MAIL_DELIMITOR__, $this->_merchant_mails), - null, - strval(Configuration::get('PS_SHOP_EMAIL')), - strval(Configuration::get('PS_SHOP_NAME')), - null, - null, - dirname(__FILE__).'/mails/'); + { + // Send 1 email by merchant mail, because Mail::Send doesn't work with an array of recipients + $merchant_mails = explode(self::__MA_MAIL_DELIMITOR__, $this->_merchant_mails); + foreach ($merchant_mails as $merchant_mail) + { + Mail::Send( + $id_lang, + 'productoutofstock', + Mail::l('Product out of stock', $id_lang), + $template_vars, + $merchant_mail, + null, + strval($configuration['PS_SHOP_EMAIL']), + strval($configuration['PS_SHOP_NAME']), + null, + null, + dirname(__FILE__).'/mails/', + false, + $id_shop + ); + } + } } if ($this->_customer_qty && $quantity > 0) @@ -541,31 +563,44 @@ class MailAlerts extends Module $coverage = StockManagerFactory::getManager()->getProductCoverage($id_product, $id_product_attribute, $warning_coverage, $id_warehouse); // if we need to send a notification - if ($product->active == 1 && $coverage !== -1 && ($coverage < $warning_coverage) && !empty($this->_merchant_mails) && + if ($product->active == 1 && + ($coverage < $warning_coverage) && !empty($this->_merchant_mails) && Configuration::getGlobalValue('MA_MERCHANT_COVERAGE')) { - $id_lang = (int)Context::getContext()->language->id; + $context = Context::getContext(); + $id_lang = (int)$context->language->id; + $id_shop = (int)$context->shop->id; $iso = Language::getIsoById($id_lang); $product_name = Product::getProductName($id_product, $id_product_attribute, $id_lang); $template_vars = array( - '{current_coverage}' => $coverage, - '{warning_coverage}' => $warning_coverage, - '{product}' => pSQL($product_name)); + '{current_coverage}' => $coverage, + '{warning_coverage}' => $warning_coverage, + '{product}' => pSQL($product_name) + ); if (file_exists(dirname(__FILE__).'/mails/'.$iso.'/productcoverage.txt') && file_exists(dirname(__FILE__).'/mails/'.$iso.'/productcoverage.html')) { - Mail::Send($id_lang, - 'productcoverage', - Mail::l('Stock coverage', $id_lang), - $template_vars, - explode(self::__MA_MAIL_DELIMITOR__, $this->_merchant_mails), - null, - strval(Configuration::get('PS_SHOP_EMAIL')), - strval(Configuration::get('PS_SHOP_NAME')), - null, - null, - dirname(__FILE__).'/mails/'); + // Send 1 email by merchant mail, because Mail::Send doesn't work with an array of recipients + $merchant_mails = explode(self::__MA_MAIL_DELIMITOR__, $this->_merchant_mails); + foreach ($merchant_mails as $merchant_mail) + { + Mail::Send( + $id_lang, + 'productcoverage', + Mail::l('Stock coverage', $id_lang), + $template_vars, + $merchant_mail, + null, + strval(Configuration::get('PS_SHOP_EMAIL')), + strval(Configuration::get('PS_SHOP_NAME')), + null, + null, + dirname(__FILE__).'/mails/', + null, + $id_shop + ); + } } } } diff --git a/modules/mailalerts/upgrade/install-2.5.php b/modules/mailalerts/upgrade/install-2.5.php new file mode 100644 index 000000000..8696a4a2b --- /dev/null +++ b/modules/mailalerts/upgrade/install-2.5.php @@ -0,0 +1,29 @@ +execute(' + ALTER TABLE '._DB_PREFIX_.'mailalert_customer_oos + ADD '.mailalerts_stripslashes_field('id_lang').' INT( 10 ) UNSIGNED NOT NULL , + DROP PRIMARY KEY , + ADD PRIMARY KEY ( + '.mailalerts_stripslashes_field('id_customer').' , + '.mailalerts_stripslashes_field('customer_email').' , + '.mailalerts_stripslashes_field('id_product').' , + '.mailalerts_stripslashes_field('id_product_attribute').' , + '.mailalerts_stripslashes_field('id_shop').' + )' + ); +} + +function mailalerts_stripslashes_field($field) +{ + $quotes = array('"\\\'"', '"\'"'); + $dquotes = array('\'\\\\"\'', '\'"\''); + $backslashes = array('"\\\\\\\\"', '"\\\\"'); + + return '`'.bqSQL($field).'` = replace(replace(replace(`'.bqSQL($field).'`, '.$quotes[0].', '.$quotes[1].'), '.$dquotes[0].', '.$dquotes[1].'), '.$backslashes[0].', '.$backslashes[1].')'; +} \ No newline at end of file diff --git a/modules/shopimporter/shopimporter.php b/modules/shopimporter/shopimporter.php index 7b6a7cd02..b5d67680d 100644 --- a/modules/shopimporter/shopimporter.php +++ b/modules/shopimporter/shopimporter.php @@ -844,19 +844,15 @@ class shopimporter extends ImportModule default: case 'Product': $path = _PS_PROD_IMG_DIR_; - $type = 'products'; break; case 'Category': $path = _PS_CAT_IMG_DIR_; - $type = 'categories'; break; case 'Manufacturer': $path = _PS_MANU_IMG_DIR_; - $type = 'manufacturers'; break; case 'Supplier': $path = _PS_SUPP_IMG_DIR_; - $type = 'suppliers'; break; } $cover = 1; @@ -865,11 +861,8 @@ class shopimporter extends ImportModule foreach($item['images'] as $key => $image) { $tmpfile = tempnam(_PS_TMP_IMG_DIR_, 'import'); - if (@copy(str_replace(' ', '%20', $image), $tmpfile)) + if (@copy(str_replace(' ', '%20', $image), $tmpfile)) { - - $imagesTypes = ImageType::getImagesTypes($type); - ImageManager::resize($tmpfile, $path.(int)$matchId[$item[$identifier]].'.jpg'); if ($className == 'Product') { $image = new Image(); @@ -884,13 +877,13 @@ class shopimporter extends ImportModule $legend[Configuration::get('PS_LANG_DEFAULT')] = Tools::link_rewrite($val); $image->legend = $legend; $image->add(); - ImageManager::resize($tmpfile, $path.(int)$matchId[$item[$identifier]].'-'.(int)$image->id.'.jpg'); - foreach ($imagesTypes AS $k => $imageType) - ImageManager::resize($tmpfile, $path.(int)$matchId[$item[$identifier]].'-'.(int)$image->id.'-'.stripslashes($imageType['name']).'.jpg', $imageType['width'], $imageType['height']); + $path = $image->getPathForCreation(); + ImageManager::resize($tmpfile, $path.'.jpg'); } else - foreach ($imagesTypes as $imageType) - ImageManager::resize($tmpfile, $path.(int)$matchId[$item[$identifier]].'-'.stripslashes($imageType['name']).'.jpg', $imageType['width'], $imageType['height']); + { + ImageManager::resize($tmpfile, $path.(int)$matchId[$item[$identifier]].'.jpg'); + } } else @unlink($tmpfile); @@ -1490,9 +1483,11 @@ class shopimporter extends ImportModule $order->total_products_wt = (float)$item['total_products_wt']; $order->total_discounts = (float)$item['total_discounts']; $order->total_shipping = (float)$item['total_shipping']; + $order->total_shipping_tax_incl = (float)$item['total_shipping']; $order->carrier_tax_rate = (float)$carrier->getTaxesRate(new Address((int)$item[Configuration::get('PS_TAX_ADDRESS_TYPE')])); $order->total_wrapping = (float)$item['total_wrapping']; $order->total_paid = (float)$item['total_paid']; + $order->total_paid_tax_incl = (float)$item['total_paid']; $order->total_paid_real = (float)$item['total_paid_real']; $order->invoice_date = '0000-00-00 00:00:00'; $order->delivery_date = '0000-00-00 00:00:00'; @@ -1505,6 +1500,20 @@ class shopimporter extends ImportModule $order->valid = 1; else $order->valid = 0; + + if (array_key_exists('current_state', $item)) + $order->current_state = $item['current_state']; + if (array_key_exists('reference', $item)) + $order->reference = $item['reference']; + if (array_key_exists('invoice_number', $item)) + $order->invoice_number = $item['invoice_number']; + if (array_key_exists('delivery_number', $item)) + $order->delivery_number = $item['delivery_number']; + if (array_key_exists('invoice_date', $item)) + $order->invoice_date = $item['invoice_date']; + if (array_key_exists('delivery_date', $item)) + $order->delivery_date = $item['delivery_date']; + $order->save(false, false); $this->saveMatchId('order', (int)$order->id, (int)$item['id_cart']); diff --git a/themes/default/authentication.tpl b/themes/default/authentication.tpl index 72551663b..a4371c698 100644 --- a/themes/default/authentication.tpl +++ b/themes/default/authentication.tpl @@ -36,7 +36,7 @@ var idSelectedCountry = {if isset($smarty.post.id_state)}{$smarty.post.id_state|intval}{else}false{/if}; var countries = new Array(); var countriesNeedIDNumber = new Array(); -var countriesNeedZipCode = new Array(); +var countriesNeedZipCode = new Array(); {if isset($countries)} {foreach from=$countries item='country'} {if isset($country.states) && $country.contains_states} @@ -75,7 +75,7 @@ $(document).ready(function() {

    {if !isset($email_create)}{l s='Authentication'}{else}{l s='Create an account'}{/if}

    -{if !isset($back) || $back != 'my-account'}{assign var='current_step' value='login'}{include file="$tpl_dir./order-steps.tpl"}{/if} +{if !isset($back) || $back != 'my-account'}{assign var='current_step' value='login'}{include file="$tpl_dir./order-steps.tpl"}{/if} {include file="$tpl_dir./errors.tpl"} {assign var='stateExist' value=false} {assign var="postCodeExist" value=false} @@ -126,7 +126,7 @@ $(document).ready(function() { $('#center_column').html('
    '+$('#center_column').html()+'
    '); $('#noSlide').fadeOut('slow', function(){ $('#noSlide').html(jsonData.page); - // update the state (when this file is called from AJAX you still need to update the state) + // update the state (when this file is called from AJAX you still need to update the state) bindStateInputAndUpdate(); $(this).fadeIn('slow', function(){ document.location = '#account-creation'; @@ -160,7 +160,7 @@ $(document).ready(function() {

    {l s='Create an account'}

    -

    {l s='Please enter your email address to create an account.'}.

    +

    {l s='Please enter your email address to create an account.'}

    @@ -339,7 +339,7 @@ $(document).ready(function() {

    - {/if} + {/if} @@ -551,7 +551,7 @@ $(document).ready(function() {

    - {/if} + {/if} {if $stateExist eq false} -{/if} \ No newline at end of file +{/if} diff --git a/themes/default/order-follow.tpl b/themes/default/order-follow.tpl index bf4d6a7d8..41abbb6f2 100644 --- a/themes/default/order-follow.tpl +++ b/themes/default/order-follow.tpl @@ -34,7 +34,7 @@

    {l s='Please provide an explanation for your RMA:'}

    -
    +

    diff --git a/themes/default/product.tpl b/themes/default/product.tpl index 97f5bbb08..dfd32a4ae 100644 --- a/themes/default/product.tpl +++ b/themes/default/product.tpl @@ -433,17 +433,10 @@ var fieldRequired = '{l s='Please fill in all the required fields before saving {/if} {*close if for show price*} {/if} - {if (!$allow_oosp && $product->quantity <= 0) OR !$product->available_for_order OR (isset($restricted_country_mode) AND $restricted_country_mode) OR $PS_CATALOG_MODE} - - - {l s='Add to cart'} - - {else} -

    - - -

    - {/if} +

    quantity <= 0) OR !$product->available_for_order OR (isset($restricted_country_mode) AND $restricted_country_mode) OR $PS_CATALOG_MODE}style="display:none"{/if} class="buttons_bottom_block"> + + +

    {if isset($HOOK_PRODUCT_ACTIONS) && $HOOK_PRODUCT_ACTIONS}{$HOOK_PRODUCT_ACTIONS}{/if}
    diff --git a/tools/smarty/sysplugins/smarty_internal_templatebase.php b/tools/smarty/sysplugins/smarty_internal_templatebase.php index 84315b2d6..2da7e0f5f 100644 --- a/tools/smarty/sysplugins/smarty_internal_templatebase.php +++ b/tools/smarty/sysplugins/smarty_internal_templatebase.php @@ -278,9 +278,7 @@ abstract class Smarty_Internal_TemplateBase extends Smarty_Internal_Data { // // render cached template // - /* PrestaShop related to PSCFV-10040 - http://www.smarty.net/forums/viewtopic.php?p=76467 */ - if (isset($_template->properties['unifunc'])) - $_template->properties['unifunc']($_template); + $_template->properties['unifunc']($_template); // any unclosed {capture} tags ? if (isset($_template->_capture_stack[0][0])) { $_template->capture_error();
  • {if $has_bulk_actions} - + {/if}