Advertisement
Guest User

Untitled

a guest
Jan 29th, 2020
3,017
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 369.22 KB | None | 0 0
  1. <?php
  2. /**
  3. * NOTICE OF LICENSE
  4. *
  5. * This source file is subject to a commercial license from Common-Services Co., Ltd.
  6. * Use, copy, modification or distribution of this source file without written
  7. * license agreement from the SARL SMC is strictly forbidden.
  8. * In order to obtain a license, please contact us: [email protected]
  9. * ...........................................................................
  10. * INFORMATION SUR LA LICENCE D'UTILISATION
  11. *
  12. * L'utilisation de ce fichier source est soumise a une licence commerciale
  13. * concedee par la societe Common-Services Co., Ltd.
  14. * Toute utilisation, reproduction, modification ou distribution du present
  15. * fichier source sans contrat de licence ecrit de la part de la Common-Services Co. Ltd. est
  16. * expressement interdite.
  17. * Pour obtenir une licence, veuillez contacter Common-Services Co., Ltd. a l'adresse: [email protected]
  18. *
  19. * @author Olivier B.
  20. * @copyright Copyright (c) 2011-2018 Common Services Co Ltd - 90/25 Sukhumvit 81 - 10260 Bangkok - Thailand
  21. * @license Commercial license
  22. * @package Amazon Market Place
  23. * Support by mail: [email protected]
  24. */
  25.  
  26. if (!defined('MODULE_AMAZON')) {
  27. define('MODULE_AMAZON', 'amazon');
  28. }
  29.  
  30.  
  31. require_once(_PS_MODULE_DIR_.'/amazon/classes/amazon.product.class.php');
  32. require_once(_PS_MODULE_DIR_.'/amazon/classes/amazon.context.class.php');
  33. require_once(_PS_MODULE_DIR_.'/amazon/classes/amazon.configuration.class.php');
  34.  
  35. @define('AMAZON_EXPERIMENTAL_FEATURES', in_array($_SERVER['SERVER_ADDR'], array('91.121.46.68', 'w.x.y.z')) || isset($_SERVER['DropBox']));
  36.  
  37. class Amazon extends Module
  38. {
  39. const MARKETPLACE = 'amazon';
  40.  
  41. const ADD = 'a';
  42. const REMOVE = 'd';
  43. const UPDATE = 'u';
  44. const REPRICE = 'r';
  45.  
  46. const FORMAT_TITLE = 1;
  47. const FORMAT_MANUFACTURER_TITLE = 2;
  48. const FORMAT_MANUFACTURER_TITLE_REFERENCE = 3;
  49.  
  50. const FIELD_DESCRIPTION_SHORT = 'description_short';
  51. const FIELD_DESCRIPTION_LONG = 'description';
  52. const FIELD_DESCRIPTION_BOTH = 'both';
  53. const FIELD_DESCRIPTION_NONE = 'none';
  54.  
  55. const BULLET_POINT_STRATEGY_ATTRIBUTES = 1;
  56. const BULLET_POINT_STRATEGY_ATTRIBUTES_FEATURES = 2;
  57. const BULLET_POINT_STRATEGY_FEATURES = 3;
  58. const BULLET_POINT_STRATEGY_DESC = 4;
  59. const BULLET_POINT_STRATEGY_DESC_ATTRIBUTES_FEATURES = 5;
  60. const BULLET_POINT_STRATEGY_DESC_FEATURES = 6;
  61.  
  62. const ACCOUNT_TYPE_GLOBAL = 1;
  63. const ACCOUNT_TYPE_INDIVIDUAL = 2;
  64.  
  65. const PAYMENT_METHOD_TITLE = 'Amazon MarketPlace';
  66.  
  67. const ENABLE_EXPERIMENTAL_FEATURES = AMAZON_EXPERIMENTAL_FEATURES;
  68.  
  69. const SHIPPING_OVERRIDE_ADDITIVE = 'Additive';
  70. const SHIPPING_OVERRIDE_EXCLUSIVE = 'Exclusive';
  71.  
  72. const EXEMPTION_NONE = 0;
  73. const EXEMPTION_COMPATIBILITY = 1; /*For backward compatibility*/
  74. const EXEMPTION_MODEL_NUMBER = 2;
  75. const EXEMPTION_MODEL_NAME = 3;
  76. const EXEMPTION_MFR_PART_NUMBER = 4;
  77. const EXEMPTION_CATALOG_NUMBER = 5;
  78. const EXEMPTION_STYLE_NUMBER = 6;
  79. const EXEMPTION_ATTR_EAN = 7;
  80. const EXEMPTION_GENERIC = 10;
  81.  
  82. const FBA_STOCK_SWITCH = 1;
  83. const FBA_STOCK_SYNCH = 2;
  84.  
  85. const FBA_NOTIFICATION_SHOP = 1;
  86. const FBA_NOTIFICATION_CUSTOMER = 2;
  87. const FBA_NOTIFICATION_BOTH = 3;
  88.  
  89. const ORDER_STATE_STANDARD = 'STD';
  90. const ORDER_STATE_PREORDER = 'PRE';
  91. const ORDER_STATE_PRIMEORDER = 'PRIME';
  92.  
  93. const AFN = 'AFN';
  94. const MFN = 'MFN';
  95.  
  96. const LENGTH_TITLE = 500;
  97. const LENGTH_BULLET_POINT = 500;
  98. const LENGTH_DESCRIPTION = 2000;
  99.  
  100. const LF = "\n";
  101. const BR = '<br />';
  102. const TEMPLATE_HEADER = 1;
  103. const TEMPLATE_FOOTER = 2;
  104. const TEMPLATE_LICENSE = 3;
  105. const TEMPLATE_VALIDATE = 4;
  106. const TEMPLATE_CONFIGURE = 5;
  107. const TEMPLATE_TABS = 10;
  108. const TEMPLATE_TAB_SETTINGS = 19;
  109. const TEMPLATE_TAB_TOOLS = 20;
  110. const TEMPLATE_TAB_CRON = 21;
  111. const TEMPLATE_TAB_FILTERS = 22;
  112. const TEMPLATE_TAB_PARAMETERS = 23;
  113. const TEMPLATE_TAB_CATEGORIES = 24;
  114. const TEMPLATE_TAB_PROFILES = 25;
  115. const TEMPLATE_TAB_MAPPING = 26;
  116. const TEMPLATE_TAB_INFO = 27;
  117. const TEMPLATE_TAB_SHIPPING = 28;
  118. const TEMPLATE_TAB_MESSAGING = 29;
  119. const TEMPLATE_TAB_FBA = 30;
  120. const TEMPLATE_TAB_FEATURES = 31;
  121. const TEMPLATE_TAB_REPRICING = 32;
  122. const TEMPLATE_ORDER_DETAIL = 42;
  123. const TEMPLATE_TAB_AMAZON = 43;
  124. const TEMPLATE_TAB_GLOSSARY = 44;
  125.  
  126. private static $templates = array(
  127. self::TEMPLATE_TABS => 'views/templates/admin/configure/tabs.tpl',
  128. self::TEMPLATE_HEADER => 'views/templates/admin/configure/header.tpl',
  129. self::TEMPLATE_FOOTER => 'views/templates/admin/configure/footer.tpl',
  130. self::TEMPLATE_VALIDATE => 'views/templates/admin/configure/validate.tpl',
  131. self::TEMPLATE_CONFIGURE => 'views/templates/admin/configure/configure.tpl',
  132. self::TEMPLATE_LICENSE => 'views/templates/admin/configure/license.tpl',
  133. self::TEMPLATE_TAB_SETTINGS => 'views/templates/admin/configure/settings.tab.tpl',
  134. self::TEMPLATE_TAB_TOOLS => 'views/templates/admin/configure/tools.tab.tpl',
  135. self::TEMPLATE_TAB_CRON => 'views/templates/admin/configure/cron.tab.tpl',
  136. self::TEMPLATE_TAB_FILTERS => 'views/templates/admin/configure/filters.tab.tpl',
  137. self::TEMPLATE_TAB_PARAMETERS => 'views/templates/admin/configure/parameters.tab.tpl',
  138. self::TEMPLATE_TAB_PROFILES => 'views/templates/admin/configure/profiles.tab.tpl',
  139. self::TEMPLATE_TAB_CATEGORIES => 'views/templates/admin/configure/categories.tab.tpl',
  140. self::TEMPLATE_TAB_MAPPING => 'views/templates/admin/configure/mapping.tab.tpl',
  141. self::TEMPLATE_TAB_INFO => 'views/templates/admin/configure/informations.tab.tpl',
  142. self::TEMPLATE_TAB_FEATURES => 'views/templates/admin/configure/features.tab.tpl',
  143. self::TEMPLATE_TAB_SHIPPING => 'views/templates/admin/configure/shipping.tab.tpl',
  144. self::TEMPLATE_TAB_MESSAGING => 'views/templates/admin/configure/messaging.tab.tpl',
  145. self::TEMPLATE_TAB_FBA => 'views/templates/admin/configure/fba.tab.tpl',
  146. self::TEMPLATE_TAB_REPRICING => 'views/templates/admin/configure/repricing.tab.tpl',
  147. self::TEMPLATE_TAB_AMAZON => 'views/templates/admin/configure/amazon.tab.tpl',
  148. self::TEMPLATE_TAB_GLOSSARY => 'views/templates/admin/configure/glossary.tpl',
  149. self::TEMPLATE_ORDER_DETAIL => 'views/templates/admin/AdminOrderDetailAmazon.tpl'
  150. );
  151.  
  152. const ROUNDING_ONE_DIGIT = 1;
  153. const ROUNDING_TWO_DIGITS = 2;
  154. const ROUNDING_SMART = 3;
  155. const ROUNDING_NONE = 4;
  156.  
  157. const SORT_ORDER_FIRSTNAME_LASTNAME = 1;
  158. const SORT_ORDER_LASTNAME_FIRSTNAME = 2;
  159.  
  160. const MAX_PROFILES = 10;
  161.  
  162. const RECOMMENDED_IMAGE_SIZE = 1000;
  163.  
  164. /**
  165. * Table name definition
  166. */
  167. const TABLE_MARKETPLACE_STRATEGIES = 'marketplace_strategies';
  168. const TABLE_MARKETPLACE_ACTIONS = 'marketplace_product_action';
  169. const TABLE_MARKETPLACE_CONFIGURATION = 'marketplace_configuration';
  170. const TABLE_MARKETPLACE_NEW_CONFIGURATION = 'amazon_configuration';
  171. const TABLE_MARKETPLACE_ORDERS = 'marketplace_orders';
  172. const TABLE_MARKETPLACE_ORDER_ITEMS = 'marketplace_order_items';
  173. const TABLE_MARKETPLACE_OPTIONS = 'marketplace_product_option';
  174. const TABLE_MARKETPLACE_ORDER_ADDRESS = 'marketplace_order_address';
  175. const TABLE_MARKETPLACE_STATS = 'marketplace_stats';
  176. const TABLE_MARKETPLACE_VAT = 'marketplace_vat_report';
  177. const TABLE_MARKETPLACE_TAXES = 'marketplace_taxes';
  178.  
  179. /**
  180. * Configuration key definition
  181. */
  182. const CONFIG_MASTER = 'MASTER';
  183. const CONFIG_DEFAULT_TAX_RULE_FOR_MP = 'DEFAULT_TAX_RULE';
  184.  
  185. const TRASH_DOMAIN = 'amazon.mp.common-services.com';
  186.  
  187. public $id_lang;
  188. public $name = 'amazon';
  189.  
  190. public $shipping_overrides_std = array();
  191. public $shipping_overrides_exp = array();
  192. public $extra_carrier_codes = array();
  193.  
  194. public $carrier_fba = array(
  195. 'Standard',
  196. 'Expedited',
  197. 'Priority'
  198. );
  199.  
  200. public $path;
  201. public $url;
  202. public $base;
  203. public $images;
  204. public $ps16x = false;
  205. public $ps17x = false;
  206. public $ps15x = false;
  207. public $ps14x = false;
  208.  
  209. private $_html = '';
  210. private $_postErrors = array();
  211. private $config = array();
  212. private $profiles = null;
  213.  
  214. private static $carriers = null;
  215.  
  216. private $_config = array(
  217. 'AMAZON_CURRENT_VERSION' => null,
  218. 'AMAZON_ACTIVE' => null,
  219. 'AMAZON_EMPLOYEE' => null,
  220. 'AMAZON_MERCHANT_ID' => null,
  221. 'AMAZON_MARKETPLACE_ID' => null,
  222. 'AMAZON_AWS_KEY_ID' => null,
  223. 'AMAZON_SECRET_KEY' => null,
  224. 'AMAZON_CURRENCY' => null,
  225. 'AMAZON_REGION' => null,
  226. 'AMAZON_OUT_OF_STOCK' => null,
  227. 'AMAZON_PRICE_RULE' => null,
  228. 'AMAZON_CUSTOMER_ID' => null,
  229. 'AMAZON_CARRIER' => null, /* Prestashop Side Carrier*/
  230. 'AMAZON_AMAZON_CARRIER' => null, /* Amazon Side Carrier*/
  231. /*Orders Statuses*/
  232. 'AMAZON_ORDER_STATE' => null,
  233. 'AMAZON_PREPARATION_STATE' => null,
  234. 'AMAZON_SENT_STATE' => null,
  235. 'AMAZON_CANCELED_STATE' => null,
  236. 'AMAZON_CARRIER_DEFAULT' => null,
  237. /*Amazon Europe*/
  238. 'AMAZON_MASTER' => null,
  239. /*Options*/
  240. 'AMAZON_EMAIL' => null,
  241. 'AMAZON_DEBUG_MODE' => null,
  242. 'AMAZON_FIELD' => null,
  243. 'AMAZON_USE_ASIN' => null,
  244. 'AMAZON_STOCK_ONLY' => null,
  245. 'AMAZON_PRICES_ONLY' => null,
  246. 'AMAZON_PRICE_ROUNDING' => null,
  247. 'AMAZON_SAFE_ENCODING' => null,
  248. // Aug-23-2018: Remove Carriers/Module option
  249. /*Generic Parameters*/
  250. 'AMAZON_SPECIALS' => null,
  251. /*2014-06-28*/
  252. 'AMAZON_SPECIALS_APPLY_RULES' => null,
  253. 'AMAZON_PREORDER' => null,
  254. 'AMAZON_TAXES' => null,
  255. 'AMAZON_DELETE_PRODUCTS' => null,
  256. 'AMAZON_UPDATE_PRODUCTS' => null,
  257. 'AMAZON_HTML_DESCRIPTIONS' => null,
  258. /*Reports*/
  259. 'AMAZON_REPORT_ID' => null,
  260. /*Hidden Settings*/
  261. 'AMAZON_HIDDEN_SETTINGS' => false,
  262. /*Shipping Rules for trader module*/
  263. 'AMAZON_SHIPPING_RULES' => null,
  264. /*Condition*/
  265. 'AMAZON_CONDITION_MAP' => null,
  266. /*Account Type*/
  267. 'AMAZON_ACCOUNT_TYPE' => false,
  268. 'AMAZON_TITLE_FORMAT' => null,
  269. 'AMAZON_AUTO_CREATE' => null,
  270. 'AMAZON_IMAGE_TYPE' => null,
  271. 'AMAZON_DESCRIPTION_FIELD' => self::FIELD_DESCRIPTION_LONG,
  272. /*Shipping Overrides*/
  273. 'AMAZON_SHIPPING_OVERRIDES_STD' => null,
  274. 'AMAZON_SHIPPING_OVERRIDES_EXP' => null,
  275. /*Crazy Features*/
  276. 'AMAZON_BRUTE_FORCE' => false,
  277. /*Module Environment*/
  278. 'AMAZON_API_TIMER' => null, /*use to store the antithrottling timer*/
  279. /*Mappings*/
  280. 'AMAZON_MAPPING' => null,
  281. /*Cron Variables*/
  282. 'AMAZON_CRON_TOKEN' => null,
  283. /*FBA Settings*/
  284. 'AMAZON_FBA_ORDER_STATE' => null,
  285. 'AMAZON_FBA_SENT_STATE' => null,
  286. 'AMAZON_FBA_MULTICHANNEL_STATE' => null,
  287. 'AMAZON_FBA_MULTICHANNEL_SENT' => null,
  288. 'AMAZON_FBA_PRICE_FORMULA' => null,
  289. 'AMAZON_FBA_MULTICHANNEL' => null,
  290. 'AMAZON_FBA_MULTICHANNEL_AUTO' => null,
  291. 'AMAZON_FBA_DECREASE_STOCK' => null,
  292. 'AMAZON_CARRIER_MULTICHANNEL' => null,
  293. 'AMAZON_WAREHOUSE' => null,
  294. /*2013-08-17*/
  295. 'AMAZON_EXCLUDED_MANUFACTURERS' => null,
  296. 'AMAZON_EXCLUDED_SUPPLIERS' => null,
  297. /* 2014-06-17 */
  298. 'AMAZON_PRICE_FILTER' => null,
  299. /*2013-09-15*/
  300. 'AMAZON_MAIL_INVOICE' => null,
  301. 'AMAZON_MAIL_REVIEW' => null,
  302. /*2013-12-21*/
  303. 'AMAZON_CONTEXT' => null,
  304. /*2013-12-24 - Shipping configuration*/
  305. 'AMAZON_SHIPPING' => null,
  306. 'AMAZON_SHIPPING_METHODS' => null,
  307. 'AMAZON_PRODUCTS_CREATION' => null,
  308. /*2014-06-16*/
  309. 'AMAZON_WIZARD_MATCHING_STATE' => null,
  310. 'AMAZON_WIZARD_CREATION_STATE' => null,
  311. 'AMAZON_INACTIVE_LANGUAGES' => null,
  312. /*2015-04-25*/
  313. 'AMAZON_FBA_STOCK_BEHAVIOUR' => null,
  314. 'AMAZON_FEATURES' => null,
  315. /*2015-09-09*/
  316. 'AMAZON_PRODUCT_OPTION_FIELDS' => null,
  317. 'AMAZON_INSTANT_TOKEN' => null,
  318. /*2016-03-09*/
  319. 'AMAZON_FBA_NOTIFICATION' => null,
  320. /*2013-03-24*/
  321. 'AMAZON_SORT_ORDER' => null,
  322. /*2016-04-14*/
  323. 'AMAZON_CUSTOMER_THREAD' => array(),
  324. /*2017-06-22*/
  325. 'AMAZON_CHECKSTOCK_REQUEST' => '',
  326. 'AMAZON_FIXORDERS_REQUEST' => ''
  327. );
  328. private $_platforms = array(
  329. 'au' => 'Australia',
  330. 'ca' => 'Canada',
  331. 'cn' => 'China',
  332. 'de' => 'Germany',
  333. 'es' => 'Spain',
  334. 'fr' => 'France',
  335. 'it' => 'Italy',
  336. 'in' => 'India',
  337. 'jp' => 'Japan',
  338. 'br' => 'Brazil',
  339. 'mx' => 'Mexico',
  340. 'uk' => 'United Kingdom',
  341. 'us' => 'United States'
  342. );
  343. public static $conditions = array(
  344. 11 => 'New',
  345. 1 => 'UsedLikeNew',
  346. 2 => 'UsedVeryGood',
  347. 3 => 'UsedGood',
  348. 4 => 'UsedAcceptable',
  349. 5 => 'CollectibleLikeNew',
  350. 6 => 'CollectibleVeryGood',
  351. 7 => 'CollectibleGood',
  352. 8 => 'CollectibleAcceptable',
  353. 98 => 'Refurbished', // condition code unknown yet
  354. 99 => 'Club' // condition code unknown yet
  355. );
  356.  
  357. public static $features = array();
  358. public static $features_values = array();
  359.  
  360. public static $attributes = array();
  361. public static $attributes_groups = array();
  362.  
  363. public static $amazon_default_features = array(
  364. 'module',
  365. 'creation',
  366. 'offers',
  367. 'wizard',
  368. 'prices_rules',
  369. 'second_hand',
  370. 'filters',
  371. 'import_products',
  372. 'amazon_europe',
  373. 'worldwide',
  374. 'messaging',
  375. 'smart_shipping',
  376. 'shipping',
  377. 'tools',
  378. 'fba',
  379. 'repricing',
  380. 'orders',
  381. 'orders_reports',
  382. 'gcid',
  383. 'expert_mode',
  384. 'demo_mode',
  385. 'remote_cart',
  386. 'cancel_orders',
  387. 'business'
  388. );
  389.  
  390. public $amazon_features = null;
  391.  
  392. public static $amazon_default_features_default = array(
  393. 'offers' => true,
  394. 'prices_rules' => true,
  395. 'orders' => true,
  396. 'orders_reports' => true
  397. );
  398.  
  399. public static $mwsops_required = array(
  400. 'ATVPDKIKX0DER', // US
  401. 'A13V1IB3VIYZZH', // France
  402. 'A1RKKUPIHCS9HS', // Spain
  403. 'A1PA6795UKMFR9', // Germany
  404. 'APJ6JRA9NG5V4', // Italy
  405. 'A1F83G8C2ARO7P', // Uk
  406. 'A2Q3Y263D00KWC', // Brasil
  407. 'A2EUQ1WTGCTBG2', // Canada
  408. 'A1AM78C64UM0Y8', // Mexico
  409. 'A39IBJ37TRP1C6', // Australia
  410. 'AAHKV2X7AFYLW', // China
  411. );
  412. public static $debug_mode = false;
  413.  
  414. public static $usefull_urls = array();
  415.  
  416. public function __construct()
  417. {
  418. $this->page = basename(__FILE__, '.php');
  419. $this->tab = 'market_place';
  420. $this->version = '4.4.085';
  421. $this->author = 'Common-Services';
  422. $this->author_address = '0x96116FE33A6268AE9E878Dbc609A02BdCcc285E0';
  423. $this->module_key = 'bd88475a00b7e8a2c2c3c8b89680922d';
  424. //Amazon Regular: bd88475a00b7e8a2c2c3c8b89680922d //Amazon Lite: 95bf55040245698af47e08725394866e
  425. $this->bootstrap = true;
  426. $this->need_instance = false;
  427. $this->name = 'amazon';
  428. $this->path = _PS_MODULE_DIR_.$this->name.'/';
  429.  
  430. parent::__construct();
  431.  
  432.  
  433. /* Backward compatibility */
  434. if (_PS_VERSION_ < '1.5') {
  435. require(_PS_MODULE_DIR_.$this->name.'/backward_compatibility/backward.php');
  436. }
  437.  
  438. $this->path_pdf = $this->path.'pdf/';
  439. $this->path_mail = $this->path.'mails/';
  440.  
  441. require_once(_PS_MODULE_DIR_.'/amazon/classes/amazon.tools.class.php');
  442. require_once(_PS_MODULE_DIR_.'/amazon/validate/AmazonXSD.php'); //gets code for Amazon XML Schemas
  443. require_once(_PS_MODULE_DIR_.'/amazon/classes/amazon.tools.class.php');
  444. require_once(_PS_MODULE_DIR_.'/amazon/classes/amazon.support.class.php');
  445. require_once(_PS_MODULE_DIR_.'/amazon/classes/amazon.specificfield.class.php');
  446. require_once(_PS_MODULE_DIR_.'/amazon/classes/amazon.valid_values.class.php');
  447. require_once(_PS_MODULE_DIR_.'/amazon/classes/amazon.csv.references.class.php');
  448. require_once(_PS_MODULE_DIR_.'/amazon/classes/amazon.carrier.class.php');
  449. require_once(_PS_MODULE_DIR_.'/amazon/classes/amazon.repricing.class.php');
  450. require_once(_PS_MODULE_DIR_.'/amazon/classes/amazon.taxes.class.php');
  451.  
  452. $this->url = AmazonTools::getShopUrl();
  453. $this->displayName = $this->l('Amazon');
  454. $this->description = $this->l('This extension allow to sell products and retrieve orders from the Amazon MarketPlace');
  455. $this->images = $this->url.'views/img/';
  456. $this->initContext();
  457.  
  458.  
  459. $this->amazon_features = $this->getAmazonFeatures();
  460.  
  461. if (isset($this->amazon_features['name'])) {
  462. $this->displayName = $this->amazon_features['name'];
  463. }
  464.  
  465. self::$debug_mode = (bool)Configuration::get('AMAZON_DEBUG_MODE') || (bool)Tools::getValue('debug');
  466. }
  467.  
  468. private function initContext()
  469. {
  470. if (version_compare(_PS_VERSION_, '1.7', '>=')) {
  471. $this->ps17x = $this->ps16x = true;
  472. } elseif (version_compare(_PS_VERSION_, '1.6', '>=')) {
  473. $this->ps16x = true;
  474. } elseif (version_compare(_PS_VERSION_, '1.5', '>=')) {
  475. $this->ps15x = true;
  476. } else {
  477. $this->ps14x = true;
  478. }
  479.  
  480. $this->context = Context::getContext();
  481.  
  482. $id_lang = (int)Tools::getValue('id_lang');
  483.  
  484. if ($id_lang) {
  485. // id_lang for ajax script
  486.  
  487. $language = new Language($id_lang);
  488.  
  489. if (Validate::isLoadedObject($language) && $this->context) {
  490. $this->context->language = $language;
  491. }
  492. }
  493.  
  494. if (isset($this->context->language->id)) {
  495. $this->id_lang = (int)$this->context->language->id;
  496. } else {
  497. $this->id_lang = (int)Configuration::get('PS_LANG_DEFAULT');
  498. }
  499. }
  500.  
  501. public static function getAmazonFeatures()
  502. {
  503. require_once(_PS_MODULE_DIR_.'/amazon/classes/amazon.settings.class.php');
  504.  
  505. // TODO: Implement allowed features
  506. $allowed_features = AmazonSettings::getSubscribedFeatures();
  507. $amazon_features = AmazonConfiguration::get('FEATURES');
  508.  
  509. if ($amazon_features === false) {
  510. $amazon_features = array_fill_keys(self::$amazon_default_features, false);
  511.  
  512. foreach (array_keys(self::$amazon_default_features_default) as $feature_default) {
  513. $amazon_features[$feature_default] = true;
  514. }
  515. } elseif (is_array($amazon_features)) {
  516. $amazon_features = array_merge(array_fill_keys(self::$amazon_default_features, false), $amazon_features);
  517. } else {
  518. $amazon_features = array_merge(array_fill_keys(self::$amazon_default_features, false));
  519. }
  520.  
  521. if (is_array($allowed_features)&& count($allowed_features)) {
  522. foreach ($amazon_features as $feature => $value) {
  523. if (array_key_exists($feature, $allowed_features) && $allowed_features[$feature] == false) {
  524. $amazon_features[$feature] = $allowed_features[$feature];
  525. }
  526. }
  527. $amazon_features['module'] = $allowed_features['module'];
  528. if (isset($allowed_features['name'])) {
  529. $amazon_features['name'] = $allowed_features['name'];
  530. }
  531. }
  532.  
  533. return ($amazon_features);
  534. }
  535.  
  536. public function install()
  537. {
  538. $pass = true;
  539.  
  540. foreach ($this->_config as $key => $value) {
  541. if (is_null($value)) {
  542. $value = '';
  543. }
  544.  
  545. if (is_array($value)) {
  546. $value = AmazonTools::encode(serialize($value));
  547. }
  548.  
  549. if (!Configuration::updateValue($key, $value)) {
  550. $this->_errors[] = sprintf('%s - key: %s, value: %s', $this->l('Unable to install : Some configuration values'), $key, nl2br(print_r($value, true)));
  551. $pass = false;
  552. }
  553. }
  554. if (!$pass) {
  555. $this->_errors[] = $this->l('Unable to install : Some configuration values');
  556. }
  557.  
  558. if (!parent::install()) {
  559. $this->_errors[] = $this->l('Unable to install: parent()') && $pass = false;
  560. }
  561.  
  562. $this->tabSetup(Amazon::ADD);
  563.  
  564. if (!$this->createCustomer()) {
  565. $this->_errors[] = $this->l('Unable to install: createCustomer()');
  566. $pass = false;
  567. }
  568. if (!$this->addMarketPlaceTables()) {
  569. $this->_errors[] = $this->l('Unable to install: addMarketPlaceTables()');
  570. $pass = false;
  571. }
  572. if (!$this->addMarketPlaceField()) {
  573. $this->_errors[] = $this->l('Unable to install: addMarketPlaceField()');
  574. $pass = false;
  575. }
  576. if (!$this->addConfigurationTable()) {
  577. $this->_errors[] = $this->l('Unable to install: _addConfigurationTable()');
  578. $pass = false;
  579. }
  580.  
  581. // Save initial context
  582. if ($pass) {
  583. require_once(dirname(__FILE__).'/classes/amazon.context.class.php');
  584. $pass = AmazonContext::save($this->context);
  585. }
  586. // Initialize instant token
  587. $this->setInstantToken();
  588.  
  589. // Hooks
  590. $this->_hookSetup(self::ADD);
  591.  
  592. return ((bool)$pass);
  593. }
  594.  
  595. public function tabSetup($action)
  596. {
  597. $pass = true;
  598. $adminOrders = $this->ps17x ? 'AdminParentOrders' : 'AdminOrders';
  599.  
  600. // Adding Tab
  601. switch ($action) {
  602. case Amazon::ADD:
  603. // For PS 1.5+
  604. if (version_compare(_PS_VERSION_, '1.5', '>=')) {
  605. if (Tab::getIdFromClassName('AdminAmazonProducts') && Tab::getIdFromClassName('AdminAmazonOrders') && Tab::getIdFromClassName('AdminAmazonStats')) {
  606. //
  607. return (true);
  608. }
  609.  
  610. if (!$this->installModuleTab('AdminAmazonProducts', 'Amazon', Tab::getIdFromClassName('AdminCatalog'))) {
  611. $this->_errors[] = $this->l('Unable to install: ProductsAmazon)');
  612. $pass = false;
  613. }
  614. if (!$this->installModuleTab('AdminAmazonOrders', 'Amazon', Tab::getIdFromClassName($adminOrders))) {
  615. $this->_errors[] = $this->l('Unable to install: OrdersAmazon');
  616. $pass = false;
  617. }
  618. if (self::ENABLE_EXPERIMENTAL_FEATURES) {
  619. if (!$this->installModuleTab('AdminAmazonStats', 'Amazon', Tab::getIdFromClassName('AdminStats'))) {
  620. $this->_errors[] = $this->l('Unable to install: StatsAmazon');
  621. $pass = false;
  622. }
  623. }
  624. } else {
  625. // For PS < 1.5
  626. if (Tab::getIdFromClassName('ProductsAmazon') && Tab::getIdFromClassName('OrdersAmazon') && Tab::getIdFromClassName('StatsAmazon')) {
  627. //
  628. return (true);
  629. }
  630.  
  631. if (!$this->installModuleTab('ProductsAmazon', 'Amazon', Tab::getIdFromClassName('AdminCatalog'))) {
  632. $this->_errors[] = $this->l('Unable to install: ProductsAmazon)');
  633. $pass = false;
  634. }
  635. if (!$this->installModuleTab('OrdersAmazon', 'Amazon', Tab::getIdFromClassName($adminOrders))) {
  636. $this->_errors[] = $this->l('Unable to install: OrdersAmazon');
  637. $pass = false;
  638. }
  639. if (!$this->installModuleTab('StatsAmazon', 'Amazon', Tab::getIdFromClassName('AdminStats'))) {
  640. $this->_errors[] = $this->l('Unable to install: StatsAmazon');
  641. $pass = false;
  642. }
  643. }
  644. break;
  645. case Amazon::UPDATE:
  646. if (version_compare(_PS_VERSION_, '1.5', '>=')) {
  647. // Removing Old AdminTabs
  648. //
  649. if (Tab::getIdFromClassName('ProductsAmazon') && Tab::getIdFromClassName('OrdersAmazon')) {
  650. if (!$this->uninstallModuleTab('ProductsAmazon')) {
  651. $this->_errors[] = $this->l('Unable to uninstall: ProductsAmazon Tab');
  652. $pass = false;
  653. }
  654. if (!$this->uninstallModuleTab('OrdersAmazon')) {
  655. $this->_errors[] = $this->l('Unable to uninstall: OrdersAmazon Tab');
  656. $pass = false;
  657. }
  658. }
  659.  
  660. if (Tab::getIdFromClassName('StatsAmazon')) {
  661. if (!$this->uninstallModuleTab('StatsAmazon')) {
  662. $this->_errors[] = $this->l('Unable to uninstall: StatsAmazon Tab');
  663. $pass = false;
  664. }
  665. }
  666.  
  667. // Adding New
  668. return ($this->tabSetup(Amazon::ADD));
  669. }
  670. break;
  671. case Amazon::REMOVE:
  672. // Removing New AdminTabs
  673. //
  674. if (Tab::getIdFromClassName('AdminAmazonOrders') && Tab::getIdFromClassName('AdminAmazonProducts')) {
  675. if (!$this->uninstallModuleTab('AdminAmazonProducts')) {
  676. $this->_errors[] = $this->l('Unable to uninstall: ProductsAmazon Tab');
  677. $pass = false;
  678. }
  679. if (!$this->uninstallModuleTab('AdminAmazonOrders')) {
  680. $this->_errors[] = $this->l('Unable to uninstall: OrdersAmazon Tab');
  681. $pass = false;
  682. }
  683. }
  684. if (self::ENABLE_EXPERIMENTAL_FEATURES) {
  685. if (Tab::getIdFromClassName('AdminAmazonStats')) {
  686. if (!$this->uninstallModuleTab('AdminAmazonStats')) {
  687. $this->_errors[] = $this->l('Unable to uninstall: StatsAmazon Tab');
  688. $pass = false;
  689. }
  690. }
  691. }
  692. // Removing Old AdminTabs
  693. //
  694. if (Tab::getIdFromClassName('ProductsAmazon') && Tab::getIdFromClassName('OrdersAmazon')) {
  695. if (!$this->uninstallModuleTab('ProductsAmazon')) {
  696. $this->_errors[] = $this->l('Unable to uninstall: ProductsAmazon Tab');
  697. $pass = false;
  698. }
  699. if (!$this->uninstallModuleTab('OrdersAmazon')) {
  700. $this->_errors[] = $this->l('Unable to uninstall: OrdersAmazon Tab');
  701. $pass = false;
  702. }
  703. }
  704. if (Tab::getIdFromClassName('StatsAmazon')) {
  705. if (!$this->uninstallModuleTab('StatsAmazon')) {
  706. $this->_errors[] = $this->l('Unable to uninstall: StatsAmazon Tab');
  707. $pass = false;
  708. }
  709. }
  710. break;
  711. }
  712.  
  713. return ($pass);
  714. }
  715.  
  716. private function installModuleTab($tabClass = null, $tabName = null, $idTabParent = 0)
  717. {
  718. $tabNameLang = array();
  719.  
  720. if (Tab::getIdFromClassName($tabClass)) {
  721. return (true);
  722. }
  723.  
  724. foreach (Language::getLanguages(false) as $language) {
  725. $tabNameLang[$language['id_lang']] = $tabName;
  726. }
  727.  
  728. $tab = new Tab();
  729. $tab->name = $tabNameLang;
  730. $tab->class_name = $tabClass;
  731. $tab->module = $this->name;
  732. $tab->id_parent = (int)$idTabParent;
  733.  
  734. return ($tab->save());
  735. }
  736.  
  737. private function uninstallModuleTab($tabClass)
  738. {
  739. $pass = true;
  740. @unlink(_PS_IMG_DIR_.'t/'.$tabClass.'.gif');
  741. $idTab = Tab::getIdFromClassName($tabClass);
  742. if ($idTab != 0) {
  743. $tab = new Tab($idTab);
  744. $pass = $tab->delete();
  745. }
  746.  
  747. return ($pass);
  748. }
  749.  
  750. private function createCustomer()
  751. {
  752. if (($id_customer = (int)Configuration::get('AMAZON_CUSTOMER_ID'))) {
  753. $customer = new Customer($id_customer);
  754.  
  755. if (Validate::isLoadedObject($customer)) {
  756. return ($customer->id);
  757. }
  758. }
  759. $var = explode('@', Configuration::get('PS_SHOP_EMAIL'));
  760. $max = 10;
  761.  
  762. while ($max--) {
  763. $email = 'no-reply-'.rand().'@'.$var[1];
  764.  
  765. if (!Validate::isEmail($email)) {
  766. return(false);
  767. }
  768.  
  769. if (!Customer::customerExists($email)) {
  770. $customer = new Customer();
  771. $customer->firstname = 'Amazon';
  772. $customer->lastname = 'Amazon Market Place';
  773. $customer->company = 'Amazon';
  774. $customer->email = $email;
  775. $customer->birthday = '1970-01-01';
  776. $customer->newsletter = false;
  777. $customer->optin = false;
  778. $customer->passwd = md5(rand());
  779. $customer->active = true;
  780. $customer->date_add = date('Y-m-d H:i:s');
  781. $customer->date_upd = $customer->date_add;
  782. $customer->add();
  783.  
  784. if (Validate::isLoadedObject($customer)) {
  785. Configuration::updateValue('AMAZON_CUSTOMER_ID', $customer->id);
  786. return($customer->id);
  787. } else {
  788. return(false);
  789. }
  790. }
  791. }
  792. return (false);
  793. }
  794.  
  795. private function addMarketPlaceTables()
  796. {
  797. $pass = true;
  798. $errors = null;
  799.  
  800. require_once(dirname(__FILE__).'/classes/amazon.order_info.class.php');
  801. require_once(dirname(__FILE__).'/classes/amazon.order.class.php');
  802.  
  803. $currentVersion = Configuration::get('AMAZON_CURRENT_VERSION', null, 0, 0);
  804.  
  805. if (!AmazonTools::tableExists(_DB_PREFIX_.Amazon::TABLE_MARKETPLACE_STRATEGIES)) {
  806. $sql = 'CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_STRATEGIES.'` (
  807. `id` int(11) NOT NULL AUTO_INCREMENT,
  808. `id_product` int(11) NOT NULL,
  809. `id_product_attribute` INT NULL DEFAULT NULL,
  810. `id_lang` int(11) NOT NULL,
  811. `minimum_price` float NOT NULL,
  812. `actual_price` float NOT NULL,
  813. `target_price` float NOT NULL,
  814. `gap` float NOT NULL,
  815. PRIMARY KEY (`id`),
  816. KEY `id_product` (`id_product`),
  817. KEY `id_product_lang` (`id_product`,`id_lang`)
  818. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;';
  819.  
  820. if (!Db::getInstance()->execute($sql)) {
  821. $errors .= 'ERROR: '.$sql.nl2br(Amazon::LF);
  822. $errors .= Db::getInstance()->getMsgError();
  823. $pass = false;
  824. }
  825. }
  826.  
  827. if (!AmazonTools::tableExists(_DB_PREFIX_.Amazon::TABLE_MARKETPLACE_ACTIONS)) {
  828. $sql = '
  829. CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_ACTIONS.'` (
  830. `id_product` int(11) NOT NULL,
  831. `id_product_attribute` int(11) DEFAULT NULL,
  832. `id_lang` int(11) NOT NULL,
  833. `sku` varchar(64) DEFAULT NULL,
  834. `marketplace` varchar(12) NOT NULL,
  835. `action` char(1) NOT NULL,
  836. `date_add` datetime DEFAULT NULL,
  837. `date_upd` datetime DEFAULT NULL,
  838. UNIQUE KEY `id_product` (`id_product`,`id_lang`,`marketplace`,`action`),
  839. KEY `id_lang` (`id_lang`,`marketplace`)
  840. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;';
  841.  
  842. if (!Db::getInstance()->execute($sql)) {
  843. $errors .= 'ERROR: '.$sql.nl2br("");
  844. $errors .= Db::getInstance()->getMsgError();
  845. $pass = false;
  846. }
  847. }
  848.  
  849. if (!AmazonTools::tableExists(_DB_PREFIX_.self::TABLE_MARKETPLACE_ORDER_ITEMS)) {
  850. require_once(_PS_MODULE_DIR_.'/amazon/classes/amazon.order_item.class.php');
  851.  
  852. if (!AmazonOrderItem::createTable()) {
  853. $errors .= explode(Amazon::LF, AmazonOrderItem::$errors);
  854. $pass = false;
  855. }
  856. }
  857. if (!AmazonTools::tableExists(_DB_PREFIX_.self::TABLE_MARKETPLACE_ORDER_ADDRESS)) {
  858. require_once(_PS_MODULE_DIR_.'/amazon/classes/amazon.address.class.php');
  859.  
  860. if (!AmazonAddress::createTable()) {
  861. $errors .= explode(Amazon::LF, AmazonAddress::$errors);
  862. $pass = false;
  863. }
  864. }
  865. require_once(_PS_MODULE_DIR_.'/amazon/classes/amazon.stat.class.php');
  866. if (!AmazonTools::tableExists(_DB_PREFIX_.self::TABLE_MARKETPLACE_STATS)) {
  867. if (!AmazonStat::createTable()) {
  868. $errors .= explode(Amazon::LF, 'Cannot create marketplace_stat table');
  869. $pass = false;
  870. }
  871. } else {
  872. if (!AmazonStat::addStatTaxColumns()) {
  873. $errors .= explode(Amazon::LF, 'Cannot update marketplace_stat table');
  874. $pass = false;
  875. }
  876. }
  877. if (!AmazonTools::tableExists(_DB_PREFIX_.self::TABLE_MARKETPLACE_VAT)) {
  878. require_once(_PS_MODULE_DIR_.'/amazon/classes/amazon.stat.class.php');
  879.  
  880. if (!AmazonStat::createVatTable()) {
  881. $errors .= explode(Amazon::LF, 'Cannot create marketplace_vat table');
  882. $pass = false;
  883. }
  884. }
  885.  
  886. if (!AmazonTools::tableExists(_DB_PREFIX_.Amazon::TABLE_MARKETPLACE_ORDERS)) {
  887. require_once(_PS_MODULE_DIR_.'/amazon/classes/amazon.order.class.php');
  888.  
  889. if (!AmazonOrder::createTable()) {
  890. $errors .= explode(Amazon::LF, AmazonOrder::$errors);
  891. $pass = false;
  892. }
  893. } elseif (!AmazonTools::fieldExists(_DB_PREFIX_.Amazon::TABLE_MARKETPLACE_ORDERS, 'sales_channel') && !AmazonTools::fieldExists(_DB_PREFIX_.Amazon::TABLE_MARKETPLACE_ORDERS, 'latest_delivery_date')) {
  894. require_once(_PS_MODULE_DIR_.'/amazon/classes/amazon.order.class.php');
  895.  
  896. if (!AmazonOrder::updateTable()) {
  897. $errors .= explode(Amazon::LF, AmazonOrder::$errors);
  898. $pass = false;
  899. }
  900. }
  901. if (AmazonTools::tableExists(_DB_PREFIX_.Amazon::TABLE_MARKETPLACE_ORDERS)) {
  902. require_once(_PS_MODULE_DIR_.'/amazon/classes/amazon.order.class.php');
  903.  
  904. if (!AmazonOrder::fixIndex()) {
  905. $errors .= explode(Amazon::LF, AmazonOrder::$errors);
  906. $pass = false;
  907. }
  908. }
  909.  
  910. if (AmazonTools::tableExists(_DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS)) {
  911. $sqls = array();
  912.  
  913. $fields = array();
  914.  
  915. // Amazon Update - Add new fields
  916. //
  917. $query = Db::getInstance()->executeS('SHOW COLUMNS FROM `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'`');
  918. if ($query) {
  919. foreach ($query as $row) {
  920. $fields[$row['Field']] = 1;
  921. }
  922. }
  923.  
  924. // For versions before 3.8 - Added on 2013-09-21
  925. //
  926. if (version_compare($currentVersion, '3.8', '<')) {
  927. if (!isset($fields['nopexport'])) {
  928. $sqls[] = 'ALTER TABLE `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'` ADD `nopexport` TINYINT NULL DEFAULT NULL AFTER `force`';
  929. }
  930. if (!isset($fields['noqexport'])) {
  931. $sqls[] = 'ALTER TABLE `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'` ADD `noqexport` TINYINT NULL DEFAULT NULL AFTER `nopexport`';
  932. }
  933. if (!isset($fields['latency'])) {
  934. $sqls[] = 'ALTER TABLE `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'` ADD `latency` TINYINT NULL DEFAULT NULL AFTER `noqexport`';
  935. }
  936. if (!isset($fields['disable'])) {
  937. $sqls[] = 'ALTER TABLE `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'` ADD `disable` TINYINT NULL DEFAULT NULL AFTER `latency`';
  938. }
  939. if (!isset($fields['price'])) {
  940. $sqls[] = 'ALTER TABLE `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'` ADD `price` FLOAT NULL DEFAULT NULL AFTER `disable`';
  941. }
  942. if (!isset($fields['asin1'])) {
  943. $sqls[] = 'ALTER TABLE `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'` ADD `asin1` VARCHAR(16) NULL DEFAULT NULL AFTER `price`';
  944. }
  945. if (!isset($fields['asin2'])) {
  946. $sqls[] = 'ALTER TABLE `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'` ADD `asin2` VARCHAR(16) NULL DEFAULT NULL AFTER `asin1`';
  947. }
  948. if (!isset($fields['asin3'])) {
  949. $sqls[] = 'ALTER TABLE `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'` ADD `asin3` VARCHAR(16) NULL DEFAULT NULL AFTER `asin2`';
  950. }
  951. if (!isset($fields['shipping'])) {
  952. $sqls[] = 'ALTER TABLE `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'` ADD `shipping` FLOAT NULL DEFAULT NULL AFTER `asin3`';
  953. }
  954. if (!isset($fields['shipping_type'])) {
  955. $sqls[] = 'ALTER TABLE `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'` ADD `shipping_type` FLOAT NULL DEFAULT NULL AFTER `shipping`';
  956. }
  957. if (!isset($fields['fba'])) {
  958. $sqls[] = 'ALTER TABLE `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'` ADD `fba` TINYINT NULL DEFAULT NULL AFTER `noqexport`';
  959. }
  960. if (!isset($fields['fba_value'])) {
  961. $sqls[] = 'ALTER TABLE `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'` ADD `fba_value` FLOAT NULL DEFAULT NULL AFTER `fba`';
  962. }
  963. }
  964.  
  965. // For versions before 3.9 - Added on 2013-09-21
  966. //
  967. if (version_compare($currentVersion, '3.9', '<')) {
  968. if (!isset($fields['bullet_point1'])) {
  969. $sqls[] = 'ALTER TABLE `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'` ADD `bullet_point1` VARCHAR('.self::LENGTH_BULLET_POINT.') NULL DEFAULT NULL AFTER `text`';
  970. }
  971. if (!isset($fields['bullet_point2'])) {
  972. $sqls[] = 'ALTER TABLE `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'` ADD `bullet_point2` VARCHAR('.self::LENGTH_BULLET_POINT.') NULL DEFAULT NULL AFTER `bullet_point1`';
  973. }
  974. if (!isset($fields['bullet_point3'])) {
  975. $sqls[] = 'ALTER TABLE `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'` ADD `bullet_point3` VARCHAR('.self::LENGTH_BULLET_POINT.') NULL DEFAULT NULL AFTER `bullet_point2`';
  976. }
  977. if (!isset($fields['bullet_point4'])) {
  978. $sqls[] = 'ALTER TABLE `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'` ADD `bullet_point4` VARCHAR('.self::LENGTH_BULLET_POINT.') NULL DEFAULT NULL AFTER `bullet_point3`';
  979. }
  980. if (!isset($fields['bullet_point5'])) {
  981. $sqls[] = 'ALTER TABLE `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'` ADD `bullet_point5` VARCHAR('.self::LENGTH_BULLET_POINT.') NULL DEFAULT NULL AFTER `bullet_point4`';
  982. }
  983. if (!isset($fields['id_product_attribute'])) {
  984. $sqls[] = 'ALTER TABLE `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'` ADD `id_product_attribute` INT(11) NULL DEFAULT NULL AFTER `id_lang`';
  985. }
  986. }
  987.  
  988. // For versions before 4.0 - Added on 2014-10-15
  989. //
  990. if (version_compare($currentVersion, '4.0', '<')) {
  991. if (!isset($fields['gift_wrap'])) {
  992. $sqls[] = 'ALTER TABLE `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'` ADD `gift_wrap` TINYINT NULL DEFAULT NULL AFTER `shipping_type`';
  993. }
  994. if (!isset($fields['gift_message'])) {
  995. $sqls[] = 'ALTER TABLE `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'` ADD `gift_message` TINYINT NULL DEFAULT NULL AFTER `gift_wrap`';
  996. }
  997. }
  998.  
  999. if (version_compare($currentVersion, '4', '<')) {
  1000. $query = Db::getInstance()->executeS('SHOW INDEX FROM `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'`');
  1001.  
  1002. $ASIN_Index = false;
  1003. $Product_Index = false;
  1004. $Old_Product_Index1 = false;
  1005. $Old_Product_Index2 = false;
  1006.  
  1007. foreach ($query as $table_item) {
  1008. if ($table_item['Key_name'] === 'ASIN') {
  1009. $ASIN_Index = true;
  1010. } elseif ($table_item['Key_name'] === 'id_product') {
  1011. $Old_Product_Index1 = true;
  1012. } elseif ($table_item['Key_name'] === 'id_product_lang_attribute') {
  1013. $Old_Product_Index2 = true;
  1014. } elseif ($table_item['Key_name'] === 'PRIMARY') {
  1015. $Product_Index = true;
  1016. }
  1017. }
  1018.  
  1019. if ($Old_Product_Index1) {
  1020. $sqls[] = 'ALTER TABLE `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'` DROP INDEX `id_product` ';
  1021. }
  1022.  
  1023. if ($Old_Product_Index2) {
  1024. $sqls[] = 'ALTER TABLE `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'` DROP INDEX `id_product_lang_attribute`';
  1025. }
  1026.  
  1027. if (!$ASIN_Index) {
  1028. $sqls[] = 'ALTER TABLE `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'` ADD INDEX `ASIN` ( `asin1` )';
  1029. }
  1030.  
  1031. if (!$Product_Index) {
  1032. $sqls[] = 'ALTER TABLE `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'` ADD PRIMARY KEY `product_index` (`id_product`, `id_product_attribute`, `id_lang`)';
  1033. }
  1034. }
  1035.  
  1036. // For very older versions - Added on 2013-09-21
  1037. //
  1038. if (version_compare($currentVersion, '3.5', '<')) {
  1039. // For Next updates - for old module installations - the scheme has changed
  1040. //
  1041. if (isset($fields['latency'])) {
  1042. $sqls[] = 'ALTER TABLE `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'` CHANGE `latency` `latency` TINYINT NULL DEFAULT NULL';
  1043. }
  1044. if (isset($fields['nopexport'])) {
  1045. $sqls[] = 'ALTER TABLE `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'` CHANGE `nopexport` `nopexport` TINYINT NULL DEFAULT NULL';
  1046. }
  1047. if (isset($fields['noqexport'])) {
  1048. $sqls[] = 'ALTER TABLE `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'` CHANGE `noqexport` `noqexport` TINYINT NULL DEFAULT NULL';
  1049. }
  1050. if (isset($fields['price'])) {
  1051. $sqls[] = 'ALTER TABLE `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'` CHANGE `price` `price` FLOAT NULL DEFAULT NULL';
  1052. }
  1053. if (isset($fields['asin1'])) {
  1054. $sqls[] = 'ALTER TABLE `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'` CHANGE `asin1` `asin1` VARCHAR(16) NULL DEFAULT NULL';
  1055. }
  1056. if (isset($fields['asin2'])) {
  1057. $sqls[] = 'ALTER TABLE `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'` CHANGE `asin2` `asin2` VARCHAR(16) NULL DEFAULT NULL';
  1058. }
  1059. if (isset($fields['asin3'])) {
  1060. $sqls[] = 'ALTER TABLE `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'` CHANGE `asin3` `asin3` VARCHAR(16) NULL DEFAULT NULL';
  1061. }
  1062. if (isset($fields['disable'])) {
  1063. $sqls[] = 'ALTER TABLE `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'` CHANGE `disable` `disable` TINYINT NULL DEFAULT NULL';
  1064. }
  1065. if (isset($fields['force'])) {
  1066. $sqls[] = 'ALTER TABLE `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'` CHANGE `force` `force` TINYINT NULL DEFAULT NULL';
  1067. }
  1068. if (isset($fields['text'])) {
  1069. $sqls[] = 'ALTER TABLE `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'` CHANGE `text` `text` VARCHAR(256) NULL DEFAULT NULL';
  1070. }
  1071.  
  1072. // Added on 2012/11/26
  1073. //
  1074. if (!isset($fields['id_product_attribute'])) {
  1075. $sqls[] = 'ALTER TABLE `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'` ADD `id_product_attribute` INT NULL DEFAULT NULL AFTER `id_lang`';
  1076.  
  1077. $sqls[] = 'ALTER TABLE `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'`
  1078. ADD UNIQUE `id_product_lang_attribute` ( `id_product` , `id_lang` , `id_product_attribute` )';
  1079. }
  1080. }
  1081.  
  1082. if (!isset($fields['browsenode'])) {
  1083. $sqls[] = 'ALTER TABLE `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'` ADD `browsenode` varchar(16) DEFAULT NULL AFTER `gift_message`';
  1084. }
  1085. if (!isset($fields['repricing_min'])) {
  1086. $sqls[] = 'ALTER TABLE `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'` ADD `repricing_min` FLOAT NULL DEFAULT NULL AFTER `browsenode`';
  1087. }
  1088. if (!isset($fields['repricing_max'])) {
  1089. $sqls[] = 'ALTER TABLE `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'` ADD `repricing_max` FLOAT NULL DEFAULT NULL AFTER `repricing_min`';
  1090. }
  1091. if (!isset($fields['repricing_gap'])) {
  1092. $sqls[] = 'ALTER TABLE `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'` ADD `repricing_gap` FLOAT NULL DEFAULT NULL AFTER `repricing_max`';
  1093. }
  1094. if (!isset($fields['shipping_group'])) {
  1095. $sqls[] = 'ALTER TABLE `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'` ADD `shipping_group` varchar(32) DEFAULT NULL AFTER `repricing_gap`';
  1096. }
  1097.  
  1098. foreach ($sqls as $sql) {
  1099. if (!Db::getInstance()->execute($sql)) {
  1100. $errors .= 'ERROR: '.$sql.nl2br(Amazon::LF);
  1101. $pass = false;
  1102. }
  1103. }
  1104. } else {
  1105. $sql = 'CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'` (
  1106. `id_product` int(11) NOT NULL,
  1107. `id_lang` int(11) NOT NULL,
  1108. `id_product_attribute` int(11) NOT NULL DEFAULT 0,
  1109. `force` tinyint(4) DEFAULT NULL,
  1110. `nopexport` tinyint(4) DEFAULT NULL,
  1111. `noqexport` tinyint(4) DEFAULT NULL,
  1112. `fba` tinyint(4) DEFAULT NULL,
  1113. `fba_value` FLOAT DEFAULT NULL,
  1114. `latency` tinyint(4) DEFAULT NULL,
  1115. `disable` tinyint(4) DEFAULT NULL,
  1116. `price` FLOAT DEFAULT NULL,
  1117. `asin1` varchar(16) DEFAULT NULL,
  1118. `asin2` varchar(16) DEFAULT NULL,
  1119. `asin3` varchar(16) DEFAULT NULL,
  1120. `text` varchar(256) DEFAULT NULL,
  1121. `bullet_point1` varchar('.self::LENGTH_BULLET_POINT.') DEFAULT NULL,
  1122. `bullet_point2` varchar('.self::LENGTH_BULLET_POINT.') DEFAULT NULL,
  1123. `bullet_point3` varchar('.self::LENGTH_BULLET_POINT.') DEFAULT NULL,
  1124. `bullet_point4` varchar('.self::LENGTH_BULLET_POINT.') DEFAULT NULL,
  1125. `bullet_point5` varchar('.self::LENGTH_BULLET_POINT.') DEFAULT NULL,
  1126. `shipping` float DEFAULT NULL,
  1127. `shipping_type` tinyint(4) DEFAULT NULL,
  1128. `gift_wrap` tinyint(4) DEFAULT NULL,
  1129. `gift_message` tinyint(4) DEFAULT NULL,
  1130. `browsenode` varchar(16) DEFAULT NULL,
  1131. `repricing_min` FLOAT DEFAULT NULL,
  1132. `repricing_max` FLOAT DEFAULT NULL,
  1133. `repricing_gap` FLOAT DEFAULT NULL,
  1134. `shipping_group` varchar(32) DEFAULT NULL,
  1135. PRIMARY KEY `product_index` (`id_product`, `id_product_attribute`, `id_lang`),
  1136. KEY `ASIN` (`asin1`)
  1137. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;';
  1138.  
  1139. if (!Db::getInstance()->execute($sql)) {
  1140. $errors .= 'ERROR: '.$sql.nl2br(Amazon::LF);
  1141. $errors .= Db::getInstance()->getMsgError();
  1142. $pass = false;
  1143. }
  1144. }
  1145.  
  1146. // Amazon Product Options - Save available fields
  1147. //
  1148. $fields = array();
  1149. $query = Db::getInstance()->executeS('SHOW COLUMNS FROM `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS.'`');
  1150. if ($query) {
  1151. foreach ($query as $row) {
  1152. $fields[] = $row['Field'];
  1153. }
  1154. }
  1155.  
  1156. if (count($fields)) {
  1157. Configuration::UpdateValue('AMAZON_PRODUCT_OPTION_FIELDS', implode(',', $fields), false, 0, 0);
  1158. }
  1159.  
  1160. require_once(_PS_MODULE_DIR_.'/amazon/classes/amazon.valid_values.class.php');
  1161.  
  1162. if (!AmazonValidValues::tableCreate()) {
  1163. $errors .= 'ERROR: Unable to create valid values table'.nl2br(Amazon::LF);
  1164. $errors .= Db::getInstance()->getMsgError();
  1165. $pass = false;
  1166. }
  1167.  
  1168. require_once(_PS_MODULE_DIR_.'/amazon/classes/amazon.remote_cart.class.php');
  1169.  
  1170.  
  1171. if ($this->amazon_features['remote_cart'] && !AmazonRemoteCart::tableCreate()) {
  1172. $errors .= 'ERROR: Unable to create remote cart table'.nl2br(Amazon::LF);
  1173. $errors .= Db::getInstance()->getMsgError();
  1174. $pass = false;
  1175. }
  1176.  
  1177. require_once(_PS_MODULE_DIR_.'/amazon/classes/amazon.taxes.class.php');
  1178.  
  1179. if (!AmazonTools::tableExists(_DB_PREFIX_.Amazon::TABLE_MARKETPLACE_TAXES)) {
  1180. if (!AmazonTaxes::createTable()) {
  1181. $errors .= 'ERROR: ';
  1182. $errors .= Db::getInstance()->getMsgError();
  1183. $pass = false;
  1184. } else {
  1185. if (!AmazonTaxes::populatePtc()) {
  1186. $errors .= 'ERROR: ';
  1187. $errors .= Db::getInstance()->getMsgError();
  1188. $pass = false;
  1189. }
  1190. }
  1191. } else {
  1192. $sql = 'SELECT count(ptc) as count FROM `'._DB_PREFIX_.Amazon::TABLE_MARKETPLACE_TAXES.'`';
  1193. $count = Db::getInstance()->getValue($sql);
  1194. if (!$count) {
  1195. if (!AmazonTaxes::populatePtc()) {
  1196. $errors .= 'ERROR: ';
  1197. $errors .= Db::getInstance()->getMsgError();
  1198. $pass = false;
  1199. }
  1200. }
  1201. }
  1202.  
  1203. if ($errors) {
  1204. $this->_errors[] = $errors;
  1205. }
  1206.  
  1207. return ($pass);
  1208. }
  1209.  
  1210. private function addMarketPlaceField()
  1211. {
  1212. $pass = true;
  1213.  
  1214. // For Updates : Set All Order to checked to avoid to send many orders statuses to Amazon
  1215. //
  1216. require_once(dirname(__FILE__).'/classes/amazon.order_info.class.php');
  1217. require_once(dirname(__FILE__).'/classes/amazon.order.class.php');
  1218.  
  1219. if (AmazonTools::fieldExists(_DB_PREFIX_.'orders', 'mp_status')) {
  1220. $query = Db::getInstance()->getRow('SELECT count(`id_order`) as `count` FROM `'._DB_PREFIX_.'orders` WHERE `mp_status` = '.AmazonOrder::CHECKED.' AND (`module` = "amazon" OR `module` = "Amazon")');
  1221.  
  1222. if (isset($query['count']) && $query['count'] == 0) {
  1223. Db::getInstance()->execute('UPDATE `'._DB_PREFIX_.'orders` SET `mp_status` = '.(int)AmazonOrder::CHECKED.' WHERE `module` = "amazon" OR `module` = "Amazon"');
  1224. }
  1225. }
  1226. return ($pass);
  1227. }
  1228.  
  1229. /**
  1230. * Add amazon_configuration table
  1231. * @return bool
  1232. */
  1233. private function addConfigurationTable()
  1234. {
  1235. $config_table = _DB_PREFIX_ . AmazonConfiguration::$configuration_table;
  1236. $config_lang_table = $config_table . '_lang';
  1237. $result = true;
  1238.  
  1239. if (! AmazonTools::tableExists($config_table)) {
  1240. $sql = "CREATE TABLE `{$config_table}` (
  1241. `id_configuration` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  1242. `id_shop_group` INT(11) UNSIGNED DEFAULT NULL,
  1243. `id_shop` INT(11) UNSIGNED DEFAULT NULL,
  1244. `name` VARCHAR(254) NOT NULL,
  1245. `value` LONGTEXT,
  1246. `date_add` DATETIME NOT NULL,
  1247. `date_upd` DATETIME NOT NULL,
  1248. PRIMARY KEY (`id_configuration`),
  1249. KEY `name` (`name`),
  1250. KEY `id_shop` (`id_shop`),
  1251. KEY `id_shop_group` (`id_shop_group`)
  1252. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;";
  1253.  
  1254. $result &= Db::getInstance()->execute($sql);
  1255. }
  1256.  
  1257. if (! AmazonTools::tableExists($config_lang_table)) {
  1258. $sql = "CREATE TABLE `{$config_lang_table}` (
  1259. `id_configuration` int(10) unsigned NOT NULL,
  1260. `id_lang` int(10) unsigned NOT NULL,
  1261. `value` text,
  1262. `date_upd` datetime DEFAULT NULL,
  1263. PRIMARY KEY (`id_configuration`,`id_lang`)
  1264. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci";
  1265.  
  1266. $result &= Db::getInstance()->execute($sql);
  1267. }
  1268.  
  1269. return $result;
  1270. }
  1271.  
  1272. private function _hookSetup($action)
  1273. {
  1274. if (version_compare(_PS_VERSION_, '1.5', '<')) {
  1275. //
  1276. $expectedHooks = array(
  1277. 'addproduct',
  1278. 'deleteProduct',
  1279. 'updateProductAttribute',
  1280. 'updateQuantity',
  1281. 'updateproduct',
  1282. 'updateCarrier',
  1283. 'adminOrder',
  1284. 'backOfficeHeader',
  1285. 'postUpdateOrderStatus',
  1286. 'paymentConfirm',
  1287. // GDPR compliant
  1288. 'registerGDPRConsent',
  1289. 'actionDeleteGDPRCustomer',
  1290. 'actionExportGDPRData'
  1291. );
  1292. } else {
  1293. //
  1294. $expectedHooks = array(
  1295. 'actionObjectProductUpdateAfter',
  1296. 'displayAdminOrder',
  1297. 'displayBackOfficeHeader',
  1298. 'actionCarrierUpdate',
  1299. 'actionUpdateQuantity',
  1300. 'actionProductAttributeDelete',
  1301. 'deleteProductAttribute',
  1302. 'actionProductDelete',
  1303. 'actionAttributeGroupDelete',
  1304. 'actionProductAdd',
  1305. 'actionProductUpdate',
  1306. 'actionAttributeGroupSave',
  1307. 'actionOrderStatusPostUpdate',
  1308. 'actionOrderHistoryAddAfter',
  1309. 'displayAdminProductsExtra',
  1310. 'actionEmailAddAfterContent',
  1311. 'actionObjectStockAvailableUpdateAfter',
  1312. 'actionAdminOrdersListingFieldsModifier',
  1313. 'displayPDFInvoice',
  1314. // GDPR compliant
  1315. 'registerGDPRConsent',
  1316. 'actionDeleteGDPRCustomer',
  1317. 'actionExportGDPRData'
  1318. );
  1319. }
  1320.  
  1321. $pass = true;
  1322.  
  1323. if ($action == Amazon::ADD) {
  1324. foreach ($expectedHooks as $expectedHook) {
  1325. if (!$this->isRegisteredInHook($expectedHook)) {
  1326. if (!$this->registerHook($expectedHook)) {
  1327. $this->_errors[] = $this->l('Unable to Register Hook').':'.$expectedHook;
  1328. $pass = false;
  1329. }
  1330. }
  1331. }
  1332. }
  1333. if ($action == Amazon::REMOVE) {
  1334. foreach ($expectedHooks as $expectedHook) {
  1335. if ($this->isRegisteredInHook($expectedHook)) {
  1336. if (!$this->unregisterHook($expectedHook)) {
  1337. $this->_errors[] = $this->l('Unable to Unregister Hook').':'.$expectedHook;
  1338. $pass = false;
  1339. }
  1340. }
  1341. }
  1342. }
  1343.  
  1344. return ($pass);
  1345. }
  1346.  
  1347. public function uninstall()
  1348. {
  1349. $pass = true;
  1350.  
  1351. // Remove Hooks
  1352. //
  1353. $this->_hookSetup(self::REMOVE);
  1354.  
  1355. // Remove Tabs
  1356. //
  1357. $this->tabSetup(self::REMOVE);
  1358.  
  1359. if (!parent::uninstall()) {
  1360. $this->_errors[] = $this->l('Unable to uninstall: parent()') && $pass = false;
  1361. }
  1362.  
  1363. if (!$this->_deleteCustomer()) {
  1364. $this->_errors[] = $this->l('Unable to uninstall: Amazon Customer') && $pass = false;
  1365. }
  1366.  
  1367. if (!$this->_removeMarketPlaceTables()) {
  1368. $this->_errors[] = $this->l('Unable to uninstall: MarketPlace Tables') && $pass = false;
  1369. }
  1370.  
  1371. foreach ($this->_config as $key => $value) {
  1372. if (!Configuration::deleteByName($key)) {
  1373. $pass = $pass && false;
  1374. }
  1375. }
  1376.  
  1377. if (!$pass) {
  1378. $this->_errors[] = $this->l('Unable to uninstall : Some configuration values');
  1379. }
  1380.  
  1381. return ($pass);
  1382. }
  1383.  
  1384. private function _deleteCustomer()
  1385. {
  1386. $customer = new Customer(Configuration::get('AMAZON_CUSTOMER_ID'));
  1387.  
  1388. if (Customer::customerExists($customer->email)) {
  1389. //
  1390. return ($customer->delete());
  1391. } else {
  1392. //
  1393. return (true);
  1394. }
  1395. }
  1396.  
  1397. private function _removeMarketPlaceTables()
  1398. {
  1399. $pass = true;
  1400. return($pass);
  1401. /*
  1402. *
  1403. * require_once(dirname(__FILE__).'/classes/amazon.order.class.php');
  1404. *
  1405. // Check if exists
  1406. //
  1407. $tables = array();
  1408. $query = Db::getInstance()->executeS('SHOW TABLES');
  1409. foreach ($query as $rows) {
  1410. foreach ($rows as $table) {
  1411. $tables[$table] = 1;
  1412. }
  1413. }
  1414.  
  1415. foreach (array(
  1416. 'marketplace_product_action',
  1417. 'marketplace_configuration',
  1418. 'marketplace_product_option',
  1419. 'marketplace_strategies'
  1420. ) as $marketplace_table) {
  1421. if (isset($tables[_DB_PREFIX_.$marketplace_table])) {
  1422. $sql = 'DROP TABLE IF EXISTS `'._DB_PREFIX_.$marketplace_table.'` ; ';
  1423.  
  1424. if (!Db::getInstance()->execute($sql)) {
  1425. $pass = false;
  1426. }
  1427. }
  1428. }
  1429.  
  1430. return ($pass);
  1431. */
  1432. }
  1433.  
  1434. public function getContent()
  1435. {
  1436. if ($this->ps17x) {
  1437. $this->_html .= $this->_autoAddCSS($this->url.'views/css/amazon16.css');
  1438. $this->_html .= $this->_autoAddCSS($this->url.'views/css/amazon17.css');
  1439. } elseif ($this->ps16x) {
  1440. $this->_html .= $this->_autoAddCSS($this->url.'views/css/amazon16.css');
  1441. } else {
  1442. $this->_html .= $this->_autoAddCSS($this->url.'views/css/amazon.css');
  1443. }
  1444.  
  1445. $this->versionCheck();
  1446.  
  1447. /*Actions from Tools Menu*/
  1448. if (Tools::isSubmit('tools_code_import_submit')) {
  1449. $this->toolsCodeImport();
  1450. }
  1451.  
  1452. /*Action from Configuration*/
  1453. if (Tools::isSubmit('submit')) {
  1454. $this->_postValidation();
  1455.  
  1456. $this->_postProcess();
  1457. }
  1458.  
  1459. // July-16-2018: Must keep this, although already get feature in construct. Because they may change after save.
  1460. // Maybe in construct, it's used for children class
  1461. $this->amazon_features = $this->getAmazonFeatures();
  1462.  
  1463. // Unactivate worldwide if necessary
  1464. if (!$this->amazon_features['worldwide']) {
  1465. foreach (array_keys($this->_platforms) as $cc) {
  1466. if (!AmazonTools::isUnifiedAccount($cc)) {
  1467. unset($this->_platforms[$cc]);
  1468. }
  1469. }
  1470. }
  1471.  
  1472. $this->_displayForm();
  1473.  
  1474. return $this->_html;
  1475. }
  1476.  
  1477. protected function _autoAddJS($url)
  1478. {
  1479. if (version_compare(_PS_VERSION_, '1.5', '>=')) {
  1480. if (isset($this->context->controller) && method_exists($this->context->controller, 'addJquery')) {
  1481. $this->context->controller->addJquery();
  1482. }
  1483.  
  1484. return ($this->context->controller->addJS($url) && '');
  1485. }
  1486.  
  1487. return (sprintf(html_entity_decode('&lt;script type="text/javascript" src="%s"&gt;&lt;/script&gt;')."\n", $url));
  1488. }
  1489.  
  1490. protected function _autoAddCSS($url, $media = 'all')
  1491. {
  1492. if (version_compare(_PS_VERSION_, '1.5', '>=')) {
  1493. return ($this->context->controller->addCSS($url, $media) && '');
  1494. }
  1495.  
  1496. return (sprintf(html_entity_decode('&lt;link rel="stylesheet" type="text/css" href="%s"&gt;')."\n", $url));
  1497. }
  1498.  
  1499. protected function _addJQueryUI($name)
  1500. {
  1501. if (version_compare(_PS_VERSION_, '1.5', '>=')) {
  1502. $this->context->controller->addJqueryUI($name);
  1503. return;
  1504. }
  1505.  
  1506. return;
  1507. }
  1508.  
  1509. public function versionCheck()
  1510. {
  1511. $currentVersion = Configuration::get('AMAZON_CURRENT_VERSION', null, 0, 0);
  1512.  
  1513. if ($currentVersion == null && !Tools::isSubmit('submit')) {
  1514. $this->smarty->assign(array(
  1515. 'versionCheckText1' => $this->l('Be effective, do not waste your time :'),
  1516. 'versionCheckText2' => $this->l('To start, Supposing you only have basis knowledge on it, please use basis functions'),
  1517. 'versionCheckText3' => $this->l('Do not try to hard tune the module. Almost all parameters are correctly configured by default.'),
  1518. 'ps16x' => $this->ps16x
  1519. ));
  1520.  
  1521. $this->_html .= $this->display(__FILE__, 'views/templates/admin/support/version_check.tpl');
  1522. }
  1523.  
  1524. return (false);
  1525. }
  1526.  
  1527.  
  1528. private function toolsCodeImport()
  1529. {
  1530. $replace = (int)Tools::getValue('tools_code_import_replace');
  1531.  
  1532. if (isset($_FILES['tools_code_import']) && isset($_FILES['tools_code_import']['tmp_name']) && isset($_FILES['tools_code_import']['error']) && !$_FILES['tools_code_import']['error']) {
  1533. $refImport = new AmazonCSVReferences($_FILES['tools_code_import']['tmp_name']);
  1534.  
  1535. $result = $refImport->getData();
  1536.  
  1537. if (!$result || !is_array($result) || !count($result)) {
  1538. $this->_postErrors[] = $this->l('Unable to process the file, please verify your file and read instructions');
  1539.  
  1540. return (false);
  1541. }
  1542. $validation_failed = 0;
  1543. $validation_lang_failed = 0;
  1544.  
  1545. if ($result) {
  1546. $count = 0;
  1547. foreach ($result as $refitem) {
  1548. // Parent
  1549. //
  1550. if (!(int)$refitem->id_product_attribute) {
  1551. $product = new Product($refitem->id_product);
  1552.  
  1553. if (!Validate::isLoadedObject($product)) {
  1554. continue;
  1555. }
  1556.  
  1557. if (!$product->validateFields(false, false)) {
  1558. $validation_failed++;
  1559. continue;
  1560. }
  1561.  
  1562. $pass = false;
  1563. foreach (array('ean13', 'upc', 'reference') as $field) {
  1564. if (is_numeric($product->{$field}) && (int)$product->{$field} > 0 && $replace == false) {
  1565. continue;
  1566. }
  1567.  
  1568. if (!is_numeric($product->{$field}) && !empty($product->{$field}) && $replace == false) {
  1569. continue;
  1570. }
  1571.  
  1572. if ($field === 'reference' && !AmazonTools::validateSKU(trim($product->reference))) {
  1573. continue;
  1574. }
  1575.  
  1576. $pass = true;
  1577. $product->{$field} = trim($refitem->{$field});
  1578. }
  1579. if (Tools::strlen($refitem->manufacturer) && Validate::isCatalogName($refitem->manufacturer)) {
  1580. if ($id_manufacturer = Manufacturer::getIdByName($refitem->manufacturer)) {
  1581. $product->id_manufacturer = (int)$id_manufacturer;
  1582. } else {
  1583. $manufacturer = new Manufacturer();
  1584. $manufacturer->name = trim($refitem->manufacturer);
  1585. $manufacturer->active = true;
  1586.  
  1587. if ($manufacturer->validateFields(false) && $manufacturer->validateFieldsLang(false) && $manufacturer->add()) {
  1588. $product->id_manufacturer = (int)$manufacturer->id;
  1589. }
  1590. }
  1591. }
  1592.  
  1593. if (!$product->validateFieldsLang(false, false)) {
  1594. $validation_failed++;
  1595. continue;
  1596. }
  1597.  
  1598. if ($pass) {
  1599. $product->update();
  1600. }
  1601.  
  1602. $count++;
  1603. } else {
  1604. // Children
  1605.  
  1606. foreach (array('ean13', 'upc', 'reference') as $field) {
  1607. if ($replace) {
  1608. $condition = '1';
  1609. } else {
  1610. $condition = ($field === 'reference') ? 'NOT `'.pSQL($field).'` > ""' : ' NOT `'.pSQL($field).'` > 0';
  1611. }
  1612.  
  1613. if ($field === 'reference' && !AmazonTools::validateSKU(trim($refitem->reference))) {
  1614. continue;
  1615. }
  1616.  
  1617. // We have to use a query because the combinations functions are a messup between differents Prestashop versions (PS 1.3, 1.4, 1.5)
  1618. Db::getInstance()->execute('UPDATE `'._DB_PREFIX_.'product_attribute` SET `'.pSQL($field).'`="'.pSQL(trim($refitem->{$field})).'" WHERE `id_product`='.(int)$refitem->id_product.' AND `id_product_attribute`='.(int)$refitem->id_product_attribute.' AND '.$condition);
  1619. }
  1620. // as we write directly into the db, trigger a hook
  1621. if (version_compare(_PS_VERSION_, '1.5', '<')) {
  1622. Hook::updateProductAttribute((int)$refitem->id_product_attribute);
  1623. } else {
  1624. Hook::exec('actionProductAttributeUpdate', array('id_product_attribute' => (int)$refitem->id_product_attribute));
  1625. }
  1626.  
  1627. $count++;
  1628. }
  1629. }
  1630.  
  1631. if ($validation_failed || $validation_lang_failed) {
  1632. $this->warning = sprintf('Notice: %d validation errors %d lang validation errors', $validation_failed, $validation_lang_failed);
  1633. }
  1634.  
  1635. if (!$this->_postErrors && $count) {
  1636. $this->_html .= html_entity_decode('&lt;div class="conf confirm '.($this->ps16x ? 'alert alert-success' : '').'"&gt;')
  1637. .sprintf($this->l('Products References File: %d products updated'), $count).html_entity_decode('&lt;/div&gt;');
  1638. }
  1639. }
  1640. }
  1641.  
  1642. return (false);
  1643. }
  1644.  
  1645. private function _postValidation()
  1646. {
  1647. $actives = Tools::getValue('actives');
  1648.  
  1649. $merchantIds = Tools::getValue('merchantId');
  1650. $marketPlaceIds = Tools::getValue('marketPlaceId');
  1651. $awsKeyIds = Tools::getValue('awsKeyId');
  1652. $awsSecretKeys = Tools::getValue('awsSecretKey');
  1653. $mwsTokens = Tools::getValue('mwsToken');
  1654.  
  1655. $currencies = Tools::getValue('marketPlaceCurrency');
  1656. $regions = Tools::getValue('marketPlaceRegion');
  1657.  
  1658. $carriers = Tools::getValue('carrier');
  1659. $amazon_carriers = Tools::getValue('amazon_carrier');
  1660. $carrier_default = Tools::getValue('carrier_default');
  1661.  
  1662. $categories = Tools::getValue('category');
  1663.  
  1664. $order_state = Tools::getValue('order_state');
  1665. $send_state = Tools::getValue('sent_state');
  1666.  
  1667. $amazonEurope = Tools::getValue('amazonEurope');
  1668. $marketPlaceMaster = Tools::getValue('marketPlaceMaster');
  1669.  
  1670. $condition_map = Tools::getValue('condition_map');
  1671. $profiles = Tools::getValue('profiles');
  1672.  
  1673. $amazon_features = array_fill_keys(self::$amazon_default_features, false);
  1674. $features = array_merge($amazon_features, Tools::getValue('features', array()));
  1675.  
  1676. $mapping = Tools::getValue('mapping', array(
  1677. 'features' => array(),
  1678. 'attributes' => array(),
  1679. 'fixed' => array(),
  1680. 'ungroup' => false
  1681. ));
  1682.  
  1683. $merchantId = array();
  1684. $marketPlaceId = array();
  1685. $awsKeyId = array();
  1686. $awsSecretKey = array();
  1687. $mwsToken = array();
  1688.  
  1689. $currency = array();
  1690. $region = array();
  1691.  
  1692. $carrier = array();
  1693.  
  1694. $error = null;
  1695. $warning = null;
  1696.  
  1697. $price_rules = Tools::getValue('price_rule');
  1698. $pass = false;
  1699.  
  1700. foreach (AmazonTools::languages() as $language) {
  1701. $id_lang = $language['id_lang'];
  1702.  
  1703. if (!(isset($actives[$id_lang]) && (int)$actives[$id_lang])) {
  1704. continue;
  1705. }
  1706.  
  1707. $pass = true;
  1708.  
  1709. $merchantId[$id_lang] = isset($merchantIds[$id_lang]) ? trim($merchantIds[$id_lang]) : '';
  1710. $marketPlaceId[$id_lang] = isset($marketPlaceIds[$id_lang]) ? trim($marketPlaceIds[$id_lang]) : '';
  1711. $awsKeyId[$id_lang] = isset($awsKeyIds[$id_lang]) ? trim($awsKeyIds[$id_lang]) : '';
  1712. $awsSecretKey[$id_lang] = isset($awsSecretKeys[$id_lang]) ? trim($awsSecretKeys[$id_lang]) : '';
  1713. $mwsToken[$id_lang] = isset($mwsTokens[$id_lang]) ? trim($mwsTokens[$id_lang]) : '';
  1714.  
  1715. $carrier[$id_lang] = isset($carriers[$id_lang]) ? $carriers[$id_lang] : '';
  1716.  
  1717. $currency[$id_lang] = isset($currencies[$id_lang]) ? $currencies[$id_lang] : '';
  1718. $region[$id_lang] = isset($regions[$id_lang]) ? $regions[$id_lang] : '';
  1719.  
  1720. $tokenEurope = 1;
  1721.  
  1722. if (!empty($merchantId[$id_lang])) {
  1723. if (((int)$amazonEurope && $marketPlaceMaster == $regions[$id_lang]) || !$amazonEurope) {
  1724. if (!$mwsToken[$id_lang] && empty($awsKeyId[$id_lang]) && $id_lang == $language['id_lang']) {
  1725. $this->_postErrors[]= $this->l('You must fill your Amazon Web Service ID').' - ('.$language['name'].')';
  1726. }
  1727.  
  1728. if (empty($awsSecretKey[$id_lang]) && !$mwsToken[$id_lang]) {
  1729. $this->_postErrors[]= $this->l('You must fill your Amazon Secret Key').' - ('.$language['name'].')';
  1730. }
  1731.  
  1732. if (!$mwsToken[$id_lang] && (empty($merchantId[$id_lang]) || !preg_match('/([0-9A-Z]{12,})/', $merchantId[$id_lang]))) {
  1733. $this->_postErrors[]= $this->l('Merchant ID is invalid').' - ('.$language['name'].')';
  1734. }
  1735.  
  1736. $tokenEurope = 1;
  1737. }
  1738.  
  1739. if (empty($marketPlaceId[$id_lang]) && $id_lang == $language['id_lang']) {
  1740. $this->_postErrors[]= $this->l('You must fill your MarketPlace ID').' ('.$language['name'].')';
  1741. }
  1742.  
  1743. if (empty($region[$id_lang])) {
  1744. $this->_postErrors[]= $this->l('Region must be selected').' ('.$language['name'].')';
  1745. }
  1746.  
  1747. if (empty($currency[$id_lang])) {
  1748. $this->_postErrors[]= $this->l('Currency must be selected').' ('.$language['name'].')';
  1749. }
  1750.  
  1751. $check_price_rules = $this->_checkPriceRules($price_rules);
  1752. if (Tools::strlen($check_price_rules)) {
  1753. $this->_postErrors[]= $check_price_rules;
  1754. }
  1755.  
  1756. if ($this->amazon_features['orders']) {
  1757. if (!is_array($carrier) || !max($carrier[$id_lang]) || !isset($carrier_default[$id_lang]['prestashop']) || !max($carrier_default[$id_lang]['prestashop'])) {
  1758. $this->_postErrors[]= $this->l('You must choose a Carrier').' ('.$language['name'].')';
  1759. }
  1760.  
  1761. if (!is_array($amazon_carriers) || !max($amazon_carriers[$id_lang]) || !isset($carrier_default[$id_lang]['amazon']) || !max($carrier_default[$id_lang]['amazon'])) {
  1762. $this->_postErrors[]= $this->l('You must choose an Amazon Carrier').' ('.$language['name'].')';
  1763. }
  1764. }
  1765.  
  1766. if (is_array($region) && count(array_values($regions)) > 1 && count(array_values($regions)) != count(array_unique(array_values($regions)))) {
  1767. $this->_postErrors[]= $this->l('Platform is used several times, platform has to be used only one time');
  1768. }
  1769. }
  1770. }
  1771.  
  1772. if ($pass && !is_array($categories) || !max($categories)) {
  1773. $this->_postErrors[]= $this->l('Categories Tab must be configured !');
  1774. }
  1775.  
  1776. if ($this->amazon_features['orders']) {
  1777. if ($pass && ((is_array($order_state) && !max($order_state)) || (!is_array($order_state) && !(int)$order_state))) {
  1778. $this->_postErrors[]= $this->l('Incoming order status must be set in the parameters tab !');
  1779. }
  1780.  
  1781. if ($pass && ((is_array($send_state) && !max($send_state)) || (!is_array($send_state) && !(int)$send_state))) {
  1782. $this->_postErrors[]= $this->l('Sent order status must be set in the parameters tab !');
  1783. }
  1784. }
  1785.  
  1786. if (!isset($condition_map['New']) || empty($condition_map['New']) && $this->amazon_features['second_hand']) {
  1787. $this->_postErrors[]= $this->l('The condition map must be filled');
  1788. }
  1789.  
  1790. if (isset($amazonEurope) && (int)$amazonEurope && isset($marketPlaceMaster) && empty($marketPlaceMaster)) {
  1791. $this->_postErrors[]= $this->l('Amazon Europe is set, you must define a Master Platform !');
  1792. }
  1793.  
  1794. if (isset($features['creation']) && $features['creation']) {
  1795. $languages = AmazonTools::languages();
  1796.  
  1797. if ($profiles && isset($profiles['name']) && is_array($profiles['name'])) {
  1798. if (is_array($mapping) && isset($mapping['mandatory']) && count($mapping['mandatory'])) {
  1799. foreach ($mapping['mandatory'] as $field_type => $mapping_l1) {
  1800. foreach ($mapping['mandatory'][$field_type] as $mapping_type => $mapping_l2) {
  1801. foreach ($mapping_l2 as $id_lang => $mapping_l3) {
  1802. if (!is_array($mapping_l3)) {
  1803. continue;
  1804. }
  1805.  
  1806. foreach (array_unique(array_keys($mapping_l3)) as $group) {
  1807. $has_mapping = isset($mapping[$field_type]) && isset($mapping[$field_type][$mapping_type]) && isset($mapping[$field_type][$mapping_type][$id_lang]) && isset($mapping[$field_type][$mapping_type][$id_lang][$group]) && count($mapping[$field_type][$mapping_type][$id_lang][$group]);
  1808.  
  1809. if (!$has_mapping) {
  1810. if ($field_type === 'features') {
  1811. $field_type_label = $this->l('Feature');
  1812. } elseif ($field_type === 'attributes') {
  1813. $field_type_label = $this->l('Attribute');
  1814. } else {
  1815. continue;
  1816. }
  1817. $lang_name = $languages[$id_lang]['name'];
  1818.  
  1819. $this->_postErrors[]= sprintf($this->l('Mappings tab: %s mapping for "%s" is mandatory (%s)'), $field_type_label, $group, $lang_name);
  1820. }
  1821. }
  1822. }
  1823. }
  1824. }
  1825. }
  1826.  
  1827. foreach ($profiles['name'] as $id => $profile) {
  1828. if (empty($profiles['name'][$id])) {
  1829. continue;
  1830. }
  1831.  
  1832. $name = $profiles['name'][$id];
  1833.  
  1834. if (!Tools::strlen($profile_key = AmazonTools::toKey($name))) {
  1835. continue;
  1836. }
  1837.  
  1838. foreach (AmazonTools::languages() as $language) {
  1839. $id_lang = $language['id_lang'];
  1840. $lang_name = AmazonTools::ucfirst($language['name']);
  1841.  
  1842. if (!isset($profiles['universe'][$id][$id_lang]) || empty($profiles['universe'][$id][$id_lang])) {
  1843. if (!isset($profiles['product_type'][$id][$id_lang]) || empty($profiles['product_type'][$id][$id_lang])) {
  1844. continue;
  1845. }
  1846.  
  1847. $this->_postErrors[]= sprintf($this->l('Profiles Tab: The "Universe" for Profile "%s" is not selected.'), $profiles['name'][$id]).' - ';
  1848. $this->_postErrors[]= $lang_name;
  1849. }
  1850.  
  1851. if (!isset($profiles['product_type'][$id][$id_lang]) || empty($profiles['product_type'][$id][$id_lang])) {
  1852. $this->_postErrors[]= sprintf($this->l('Profiles Tab: The \"Product Type\" for Profile \"%s\" has not been selected.'), $profiles['name'][$id]).' - ';
  1853. $this->_postErrors[]= $lang_name;
  1854. }
  1855.  
  1856. if (isset($profiles['extra'][$profile_key][$id_lang]) && is_array($profiles['extra'][$profile_key][$id_lang]) && count($profiles['extra'][$profile_key][$id_lang])) {
  1857. if (!isset($profiles['extra'][$profile_key][$id_lang]['field'])) {
  1858. $profiles['extra'][$profile_key][$id_lang]['field'] = array();
  1859. }
  1860.  
  1861. $has_choice_required = false ;
  1862. $missing_choice_selected = true;
  1863.  
  1864. // check choices field
  1865. if (isset($profiles['extra'][$profile_key][$id_lang]['choices_required'])) {
  1866. $has_choice_required = $profiles['extra'][$profile_key][$id_lang]['choices_required'];
  1867. }
  1868.  
  1869. foreach (array_keys($profiles['extra'][$profile_key][$id_lang]['field']) as $field) {
  1870. if (!isset($profiles['extra'][$profile_key][$id_lang]['required'])
  1871. || !isset($profiles['extra'][$profile_key][$id_lang]['choices'])) {
  1872. continue;
  1873. }
  1874.  
  1875. if (!isset($profiles['extra'][$profile_key][$id_lang]['required'][$field]) &&
  1876. !isset($profiles['extra'][$profile_key][$id_lang]['choices'][$field])) {
  1877. continue;
  1878. }
  1879.  
  1880. $has_value = isset($profiles['extra'][$profile_key][$id_lang]['field'][$field])
  1881. && Tools::strlen($profiles['extra'][$profile_key][$id_lang]['field'][$field]);
  1882. $is_default = $has_value && AmazonSpecificField::isDefault($profiles['extra'][$profile_key][$id_lang]['field'][$field]);
  1883.  
  1884. if (!$has_value && $is_default) {
  1885. $this->_postErrors[]= sprintf($this->l('Profiles Tab: The "%s" value for Profile "%s" is required.'), $field, $profiles['name'][$id]).' - ';
  1886. $this->_postErrors[]= $lang_name;
  1887. }
  1888.  
  1889. if ($has_choice_required) {
  1890. if (isset($profiles['extra'][$profile_key][$id_lang]['choices'][$field])
  1891. && isset($profiles['extra'][$profile_key][$id_lang]['field'][$field])
  1892. && Tools::strlen($profiles['extra'][$profile_key][$id_lang]['field'][$field])) {
  1893. $missing_choice_selected = false;
  1894. }
  1895. }
  1896. }
  1897.  
  1898. // one of choice field required
  1899. if ($has_choice_required && $missing_choice_selected) {
  1900. $this->_postErrors[]= sprintf($this->l('Profiles Tab : One of (%s) for Profile "%s" is expected.'), implode(", ", array_keys($profiles['extra'][$profile_key][$id_lang]['choices'])), $profiles['name'][$id]).' - ';
  1901. $this->_postErrors[]= $lang_name;
  1902. }
  1903.  
  1904. // Check variations
  1905. if (isset($profiles['extra'][$profile_key][$id_lang]['variant']) && Tools::strlen($profiles['extra'][$profile_key][$id_lang]['variant'])) {
  1906. $variationTheme = $profiles['extra'][$profile_key][$id_lang]['variant'];
  1907.  
  1908. if (strpos($variationTheme, '-')) {
  1909. $variationFields = explode('-', $variationTheme);
  1910. } else {
  1911. $variationFields = array($variationTheme);
  1912. }
  1913.  
  1914. foreach ($variationFields as $variationField) {
  1915. if (!isset($profiles['extra'][$profile_key][$id_lang]['field'][$variationField]) || !Tools::strlen($profiles['extra'][$profile_key][$id_lang]['field'][$variationField])) {
  1916. $this->_postErrors[]= sprintf($this->l('Profiles Tab: %s: Variant "%s" is selected, then field "%s" is required.'), $profiles['name'][$id], $variationTheme, $variationField).' - ';
  1917. $this->_postErrors[]= $lang_name;
  1918. }
  1919. }
  1920. }
  1921. }
  1922.  
  1923. $marketPlaceIdChk = isset($marketPlaceIds[$id_lang]) ? trim($marketPlaceIds[$id_lang]) : null;
  1924.  
  1925. if ($marketPlaceIdChk && !AmazonTools::isEuropeMarketplaceId($marketPlaceIdChk)) {
  1926. continue;
  1927. }
  1928.  
  1929. $pass = true;
  1930. $warn = false;
  1931.  
  1932. if (isset($profiles['browsenode'][$id][$id_lang]) && preg_match('/[,; ]/', $profiles['browsenode'][$id][$id_lang])) {
  1933. $result = preg_split('/[,; ]/', $profiles['browsenode'][$id][$id_lang]);
  1934.  
  1935. if (is_array($result)) {
  1936. foreach ($result as $browsenode) {
  1937. if (empty($browsenode)) {
  1938. continue;
  1939. }
  1940.  
  1941. if (!is_numeric(trim($browsenode))) {
  1942. $pass = false;
  1943. }
  1944. }
  1945. } else {
  1946. $pass = false;
  1947. }
  1948. } elseif (isset($profiles['browsenode'][$id][$id_lang]) && !empty($profiles['browsenode'][$id][$id_lang])) {
  1949. if (!is_numeric(trim($profiles['browsenode'][$id][$id_lang]))) {
  1950. $pass = false;
  1951. }
  1952. } elseif (isset($profiles['browsenode'][$id][$id_lang]) && empty($profiles['browsenode'][$id][$id_lang])) {
  1953. if (!is_numeric(trim($profiles['browsenode'][$id][$id_lang]))) {
  1954. $warn = true;
  1955. }
  1956. }
  1957.  
  1958. if (!$pass) {
  1959. //
  1960. $this->_postErrors[]= sprintf($this->l('Profiles Tab: Incorrect value for Browse Node(%s) for Profile "%s" - The value can be only numeric or a list of numerics'), Tools::strtoupper($language['iso_code']), $profiles['name'][$id]).' - ';
  1961. $this->_postErrors[]= $lang_name;
  1962. } elseif ($warn) {
  1963. $warning .= sprintf($this->l('Profiles Tab: Browse Node(%s) for Profile "%s" - this value is highly recommended'), Tools::strtoupper($language['iso_code']), $profiles['name'][$id]).' - ';
  1964. $warning .= $lang_name.Amazon::BR;
  1965. }
  1966. }
  1967. }
  1968. }
  1969. }
  1970.  
  1971. if (!Tools::getValue('post-check')) {
  1972. $post_count = Tools::getValue('post-count');
  1973. $this->_postErrors[]= sprintf($this->l('Post check failed, expecting %d values, please check max_input_vars configuration'), $post_count);
  1974. }
  1975.  
  1976. if (!empty($warning)) {
  1977. $this->warning = $warning;
  1978. }
  1979. }
  1980.  
  1981. private function _checkPriceRules($price_rules)
  1982. {
  1983. if (!is_array($price_rules)) {
  1984. //
  1985. return ($this->l('An error occured with price rules, not an array.'));
  1986. }
  1987.  
  1988. $error = '';
  1989. $actives = Tools::getValue('actives');
  1990.  
  1991. foreach (AmazonTools::languages() as $language) {
  1992. $id_lang = $language['id_lang'];
  1993. $rule = isset($price_rules[$id_lang]['rule']) ? $price_rules[$id_lang]['rule'] : null;
  1994. $type = isset($price_rules[$id_lang]['type']) ? $price_rules[$id_lang]['type'] : null;
  1995.  
  1996. if (!(isset($actives[$id_lang]) && (int)$actives[$id_lang])) {
  1997. continue;
  1998. }
  1999.  
  2000. if (!isset($rule) || !is_array($rule)) {
  2001. continue;
  2002. }
  2003.  
  2004. if (!is_array($rule['from']) || !count($rule['from']) || !is_array($rule['to']) || !count($rule['to'])) {
  2005. continue;
  2006. }
  2007.  
  2008. if (!reset($rule['from']) && !reset($rule['to'])) {
  2009. continue;
  2010. }
  2011.  
  2012. if ((reset($rule['from']) && !reset($rule['to'])) || (!reset($rule['from']) && reset($rule['from']) != '0' && reset($rule['to']))) {
  2013. $error .= sprintf('%s %s => %s'.nl2br(Amazon::LF), $this->l('Price rule incomplete for'), $language['name'], $this->l('Missing range element'));
  2014. continue;
  2015. }
  2016.  
  2017. if (($type === 'percent' && !reset($rule['percent'])) || ($type === 'value' && !reset($rule['value']))) {
  2018. $error .= sprintf('%s %s => %s'.nl2br(Amazon::LF), $this->l('Price rule incomplete for'), $language['name'], $this->l('Missing value'));
  2019. continue;
  2020. }
  2021.  
  2022. $prev_from = -1;
  2023. $prev_to = -1;
  2024.  
  2025. foreach ($rule['from'] as $key => $val) {
  2026. if (max($prev_from, $val) == $prev_from) {
  2027. $error .= sprintf('%s (%s) => %s %d'.nl2br(Amazon::LF), $this->l('Your range FROM is lower than the previous one'), $language['name'], $this->l('Rule ligne'), $key + 1);
  2028. break;
  2029. } else {
  2030. if ($rule['to'][$key] && max($prev_to, $rule['to'][$key]) == $prev_to) {
  2031. $error .= sprintf('%s (%s) => %s %d'.nl2br(Amazon::LF), $this->l('Your range TO is lower than the previous one'), $language['name'], $this->l('Rule ligne'), $key + 1);
  2032. break;
  2033. } else {
  2034. if ($rule['to'][$key] && max($rule['to'][$key], $val) == $val) {
  2035. $error .= sprintf('%s (%s) => %s %d'.nl2br(Amazon::LF), $this->l('Your range TO is lower than your range FROM'), $language['name'], $this->l('Rule ligne'), $key + 1);
  2036. break;
  2037. }
  2038. }
  2039. }
  2040.  
  2041. $prev_from = $val;
  2042. $prev_to = $rule['to'][$key];
  2043. }
  2044. }
  2045.  
  2046. return ($error);
  2047. }
  2048.  
  2049. private function _postProcess()
  2050. {
  2051. // Initialize instant token
  2052. $this->setInstantToken();
  2053.  
  2054. // Prestashop bug fixes
  2055. //
  2056. $this->_fixPrestashopIssues();
  2057.  
  2058. // Tables Updates
  2059. //
  2060. if (!$this->addMarketPlaceTables()) {
  2061. $this->_errors[] = 'install tables failed';
  2062. }
  2063.  
  2064. if (!$this->addMarketPlaceField()) {
  2065. $this->_errors[] = 'install marketplace fields failed';
  2066. }
  2067.  
  2068. if (!$this->addConfigurationTable()) {
  2069. $this->_errors[] = 'install configuration table failed';
  2070. } else {
  2071. //clear cache of static variable inside function tableExists, please also note we call the CommonTools, not AmazonTools
  2072. CommonTools::tableExists(_DB_PREFIX_.AmazonConfiguration::$configuration_table, false);
  2073. }
  2074.  
  2075. // Hooks
  2076. $this->_hookSetup(self::ADD);
  2077.  
  2078. // Update Tabs
  2079. //
  2080. $this->tabSetup(self::UPDATE);
  2081.  
  2082. $actives = Tools::getValue('actives');
  2083.  
  2084. $merchantIds = Tools::getValue('merchantId');
  2085. $marketPlaceIds = Tools::getValue('marketPlaceId');
  2086. $awsKeyIds = Tools::getValue('awsKeyId');
  2087. $awsSecretKeys = Tools::getValue('awsSecretKey');
  2088. $mwsTokens = Tools::getValue('mwsToken');
  2089.  
  2090. $currencies = Tools::getValue('marketPlaceCurrency');
  2091. $regions = Tools::getValue('marketPlaceRegion');
  2092.  
  2093. $price_rules = Tools::getValue('price_rule');
  2094. $outofstocks = Tools::getValue('outofstock');
  2095. $roundings = Tools::getValue('rounding');
  2096. $ptcs = Tools::getValue('ptc');
  2097. $default_tax_rules = Tools::getValue('default_tax_rule');
  2098. $sort_orders = Tools::getValue('sort_order');
  2099. $carriers = Tools::getValue('carrier');
  2100. $amazon_carrier = Tools::getValue('amazon_carrier');
  2101. $synch_fields = Tools::getValue('synch_field');
  2102. $use_asins = Tools::getValue('use_asin');
  2103.  
  2104. $categories = Tools::getValue('category');
  2105.  
  2106. $order_state = Tools::getValue('order_state');
  2107. $send_state = Tools::getValue('sent_state');
  2108. $canceled_state = Tools::getValue('canceled_state');
  2109. $preparation_state = Tools::getValue('preparation_state');
  2110.  
  2111. $fba_order_state = Tools::getValue('fba_order_state');
  2112. $fba_multichannel_state = Tools::getValue('fba_multichannel_state');
  2113. $fba_decrease_stock = Tools::getValue('fba_decrease_stock');
  2114. $fba_multichannel_sent_state = Tools::getValue('fba_multichannel_sent_state');
  2115. $fba_multichannel_done_state = Tools::getValue('fba_multichannel_done_state');
  2116. $fba_stock_behaviour = (int)Tools::getValue('fba_stock_behaviour');
  2117. $fba_notification = (int)Tools::getValue('fba_notification');
  2118.  
  2119. $warehouse = Tools::getValue('warehouse');
  2120. $id_employee = Tools::getValue('employee');
  2121. $id_group = Tools::getValue('id_group');
  2122. $id_business_group = Tools::getValue('id_business_group');
  2123.  
  2124. $carrier_default = Tools::getValue('carrier_default');
  2125. $carrier_multichannel = Tools::getValue('carrier_multichannel');
  2126.  
  2127. $marketPlaceMaster = Tools::getValue('marketPlaceMaster');
  2128.  
  2129. $debugMode = (bool)Tools::getValue('debug_mode');
  2130. $email = (bool)Tools::getValue('email');
  2131. $features = Tools::getValue('features');
  2132.  
  2133. $fba_price_formula = Tools::getValue('fba_formula');
  2134. $fba_multichannel = (bool)Tools::getValue('fba_multichannel');
  2135. $fba_multichannel_auto = (bool)Tools::getValue('fba_multichannel_auto');
  2136.  
  2137. $specials = (bool)Tools::getValue('specials');
  2138. $specials_apply_rules = (bool)Tools::getValue('specials_apply_rules');
  2139. $preorder = (bool)Tools::getValue('preorder');
  2140. $taxes = (int)Tools::getValue('taxes');
  2141. $delete_products = (bool)Tools::getValue('delete_products');
  2142. $stock_only = (bool)Tools::getValue('stock_only');
  2143. $html_descriptions = (bool)Tools::getValue('html_descriptions');
  2144. $prices_only = (bool)Tools::getValue('prices_only');
  2145. $payment_region = (bool)Tools::getValue('payment_region');
  2146.  
  2147. $description_field = Tools::getValue('description_field');
  2148.  
  2149. $image_type = Tools::getValue('image_type');
  2150. $safe_encoding = (bool)Tools::getValue('safe_encoding');
  2151. // Aug-23-2018: Remove Carriers/Modules option
  2152.  
  2153. $auto_create = (bool)Tools::getValue('auto_create');
  2154.  
  2155. $condition_map = Tools::getValue('condition_map');
  2156.  
  2157. $account_type = Tools::getValue('account_type');
  2158. $title_format = Tools::getValue('title_format');
  2159.  
  2160. $override_stds = Tools::getValue('overrides_std');
  2161. $override_exps = Tools::getValue('overrides_exp');
  2162.  
  2163. $brute_force = (bool)Tools::getValue('brute_force');
  2164.  
  2165. $repricing = Tools::getValue('repricing', array());
  2166. $default_strategies = Tools::getValue('default_strategy', array());
  2167.  
  2168. $custom_mapping = Tools::getValue('custom_mapping');
  2169. $mapping = Tools::getValue('mapping', array(
  2170. 'features' => array(),
  2171. 'attributes' => array(),
  2172. 'fixed' => array(),
  2173. 'ungroup' => false
  2174. ));
  2175.  
  2176. $excluded_manufacturers = Tools::getValue('selected-manufacturers');
  2177. $excluded_suppliers = Tools::getValue('selected-suppliers');
  2178. $price_filter = Tools::getValue('price_filter');
  2179.  
  2180. $inactive_languages = (bool)Tools::getValue('inactive_languages');
  2181. $disable_ssl_check = (bool)Tools::getValue('disable_ssl_check');
  2182.  
  2183. $shipping_params = Tools::getValue('shipping');
  2184. $shipping_methods = Tools::getValue('shipping_method');
  2185.  
  2186. $profiles = Tools::getValue('profiles');
  2187. $profile2category = Tools::getValue('profile2category');
  2188.  
  2189. $repricing_strategies = Tools::getValue('strategies');
  2190.  
  2191. $active = array();
  2192.  
  2193. $merchantId = array();
  2194. $marketPlaceId = array();
  2195. $awsKeyId = array();
  2196. $awsSecretKey = array();
  2197.  
  2198. $currency = array();
  2199. $region = array();
  2200.  
  2201. $outofstock = array();
  2202. $rounding = array();
  2203. $ptc = array();
  2204. $default_tax_rule = array();
  2205. $sort_order = array();
  2206.  
  2207. $carrier = array();
  2208. $synch_field = array();
  2209. $use_asin = array();
  2210.  
  2211. $shipping_rule = array();
  2212.  
  2213. $override_exp = array();
  2214. $override_std = array();
  2215.  
  2216. $amazonTokens = array();
  2217.  
  2218. // For post treatments ....
  2219. //
  2220. foreach (AmazonTools::languages() as $language) {
  2221. $id_lang = $language['id_lang'];
  2222.  
  2223. if (!(isset($actives[$id_lang]) && (int)$actives[$id_lang])) {
  2224. continue;
  2225. }
  2226.  
  2227. $active[$id_lang] = isset($actives[$id_lang]) ? (int)$actives[$id_lang] : '';
  2228.  
  2229. $merchantId[$id_lang] = isset($merchantIds[$id_lang]) ? trim($merchantIds[$id_lang]) : '';
  2230. $marketPlaceId[$id_lang] = isset($marketPlaceIds[$id_lang]) ? trim($marketPlaceIds[$id_lang]) : '';
  2231. $awsKeyId[$id_lang] = isset($awsKeyIds[$id_lang]) ? trim($awsKeyIds[$id_lang]) : '';
  2232. $awsSecretKey[$id_lang] = isset($awsSecretKeys[$id_lang]) ? trim($awsSecretKeys[$id_lang]) : '';
  2233.  
  2234. $currency[$id_lang] = isset($currencies[$id_lang]) ? $currencies[$id_lang] : '';
  2235.  
  2236. if (is_array($region) && array_key_exists($id_lang, $regions)) {
  2237. $region_to_id_lang = array_flip($region);
  2238.  
  2239. if (isset($region_to_id_lang[$regions[$id_lang]])) {
  2240. $pass = false;
  2241. } else {
  2242. $pass = true;
  2243. }
  2244. } else {
  2245. $pass = true;
  2246. }
  2247.  
  2248. if ($pass) {
  2249. $region[$id_lang] = isset($regions[$id_lang]) ? $regions[$id_lang] : '';
  2250. }
  2251.  
  2252. $outofstock[$id_lang] = isset($outofstocks[$id_lang]) ? trim($outofstocks[$id_lang]) : '';
  2253.  
  2254. $rounding[$id_lang] = isset($roundings[$id_lang]) ? (int)$roundings[$id_lang] : '1';
  2255. $ptc[$id_lang] = isset($ptcs[$id_lang]) ? $ptcs[$id_lang] : null;
  2256. $default_tax_rule[$id_lang] = isset($default_tax_rules[$id_lang]) ? $default_tax_rules[$id_lang] : null;
  2257. $sort_order[$id_lang] = isset($sort_orders[$id_lang]) ? (int)$sort_orders[$id_lang] : '1';
  2258.  
  2259. $carrier[$id_lang] = isset($carriers[$id_lang]) ? $carriers[$id_lang] : '';
  2260. $amazon_carrier[$id_lang] = isset($amazon_carrier[$id_lang]) ? $amazon_carrier[$id_lang] : '';
  2261.  
  2262. $synch_field[$id_lang] = isset($synch_fields[$id_lang]) ? $synch_fields[$id_lang] : '';
  2263.  
  2264. $use_asin[$id_lang] = isset($use_asins[$id_lang]) ? $use_asins[$id_lang] : '';
  2265.  
  2266. $override_std[$id_lang] = isset($override_stds[$id_lang]) ? $override_stds[$id_lang] : '';
  2267. $override_exp[$id_lang] = isset($override_exps[$id_lang]) ? $override_exps[$id_lang] : '';
  2268.  
  2269. if (isset($price_rules[$id_lang]) && is_array($price_rules[$id_lang]) && isset($price_rules[$id_lang]['rule']['from']) && is_array($price_rules[$id_lang]['rule']['from']) && is_array($price_rules[$id_lang]['rule']['to'])) {
  2270. foreach ($price_rules[$id_lang]['rule']['from'] as $index => $val) {
  2271. if (!is_numeric($val)) {
  2272. unset($price_rules[$id_lang]['rule']['from'][$index]);
  2273. unset($price_rules[$id_lang]['rule']['to'][$index]);
  2274. unset($price_rules[$id_lang]['rule']['percent'][$index]);
  2275. unset($price_rules[$id_lang]['rule']['value'][$index]);
  2276. }
  2277. }
  2278. $price_rules[$id_lang]['rule']['from'] = isset($price_rules[$id_lang]['rule']['from']) ? array_values($price_rules[$id_lang]['rule']['from']) : '';
  2279. $price_rules[$id_lang]['rule']['to'] = isset($price_rules[$id_lang]['rule']['to']) ? array_values($price_rules[$id_lang]['rule']['to']) : '';
  2280. $price_rules[$id_lang]['rule']['percent'] = isset($price_rules[$id_lang]['rule']['percent']) ? array_values($price_rules[$id_lang]['rule']['percent']) : '';
  2281. $price_rules[$id_lang]['rule']['value'] = isset($price_rules[$id_lang]['rule']['value']) ? array_values($price_rules[$id_lang]['rule']['value']) : '';
  2282. }
  2283.  
  2284. // Cron Token
  2285. //
  2286. if (isset($awsSecretKeys[$id_lang])) {
  2287. $amazonTokens[$id_lang] = md5($awsSecretKeys[$id_lang]);
  2288. }
  2289. }
  2290.  
  2291. AmazonConfiguration::updateValue('ACTIVE', $active);
  2292. AmazonConfiguration::updateValue('MERCHANT_ID', $merchantId);
  2293. AmazonConfiguration::updateValue('MARKETPLACE_ID', $marketPlaceId);
  2294. AmazonConfiguration::updateValue('AWS_KEY_ID', $awsKeyId);
  2295. AmazonConfiguration::updateValue('SECRET_KEY', $awsSecretKey);
  2296. AmazonConfiguration::updateValue('MWS_TOKEN', $mwsTokens);
  2297.  
  2298. AmazonConfiguration::updateValue('CURRENCY', $currency);
  2299. AmazonConfiguration::updateValue('REGION', $region);
  2300.  
  2301. AmazonConfiguration::updateValue('OUT_OF_STOCK', $outofstock);
  2302. AmazonConfiguration::updateValue('PRICE_RULE', $price_rules);
  2303. AmazonConfiguration::updateValue('PRICE_ROUNDING', $rounding);
  2304. AmazonConfiguration::updateValue('PTC', $ptc);
  2305. AmazonConfiguration::updateValue(self::CONFIG_DEFAULT_TAX_RULE_FOR_MP, $default_tax_rule);
  2306. AmazonConfiguration::updateValue('SORT_ORDER', $sort_order);
  2307. AmazonConfiguration::updateValue('CARRIER', $carrier);
  2308. AmazonConfiguration::updateValue('AMAZON_CARRIER', $amazon_carrier);
  2309.  
  2310. AmazonConfiguration::updateValue('FIELD', $synch_field);
  2311. AmazonConfiguration::updateValue('USE_ASIN', $use_asin);
  2312.  
  2313. AmazonConfiguration::updateValue('ORDER_STATE', $order_state);
  2314. AmazonConfiguration::updateValue('PREPARATION_STATE', $preparation_state);
  2315. AmazonConfiguration::updateValue('SENT_STATE', $send_state);
  2316. AmazonConfiguration::updateValue('CANCELED_STATE', $canceled_state);
  2317.  
  2318. Configuration::updateValue('AMAZON_FBA_ORDER_STATE', (int)$fba_order_state);
  2319. Configuration::updateValue('AMAZON_FBA_MULTICHANNEL_STATE', (int)$fba_multichannel_state);
  2320. Configuration::updateValue('AMAZON_FBA_MULTICHANNEL_SENT', (int)$fba_multichannel_sent_state);
  2321. Configuration::updateValue('AMAZON_FBA_MULTICHANNEL_DONE', (int)$fba_multichannel_done_state);
  2322. Configuration::updateValue('AMAZON_FBA_STOCK_BEHAVIOUR', (int)$fba_stock_behaviour);
  2323. Configuration::updateValue('AMAZON_FBA_NOTIFICATION', (int)$fba_notification);
  2324.  
  2325. Configuration::updateValue('AMAZON_WAREHOUSE', (int)$warehouse);
  2326.  
  2327. if (!$id_employee || !is_numeric($id_employee)) {
  2328. $id_employee = (int)$this->context->employee->id;
  2329. }
  2330.  
  2331. Configuration::updateValue('AMAZON_EMPLOYEE', (int)$id_employee);
  2332.  
  2333. Configuration::updateValue('AMAZON_CUSTOMER_GROUP', (int)$id_group);
  2334. Configuration::updateValue('AMAZON_BUSINESS_CUSTOMER_GROUP', (int)$id_business_group);
  2335.  
  2336. AmazonConfiguration::updateValue('CARRIER_DEFAULT', $carrier_default);
  2337. AmazonConfiguration::updateValue('CARRIER_MULTICHANNEL', $carrier_multichannel);
  2338.  
  2339. AmazonConfiguration::updateValue(self::CONFIG_MASTER, $marketPlaceMaster);
  2340.  
  2341. Configuration::updateValue('AMAZON_EMAIL', (bool)$email);
  2342. Configuration::updateValue('AMAZON_DEBUG_MODE', (bool)$debugMode);
  2343.  
  2344. AmazonConfiguration::updateValue('FEATURES', $features);
  2345. AmazonConfiguration::updateValue('FBA_PRICE_FORMULA', $fba_price_formula);
  2346.  
  2347. Configuration::updateValue('AMAZON_FBA_MULTICHANNEL', $fba_multichannel);
  2348. Configuration::updateValue('AMAZON_FBA_MULTICHANNEL_AUTO', $fba_multichannel_auto);
  2349. Configuration::updateValue('AMAZON_FBA_DECREASE_STOCK', (int)$fba_decrease_stock);
  2350.  
  2351. AmazonConfiguration::updateValue('SPECIALS', $specials);
  2352. Configuration::updateValue('AMAZON_SPECIALS_APPLY_RULES', (bool)$specials_apply_rules);
  2353. Configuration::updateValue('AMAZON_PREORDER', (bool)$preorder);
  2354. AmazonConfiguration::updateValue('TAXES', $taxes);
  2355.  
  2356. AmazonConfiguration::updateValue('CONDITION_MAP', $condition_map);
  2357.  
  2358. AmazonConfiguration::updateValue('ACCOUNT_TYPE', $account_type);
  2359. AmazonConfiguration::updateValue('TITLE_FORMAT', $title_format);
  2360.  
  2361. AmazonConfiguration::updateValue('SHIPPING_OVERRIDES_STD', $override_std);
  2362. AmazonConfiguration::updateValue('SHIPPING_OVERRIDES_EXP', $override_exp);
  2363.  
  2364. AmazonConfiguration::updateValue('CRON_TOKEN', $amazonTokens);
  2365.  
  2366. AmazonConfiguration::updateValue('DELETE_PRODUCTS', $delete_products);
  2367. AmazonConfiguration::updateValue('STOCK_ONLY', $stock_only);
  2368. Configuration::updateValue('AMAZON_PRICES_ONLY', $prices_only);
  2369. Configuration::updateValue('AMAZON_PAYMENT_REGION', $payment_region);
  2370.  
  2371. AmazonConfiguration::updateValue('BRUTE_FORCE', $brute_force);
  2372.  
  2373. Configuration::updateValue('AMAZON_HTML_DESCRIPTIONS', $html_descriptions);
  2374. Configuration::updateValue('AMAZON_DESCRIPTION_FIELD', $description_field);
  2375.  
  2376. Configuration::updateValue('AMAZON_AUTO_CREATE', (int)$auto_create);
  2377.  
  2378. Configuration::updateValue('AMAZON_IMAGE_TYPE', $image_type);
  2379. Configuration::updateValue('AMAZON_SAFE_ENCODING', $safe_encoding);
  2380. // Aug-23-2018: Remove save Carriers/Modules option
  2381.  
  2382. AmazonConfiguration::updateValue('mapping', is_array($mapping) ? $this->filterRecursive($mapping) : array());
  2383.  
  2384. AmazonConfiguration::updateValue('EXCLUDED_MANUFACTURERS', $excluded_manufacturers);
  2385. AmazonConfiguration::updateValue('EXCLUDED_SUPPLIERS', $excluded_suppliers);
  2386. AmazonConfiguration::updateValue('PRICE_FILTER', $price_filter);
  2387. Configuration::updateValue('AMAZON_INACTIVE_LANGUAGES', $inactive_languages);
  2388. Configuration::updateValue('AMAZON_DISABLE_SSL_CHECK', $disable_ssl_check);
  2389.  
  2390. // Configure Hidden Settings - Expert Mode
  2391. AmazonConfiguration::updateValue('MAIL_INVOICE', Tools::getValue('mail_invoice'));
  2392. AmazonConfiguration::updateValue('MAIL_REVIEW', Tools::getValue('mail_review'));
  2393. AmazonConfiguration::updateValue('CUSTOMER_THREAD', Tools::getValue('customer_thread'));
  2394.  
  2395. // Whole Shipping Tab configuration - 2013-12-24
  2396. AmazonConfiguration::updateValue('SHIPPING', $shipping_params);
  2397. AmazonConfiguration::updateValue('SHIPPING_METHODS', $shipping_methods);
  2398.  
  2399. AmazonConfiguration::updateValue('REPRICING', $repricing);
  2400.  
  2401. //
  2402. // Context management - save the full shop context
  2403. //
  2404. $employee = new Employee($id_employee);
  2405.  
  2406. AmazonContext::save($this->context, $employee);
  2407.  
  2408. //
  2409. // RepricingStrategies
  2410. //
  2411. if (isset($repricing_strategies) && count($repricing_strategies)) {
  2412. $this->_saveRepricingStrategies($repricing_strategies, $default_strategies);
  2413. }
  2414.  
  2415. //
  2416. // Profiles
  2417. //
  2418. if (isset($profiles) && count($profiles)) {
  2419. $this->_saveProfiles($profiles);
  2420. }
  2421.  
  2422. if (is_array($custom_mapping) && count($custom_mapping)) {
  2423. AmazonValidValues::saveCustomMapping($custom_mapping);
  2424. }
  2425.  
  2426. //
  2427. // Categories & Profiles Mapping
  2428. //
  2429. AmazonConfiguration::updateValue('profiles_categories', (array)$profile2category);
  2430. AmazonConfiguration::updateValue('categories', (array)$categories);
  2431.  
  2432. // Customer Account and Addresses - verify/create/update
  2433. //
  2434. if (($id_customer = $this->createCustomer())) {
  2435. /*Smart Shipping is Active : create or update addresses*/
  2436. if (is_array($regions) && count($regions) && isset($shipping_params['smart_shipping']['active']) && $shipping_params['smart_shipping']['active']) {
  2437. require_once(_PS_MODULE_DIR_.'/amazon/classes/amazon.address.class.php');
  2438.  
  2439. AmazonAddress::createShippingLocations($regions, $id_customer);
  2440. }
  2441. }
  2442. Configuration::deleteByName('AMAZON_CURRENT_VERSION');
  2443. Configuration::updateValue('AMAZON_CURRENT_VERSION', $this->version, false, 0, 0);
  2444.  
  2445. if (!$this->_postErrors) {
  2446. $this->_html .= html_entity_decode('&lt;div class="conf confirm '.($this->ps16x ? 'alert alert-success' : '').'"&gt;'.$this->l('Configuration updated').'&lt;/div&gt;');
  2447. }
  2448. }
  2449.  
  2450. private function _fixPrestashopIssues()
  2451. {
  2452. // Create an empty mail translation file if it is empty to fix the issue :
  2453. // http://forge.prestashop.com/browse/PSCFV-10380
  2454. //
  2455. $mail_invoice = AmazonConfiguration::get('MAIL_INVOICE');
  2456.  
  2457. if (isset($mail_invoice['active']) && $mail_invoice['active']) {
  2458. foreach (AmazonTools::languages() as $language) {
  2459. $iso_code = $language['iso_code'];
  2460.  
  2461. $dir = _PS_MAIL_DIR_.$iso_code;
  2462. $file = _PS_MAIL_DIR_.$iso_code.'/lang.php';
  2463.  
  2464. if (!is_dir($dir)) {
  2465. @mkdir($dir);
  2466. }
  2467.  
  2468. if (!file_exists($file)) {
  2469. @file_put_contents($file, null);
  2470. }
  2471. }
  2472. }
  2473. }
  2474.  
  2475. private function filterNull($var)
  2476. {
  2477. return ($var !== null && $var !== false && $var !== '');
  2478. }
  2479.  
  2480. private function filterRecursive($array)
  2481. {
  2482. foreach ($array as &$value) {
  2483. if (is_array($value)) {
  2484. $value = $this->filterRecursive($value);
  2485. }
  2486. }
  2487.  
  2488. return array_filter($array, array($this, 'filterNull'));
  2489. }
  2490.  
  2491. private function _saveRepricingStrategies($strategies, $default_strategies)
  2492. {
  2493. $out_strategies = array();
  2494.  
  2495. if (is_array($strategies) && count($strategies) && isset($strategies['name']) && is_array($strategies['name']) && count($strategies['name'])) {
  2496. foreach ($strategies['name'] as $id_lang => $names) {
  2497. if (!is_array($names) || !count($names)) {
  2498. continue;
  2499. }
  2500.  
  2501. foreach ($names as $index => $name) {
  2502. $key = AmazonTools::toKey($name);
  2503.  
  2504. foreach ($strategies as $conf_item => $conf) {
  2505. $has_lang = is_array($conf) && isset($conf[$id_lang]) && is_array($conf[$id_lang]) && count($conf[$id_lang]);
  2506. $has_data = isset($conf[$id_lang][$index]);
  2507.  
  2508. if ($has_lang && $has_data) {
  2509. $out_strategies[$conf_item][$id_lang][$key] = $conf[$id_lang][$index];
  2510. }
  2511. }
  2512. }
  2513. }
  2514. }
  2515. AmazonConfiguration::updateValue('strategies', $strategies);
  2516. AmazonConfiguration::updateValue('default_strategies', $default_strategies);
  2517. }
  2518.  
  2519. private function _saveProfiles($profiles)
  2520. {
  2521. require_once(_PS_MODULE_DIR_.'/amazon/validate/Node.php');
  2522. require_once(_PS_MODULE_DIR_.'/amazon/validate/XmlDataType.php');
  2523. require_once(_PS_MODULE_DIR_.'/amazon/validate/XmlRestriction.php');
  2524. require_once(_PS_MODULE_DIR_.'/amazon/validate/AmazonXSD.php'); //gets code for Amazon XML Schemas
  2525. require_once(_PS_MODULE_DIR_.'/amazon/validate/AmazonValidator.php');
  2526. require_once(_PS_MODULE_DIR_.'/amazon/validate/Tools.php');
  2527.  
  2528. $profiles['parameters'] = array();
  2529. $profiles['attributes'] = array();
  2530.  
  2531.  
  2532. if (isset($profiles['name']) && is_array($profiles['name'])) {
  2533. if (!isset($profiles['version4'])) {
  2534. return (null);
  2535. }
  2536.  
  2537. foreach ($profiles['name'] as $id => $profile) {
  2538. if (!isset($profiles['name'][$id]) || empty($profiles['name'][$id])) {
  2539. continue;
  2540. }
  2541.  
  2542. $languages = AmazonTools::languages();
  2543.  
  2544. foreach ($languages as $language) {
  2545. $id_lang = $language['id_lang'];
  2546.  
  2547. if (Amazon::$debug_mode) {
  2548. CommonTools::p(sprintf('%s:#%d universe: %s'."\n", basename(__FILE__), __LINE__, print_r($profiles['universe'][$id][$id_lang], true)));
  2549. }
  2550. if (!array_key_exists($id_lang, $profiles['universe'][$id]) || empty($profiles['universe'][$id][$id_lang])) {
  2551. continue;
  2552. }
  2553.  
  2554. $category = $profiles['universe'][$id][$id_lang];
  2555.  
  2556.  
  2557. if (Amazon::$debug_mode) {
  2558. CommonTools::p(sprintf('%s:#%d category: %s id_lang: %d , id: %d', basename(__FILE__), __LINE__, $category, $id_lang, $id));
  2559. }
  2560.  
  2561. try {
  2562. $productFactory = new AmazonXSD($category.'.xsd');
  2563. $productInstance = $productFactory->getInstance();
  2564.  
  2565. $referenceElement = $profiles['product_type'][$id][$id_lang] ? $profiles['product_type'][$id][$id_lang] : null;
  2566.  
  2567. if ($referenceElement && Amazon::$debug_mode) {
  2568. CommonTools::p(sprintf('%s:#%d reference element: %s', basename(__FILE__), __LINE__, print_r($referenceElement, true)));
  2569. }
  2570.  
  2571. if ($category != 'CE') {
  2572. $productFactory->filterProductType($category, $referenceElement);
  2573.  
  2574. foreach (array('ProductType', 'ClothingType', 'VariationData', 'Parentage', 'VariationTheme') as $searchedElement) {
  2575. if (Amazon::$debug_mode) {
  2576. CommonTools::p(sprintf('%s:#%d lookup, id: %d, element: %s, reference element: %s'."\n", basename(__FILE__), __LINE__, $id, $searchedElement, $referenceElement));
  2577. }
  2578.  
  2579. if (($path = AmazonXSDTools::searchPath($productInstance, $searchedElement, $referenceElement))) {
  2580. $profiles['parameters'][$id][$id_lang][$searchedElement] = $path;
  2581.  
  2582. if (Amazon::$debug_mode) {
  2583. CommonTools::p(sprintf('%s:#%d parameters, id: %d, element: %s, path: %s', basename(__FILE__), __LINE__, $id, $searchedElement, print_r($path, true)));
  2584. }
  2585. }
  2586. }
  2587.  
  2588. } else {
  2589. $field = 'ProductType';
  2590. $product_subtype = $referenceElement;
  2591. $referenceElement = 'ConsumerElectronics';
  2592.  
  2593. //$productFactory->filterProductType($category, $referenceElement);
  2594.  
  2595. if (($path = AmazonXSDTools::searchPath($productInstance, $field, $referenceElement))) {
  2596. $profiles['parameters'][$id][$id_lang][$field] = $path;
  2597. }
  2598.  
  2599. $field = 'ProductSubtype';
  2600.  
  2601. if (($path = AmazonXSDTools::searchPath($productInstance, $field, $product_subtype))) {
  2602. $profiles['parameters'][$id][$id_lang][$field] = $path;
  2603. }
  2604.  
  2605. foreach (array(
  2606. 'VariationData',
  2607. 'Parentage',
  2608. 'VariationTheme'
  2609. ) as $searchedElement) {
  2610. if (($path = AmazonXSDTools::searchPath($productInstance, $searchedElement, $referenceElement, true))) {
  2611. $profiles['parameters'][$id][$id_lang][$searchedElement] = $path;
  2612. }
  2613. }
  2614. }
  2615.  
  2616. $profile_key = AmazonTools::toKey($profile);
  2617.  
  2618. $has_extra = isset($profiles['extra']) && isset($profiles['extra'][$profile_key]) && isset($profiles['extra'][$profile_key][$id_lang]) && count($profiles['extra'][$profile_key][$id_lang]);
  2619. $has_profile_fields = $has_extra && isset($profiles['extra'][$profile_key][$id_lang]) && isset($profiles['extra'][$profile_key][$id_lang]['field']);
  2620. $has_variant_field = $has_extra && isset($profiles['extra'][$profile_key][$id_lang]) && isset($profiles['extra'][$profile_key][$id_lang]['variant']);
  2621.  
  2622. if ($has_extra) {
  2623. $p_extra = &$profiles['extra'][$profile_key][$id_lang];
  2624. }
  2625.  
  2626. // Add to the path the mandatory fields
  2627. //
  2628. if ($has_profile_fields) {
  2629. foreach ($p_extra['field'] as $field => $value) {
  2630. $has_default = is_array($p_extra) && isset($p_extra['default']) && isset($p_extra['default'][$field]) && (!empty($p_extra['default'][$field]) || is_numeric($p_extra['default'][$field]));
  2631.  
  2632. if (empty($value) && !is_numeric($value) && !$has_default) {
  2633. continue;
  2634. }
  2635.  
  2636. $path = AmazonXSDTools::searchPath($productInstance, $field, $referenceElement);
  2637.  
  2638. if ($path) {
  2639. $profiles['parameters'][$id][$id_lang][$field] = $path;
  2640. }
  2641. }
  2642. }
  2643. // Add path for generic variants
  2644. //
  2645. if ($has_variant_field && Tools::strlen($p_extra['variant'])) {
  2646. $variationTheme = $p_extra['variant'];
  2647.  
  2648. if (strpos($variationTheme, 'Color') !== false) {
  2649. $variationTheme .= '-ColorMap';
  2650. }
  2651. if (strpos($variationTheme, 'Size') !== false) {
  2652. $variationTheme .= '-SizeMap';
  2653. }
  2654.  
  2655. if (strpos($variationTheme, '-')) {
  2656. $variationFields = explode('-', $variationTheme);
  2657.  
  2658. $variationFieldsList = $variationFields;
  2659. } else {
  2660. $variationFieldsList = array($variationTheme);
  2661. }
  2662.  
  2663. if (!is_array($variationFieldsList) || !count($variationFieldsList)) {
  2664. continue;
  2665. }
  2666.  
  2667. foreach ($variationFieldsList as $tagName) {
  2668. // Rewrite particular cases
  2669. if (isset(AmazonXSD::$rewriteFieldsUniverse[$category]) && isset(AmazonXSD::$rewriteFieldsUniverse[$category][$tagName])) {
  2670. $tagName = AmazonXSD::$rewriteFieldsUniverse[$category][$tagName];
  2671. } elseif (isset(AmazonXSD::$rewriteFields[$tagName])) {
  2672. $tagName = AmazonXSD::$rewriteFields[$tagName];
  2673. }
  2674.  
  2675. $path = AmazonXSDTools::searchPath($productInstance, $tagName, $referenceElement);
  2676.  
  2677.  
  2678. if (Amazon::$debug_mode) {
  2679. CommonTools::p(sprintf('%s:#%d variation field: %s, path: %s'."\n", basename(__FILE__), __LINE__), print_r($tagName, true), print_r($path, true));
  2680. }
  2681.  
  2682. if ($path) {
  2683. $profiles['parameters'][$id][$id_lang][$tagName] = $path;
  2684. }
  2685. }
  2686. }
  2687.  
  2688. $price_rule = is_array($profiles) && isset($profiles['price_rule']) ? $profiles['price_rule'][$id][$id_lang] : null;
  2689.  
  2690. if (isset($price_rule) && is_array($price_rule) && isset($price_rule['rule']['from']) && is_array($price_rule['rule']['from']) && is_array($price_rule['rule']['to'])) {
  2691. foreach ($price_rule['rule']['from'] as $index => $val) {
  2692. if (!is_numeric($val)) {
  2693. unset($price_rule['rule']['from'][$index]);
  2694. unset($price_rule['rule']['to'][$index]);
  2695. unset($price_rule['rule']['percent'][$index]);
  2696. unset($price_rule['rule']['value'][$index]);
  2697. }
  2698. }
  2699.  
  2700. if (count($price_rule['rule']['from'])) {
  2701. $price_rule['rule']['from'] = array_values($price_rule['rule']['from']);
  2702. $price_rule['rule']['to'] = array_values($price_rule['rule']['to']);
  2703. $price_rule['rule']['percent'] = array_values($price_rule['rule']['percent']);
  2704. $price_rule['rule']['value'] = array_values($price_rule['rule']['value']);
  2705. }
  2706.  
  2707. $profiles['price_rule'][$id][$id_lang] = null;
  2708.  
  2709. if (isset($price_rule['rule']['from']) && is_array($price_rule['rule']['from']) && count($price_rule['rule']['from']) && is_numeric(max($price_rule['rule']['from']))) {
  2710. $profiles['price_rule'][$id][$id_lang] = $price_rule;
  2711. }
  2712. }
  2713.  
  2714. $profiles['category'][$id][$id_lang] = $category;
  2715. } catch (Exception $e) {
  2716. $this->_postErrors[] = $this->l('Amazon XSD Exception :').$e->getMessage();
  2717. }
  2718. }
  2719. }
  2720. }
  2721. if ($profiles && is_array($profiles) && count($profiles)) {
  2722. AmazonConfiguration::updateValue('profiles', $profiles);
  2723.  
  2724. if (Amazon::$debug_mode) {
  2725. CommonTools::d(sprintf('%s:#%d profiles: %s'."\n", basename(__FILE__), __LINE__, print_r($profiles, true)));
  2726. }
  2727. }
  2728.  
  2729. return;
  2730. }
  2731.  
  2732. private function _displayForm()
  2733. {
  2734. if (self::$debug_mode) {
  2735. @ini_set('display_errors', 'on');
  2736. @error_reporting(E_ALL | E_STRICT);
  2737. }
  2738.  
  2739. if (defined('Carrier::ALL_CARRIERS')) {
  2740. $all_carriers = Carrier::ALL_CARRIERS;
  2741. } elseif (defined('ALL_CARRIERS')) {
  2742. $all_carriers = ALL_CARRIERS;
  2743. } else {
  2744. $all_carriers = 5;
  2745. }
  2746. self::$carriers = Carrier::getCarriers($this->id_lang, false, false, false, null, $all_carriers);
  2747.  
  2748. $this->_addJQueryUI('ui.widget');
  2749. $this->_addJQueryUI('ui.draggable');
  2750.  
  2751. $this->_loadSettings();
  2752.  
  2753. $amazon_support = new AmazonSupport();
  2754. $view_params = array(
  2755. 'header' => array(
  2756. 'description' => $this->description,
  2757. 'module_path' => $this->path,
  2758. 'experimental' => self::ENABLE_EXPERIMENTAL_FEATURES,
  2759. 'widget' => isset($this->amazon_features['module']) && ($this->amazon_features['module'] == 'amazon'),
  2760. 'widget_data' => $amazon_support->getWidget($this->name, $this->displayName, $this->version),
  2761. 'documentation' => AmazonSupport::gethreflink(),
  2762. 'images_url' => $this->images,
  2763. 'module_url' => $this->url,
  2764. 'version' => $this->version,
  2765. 'debug' => (bool)$this->config['debug'],
  2766. 'debug_content' => sprintf('Memory Peak: %.02f MB Post Count: %d',
  2767. memory_get_peak_usage() / 1024 / 1024, count($_POST, COUNT_RECURSIVE)),
  2768.  
  2769. 'error' => false,
  2770. 'warning' => false,
  2771. 'class_warning' => 'warn ' . ($this->ps16x ? 'alert alert-warning' : ''),
  2772. 'class_error' => 'error ' . ($this->ps16x ? 'alert alert-danger' : ''),
  2773. 'class_success' => 'confirm ' . ($this->ps16x ? 'alert alert-success' : 'conf'),
  2774. 'class_info' => 'hint ' . ($this->ps16x ? 'alert alert-info' : 'conf'),
  2775.  
  2776. // Scripts to inject in configure header
  2777. 'scripts' => array(
  2778. $this->url.'views/js/amazon.js',
  2779. $this->url.'views/js/configure/amazon-information.js',
  2780. $this->url.'views/js/amazon-profile.js',
  2781. $this->url.'views/js/amazon-features.js',
  2782. $this->url.'views/js/amazon-mappings.js',
  2783. $this->url.'views/js/amazon-repricing.js',
  2784. $this->url.'views/js/amazon-shipping.js',
  2785. $this->url.'views/js/amazon-messaging.js',
  2786. $this->url.'views/js/amazon-fba.js',
  2787. $this->url.'views/js/configure/html2canvas.min.js',
  2788. )
  2789. )
  2790. );
  2791.  
  2792. if (count($this->_postErrors)) {
  2793. $view_params['header']['error'] = true;
  2794. $view_params['header']['error_content'] = null;
  2795.  
  2796. foreach ($this->_postErrors as $err) {
  2797. $view_params['header']['error_content'] .= $err.html_entity_decode("&lt;br /&gt;");
  2798. }
  2799. }
  2800.  
  2801. if ($this->warning) {
  2802. $view_params['header']['warning'] = true;
  2803. $view_params['header']['warning_content'] = $this->warning;
  2804. }
  2805.  
  2806. $this->context->smarty->assign($view_params);
  2807. $this->context->smarty->assign(array('psIs16' => $this->ps16x, 'psIs15' => $this->ps15x, 'psIs14' => $this->ps14x));
  2808.  
  2809. $this->_html .= $this->context->smarty->fetch($this->path.self::$templates[self::TEMPLATE_HEADER]);
  2810.  
  2811. $this->_content();
  2812. }
  2813.  
  2814. private function setInstantToken()
  2815. {
  2816. return(Configuration::UpdateValue('AMAZON_INSTANT_TOKEN', md5(_PS_ROOT_DIR_._PS_VERSION_.isset($_SERVER['REQUEST_TIME']) ? $_SERVER['REQUEST_TIME'] : time()), false, 0, 0));
  2817. }
  2818.  
  2819. private function _loadSettings()
  2820. {
  2821. $this->config['instant_token'] = Configuration::get('AMAZON_INSTANT_TOKEN', null, 0, 0);
  2822.  
  2823. if (AmazonConfiguration::get('TAXES') === false) {
  2824. $this->config['taxes'] = false;
  2825. } else {
  2826. $this->config['taxes'] = AmazonConfiguration::get('TAXES');
  2827. }
  2828.  
  2829. $this->config['out_of_stock'] = AmazonConfiguration::get('OUT_OF_STOCK');
  2830. $this->config['price_rule'] = AmazonConfiguration::get('PRICE_RULE');
  2831. $this->config['rounding'] = AmazonConfiguration::get('PRICE_ROUNDING');
  2832. $this->config['ptc'] = AmazonConfiguration::get('PTC');
  2833. $this->config['default_tax_rule'] = AmazonConfiguration::get(self::CONFIG_DEFAULT_TAX_RULE_FOR_MP);
  2834. $this->config['sort_order'] = AmazonConfiguration::get('SORT_ORDER');
  2835. $this->config['asin_has_priority'] = AmazonConfiguration::get('USE_ASIN');
  2836.  
  2837. // Carrier configuration table
  2838. //
  2839. $this->config['incoming_carrier_amazon'] = AmazonConfiguration::get('AMAZON_CARRIER');
  2840. $this->config['incoming_carrier_prestashop'] = AmazonConfiguration::get('CARRIER');
  2841. $this->config['outgoing_carrier'] = AmazonConfiguration::get('CARRIER_DEFAULT');
  2842. $this->config['multichannel_carrier'] = AmazonConfiguration::get('CARRIER_MULTICHANNEL');
  2843.  
  2844. // Shipping Overrides Settings
  2845. //
  2846. $this->config['shipping_override_std'] = AmazonConfiguration::get('SHIPPING_OVERRIDES_STD');
  2847. $this->config['shipping_override_exp'] = AmazonConfiguration::get('SHIPPING_OVERRIDES_EXP');
  2848. // Field for Synch
  2849. //
  2850. $this->config['synch_field'] = AmazonConfiguration::get('FIELD');
  2851.  
  2852.  
  2853. $this->config['debug'] = self::$debug_mode = Configuration::get('AMAZON_DEBUG_MODE');
  2854.  
  2855. if (!is_numeric($this->config['debug'])) {
  2856. //backward compatibility workarround
  2857.  
  2858. $this->config['debug'] = false;
  2859. } else {
  2860. $this->config['debug'] = (bool)$this->config['debug'];
  2861. }
  2862.  
  2863. $this->config['specials'] = AmazonConfiguration::get('SPECIALS') ? true : false;
  2864. $this->config['specials_apply_rules'] = (bool)Configuration::get('AMAZON_SPECIALS_APPLY_RULES');
  2865. $this->config['preorder'] = (bool)Configuration::get('AMAZON_PREORDER');
  2866. $this->config['delete_products'] = AmazonConfiguration::get('DELETE_PRODUCTS') ? true : false;
  2867. $this->config['stocks_only'] = AmazonConfiguration::get('STOCK_ONLY') ? true : false;
  2868. $this->config['prices_only'] = Configuration::get('AMAZON_PRICES_ONLY') ? true : false;
  2869.  
  2870. $this->config['title_format'] = AmazonConfiguration::get('TITLE_FORMAT');
  2871. $this->config['account_type'] = AmazonConfiguration::get('ACCOUNT_TYPE');
  2872.  
  2873. if (!is_numeric($this->config['title_format'])) {
  2874. $this->config['title_format'] = self::FORMAT_TITLE;
  2875. }
  2876.  
  2877. if (empty($this->config['account_type']) || !is_numeric($this->config['account_type'])) {
  2878. $this->config['account_type'] = self::ACCOUNT_TYPE_INDIVIDUAL;
  2879. }
  2880.  
  2881. $this->config['condition_map'] = AmazonConfiguration::get('CONDITION_MAP');
  2882.  
  2883. // Marketplace Settings
  2884. //
  2885. $this->config['actives'] = AmazonConfiguration::get('ACTIVE');
  2886. $this->config['amazon_merchant_ids'] = AmazonConfiguration::get('MERCHANT_ID');
  2887. $this->config['amazon_marketplace_ids'] = AmazonConfiguration::get('MARKETPLACE_ID');
  2888. $this->config['amazon_key_ids'] = AmazonConfiguration::get('AWS_KEY_ID');
  2889. $this->config['amazon_secret_ids'] = AmazonConfiguration::get('SECRET_KEY');
  2890. $this->config['amazon_mws_token'] = AmazonConfiguration::get('MWS_TOKEN');
  2891.  
  2892. if (!is_array($this->config['actives'])) {
  2893. $this->config['actives'] = array();
  2894. }
  2895.  
  2896. $this->config['features']['debug_mode'] = (bool)$this->config['debug']; //retro-compatibility
  2897.  
  2898. $this->config['marketplace_master'] = AmazonConfiguration::get(self::CONFIG_MASTER);
  2899.  
  2900. $this->config['regions'] = AmazonConfiguration::get('REGION');
  2901. $this->config['currencies'] = AmazonConfiguration::get('CURRENCY');
  2902.  
  2903. // Security
  2904. //
  2905. $this->config['tokens'] = AmazonConfiguration::get('CRON_TOKEN');
  2906.  
  2907. // Categories
  2908. //
  2909. $this->config['categories'] = AmazonConfiguration::get('categories');
  2910. $this->config['profiles_to_categories'] = AmazonConfiguration::get('profiles_categories');
  2911. $this->config['brute_force'] = AmazonConfiguration::get('BRUTE_FORCE');
  2912.  
  2913. // Mappings
  2914. //
  2915. $mapping = AmazonConfiguration::get('mapping');
  2916.  
  2917. if (is_array($mapping) && count($mapping)) {
  2918. $this->config['mapping'] = $mapping;
  2919. } else {
  2920. $this->config['mapping'] = array();
  2921. }
  2922.  
  2923.  
  2924. // Orders States
  2925. //
  2926. $this->config['order_state'] = AmazonConfiguration::get('ORDER_STATE');
  2927. $this->config['preparation_state'] = AmazonConfiguration::get('PREPARATION_STATE');
  2928. $this->config['send_state'] = AmazonConfiguration::get('SENT_STATE');
  2929. $this->config['canceled_state'] = AmazonConfiguration::get('CANCELED_STATE');
  2930.  
  2931. if (!is_array($this->config['order_state']) && (int)$this->config['order_state']) {
  2932. // compatibility with previous versions
  2933.  
  2934. $previous_order_state = (int)$this->config['order_state'];
  2935. $this->config['order_state'] = array();
  2936. $this->config['order_state'][self::ORDER_STATE_STANDARD] = $previous_order_state;
  2937. $this->config['order_state'][self::ORDER_STATE_PRIMEORDER] = $previous_order_state;
  2938.  
  2939. if ($this->config['preorder']) {
  2940. $this->config['order_state'][self::ORDER_STATE_PREORDER] = $previous_order_state;
  2941. }
  2942. } elseif (!isset($this->config['order_state']) || !is_array($this->config['order_state'])) {
  2943. $this->config['order_state'] = array();
  2944. $this->config['order_state'][self::ORDER_STATE_STANDARD] = defined('_PS_OS_PAYMENT_') ? _PS_OS_PAYMENT_ : (int)Configuration::get('PS_OS_PAYMENT');
  2945. $this->config['order_state'][self::ORDER_STATE_PRIMEORDER] = defined('_PS_OS_PAYMENT_') ? _PS_OS_PAYMENT_ : (int)Configuration::get('PS_OS_PAYMENT');
  2946.  
  2947. if ($this->config['preorder']) {
  2948. $this->config['order_state'][self::ORDER_STATE_PREORDER] = defined('_PS_OS_PAYMENT_') ? _PS_OS_PAYMENT_ : (int)Configuration::get('PS_OS_PAYMENT');
  2949. }
  2950. }
  2951.  
  2952. if (!$this->config['preorder'] && is_array($this->config['order_state'])) {
  2953. $this->config['order_state'][self::ORDER_STATE_PREORDER] = null;
  2954. }
  2955. if (is_array($this->config['order_state']) && !isset($this->config['order_state'][self::ORDER_STATE_PRIMEORDER])) {
  2956. $this->config['order_state'][self::ORDER_STATE_PRIMEORDER] = defined('_PS_OS_PAYMENT_') ? _PS_OS_PAYMENT_ : (int)Configuration::get('PS_OS_PAYMENT');
  2957. }
  2958.  
  2959. if ($this->config['preparation_state'] === false) {
  2960. $this->config['preparation_state'] = defined('_PS_OS_PREPARATION_') ? _PS_OS_PREPARATION_ : (int)Configuration::get('PS_OS_PREPARATION');
  2961. }
  2962.  
  2963. if ($this->config['send_state'] === false) {
  2964. $this->config['send_state'] = defined('_PS_OS_SHIPPING_') ? _PS_OS_SHIPPING_ : (int)Configuration::get('PS_OS_SHIPPING');
  2965. }
  2966.  
  2967. if ($this->config['canceled_state'] === false) {
  2968. $this->config['canceled_state'] = defined('_PS_OS_CANCELED_') ? _PS_OS_CANCELED_ : (int)Configuration::get('PS_OS_CANCELED');
  2969. }
  2970.  
  2971. // FBA Settings
  2972. //
  2973. $this->config['fba_order_state'] = Configuration::get('AMAZON_FBA_ORDER_STATE');
  2974. $this->config['fba_multichannel_state'] = Configuration::get('AMAZON_FBA_MULTICHANNEL_STATE');
  2975. $this->config['fba_multichannel_sent_state'] = Configuration::get('AMAZON_FBA_MULTICHANNEL_SENT');
  2976. $this->config['fba_multichannel_done_state'] = Configuration::get('AMAZON_FBA_MULTICHANNEL_DONE');
  2977.  
  2978. $this->config['fba_formula'] = AmazonConfiguration::get('FBA_PRICE_FORMULA');
  2979. $this->config['fba_multichannel'] = (bool)Configuration::get('AMAZON_FBA_MULTICHANNEL');
  2980. $this->config['fba_multichannel_auto'] = (bool)Configuration::get('AMAZON_FBA_MULTICHANNEL_AUTO');
  2981. $this->config['fba_decrease_stock'] = (bool)Configuration::get('AMAZON_FBA_DECREASE_STOCK');
  2982. $this->config['fba_stock_behaviour'] = Configuration::get('AMAZON_FBA_STOCK_BEHAVIOUR');
  2983. $this->config['fba_notification'] = Configuration::get('AMAZON_FBA_NOTIFICATION');
  2984.  
  2985. if (!$this->config['fba_stock_behaviour']) {
  2986. $this->config['fba_stock_behaviour'] = self::FBA_STOCK_SWITCH;
  2987. }
  2988. if (!$this->config['fba_notification']) {
  2989. $this->config['fba_notification'] = self::FBA_NOTIFICATION_BOTH;
  2990. }
  2991.  
  2992. if ($this->config['fba_order_state'] === false) {
  2993. $this->config['fba_order_state'] = $this->config['order_state'];
  2994. }
  2995.  
  2996. // PS 1.5 - Warehouse for Advanced stock management
  2997. //
  2998. $this->config['warehouse'] = Configuration::get('AMAZON_WAREHOUSE');
  2999.  
  3000. $this->config['employee'] = Configuration::get('AMAZON_EMPLOYEE');
  3001.  
  3002. $id_group = (int)Configuration::get('AMAZON_CUSTOMER_GROUP');
  3003.  
  3004. if (!$id_group || !is_numeric($id_group)) {
  3005. if (version_compare(_PS_VERSION_, '1.5', '>=')) {
  3006. $id_group = Configuration::get('PS_CUSTOMER_GROUP');
  3007. } else {
  3008. $id_group = (int)_PS_DEFAULT_CUSTOMER_GROUP_;
  3009. }
  3010. }
  3011.  
  3012. $this->config['id_group'] = $id_group;
  3013. $this->config['id_business_group'] = (int)Configuration::get('AMAZON_BUSINESS_CUSTOMER_GROUP');
  3014.  
  3015. $this->config['auto_create'] = Configuration::get('AMAZON_AUTO_CREATE');
  3016. $this->config['image_type'] = Configuration::get('AMAZON_IMAGE_TYPE');
  3017. // Aug-23-2018: Remove Carriers/Modules setting
  3018. $this->config['safe_encoding'] = Configuration::get('AMAZON_SAFE_ENCODING');
  3019.  
  3020. $this->config['description_field'] = Configuration::get('AMAZON_DESCRIPTION_FIELD');
  3021. $this->config['features'] = $this->amazon_features;
  3022.  
  3023. $this->config['html_descriptions'] = (bool)Configuration::get('AMAZON_HTML_DESCRIPTIONS');
  3024. $this->config['inactive_languages'] = (bool)Configuration::get('AMAZON_INACTIVE_LANGUAGES');
  3025. $this->config['disable_ssl_check'] = (bool)Configuration::get('AMAZON_DISABLE_SSL_CHECK');
  3026.  
  3027. $this->config['payment_region'] = Configuration::get('AMAZON_PAYMENT_REGION');
  3028.  
  3029. // Filters
  3030. $this->config['excluded_manufacturers'] = AmazonConfiguration::get('EXCLUDED_MANUFACTURERS');
  3031. $this->config['excluded_suppliers'] = AmazonConfiguration::get('EXCLUDED_SUPPLIERS');
  3032. $this->config['price_filter'] = AmazonConfiguration::get('PRICE_FILTER');
  3033.  
  3034. // Email Notification
  3035. $this->config['email'] = (bool)Configuration::get('AMAZON_EMAIL');
  3036.  
  3037. $this->config['mail_invoice'] = AmazonConfiguration::get('MAIL_INVOICE');
  3038. $this->config['mail_review'] = AmazonConfiguration::get('MAIL_REVIEW');
  3039. $this->config['mail_customer_thread'] = AmazonConfiguration::get('CUSTOMER_THREAD');
  3040.  
  3041. // Shipping Configuration
  3042. //
  3043. $this->config['shipping'] = AmazonConfiguration::get('SHIPPING');
  3044. $this->config['shipping_methods'] = AmazonConfiguration::get('SHIPPING_METHODS');
  3045.  
  3046. self::loadFeatures(false, $this->config['features']['expert_mode'] ? true : false);
  3047. self::loadAttributes();
  3048.  
  3049. $this->shipping_overrides_std = AmazonSettings::getShippingMethods(AmazonCarrier::SHIPPING_STANDARD);
  3050. $this->shipping_overrides_exp = AmazonSettings::getShippingMethods(AmazonCarrier::SHIPPING_EXPRESS);
  3051. $this->extra_carrier_codes = AmazonSettings::getShippingMethods(AmazonCarrier::SHIPPING_CODES);
  3052.  
  3053. // Repricing Configuration
  3054. $this->config['repricing'] = AmazonConfiguration::get('REPRICING');
  3055.  
  3056. $profiles = AmazonConfiguration::get('profiles');
  3057.  
  3058. if (is_array($profiles) && count($profiles) && isset($profiles['name']) && is_array($profiles['name'])) {
  3059. $this->profiles = $profiles;
  3060. } else {
  3061. $this->profiles = array();
  3062. $this->profiles['name'] = array();
  3063. }
  3064. }
  3065.  
  3066. private function _tabs(&$view_params)
  3067. {
  3068. $selected_tab = $this->selectedTab();
  3069.  
  3070. $view_params['tabs'] = array();
  3071. $view_params['tabs']['images_url'] = $this->images;
  3072.  
  3073. $view_params['tabs']['amazon'] = 'Amazon';
  3074. $view_params['tabs']['amazon_selected'] = ($selected_tab === 'amazon' ? 'selected' : '');
  3075.  
  3076. $view_params['tabs']['informations'] = $this->l('Informations');
  3077. $view_params['tabs']['informations_selected'] = ($selected_tab === 'informations' ? 'selected' : '');
  3078.  
  3079. $view_params['tabs']['features'] = $this->l('Features');
  3080. $view_params['tabs']['features_selected'] = ($selected_tab === 'features' ? 'selected' : '');
  3081.  
  3082. $view_params['tabs']['platforms'] = array();
  3083.  
  3084. $country_iso_code = Configuration::get('PS_LOCALE_COUNTRY');
  3085.  
  3086. foreach (AmazonTools::languages() as $language) {
  3087. $index = $language['iso_code'];
  3088. $view_params['tabs']['platforms'][$index]['iso_code'] = $index;
  3089. $view_params['tabs']['platforms'][$index]['name_short'] = preg_replace('/ .*/', '', $language['name']);
  3090. $view_params['tabs']['platforms'][$index]['name_long'] = $language['name'];
  3091. $view_params['tabs']['platforms'][$index]['selected'] = ($selected_tab === $language['iso_code'] ? 'selected' : '');
  3092. $view_params['tabs']['platforms'][$index]['geo_flag'] = $this->geoFlag($language['id_lang']);
  3093. $view_params['tabs']['platforms'][$index]['area'] = $language['area'];
  3094. $view_params['tabs']['platforms'][$index]['display'] = Tools::strtolower($country_iso_code) === Tools::strtolower($language['country_iso_code']) ? true : false;
  3095. }
  3096.  
  3097. $view_params['tabs']['parameters'] = $this->l('Parameters');
  3098. $view_params['tabs']['parameters_selected'] = ($selected_tab === 'parameters' ? 'selected' : '');
  3099.  
  3100. $view_params['tabs']['categories'] = $this->l('Categories');
  3101. $view_params['tabs']['categories_selected'] = ($selected_tab === 'categories' ? 'selected' : '');
  3102.  
  3103. $view_params['tabs']['mapping'] = $this->l('Mappings');
  3104. $view_params['tabs']['mapping_selected'] = ($selected_tab === 'mapping' ? 'selected' : '');
  3105.  
  3106. $view_params['tabs']['profiles'] = $this->l('Profiles');
  3107. $view_params['tabs']['profiles_selected'] = ($selected_tab === 'profiles' ? 'selected' : '');
  3108.  
  3109. $view_params['tabs']['shipping'] = $this->l('Shipping');
  3110. $view_params['tabs']['shipping_selected'] = ($selected_tab === 'shipping' ? 'selected' : '');
  3111.  
  3112. $view_params['tabs']['filters'] = $this->l('Filters');
  3113. $view_params['tabs']['filters_selected'] = ($selected_tab === 'filters' ? 'selected' : '');
  3114.  
  3115. $view_params['tabs']['messaging'] = $this->l('Messaging');
  3116. $view_params['tabs']['messaging_selected'] = ($selected_tab === 'messaging' ? 'selected' : '');
  3117.  
  3118. $view_params['tabs']['fba'] = $this->l('Amazon FBA');
  3119. $view_params['tabs']['fba_selected'] = ($selected_tab === 'fba' ? 'selected' : '');
  3120.  
  3121. $view_params['tabs']['repricing'] = $this->l('Repricing');
  3122. $view_params['tabs']['repricing_selected'] = ($selected_tab === 'repricing' ? 'selected' : '');
  3123.  
  3124. $view_params['tabs']['tools'] = $this->l('Tools');
  3125. $view_params['tabs']['tools_selected'] = ($selected_tab === 'tools' ? 'selected' : '');
  3126.  
  3127. $view_params['tabs']['cron'] = $this->l('Scheduled Tasks');
  3128. $view_params['tabs']['cron_selected'] = ($selected_tab === 'cron' ? 'selected' : '');
  3129.  
  3130. $view_params['tabs']['debug'] = $this->l('Debug Mode');
  3131. $view_params['tabs']['debug_selected'] = ($selected_tab === 'debug' ? 'selected' : '');
  3132. }
  3133.  
  3134. private function selectedTab()
  3135. {
  3136. return (($selected_tab = Tools::getValue('selected_tab')) ? $selected_tab : 'amazon');
  3137. }
  3138.  
  3139. public function geoFlag($id_lang)
  3140. {
  3141. if (isset($this->config) && isset($this->config['regions'][$id_lang]) && $this->config['regions'][$id_lang]) {
  3142. $region = $this->config['regions'][$id_lang];
  3143. } elseif ($id_lang) {
  3144. $region = Language::getIsoById($id_lang);
  3145. }
  3146.  
  3147. if (!$region) {
  3148. $region = 'na';
  3149. }
  3150.  
  3151. return ($region);
  3152. }
  3153.  
  3154. private function _content()
  3155. {
  3156. $view_params = array();
  3157.  
  3158. // Amazon Tab Content
  3159. //
  3160. $this->_glossary($view_params);
  3161.  
  3162. // Amazon Tab Content
  3163. //
  3164. $this->_amazon($view_params);
  3165.  
  3166. // Informations Tab Content
  3167. //
  3168. $this->_informations($view_params);
  3169.  
  3170. // Informations Tab Content
  3171. //
  3172. $this->_features($view_params);
  3173.  
  3174. // Marketplaces Tabs Content
  3175. //
  3176. foreach (AmazonTools::languages() as $language) {
  3177. $id_lang = $language['id_lang'];
  3178. $country_iso = $language['country_iso_code'];
  3179. $id_country = Country::getByIso($country_iso);
  3180. $this->marketplaceTab($view_params, $id_lang, $id_country);
  3181. }
  3182.  
  3183. // Parameters Tab Content
  3184. //
  3185. $this->_parameters($view_params);
  3186.  
  3187. // Categories Tab
  3188. //
  3189. $this->_categories($view_params);
  3190.  
  3191. // Mappings
  3192. //
  3193. $this->_mapping($view_params);
  3194.  
  3195. // Profiles
  3196. //
  3197. $this->_profiles($view_params);
  3198.  
  3199. // Filters
  3200. //
  3201. $this->_filters($view_params);
  3202.  
  3203. // Filters
  3204. //
  3205. $this->_shipping($view_params);
  3206.  
  3207. // Messaging
  3208. //
  3209. $this->_messaging($view_params);
  3210.  
  3211. // Tools
  3212. //
  3213. $this->_tools($view_params);
  3214.  
  3215. // FBA
  3216. //
  3217. $this->_fba($view_params);
  3218.  
  3219. // Repricing
  3220. //
  3221. $this->_repricing($view_params);
  3222.  
  3223. // Crons
  3224. //
  3225. $this->_cron($view_params);
  3226.  
  3227.  
  3228. // Main Tabs
  3229. $this->_tabs($view_params);
  3230.  
  3231. //
  3232. // Render Body
  3233. //
  3234. $context_param = sprintf('&context_key=%s', AmazonContext::getKey($this->context->shop));
  3235.  
  3236. $view_params['configure'] = array();
  3237. $view_params['configure']['tabs'] = array();
  3238.  
  3239. $view_params['configure']['form_action'] = $_SERVER['REQUEST_URI'];
  3240. $view_params['configure']['id_lang'] = $this->id_lang;
  3241. $view_params['configure']['check_url'] = $this->url.'functions/check.php?'.$context_param.'&instant_token='.$this->config['instant_token'];
  3242. $view_params['configure']['check_msg_region'] = $this->l('You must select first a platform');
  3243. $view_params['configure']['check_msg_currency'] = $this->l('You must select first a currency');
  3244. $view_params['configure']['selected_tab'] = $this->selectedTab();
  3245.  
  3246. $view_params['configure']['tabs']['amazon'] = $this->path.self::$templates[self::TEMPLATE_TAB_AMAZON];
  3247. $view_params['configure']['tabs']['informations'] = $this->path.self::$templates[self::TEMPLATE_TAB_INFO];
  3248. $view_params['configure']['tabs']['features'] = $this->path.self::$templates[self::TEMPLATE_TAB_FEATURES];
  3249.  
  3250. $view_params['configure']['tabs']['settings'] = $this->path.self::$templates[self::TEMPLATE_TAB_SETTINGS];
  3251. $view_params['configure']['tabs']['parameters'] = $this->path.self::$templates[self::TEMPLATE_TAB_PARAMETERS];
  3252. $view_params['configure']['tabs']['mapping'] = $this->path.self::$templates[self::TEMPLATE_TAB_MAPPING];
  3253. $view_params['configure']['tabs']['categories'] = $this->path.self::$templates[self::TEMPLATE_TAB_CATEGORIES];
  3254. $view_params['configure']['tabs']['profiles'] = $this->path.self::$templates[self::TEMPLATE_TAB_PROFILES];
  3255. $view_params['configure']['tabs']['filters'] = $this->path.self::$templates[self::TEMPLATE_TAB_FILTERS];
  3256. $view_params['configure']['tabs']['shipping'] = $this->path.self::$templates[self::TEMPLATE_TAB_SHIPPING];
  3257. $view_params['configure']['tabs']['messaging'] = $this->path.self::$templates[self::TEMPLATE_TAB_MESSAGING];
  3258.  
  3259. $view_params['configure']['tabs']['fba'] = $this->path.self::$templates[self::TEMPLATE_TAB_FBA];
  3260.  
  3261. $view_params['configure']['tabs']['repricing'] = $this->path.self::$templates[self::TEMPLATE_TAB_REPRICING];
  3262.  
  3263. $view_params['configure']['tabs']['tools'] = $this->path.self::$templates[self::TEMPLATE_TAB_TOOLS];
  3264. $view_params['configure']['tabs']['cron'] = $this->path.self::$templates[self::TEMPLATE_TAB_CRON];
  3265. $view_params['configure']['tabs']['glossary'] = $this->path.self::$templates[self::TEMPLATE_TAB_GLOSSARY];
  3266.  
  3267. $view_params['class_warning'] = 'warn '.($this->ps16x ? 'alert alert-warning' : '');
  3268. $view_params['class_error'] = 'error '.($this->ps16x ? 'alert alert-danger' : '');
  3269. $view_params['class_success'] = 'confirm '.($this->ps16x ? 'alert alert-success' : 'conf');
  3270. $view_params['class_info'] = 'hint '.($this->ps16x ? 'alert alert-info' : 'conf');
  3271.  
  3272. //
  3273. // Render Smarty
  3274. //
  3275. $this->context->smarty->assign($view_params);
  3276.  
  3277.  
  3278. $this->_html .= $this->context->smarty->fetch($this->path.self::$templates[self::TEMPLATE_TABS]);
  3279.  
  3280.  
  3281. $this->_html .= $this->context->smarty->fetch($this->path.self::$templates[self::TEMPLATE_CONFIGURE]);
  3282.  
  3283. // Footer
  3284. //
  3285. $footer_params = array();
  3286. $footer_params['footer']['text_footer'] = $this->l('This information is provided by The Amazon Marketplace. Please go to the following url to subscribe to these services');
  3287.  
  3288. $this->context->smarty->assign($footer_params);
  3289.  
  3290. $this->_html .= $this->context->smarty->fetch($this->path.self::$templates[self::TEMPLATE_FOOTER]);
  3291. }
  3292.  
  3293. private function _amazon(&$view_params)
  3294. {
  3295. $view_params['amazon']['selected_tab'] = $this->selectedTab() === 'amazon' ? true : false;
  3296. $view_params['amazon']['images'] = $this->images;
  3297. $view_params['amazon']['name'] = $this->displayName;
  3298. $view_params['amazon']['description'] = $this->description;
  3299. $view_params['amazon']['documentation'] = AmazonSupport::gethreflink();
  3300. $view_params['amazon']['images_url'] = $this->images;
  3301. $view_params['amazon']['version'] = $this->version;
  3302. $view_params['amazon']['ps_version'] = _PS_VERSION_;
  3303. $view_params['amazon']['is_lite'] = isset($this->amazon_features['module']) && $this->amazon_features['module'] == 'amazonlite';
  3304.  
  3305. $current_lang = $this->context->language->iso_code;
  3306. $view_params['amazon']['lang'] = $current_lang;
  3307. $view_params['amazon']['lang_fr'] = $current_lang == 'fr';
  3308.  
  3309. $view_params['amazon']['support_info'] = array();
  3310. $view_params['amazon']['support_info']['subject'] = $this->l('Support for Amazon');
  3311. $view_params['amazon']['support_info']['body'] = sprintf($this->l('Hi, I have a problem with my amazon module v%s on Pretashop v%s.'), $this->version, _PS_VERSION_);
  3312.  
  3313. return ($view_params);
  3314. }
  3315.  
  3316. private function _glossary(&$view_params)
  3317. {
  3318. $lang_admin = Language::getIsoById($this->id_lang);
  3319.  
  3320. switch ($lang_admin) {
  3321. case 'fr':
  3322. case 'it':
  3323. case 'de':
  3324. case 'es':
  3325. break;
  3326. default:
  3327. $lang_admin = 'en';
  3328. }
  3329.  
  3330. $view_params['glossary'] = AmazonSettings::getGlossary($lang_admin, 'configuration');
  3331.  
  3332.  
  3333. return ($view_params);
  3334. }
  3335.  
  3336. private function _informations(&$view_params)
  3337. {
  3338. require_once(dirname(__FILE__).'/classes/amazon.certificates.class.php');
  3339. require_once(dirname(__FILE__).'/classes/amazon.configuration_check.class.php');
  3340.  
  3341. if ((bool)Configuration::get('PS_FORCE_SMARTY_2') == true) {
  3342. die(sprintf(html_entity_decode('&lt;div class="error"&gt;%s&lt;/span&gt;'), Tools::displayError('This module is not compatible with Smarty v2. Please switch to Smarty v3 in Preferences Tab.')));
  3343. }
  3344.  
  3345. $lang = Language::getIsoById($this->id_lang);
  3346.  
  3347. // Display only if the module seems to be configured
  3348. //
  3349. $display = true;
  3350. foreach (array(
  3351. 'actives',
  3352. 'amazon_merchant_ids',
  3353. 'amazon_marketplace_ids',
  3354. 'amazon_key_ids',
  3355. 'amazon_secret_ids'
  3356. ) as $configuration_item) {
  3357. if (!is_array($this->config[$configuration_item]) || !count($this->config[$configuration_item]) || !max($this->config[$configuration_item])) {
  3358. $display = false;
  3359. }
  3360. }
  3361.  
  3362. $php_infos = array();
  3363. $prestashop_infos = array();
  3364. $env_infos = array();
  3365. $module_infos = array();
  3366. $prestashop_info_ok = $php_info_ok = true;
  3367.  
  3368. $currentVersion = Configuration::get('AMAZON_CURRENT_VERSION', null, 0, 0);
  3369. $update_mode = false;
  3370.  
  3371. if ($currentVersion && version_compare($this->version, $currentVersion, '>')) {
  3372. $module_infos['update'] = array();
  3373. $module_infos['update']['message'] = sprintf($this->l('Module Update: Your version will be auto-updated from %s to %s after configuration changes'), $currentVersion, $this->version);
  3374. $module_infos['update']['message'] .= ' - '.$this->l('Please verify again your settings. Please clear your Smarty and Browser caches...');
  3375. $module_infos['update']['tutorial'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_AFTER_INSTALLATION);
  3376. $module_infos['update']['level'] = 'info '.($this->ps16x ? 'alert alert-warning' : 'warn');
  3377. $module_infos['update']['display'] = true;
  3378. $update_mode = true;
  3379. }
  3380.  
  3381. if (!$update_mode) {
  3382. if ($this->config['features']['creation'] && (!AmazonValidValues::tableExists() || !AmazonValidValues::lastImport())) {
  3383. $module_infos['valid_values'] = array();
  3384. $module_infos['valid_values']['message'] = $this->l('You should import Amazon valid values table from Tools tab');
  3385. $module_infos['valid_values']['level'] = 'info '.($this->ps16x ? 'alert alert-info' : '');
  3386. $module_infos['valid_values']['display'] = true;
  3387. }
  3388.  
  3389. if (!AmazonTools::tableExists(_DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS)) {
  3390. $module_infos['missing_table_options'] = array();
  3391. $module_infos['missing_table_options']['message'] = sprintf('%s: %s', $this->l('Missing required table'), _DB_PREFIX_.Amazon::TABLE_MARKETPLACE_OPTIONS);
  3392. $module_infos['missing_table_options']['level'] = 'error '.($this->ps16x ? 'alert alert-danger' : '');
  3393. $module_infos['missing_table_options']['display'] = true;
  3394. }
  3395. if (!AmazonTools::tableExists(_DB_PREFIX_.Amazon::TABLE_MARKETPLACE_ACTIONS)) {
  3396. $module_infos['missing_table_action'] = array();
  3397. $module_infos['missing_table_action']['message'] = sprintf('%s: %s', $this->l('Missing required table'), _DB_PREFIX_.Amazon::TABLE_MARKETPLACE_ACTIONS);
  3398. $module_infos['missing_table_action']['level'] = 'error '.($this->ps16x ? 'alert alert-danger' : '');
  3399. $module_infos['missing_table_action']['display'] = true;
  3400. }
  3401. if (!AmazonTools::tableExists(_DB_PREFIX_.Amazon::TABLE_MARKETPLACE_ORDERS)) {
  3402. $module_infos['missing_table_orders'] = array();
  3403. $module_infos['missing_table_orders']['message'] = sprintf('%s: %s', $this->l('Missing required table'), _DB_PREFIX_.Amazon::TABLE_MARKETPLACE_ORDERS);
  3404. $module_infos['missing_table_orders']['level'] = 'error '.($this->ps16x ? 'alert alert-danger' : '');
  3405. $module_infos['missing_table_orders']['display'] = true;
  3406. }
  3407.  
  3408.  
  3409. if ($this->config['features']['expert_mode']) {
  3410. $module_infos['expert_mode'] = array();
  3411. $module_infos['expert_mode']['message'] = $this->l('Expert Mode is active');
  3412. $module_infos['expert_mode']['level'] = 'info '.($this->ps16x ? 'alert alert-warning' : 'warn');
  3413. $module_infos['expert_mode']['display'] = true;
  3414. }
  3415.  
  3416. if ($this->config['debug']) {
  3417. $module_infos['debug'] = array();
  3418. $module_infos['debug']['message'] = $this->l('Debug Mode is activated, what is not recommended');
  3419. $module_infos['debug']['level'] = 'info '.($this->ps16x ? 'alert alert-warning' : 'warn');
  3420. $module_infos['debug']['display'] = true;
  3421. }
  3422.  
  3423. if ($this->config['categories'] !== false && !is_array($this->config['categories']) || !count($this->config['categories'])) {
  3424. $module_infos['categories'] = array();
  3425. $module_infos['categories']['message'] = $this->l('You didn\'t checked yet any category, in category tab');
  3426. $module_infos['categories']['level'] = 'info '.($this->ps16x ? 'alert alert-warning' : 'warn');
  3427. $module_infos['categories']['display'] = true;
  3428. }
  3429.  
  3430. if (!$this->active) {
  3431. $module_infos['inactive'] = array();
  3432. $module_infos['inactive']['message'] = $this->l('Be careful, your module is inactive, this mode stops all pending operations for this module, please change the status to active in your module list');
  3433. $module_infos['inactive']['level'] = 'info '.($this->ps16x ? 'alert alert-warning' : 'warn');
  3434. $module_infos['inactive']['display'] = true;
  3435. }
  3436.  
  3437. $dirs = array(
  3438. _PS_MODULE_DIR_.MODULE_AMAZON.''.DIRECTORY_SEPARATOR.'validate'.DIRECTORY_SEPARATOR.'xsd',
  3439. _PS_MODULE_DIR_.MODULE_AMAZON.''.DIRECTORY_SEPARATOR.'export',
  3440. _PS_MODULE_DIR_.MODULE_AMAZON.''.DIRECTORY_SEPARATOR.'import',
  3441. _PS_MODULE_DIR_.MODULE_AMAZON.''.DIRECTORY_SEPARATOR.'settings'
  3442. );
  3443.  
  3444. $messages = array();
  3445.  
  3446. if ($this->amazon_features['creation']) {
  3447. foreach ($dirs as $dir) {
  3448. if (!AmazonTools::isDirWriteable($dir)) {
  3449. $messages[] = sprintf($this->l('You have to set write permissions to the %s directory'), $dir);
  3450. }
  3451. }
  3452. }
  3453.  
  3454. if (is_array($messages) && count($messages)) {
  3455. foreach ($messages as $key => $message) {
  3456. $module_infos['permissions_'.$key] = array();
  3457. $module_infos['permissions_'.$key]['message'] = $message;
  3458. $module_infos['permissions_'.$key]['level'] = 'error '.($this->ps16x ? 'alert alert-danger' : '');
  3459. $module_infos['permissions_'.$key]['tutorial'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_PERMISSIONS);
  3460. $module_infos['permissions_'.$key]['display'] = true;
  3461. }
  3462. }
  3463.  
  3464. // AJAX Checker
  3465. //
  3466. $env_infos['ajax'] = array();
  3467. $env_infos['ajax']['message'] = $this->l('AJAX execution failed. Please, verify first your module configuration. If the problem persists please send a screenshot of this page to the support.');
  3468. $env_infos['ajax']['tutorial'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_DOMAIN);
  3469. $env_infos['ajax']['level'] = 'error '.($this->ps16x ? 'alert alert-danger' : '');
  3470. $env_infos['ajax']['display'] = false;
  3471. $env_infos['ajax']['script'] = array(
  3472. 'name' => 'env_check_url',
  3473. 'url' => $this->url.'functions/check_env.php?action=ajax'
  3474. );
  3475.  
  3476. // Amazon Ping
  3477. //
  3478. $ping_url = $this->url.'functions/check.php?id_lang='.$this->id_lang.'&instant_token='.$this->config['instant_token'].'&action=service-status';
  3479. $ping_debug_url = AmazonTools::getHttpHost(true, true).$ping_url.'&debug=1';
  3480.  
  3481. if ($display) {
  3482. $env_infos['ping'] = array();
  3483. $env_infos['ping']['message'] = sprintf($this->l('Unable to ping Amazon. Please provide this URL to the support: %s'), $ping_debug_url);
  3484. $env_infos['ping']['level'] = 'error '.($this->ps16x ? 'alert alert-danger' : '');
  3485. $env_infos['ping']['display'] = false;
  3486. $env_infos['ping']['tutorial'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_PING);
  3487. $env_infos['ping']['script'] = array(
  3488. 'name' => 'service_check_url',
  3489. 'url' => $ping_url
  3490. );
  3491. }
  3492. }
  3493.  
  3494. // max_input_var Checker
  3495. //
  3496. $env_infos['miv'] = array();
  3497. $env_infos['miv']['message'] = sprintf($this->l('Your PHP configuration limits the maximum number of fields to post in a form : %s for max_input_vars. Please ask your hosting provider to increase this limit.'), ini_get('max_input_vars'));
  3498. $env_infos['miv']['tutorial'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_PHP);
  3499. $env_infos['miv']['level'] = $this->ps16x ? 'alert alert-danger' : 'error';
  3500. $env_infos['miv']['display'] = false;
  3501. $env_infos['miv']['script'] = array('name' => 'max_input_vars');
  3502.  
  3503. if (AmazonTools::tableExists(_DB_PREFIX_.'configuration') === null) {
  3504. $env_infos['show_tables_failed'] = array();
  3505. $env_infos['show_tables_failed']['message'] = sprintf('%s: %s', $this->l('Your hosting doesnt allow'), 'SHOW TABLES');
  3506. $env_infos['show_tables_failed']['level'] = 'error '.($this->ps16x ? 'alert alert-danger' : '');
  3507. $env_infos['show_tables_failed']['display'] = true;
  3508. $env_infos['show_tables_failed']['script'] = array('name' => 'show_tables');
  3509. }
  3510.  
  3511.  
  3512.  
  3513.  
  3514.  
  3515. // PHP Configuration Check
  3516. //
  3517. if (in_array(Tools::strtolower(@ini_get('display_errors')), array('1', 'on'))) {
  3518. $php_infos['display_error']['message'] = $this->l('PHP display_errors is On.');
  3519. $php_infos['display_error']['level'] = 'info '.($this->ps16x ? 'alert alert-info' : '');
  3520. }
  3521.  
  3522. if (!function_exists('curl_init')) {
  3523. $php_infos['curl'] = array();
  3524. $php_infos['curl']['message'] = $this->l('PHP cURL must be installed on this server. The module require the cURL library and can\'t work without it');
  3525. $php_infos['curl']['level'] = 'error '.($this->ps16x ? 'alert alert-danger' : '');
  3526. $php_infos['curl']['link'] = 'http://php.net/manual/'.$lang.'/book.curl.php';
  3527. }
  3528. if (!function_exists('hash_hmac')) {
  3529. $php_infos['curl'] = array();
  3530. $php_infos['curl']['message'] = $this->l('PHP Hash must be installed on this server. The module require the Hash library and can\'t work without it');
  3531. $php_infos['curl']['level'] = $this->ps16x ? 'alert alert-danger' : 'error';
  3532. $php_infos['curl']['link'] = 'http://php.net/manual/'.$lang.'/book.hash.php';
  3533. }
  3534.  
  3535. if (!function_exists('mb_convert_encoding')) {
  3536. $php_infos['multibyte'] = array();
  3537. $php_infos['multibyte']['message'] = $this->l('Multibyte PHP Library must be installed on this server. The module require the mb functions and can\'t work without it');
  3538. $php_infos['multibyte']['level'] = $this->ps16x ? 'alert alert-danger' : 'error';
  3539. $php_infos['multibyte']['link'] = 'http://php.net/manual/'.$lang.'/ref.mbstring.php';
  3540. }
  3541.  
  3542. if (!method_exists('DOMDocument', 'createElement')) {
  3543. $php_infos['dom'] = array();
  3544. $php_infos['dom']['message'] = $this->l('PHP DOMDocument (XML Library) must be installed on this server. The module require this library and can\'t work without it');
  3545. $php_infos['dom']['level'] = 'error '.($this->ps16x ? 'alert alert-danger' : '');
  3546. $php_infos['dom']['link'] = 'http://php.net/manual/'.$lang.'/class.domdocument.php';
  3547. }
  3548.  
  3549.  
  3550. if (($max_execution_time = ini_get('max_execution_time')) && $max_execution_time < 120) {
  3551. $php_infos['max_execution_time']['message'] = sprintf($this->l('PHP value: max_execution_time recommended value is at least 120. your limit is currently set to %d'), $max_execution_time);
  3552. $php_infos['max_execution_time']['level'] = 'warn '.($this->ps16x ? 'alert alert-warning' : '');
  3553. $php_infos['max_execution_time']['tutorial'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_PHP);
  3554. }
  3555.  
  3556. $disable_functions = array_map('trim', explode(',', ini_get('disable_functions')));
  3557.  
  3558. if (is_array($disable_functions) && count($disable_functions)) {
  3559. if (in_array('parse_ini_file', $disable_functions)) {
  3560. $php_infos['parse_ini_file']['message'] = $this->l('PHP function: parse_ini_file() should be enabled. The module requires this function to display some translations.');
  3561. $php_infos['parse_ini_file']['level'] = 'warn '.($this->ps16x ? 'alert alert-warning' : '');
  3562. }
  3563.  
  3564. if (in_array('phpinfo', $disable_functions)) {
  3565. $php_infos['parse_ini_file']['message'] = $this->l('PHP function: phpinfo() should be enabled. The module requires this function to provide some diags.');
  3566. $php_infos['parse_ini_file']['level'] = 'warn '.($this->ps16x ? 'alert alert-warning' : '');
  3567. }
  3568. }
  3569.  
  3570. $recommended_memory_limit = 128;
  3571. if ($memory_limit = AmazonConfigurationCheck::getMemoryLimit() < $recommended_memory_limit) {
  3572. $php_infos['memory']['message'] = sprintf($this->l('PHP value: memory_limit recommended value is at least %sMB. your limit is currently set to %sMB'), $recommended_memory_limit, $memory_limit);
  3573. $php_infos['memory']['level'] = 'warn '.($this->ps16x ? 'alert alert-warning' : '');
  3574. $php_infos['memory']['tutorial'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_PHP);
  3575. }
  3576.  
  3577. // Prestashop Configuration Check
  3578. //
  3579. if (!(int)Configuration::get('PS_SHOP_ENABLE')) {
  3580. $prestashop_infos['maintenance']['message'] = $this->l('Be careful, your shop is in maintenance mode, the module might not work in that mode');
  3581. $prestashop_infos['maintenance']['level'] = 'warn '.($this->ps16x ? 'alert alert-warning' : '');
  3582. }
  3583.  
  3584. if (defined('_PS_MODE_DEV_') && _PS_MODE_DEV_ === true) {
  3585. $prestashop_infos['mod_dev']['message'] = $this->l('Prestashop _PS_MODE_DEV_ is active.');
  3586. $prestashop_infos['mod_dev']['level'] = 'info '.($this->ps16x ? 'alert alert-info' : '');
  3587. $prestashop_infos['mod_dev']['id'] = 'prestashop-info-dev';
  3588. }
  3589.  
  3590. if ((bool)Configuration::get('PS_CATALOG_MODE')) {
  3591. $prestashop_infos['catalog']['message'] = $this->l('Your store is in catalog mode, you won\'t be able to import orders, you can switch off this mode in Preferences > Products tab');
  3592. $prestashop_infos['catalog']['level'] = 'warn '.($this->ps16x ? 'alert alert-warning' : '');
  3593. }
  3594.  
  3595. if (AmazonConfigurationCheck::hasOverrides()) {
  3596. $prestashop_infos['overrides']['message'] = $this->l('Your Prestashop potentially runs some overrides. This information is necessary only in case of support');
  3597. $prestashop_infos['overrides']['level'] = 'info '.($this->ps16x ? 'alert alert-info' : '');
  3598. }
  3599.  
  3600. if (!AmazonConfigurationCheck::checkShopUrl()) {
  3601. $prestashop_infos['wrong_domain']['message'] = $this->l('Your are currently connected with the following domain name:').
  3602. html_entity_decode(' &lt;span style="color:navy"&gt;'.$_SERVER['HTTP_HOST'].'&lt;/span&gt;').nl2br("").
  3603. $this->l('This one is different from the main store domain name set in \"Preferences > SEO & URLs\":').
  3604. html_entity_decode(' &lt;span style="color:green"&gt;'.Configuration::get('PS_SHOP_DOMAIN').'&lt;/span&gt;');
  3605. $prestashop_infos['wrong_domain']['level'] = 'error '.($this->ps16x ? 'alert alert-danger' : '');
  3606. $prestashop_infos['wrong_domain']['tutorial'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_DOMAIN);
  3607. }
  3608.  
  3609. if (AmazonConfiguration::shopIsFeatureActive() && in_array($this->context->shop->getContext(), array(Shop::CONTEXT_GROUP, Shop::CONTEXT_ALL))) {
  3610. $prestashop_infos['multistore']['message'] = $this->l('You are in multishop environment. To use Amazon module, you must select a target shop.');
  3611. $prestashop_infos['multistore']['level'] = 'warn '.($this->ps16x ? 'alert alert-warning' : '');
  3612. $prestashop_infos['multistore']['tutorial'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_MULTISTORE);
  3613. }
  3614.  
  3615. foreach (array('birthday', 'company', 'siret', 'optin', 'newsletter') as $field) {
  3616. if (!AmazonConfigurationCheck::mandatoryCustomerField($field)) {
  3617. $prestashop_infos[$field.'_issue']['message'] = sprintf($this->l('%s field is required, this is not a required value by default in Prestashop core program. This configuration is not allowed by Marketplaces modules. Please fix it!'), AmazonTools::ucfirst($field));
  3618. $prestashop_infos[$field.'_issue']['level'] = 'error '.($this->ps16x ? 'alert alert-danger' : '');
  3619. }
  3620. }
  3621.  
  3622. if (!AmazonConfigurationCheck::checkAddress()) {
  3623. $prestashop_infos['phone_issue']['message'] = $this->l('Phone field is not required by default, but required in your configuration. This configuration is not allowed by Marketplaces modules. Please fix it !');
  3624. $prestashop_infos['phone_issue']['level'] = $this->ps16x ? 'alert alert-danger' : 'error';
  3625. }
  3626.  
  3627. // Check Orders States
  3628. //
  3629. $i = 0;
  3630. $order_states = array('ORDER_STATE', 'PREPARATION_STATE', 'SENT_STATE');
  3631.  
  3632. if ($this->amazon_features['cancel_orders']) {
  3633. $order_states[] = 'CANCELED_STATE';
  3634. }
  3635.  
  3636. foreach ($order_states as $order_state_config) {
  3637. $id_order_state = AmazonConfiguration::get($order_state_config);
  3638.  
  3639. if ($id_order_state) {
  3640. if (is_array($id_order_state) && count($id_order_state)) {
  3641. // new format
  3642.  
  3643. $check_states = $id_order_state;
  3644. } elseif (is_numeric($id_order_state)) {
  3645. $check_states = array($id_order_state);
  3646. } else {
  3647. continue;
  3648. }
  3649.  
  3650. foreach ($check_states as $id_order_state) {
  3651. $order_state = new OrderState($id_order_state, $this->id_lang);
  3652.  
  3653. if (Validate::isLoadedObject($order_state)) {
  3654. if ($order_state->send_email) {
  3655. $prestashop_infos['mail'.$i]['message'] = sprintf($this->l('The order status: \"%s\" automatically send an email. This is not allowed by Amazon. Please configure another order status.'), $order_state->name);
  3656. $prestashop_infos['mail'.$i]['level'] = 'warn '.($this->ps16x ? 'alert alert-warning' : '');
  3657. $prestashop_infos['mail'.$i]['tutorial'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_NO_MAIL);
  3658. $i++;
  3659. }
  3660. }
  3661. }
  3662. }
  3663. }
  3664.  
  3665. if (!AmazonConfigurationCheck::checkCountryConsistency()) {
  3666. $prestashop_infos['locale_country']['message'] = sprintf('Inconsistency in localization settings, country code: "%s"', Configuration::get('PS_LOCALE_COUNTRY'));
  3667. $prestashop_infos['locale_country']['level'] = $this->ps16x ? 'alert alert-danger' : 'error';
  3668. }
  3669.  
  3670. $lang_iso_code = Tools::strtolower(Configuration::get('PS_LOCALE_LANGUAGE'));
  3671. $pass = true;
  3672. $level = $this->ps16x ? 'alert alert-danger' : 'error';
  3673.  
  3674. if (!empty($lang_iso_code)) {
  3675. if (!Validate::isLanguageIsoCode($lang_iso_code) || !Language::getIdByIso($lang_iso_code)) {
  3676. $pass = false;
  3677. $message = 'Localization > Locale Language setting doesnt match any lang in Prestashop tables';
  3678. } elseif (!AmazonTools::lang2MarketplaceId($lang_iso_code)) {
  3679. $pass = false;
  3680. $message = 'Support Info: Localization > Locale Language setting doesnt match any Amazon platform';
  3681. $level = 'info '.($this->ps16x ? 'alert alert-info' : '');
  3682. }
  3683. } else {
  3684. $message = 'Localization > Locale Language setting is empty !';
  3685. $pass = false;
  3686. }
  3687.  
  3688. if (!$pass) {
  3689. $prestashop_infos['locale_lang']['message'] = sprintf('%s: "%s"', $message, $lang_iso_code);
  3690. $prestashop_infos['locale_lang']['level'] = $level;
  3691. }
  3692.  
  3693. if (!AmazonCertificates::getDefaultCertificatePath()) {
  3694. $prestashop_infos['certificate']['message'] = sprintf('Unable to read default certificate (%s), please countact our support', AmazonCertificates::getDefaultCertificatePath());
  3695. $prestashop_infos['certificate']['level'] = $this->ps16x ? 'alert alert-danger' : 'error';
  3696. }
  3697.  
  3698. if (!count($prestashop_infos)) {
  3699. $prestashop_info_ok = true;
  3700. } else {
  3701. $prestashop_info_ok = false;
  3702. }
  3703.  
  3704. if (!count($php_infos)) {
  3705. $php_info_ok = true;
  3706. } else {
  3707. $php_info_ok = false;
  3708. }
  3709.  
  3710. $context_key = AmazonContext::getKey($this->context->shop);
  3711.  
  3712. $max_input_vars = @ini_get('max_input_vars');
  3713.  
  3714. $view_params['informations']['selected_tab'] = $this->selectedTab() === 'informations' ? true : false;
  3715. $view_params['informations']['images'] = $this->images;
  3716. $view_params['informations']['display'] = $display;
  3717. $view_params['informations']['module_infos'] = $module_infos;
  3718. $view_params['informations']['env_infos'] = $env_infos;
  3719. $view_params['informations']['php_infos'] = $php_infos;
  3720. $view_params['informations']['php_info_ok'] = $php_info_ok;
  3721. $view_params['informations']['prestashop_infos'] = $prestashop_infos;
  3722. $view_params['informations']['prestashop_info_ok'] = $prestashop_info_ok;
  3723. $view_params['informations']['mode_dev'] = defined('_PS_MODE_DEV_') && _PS_MODE_DEV_;
  3724. $view_params['informations']['support_informations_url'] = self::$usefull_urls['check'] = $this->url.'functions/check.php?id_lang='.$this->id_lang.'&instant_token='.$this->config['instant_token'].'&context_key='.$context_key;
  3725. $view_params['informations']['max_input_vars'] = $max_input_vars;
  3726. $view_params['informations']['tutorial'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_PHP);
  3727.  
  3728. return ($view_params);
  3729. }
  3730.  
  3731. private function _features(&$view_params)
  3732. {
  3733. $view_params['features']['selected_tab'] = $this->selectedTab() === 'features' ? true : false;
  3734. $view_params['features']['images'] = $this->images;
  3735. $view_params['features']['experimental'] = self::ENABLE_EXPERIMENTAL_FEATURES;
  3736. $view_params['features']['documentation'] = AmazonSupport::gethreflink();
  3737. $view_params['features']['tutorial'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_FEATURES);
  3738. $view_params['features']['images_url'] = $this->images;
  3739. $view_params['features']['version'] = $this->version;
  3740. $view_params['features']['ps_version'] = _PS_VERSION_;
  3741.  
  3742. $view_params['features']['links'] = array();
  3743. $view_params['features']['links']['synchronization'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_SYNCHRONIZATION);
  3744. $view_params['features']['links']['creation'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_CREATION);
  3745. $view_params['features']['links']['second_hand'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_SECOND_HAND);
  3746. $view_params['features']['links']['prices_rules'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_PRICES_RULES);
  3747. $view_params['features']['links']['europe'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_EUROPE);
  3748. $view_params['features']['links']['orders'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_ORDERS_IMPORT);
  3749. $view_params['features']['links']['gcid'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_GCID);
  3750. $view_params['features']['links']['filters'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_FILTERS);
  3751. $view_params['features']['links']['import_products'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_IMPORT_PRODUCTS);
  3752. $view_params['features']['links']['offers'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_OFFERS);
  3753. $view_params['features']['links']['fba'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_FBA);
  3754. $view_params['features']['links']['repricing'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_REPRICING);
  3755. $view_params['features']['links']['remote_cart'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_REMOTE_CART);
  3756. $view_params['features']['links']['shipping_template'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_SHIPPING_TEMPLATE);
  3757. $view_params['features']['links']['messaging'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_MESSAGING);
  3758. $view_params['features']['links']['cancel_orders'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_CANCEL_ORDERS);
  3759. $view_params['features']['links']['expert_mode'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_EXPERT_MODE);
  3760. $view_params['features']['links']['debug_express'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_DEBUG_EXPRESS);
  3761. $view_params['features']['links']['business'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_BUSINESS);
  3762. $view_params['features']['links']['orders_reports'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_BUSINESS);
  3763.  
  3764. if ((bool)$this->config['features']['amazon_europe'] || (bool)AmazonConfiguration::get('EUROPE')/*retro-compatibility*/) {
  3765. $this->config['features']['amazon_europe'] = true;
  3766. } else {
  3767. $this->config['features']['amazon_europe'] = false;
  3768. }
  3769.  
  3770. if ((bool)$this->config['features']['expert_mode']) {
  3771. $this->config['features']['expert_mode'] = true;
  3772. } else {
  3773. $this->config['features']['expert_mode'] = false;
  3774. }
  3775.  
  3776. $this->config['features']['debug_mode'] = (bool)$this->config['debug']; //retro-compatibility
  3777.  
  3778. $view_params['features']['config'] = $this->config['features'];
  3779.  
  3780. $view_params['features']['config']['noway'] = in_array($this->config['features']['module'], array('amazonlite', 'ready')) ? true : false;
  3781.  
  3782. $view_params['features']['validation'] = $this->_validate(true);
  3783.  
  3784. return ($view_params);
  3785. }
  3786.  
  3787. /**
  3788. * @param $view_params
  3789. * @param int $id_lang
  3790. * @param int $id_country
  3791. * @return mixed
  3792. * @throws PrestaShopDatabaseException
  3793. * @throws PrestaShopException
  3794. */
  3795. private function marketplaceTab(&$view_params, $id_lang, $id_country)
  3796. {
  3797. $selected_tab = $this->selectedTab();
  3798.  
  3799. // Langue Active
  3800. //
  3801. $actives = $this->config['actives'];
  3802.  
  3803. // Locales
  3804. //
  3805. $regions = $this->config['regions'];
  3806. $currencies = $this->config['currencies'];
  3807. $selected_currency = isset($currencies[$id_lang]) ? $currencies[$id_lang] : null;
  3808.  
  3809. $synch_field = null;
  3810.  
  3811. $active = isset($actives[$id_lang]) ? (int)$actives[$id_lang] : '';
  3812. $region = isset($regions[$id_lang]) ? $regions[$id_lang] : null;
  3813.  
  3814. $currency_tab = Currency::getCurrencies(false, false);
  3815. $current_currency = null;
  3816.  
  3817. if (is_array($currency_tab) && count($currency_tab) && isset($this->config['currencies'][$id_lang])) {
  3818. foreach ($currency_tab as $currency) {
  3819. if ($currency['iso_code'] == $this->config['currencies'][$id_lang] || $selected_currency == $currency['iso_code']) {
  3820. $current_currency = $currency;
  3821. }
  3822. }
  3823. }
  3824.  
  3825. // Carriers
  3826. $incoming_carrier_amazon = isset($this->config['incoming_carrier_amazon'][$id_lang]) ? $this->config['incoming_carrier_amazon'][$id_lang] : array(null);
  3827. $incoming_carrier_prestashop = isset($this->config['incoming_carrier_prestashop'][$id_lang]) ? $this->config['incoming_carrier_prestashop'][$id_lang] : array(null);
  3828. $outgoing_carriers = isset($this->config['outgoing_carrier'][$id_lang]['prestashop']) && is_array($this->config['outgoing_carrier'][$id_lang]['prestashop']) ? $this->config['outgoing_carrier'][$id_lang] : array('prestashop' => array(null));
  3829.  
  3830. require_once(_PS_MODULE_DIR_.'/amazon/classes/amazon.preconfiguration.class.php');
  3831.  
  3832. if (AmazonConfiguration::get('ACTIVE') == false) {
  3833. if (($preconfiguration = AmazonPreconfiguration::data($id_lang))) {
  3834. $active = true;
  3835. $region = $preconfiguration['region'];
  3836. $selected_currency = $preconfiguration['currency'];
  3837. $incoming_carrier_amazon = $preconfiguration['amazon_incoming_carrier'];
  3838. $incoming_carrier_prestashop = $preconfiguration['prestashop_incoming_carrier'];
  3839. $outgoing_carriers = $preconfiguration['outgoing_carriers'];
  3840. $synch_field = $preconfiguration['synchronization_field'];
  3841. }
  3842. }
  3843.  
  3844. // First Initialization
  3845. //
  3846. if (!isset($view_params['settings']) || !is_array($view_params['settings'])) {
  3847. $view_params['settings'] = array();
  3848. $view_params['settings']['images_url'] = $this->images;
  3849. $view_params['settings']['tutorial_1'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_SETTINGS);
  3850. $view_params['settings']['tutorial_2'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_KEYPAIRS);
  3851.  
  3852. $view_params['settings']['validate'] = array();
  3853.  
  3854. $view_params['settings']['locales'] = array();
  3855. $view_params['settings']['locales']['config'] = array();
  3856. $view_params['settings']['locales']['platforms'] = $this->_platforms;
  3857. $view_params['settings']['locales']['currencies'] = $currency_tab;
  3858. $view_params['settings']['locales']['selected_tab'] = $selected_tab;
  3859.  
  3860. $view_params['settings']['marketplace'] = array();
  3861. $view_params['settings']['marketplace']['config'] = array();
  3862.  
  3863. $view_params['settings']['general'] = array(
  3864. 'config' => array(),
  3865. 'expert_mode' => (bool)$this->config['features']['expert_mode']
  3866. );
  3867.  
  3868. $view_params['settings']['carriers'] = array();
  3869. $view_params['settings']['carriers']['config'] = array();
  3870. $view_params['settings']['carriers']['config']['incoming'] = array();
  3871. $view_params['settings']['carriers']['config']['outgoing'] = array();
  3872. $view_params['settings']['carriers']['config']['fba_multichannel'] = array();
  3873. $view_params['settings']['carriers']['fba_multichannel'] = (bool)$this->config['fba_multichannel'];
  3874.  
  3875. $view_params['settings']['overrides'] = array();
  3876. $view_params['settings']['overrides']['standard'] = array();
  3877. $view_params['settings']['overrides']['express'] = array();
  3878. $view_params['settings']['overrides']['allow'] = false;
  3879. }
  3880.  
  3881. $language = new Language($id_lang);
  3882.  
  3883. if (!Validate::isLoadedObject($language)) {
  3884. return ($view_params);
  3885. }
  3886.  
  3887. // Amazon API Configuration
  3888. //
  3889. $merchantId = isset($this->config['amazon_merchant_ids'][$id_lang]) ? trim($this->config['amazon_merchant_ids'][$id_lang]) : '';
  3890. $awsKeyId = isset($this->config['amazon_key_ids'][$id_lang]) ? trim($this->config['amazon_key_ids'][$id_lang]) : '';
  3891. $awsSecretKey = isset($this->config['amazon_secret_ids'][$id_lang]) ? trim($this->config['amazon_secret_ids'][$id_lang]) : '';
  3892. $mwsToken = isset($this->config['amazon_mws_token'][$id_lang]) ? trim($this->config['amazon_mws_token'][$id_lang]) : '';
  3893. $marketplaceId = isset($this->config['amazon_marketplace_ids'][$id_lang]) ? trim($this->config['amazon_marketplace_ids'][$id_lang]) : '';
  3894.  
  3895. $carriers = &self::$carriers;
  3896.  
  3897. // Locales
  3898. //
  3899. $view_params['settings']['locales']['config'][$id_lang]['iso_code'] = $language->iso_code;
  3900. $view_params['settings']['locales']['config'][$id_lang]['name'] = $language->name;
  3901. $view_params['settings']['locales']['config'][$id_lang]['region'] = $region;
  3902. $view_params['settings']['locales']['config'][$id_lang]['currency'] = $selected_currency;
  3903. $view_params['settings']['locales']['config'][$id_lang]['currency_required'] = !Tools::strlen(trim($selected_currency));
  3904.  
  3905. if (isset($this->_platforms[$region])) {
  3906. $view_params['settings']['locales']['config'][$id_lang]['platform_selected'] = $region;
  3907. $view_params['settings']['locales']['config'][$id_lang]['platform_selected_required'] = false;
  3908. } else {
  3909. $view_params['settings']['locales']['config'][$id_lang]['platform_selected'] = $region;
  3910. $view_params['settings']['locales']['config'][$id_lang]['platform_selected_required'] = true;
  3911. }
  3912.  
  3913. $hasEurope = true;
  3914.  
  3915. // Marketplace Settings
  3916. //
  3917. if ($this->config['features']['amazon_europe'] && empty($this->config['marketplace_master'])) {
  3918. // unconsistency
  3919.  
  3920. $hasEurope = false;
  3921. }
  3922.  
  3923. if ($hasEurope && $this->config['features']['amazon_europe'] && $this->config['marketplace_master'] == $region) {
  3924. $masterPlatform = true;
  3925. } else {
  3926. $masterPlatform = false;
  3927. }
  3928.  
  3929. if (!$hasEurope) {
  3930. $display = '';
  3931. $disabled = '';
  3932. } elseif ($this->config['features']['amazon_europe'] && !$masterPlatform && (AmazonTools::isEurope($region) || $region === 'uk')) {
  3933. $display = 'display:none;';
  3934. $disabled = 'disabled';
  3935. } else {
  3936. $display = '';
  3937. $disabled = '';
  3938. }
  3939.  
  3940. $view_params['settings']['marketplace']['config'][$id_lang]['region'] = $region;
  3941. $view_params['settings']['marketplace']['config'][$id_lang]['merchantId'] = $merchantId ? $merchantId : ' '; // space to avoid form autocomplete
  3942. $view_params['settings']['marketplace']['config'][$id_lang]['merchantId_required'] = !Tools::strlen(trim($merchantId));
  3943. // For Amazon.ca, marketplace id could be either the one from CA (old method) and the one from US (new method)
  3944. $view_params['settings']['marketplace']['config'][$id_lang]['marketPlaceId'] = (in_array($region, array(
  3945. 'ca',
  3946. 'mx'
  3947. )) && $marketplaceId) ? $marketplaceId : AmazonTools::lang2MarketplaceId($region);
  3948.  
  3949.  
  3950.  
  3951. $view_params['settings']['marketplace']['config'][$id_lang]['awsKeyId'] = $awsKeyId ? $awsKeyId : ' '; // space to avoid form autocomplete
  3952. $view_params['settings']['marketplace']['config'][$id_lang]['awsKeyId_required'] = !Tools::strlen(trim($awsKeyId));
  3953. $view_params['settings']['marketplace']['config'][$id_lang]['awsSecretKey'] = $awsSecretKey;
  3954. $view_params['settings']['marketplace']['config'][$id_lang]['awsSecretKey_required'] = !Tools::strlen(trim($awsSecretKey));
  3955. $view_params['settings']['marketplace']['config'][$id_lang]['mwsToken'] = $mwsToken;
  3956.  
  3957. // Determining behaviour
  3958. if ((Tools::strlen($awsKeyId) && Tools::strlen($awsSecretKey)) || (bool)$this->config['features']['expert_mode']) {
  3959. $view_params['settings']['marketplace']['config'][$id_lang]['displayAll'] = true;
  3960. } else {
  3961. $view_params['settings']['marketplace']['config'][$id_lang]['displayAll'] = false;
  3962. }
  3963.  
  3964. $view_params['settings']['marketplace']['config'][$id_lang]['active'] = $active;
  3965. $view_params['settings']['marketplace']['config'][$id_lang]['display'] = $display;
  3966. $view_params['settings']['marketplace']['config'][$id_lang]['disabled'] = $disabled;
  3967. $view_params['settings']['marketplace']['config'][$id_lang]['domain'] = AmazonTools::idToDomain($id_lang);
  3968. $view_params['settings']['marketplace']['config'][$id_lang]['flag'] = html_entity_decode('&lt;img src="'.$this->images.'geo_flags/'.$this->geoFlag($id_lang).'.gif" alt="'.$language->name.'" /&gt;');
  3969.  
  3970.  
  3971. $view_params['settings']['marketplace']['config'][$id_lang]['tutorial'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_API_KEYPAIRS);
  3972.  
  3973. if (isset($this->config['out_of_stock'][$id_lang]) && is_array($this->config['out_of_stock']) && $this->config['out_of_stock'][$id_lang]) {
  3974. $out_of_stock = $this->config['out_of_stock'][$id_lang];
  3975. } else {
  3976. $out_of_stock = '0';
  3977. }
  3978.  
  3979. if (isset($this->config['rounding']) && isset($this->config['rounding'][$id_lang]) && $this->config['rounding'][$id_lang]) {
  3980. $rounding = $this->config['rounding'][$id_lang];
  3981. } else {
  3982. $rounding = self::ROUNDING_NONE;
  3983. }
  3984.  
  3985. if (isset($this->config['sort_order']) && isset($this->config['sort_order'][$id_lang]) && $this->config['sort_order'][$id_lang]) {
  3986. $sort_order = $this->config['sort_order'][$id_lang];
  3987. } else {
  3988. $sort_order = self::SORT_ORDER_FIRSTNAME_LASTNAME;
  3989. }
  3990.  
  3991. if (isset($this->config['synch_field'][$id_lang]) && is_array($this->config['synch_field']) && $this->config['synch_field'][$id_lang]) {
  3992. $synch_field = $this->config['synch_field'][$id_lang];
  3993. } elseif (!$synch_field) {
  3994. $synch_field = 'ean13';
  3995. }
  3996.  
  3997. $asin_has_priority = true;
  3998.  
  3999. if (isset($this->config['asin_has_priority']) && is_array($this->config['asin_has_priority']) && isset($this->config['asin_has_priority'][$id_lang])) {
  4000. $asin_has_priority = (bool)$this->config['asin_has_priority'][$id_lang];
  4001. }
  4002.  
  4003. $view_params['settings']['general']['config'][$id_lang] = array();
  4004. $view_params['settings']['general']['config'][$id_lang]['out_of_stock'] = $out_of_stock;
  4005.  
  4006. $view_params['settings']['general']['config'][$id_lang]['price_rule'] = array();
  4007. $view_params['settings']['general']['config'][$id_lang]['price_rule']['currency_sign'] = isset($current_currency['sign']) ? $current_currency['sign'] : null;
  4008.  
  4009. $view_params['settings']['general']['config'][$id_lang]['price_rule']['rule']['from'] = array(null);
  4010. $view_params['settings']['general']['config'][$id_lang]['price_rule']['rule']['to'] = array(null);
  4011. $view_params['settings']['general']['config'][$id_lang]['price_rule']['rule']['percent'] = array(null);
  4012. $view_params['settings']['general']['config'][$id_lang]['price_rule']['rule']['value'] = array(null);
  4013. $view_params['settings']['general']['config'][$id_lang]['price_rule']['type'] = 'percent';
  4014.  
  4015. if (isset($this->config['price_rule'][$id_lang]) && isset($this->config['price_rule'][$id_lang]['type']) && $this->config['price_rule'][$id_lang]['type']) {
  4016. $view_params['settings']['general']['config'][$id_lang]['price_rule']['type'] = $this->config['price_rule'][$id_lang]['type'];
  4017.  
  4018. if (isset($this->config['price_rule'][$id_lang]['rule']['from']) && is_array($this->config['price_rule'][$id_lang]['rule']['from']) && isset($this->config['price_rule'][$id_lang]['rule']['to']) && is_array($this->config['price_rule'][$id_lang]['rule']['to'])) {
  4019. $view_params['settings']['general']['config'][$id_lang]['price_rule']['rule'] = $this->config['price_rule'][$id_lang]['rule'];
  4020. if (!count($this->config['price_rule'][$id_lang]['rule']['from']) && !count($this->config['price_rule'][$id_lang]['rule']['to']) && !count($this->config['price_rule'][$id_lang]['rule']['value'])) {
  4021. $view_params['settings']['general']['config'][$id_lang]['price_rule']['rule']['from'][0] = '';
  4022. $view_params['settings']['general']['config'][$id_lang]['price_rule']['rule']['to'][0] = '';
  4023. $view_params['settings']['general']['config'][$id_lang]['price_rule']['rule']['percent'][0] = '';
  4024. $view_params['settings']['general']['config'][$id_lang]['price_rule']['rule']['value'][0] = '';
  4025. }
  4026. }
  4027. }
  4028.  
  4029. $view_params['settings']['general']['config'][$id_lang]['rounding_1'] = ($rounding == self::ROUNDING_ONE_DIGIT ? 'checked' : '');
  4030. $view_params['settings']['general']['config'][$id_lang]['rounding_2'] = ($rounding == self::ROUNDING_TWO_DIGITS ? 'checked' : '');
  4031. $view_params['settings']['general']['config'][$id_lang]['rounding_3'] = ($rounding == self::ROUNDING_SMART ? 'checked' : '');
  4032. $view_params['settings']['general']['config'][$id_lang]['rounding_4'] = ($rounding == self::ROUNDING_NONE ? 'checked' : '');
  4033.  
  4034.  
  4035. if (isset($this->config['ptc']) && isset($this->config['ptc'][$id_lang]) && $this->config['ptc'][$id_lang]) {
  4036. $ptc_selected = $this->config['ptc'][$id_lang];
  4037. } else {
  4038. $ptc_selected = null;
  4039. }
  4040.  
  4041. $view_params['settings']['general']['config'][$id_lang]['ptc'] = AmazonTaxes::getPtcList($region);
  4042. $view_params['settings']['general']['config'][$id_lang]['ptc_selected'] = $ptc_selected;
  4043.  
  4044. // Default tax rule for marketplace, it's use for FBA oder which delivery cross country
  4045. $view_params['settings']['general']['config'][$id_lang]['default_tax_rule'] = AmazonTaxes::getTaxRuleGroupsByCountry($id_country, true);
  4046. $default_tax_rule_selected = null;
  4047. if (isset($this->config['default_tax_rule'], $this->config['default_tax_rule'][$id_lang]) && $this->config['default_tax_rule'][$id_lang]) {
  4048. $default_tax_rule_selected = $this->config['default_tax_rule'][$id_lang];
  4049. }
  4050. $view_params['settings']['general']['config'][$id_lang]['default_tax_rule_selected'] = $default_tax_rule_selected;
  4051.  
  4052. $view_params['settings']['general']['config'][$id_lang]['sort_order_1'] = ($sort_order == self::SORT_ORDER_FIRSTNAME_LASTNAME ? 'checked' : '');
  4053. $view_params['settings']['general']['config'][$id_lang]['sort_order_2'] = ($sort_order == self::SORT_ORDER_LASTNAME_FIRSTNAME ? 'checked' : '');
  4054.  
  4055. $view_params['settings']['general']['config'][$id_lang]['synch_field_ean13'] = ($synch_field === 'ean13' ? 'selected' : '');
  4056. $view_params['settings']['general']['config'][$id_lang]['synch_field_upc'] = ($synch_field === 'upc' ? 'selected' : '');
  4057. $view_params['settings']['general']['config'][$id_lang]['synch_field_both'] = ($synch_field === 'both' ? 'selected' : '');
  4058. $view_params['settings']['general']['config'][$id_lang]['synch_field_reference'] = ($synch_field === 'reference' ? 'selected' : '');
  4059.  
  4060. $view_params['settings']['general']['config'][$id_lang]['asin_has_priority'] = $asin_has_priority;
  4061.  
  4062. $amazon_carrier_list = array_merge($this->shipping_overrides_std, $this->shipping_overrides_exp);
  4063.  
  4064. $view_params['settings']['carriers']['carrier_modules_tutorial'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_CARRIERS_MODULES);
  4065. $view_params['settings']['carriers']['config']['incoming'][$id_lang] = array();
  4066.  
  4067. $has_carrier_modules = false;
  4068. $count_carriers = count($incoming_carrier_amazon);
  4069. for ($index = 0; $index < $count_carriers; $index++) {
  4070. if ($index && !$incoming_carrier_amazon[$index] && $incoming_carrier_amazon[$index] !== null) {
  4071. continue;
  4072. }
  4073.  
  4074. $view_params['settings']['carriers']['config']['incoming'][$id_lang][$index] = array();
  4075. $view_params['settings']['carriers']['config']['incoming'][$id_lang][$index]['display_add'] = ($index > 0 ? 'style="display:none"' : '');
  4076. $view_params['settings']['carriers']['config']['incoming'][$id_lang][$index]['display_del'] = ($index === 0 ? 'style="display:none"' : '');
  4077.  
  4078. foreach ($amazon_carrier_list as $carrier) {
  4079. $key = md5($carrier);
  4080.  
  4081. if (empty($key)) {
  4082. continue;
  4083. }
  4084.  
  4085. $selected = isset($incoming_carrier_amazon[$index]) && $key === $incoming_carrier_amazon[$index] ? true : false;
  4086.  
  4087. $view_params['settings']['carriers']['config']['incoming'][$id_lang][$index]['amazon_carrier'][$key]['selected'] = $selected;
  4088. $view_params['settings']['carriers']['config']['incoming'][$id_lang][$index]['amazon_carrier'][$key]['name'] = $carrier;
  4089. }
  4090.  
  4091. foreach ($carriers as $carrier) {
  4092. $id_carrier = (int)$carrier['id_carrier'];
  4093. $selected = isset($incoming_carrier_prestashop[$index]) && (int)$incoming_carrier_prestashop[$index] === $id_carrier ? true : false;
  4094.  
  4095. $view_params['settings']['carriers']['config']['incoming'][$id_lang][$index]['prestashop_carrier'][$id_carrier]['selected'] = $selected;
  4096. $view_params['settings']['carriers']['config']['incoming'][$id_lang][$index]['prestashop_carrier'][$id_carrier]['name'] = $carrier['name'];
  4097. $view_params['settings']['carriers']['config']['incoming'][$id_lang][$index]['prestashop_carrier'][$id_carrier]['is_module'] = $carrier['is_module'];
  4098.  
  4099. if ($carrier['is_module']) {
  4100. $has_carrier_modules = true;
  4101. }
  4102. }
  4103. }
  4104. $view_params['settings']['carriers']['config']['has_carrier_modules'] = $has_carrier_modules;
  4105. $view_params['settings']['carriers']['config']['carrier_modules_allowed'] = true;
  4106.  
  4107.  
  4108. // Carriers Associations for outgoing orders
  4109. //
  4110. $view_params['settings']['carriers']['config']['outgoing'][$id_lang] = array();
  4111.  
  4112. $amazon_carriers = array_merge(AmazonCarrier::$carrier_codes, $this->extra_carrier_codes);
  4113.  
  4114. asort($amazon_carriers);
  4115. $count_carriers = count($outgoing_carriers['prestashop']);
  4116. for ($index = 0; $index < $count_carriers; $index++) {
  4117. if ($index && !$outgoing_carriers['prestashop'][$index] && $outgoing_carriers['prestashop'][$index] !== null) {
  4118. continue;
  4119. }
  4120.  
  4121. $view_params['settings']['carriers']['config']['outgoing'][$id_lang][$index] = array();
  4122. $view_params['settings']['carriers']['config']['outgoing'][$id_lang][$index]['display_add'] = ($index > 0 ? 'style="display:none"' : '');
  4123. $view_params['settings']['carriers']['config']['outgoing'][$id_lang][$index]['display_del'] = ($index === 0 ? 'style="display:none"' : '');
  4124.  
  4125. foreach ($carriers as $carrier) {
  4126. $id_carrier = (int)$carrier['id_carrier'];
  4127. $selected = isset($outgoing_carriers['prestashop'][$index]) && (int)$outgoing_carriers['prestashop'][$index] == $id_carrier ? true : false;
  4128.  
  4129. $view_params['settings']['carriers']['config']['outgoing'][$id_lang][$index]['prestashop_carrier'][$id_carrier]['selected'] = $selected;
  4130. $view_params['settings']['carriers']['config']['outgoing'][$id_lang][$index]['prestashop_carrier'][$id_carrier]['name'] = $carrier['name'];
  4131. $view_params['settings']['carriers']['config']['outgoing'][$id_lang][$index]['prestashop_carrier'][$id_carrier]['is_module'] = $carrier['is_module'];
  4132.  
  4133.  
  4134. if ($carrier['is_module']) {
  4135. $has_carrier_modules = true;
  4136. }
  4137. }
  4138.  
  4139. foreach ($amazon_carriers as $carrier) {
  4140. if (isset($outgoing_carriers['amazon'][$index]) && $carrier == $outgoing_carriers['amazon'][$index]) {
  4141. $selected = true;
  4142. } else {
  4143. $selected = false;
  4144. }
  4145.  
  4146. $view_params['settings']['carriers']['config']['outgoing'][$id_lang][$index]['amazon_carrier'][$carrier]['selected'] = $selected;
  4147. $view_params['settings']['carriers']['config']['outgoing'][$id_lang][$index]['amazon_carrier'][$carrier]['name'] = $carrier;
  4148. }
  4149. }
  4150.  
  4151. // FBA Multi Channel Carriers Associations for outgoing orders
  4152. //
  4153. $view_params['settings']['carriers']['config']['fba_multichannel'][$id_lang] = array();
  4154.  
  4155. $carrier_multichannel = isset($this->config['multichannel_carrier'][$id_lang]['prestashop']) && is_array($this->config['multichannel_carrier'][$id_lang]['prestashop']) ? $this->config['multichannel_carrier'][$id_lang] : array('prestashop' => array(null));
  4156.  
  4157. if ($this->config['fba_multichannel']) {
  4158. $count_carriers = count($carrier_multichannel['prestashop']);
  4159. for ($index = 0; $index < $count_carriers; $index++) {
  4160. if ($index && !$carrier_multichannel['prestashop'][$index] && $carrier_multichannel['prestashop'][$index] !== null) {
  4161. continue;
  4162. }
  4163.  
  4164. $view_params['settings']['carriers']['config']['fba_multichannel'][$id_lang][$index] = array();
  4165. $view_params['settings']['carriers']['config']['fba_multichannel'][$id_lang][$index]['display_add'] = ($index > 0 ? 'style="display:none"' : '');
  4166. $view_params['settings']['carriers']['config']['fba_multichannel'][$id_lang][$index]['display_del'] = ($index === 0 ? 'style="display:none"' : '');
  4167.  
  4168. foreach ($carriers as $carrier) {
  4169. $id_carrier = (int)$carrier['id_carrier'];
  4170.  
  4171. $selected = isset($carrier_multichannel['prestashop'][$index]) && $carrier_multichannel['prestashop'][$index] == $id_carrier ? true : false;
  4172.  
  4173. $view_params['settings']['carriers']['config']['fba_multichannel'][$id_lang][$index]['prestashop_carrier'][$id_carrier]['selected'] = $selected;
  4174. $view_params['settings']['carriers']['config']['fba_multichannel'][$id_lang][$index]['prestashop_carrier'][$id_carrier]['name'] = $carrier['name'];
  4175. $view_params['settings']['carriers']['config']['fba_multichannel'][$id_lang][$index]['prestashop_carrier'][$id_carrier]['is_module'] = $carrier['is_module'];
  4176. }
  4177.  
  4178. foreach ($this->carrier_fba as $carrier) {
  4179. $selected = isset($carrier_multichannel['amazon']) && isset($carrier_multichannel['amazon'][$index]) && $carrier == $carrier_multichannel['amazon'][$index] ? true : false;
  4180.  
  4181. $view_params['settings']['carriers']['config']['fba_multichannel'][$id_lang][$index]['amazon_carrier'][$carrier]['selected'] = $selected;
  4182. $view_params['settings']['carriers']['config']['fba_multichannel'][$id_lang][$index]['amazon_carrier'][$carrier]['name'] = $carrier;
  4183. }
  4184. }
  4185. } // End of FBA Multi Channel Carrier Mapping
  4186.  
  4187.  
  4188. // Shipping Overrides (deprecated)
  4189. $view_params['settings']['overrides']['allow'] = is_array($this->config['shipping']) && isset($this->config['shipping']['allow_overrides']) && $this->config['shipping']['allow_overrides'];
  4190.  
  4191. if ($view_params['settings']['overrides']['allow']) {
  4192. $selected_override_std = isset($this->config['shipping_override_std'][$id_lang]) ? $this->config['shipping_override_std'][$id_lang] : array(null);
  4193. $selected_override_exp = isset($this->config['shipping_override_exp'][$id_lang]) ? $this->config['shipping_override_exp'][$id_lang] : array(null);
  4194.  
  4195. $view_params['settings']['overrides']['standard'][$id_lang] = array();
  4196. $view_params['settings']['overrides']['express'][$id_lang] = array();
  4197.  
  4198. foreach ($this->shipping_overrides_std as $override) {
  4199. $selected = ($override && $override == $selected_override_std) ? true : false;
  4200.  
  4201. $view_params['settings']['overrides']['standard'][$id_lang][$override]['name'] = $override;
  4202. $view_params['settings']['overrides']['standard'][$id_lang][$override]['selected'] = $selected;
  4203. }
  4204.  
  4205. foreach ($this->shipping_overrides_exp as $override) {
  4206. $selected = ($override && $override == $selected_override_exp) ? true : false;
  4207.  
  4208. $view_params['settings']['overrides']['express'][$id_lang][$override]['name'] = $override;
  4209. $view_params['settings']['overrides']['express'][$id_lang][$override]['selected'] = $selected;
  4210. }
  4211. }
  4212.  
  4213. // Default Shipping Method for Platform
  4214. //
  4215.  
  4216. $view_params['settings']['shipping_methods'][$id_lang] = array();
  4217.  
  4218. if (isset($this->config['shipping_methods']) && isset($this->config['shipping_methods'][$id_lang]) && $this->config['shipping_methods'][$id_lang]) {
  4219. $default_shipping_method = $this->config['shipping_methods'][$id_lang];
  4220. } else {
  4221. $default_shipping_method = null;
  4222. }
  4223.  
  4224. foreach ($this->shipping_overrides_std as $shipping_method) {
  4225. $selected = ($shipping_method && $shipping_method === $default_shipping_method) ? true : false;
  4226.  
  4227. $view_params['settings']['shipping_methods'][$id_lang][$shipping_method]['name'] = $shipping_method;
  4228. $view_params['settings']['shipping_methods'][$id_lang][$shipping_method]['selected'] = $selected;
  4229. }
  4230.  
  4231. // Validate Button
  4232. //
  4233. $view_params['settings']['validate'][$id_lang] = $this->_validate(true);
  4234.  
  4235. return ($view_params);
  4236. }
  4237.  
  4238. private function _validate($returnHTML = false)
  4239. {
  4240. static $validate = null;
  4241.  
  4242. if ($validate === null) {
  4243. $validate = $this->context->smarty->fetch($this->path.self::$templates[self::TEMPLATE_VALIDATE]);
  4244. }
  4245.  
  4246. if ($returnHTML) {
  4247. return ($validate);
  4248. }
  4249.  
  4250. $this->_html .= $validate;
  4251.  
  4252. return (false);
  4253. }
  4254.  
  4255. private function _parameters(&$view_params)
  4256. {
  4257. $view_params['parameters'] = array();
  4258. $view_params['parameters']['settings'] = array();
  4259. $view_params['parameters']['tutorial'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_PARAMETERS);
  4260.  
  4261. $view_params['parameters']['images_url'] = $this->images;
  4262. $view_params['parameters']['selected_tab'] = ($this->selectedTab() === 'parameters' ? 'selected' : '');
  4263. $view_params['parameters']['expert_mode'] = (bool)$this->config['features']['expert_mode'];
  4264. $view_params['parameters']['validation'] = $this->_validate(true);
  4265.  
  4266. $view_params['parameters']['features'] = array();
  4267.  
  4268. if ($this->config['taxes'] === false && $this->config['marketplace_master'] == null) {
  4269. require_once(_PS_MODULE_DIR_.'/amazon/classes/amazon.preconfiguration.class.php');
  4270.  
  4271. if (($preconfiguration = AmazonPreconfiguration::data($this->id_lang))) {
  4272. $this->config['taxes'] = $preconfiguration['taxes'];
  4273. $this->config['marketplace_master'] = $preconfiguration['marketplace_master'];
  4274. }
  4275. }
  4276.  
  4277. //
  4278. // Options switches
  4279. //
  4280.  
  4281. $view_params['parameters']['settings']['discount'] = (bool)$this->config['specials'];
  4282. $view_params['parameters']['settings']['specials_apply_rules'] = (bool)$this->config['specials_apply_rules'];
  4283. $view_params['parameters']['settings']['preorder'] = (bool)$this->config['preorder'];
  4284. $view_params['parameters']['settings']['taxes'] = (int)$this->config['taxes'];
  4285.  
  4286. $view_params['parameters']['settings']['account_type_global_value'] = self::ACCOUNT_TYPE_GLOBAL;
  4287. $view_params['parameters']['settings']['account_type_individual_value'] = self::ACCOUNT_TYPE_INDIVIDUAL;
  4288.  
  4289. $view_params['parameters']['settings']['account_type_global_selected'] = $this->config['account_type'] == self::ACCOUNT_TYPE_GLOBAL ? true : false;
  4290. $view_params['parameters']['settings']['account_type_individual_selected'] = $this->config['account_type'] == self::ACCOUNT_TYPE_INDIVIDUAL ? true : false;
  4291.  
  4292. $view_params['parameters']['settings']['title_format_value_1'] = self::FORMAT_TITLE;
  4293. $view_params['parameters']['settings']['title_format_value_2'] = self::FORMAT_MANUFACTURER_TITLE;
  4294. $view_params['parameters']['settings']['title_format_value_3'] = self::FORMAT_MANUFACTURER_TITLE_REFERENCE;
  4295.  
  4296. $view_params['parameters']['settings']['title_format_selected_1'] = ($this->config['title_format'] == self::FORMAT_TITLE ? true : false);
  4297. $view_params['parameters']['settings']['title_format_selected_2'] = ($this->config['title_format'] == self::FORMAT_MANUFACTURER_TITLE ? true : false);
  4298. $view_params['parameters']['settings']['title_format_selected_3'] = ($this->config['title_format'] == self::FORMAT_MANUFACTURER_TITLE_REFERENCE ? true : false);
  4299.  
  4300. $view_params['parameters']['settings']['delete_products'] = (bool)$this->config['delete_products'];
  4301. $view_params['parameters']['settings']['html_descriptions'] = (bool)$this->config['html_descriptions'];
  4302.  
  4303. $view_params['parameters']['settings']['description_field_value_1'] = self::FIELD_DESCRIPTION_LONG;
  4304. $view_params['parameters']['settings']['description_field_value_2'] = self::FIELD_DESCRIPTION_SHORT;
  4305. $view_params['parameters']['settings']['description_field_value_3'] = self::FIELD_DESCRIPTION_BOTH;
  4306. $view_params['parameters']['settings']['description_field_value_4'] = self::FIELD_DESCRIPTION_NONE;
  4307.  
  4308. $view_params['parameters']['settings']['description_field_selected_1'] = ($this->config['description_field'] == self::FIELD_DESCRIPTION_LONG ? true : false);
  4309. $view_params['parameters']['settings']['description_field_selected_2'] = ($this->config['description_field'] == self::FIELD_DESCRIPTION_SHORT ? true : false);
  4310. $view_params['parameters']['settings']['description_field_selected_3'] = ($this->config['description_field'] == self::FIELD_DESCRIPTION_BOTH ? true : false);
  4311. $view_params['parameters']['settings']['description_field_selected_4'] = ($this->config['description_field'] == self::FIELD_DESCRIPTION_NONE ? true : false);
  4312.  
  4313. // Aug-23-2018: Remove Carriers/Modules option
  4314. $view_params['parameters']['settings']['safe_encoding'] = (bool)$this->config['safe_encoding'];
  4315. $view_params['parameters']['settings']['prices_only'] = (bool)$this->config['prices_only'];
  4316. $view_params['parameters']['settings']['stock_only'] = (bool)$this->config['stocks_only'];
  4317. $view_params['parameters']['settings']['payment_region'] = (bool)$this->config['payment_region'];
  4318.  
  4319. $view_params['parameters']['settings']['auto_create'] = (bool)$this->config['auto_create'];
  4320.  
  4321. $view_params['parameters']['settings']['email'] = (bool)$this->config['email'];
  4322. $view_params['parameters']['settings']['expert_mode'] = (bool)$this->config['features']['expert_mode'];
  4323. $view_params['parameters']['settings']['debug_mode'] = (bool)$this->config['debug'];
  4324. $view_params['parameters']['settings']['inactive_languages'] = (bool)$this->config['inactive_languages'];
  4325. $view_params['parameters']['settings']['disable_ssl_check'] = (bool)$this->config['disable_ssl_check'];
  4326.  
  4327. $selected = $this->config['image_type'];
  4328.  
  4329.  
  4330. foreach (ImageType::getImagesTypes() as $imageType) {
  4331. if (!(bool)$imageType['products']) {
  4332. continue;
  4333. }
  4334.  
  4335. $view_params['parameters']['settings']['image_type'][$imageType['name']] = ($selected === $imageType['name'] ? true : false);
  4336. }
  4337.  
  4338. //
  4339. // Orders States
  4340. //
  4341.  
  4342. $view_params['parameters']['settings']['incoming_order_state'] = array();
  4343. $view_params['parameters']['settings']['incoming_order_state']['standard']['prefix'] = self::ORDER_STATE_STANDARD;
  4344. $view_params['parameters']['settings']['incoming_order_state']['standard']['title'] = $this->l('Incoming Orders');
  4345. $view_params['parameters']['settings']['incoming_order_state']['standard']['options'] = array();
  4346.  
  4347. $orderStates = OrderState::getOrderStates($this->id_lang);
  4348.  
  4349. // Incoming Orders States
  4350. //
  4351. foreach ($orderStates as $orderState) {
  4352. $id_order_state = (int)$orderState['id_order_state'];
  4353.  
  4354. if (is_array($this->config['order_state']) && $id_order_state == $this->config['order_state'][self::ORDER_STATE_STANDARD]) {
  4355. $selected = true;
  4356. } else {
  4357. $selected = false;
  4358. }
  4359.  
  4360. $view_params['parameters']['settings']['incoming_order_state']['standard']['options'][$id_order_state]['name'] = $orderState['name'];
  4361. $view_params['parameters']['settings']['incoming_order_state']['standard']['options'][$id_order_state]['selected'] = $selected;
  4362. }
  4363.  
  4364. // Prime
  4365. //
  4366. $view_params['parameters']['settings']['incoming_order_state']['prime']['enabled'] = true;
  4367. $view_params['parameters']['settings']['incoming_order_state']['prime']['active'] = true;
  4368. $view_params['parameters']['settings']['incoming_order_state']['prime']['prefix'] = self::ORDER_STATE_PRIMEORDER;
  4369. $view_params['parameters']['settings']['incoming_order_state']['prime']['title'] = $this->l('Prime Orders');
  4370. $view_params['parameters']['settings']['incoming_order_state']['prime']['options'] = array();
  4371.  
  4372. $current_order_state = isset($this->config['order_state'][self::ORDER_STATE_PRIMEORDER]) ? $this->config['order_state'][self::ORDER_STATE_PRIMEORDER] : null;
  4373.  
  4374. foreach ($orderStates as $orderState) {
  4375. $id_order_state = (int)$orderState['id_order_state'];
  4376.  
  4377. if (is_array($this->config['order_state']) && $id_order_state == $current_order_state) {
  4378. $selected = true;
  4379. } else {
  4380. $selected = false;
  4381. }
  4382.  
  4383. $view_params['parameters']['settings']['incoming_order_state']['prime']['options'][$id_order_state]['name'] = $orderState['name'];
  4384. $view_params['parameters']['settings']['incoming_order_state']['prime']['options'][$id_order_state]['selected'] = $selected;
  4385. }
  4386.  
  4387. // Preorder
  4388. //
  4389. $view_params['parameters']['settings']['incoming_order_state']['preorder']['enabled'] = version_compare(_PS_VERSION_, '1.5', '>=');
  4390. $view_params['parameters']['settings']['incoming_order_state']['preorder']['active'] = $this->config['preorder'];
  4391. $view_params['parameters']['settings']['incoming_order_state']['preorder']['prefix'] = self::ORDER_STATE_PREORDER;
  4392. $view_params['parameters']['settings']['incoming_order_state']['preorder']['title'] = $this->l('Pre-Orders');
  4393. $view_params['parameters']['settings']['incoming_order_state']['preorder']['options'] = array();
  4394.  
  4395. $current_order_state = isset($this->config['order_state'][self::ORDER_STATE_PREORDER]) ? $this->config['order_state'][self::ORDER_STATE_PREORDER] : null;
  4396.  
  4397. foreach ($orderStates as $orderState) {
  4398. $id_order_state = (int)$orderState['id_order_state'];
  4399.  
  4400. if (is_array($this->config['order_state']) && $id_order_state == $current_order_state) {
  4401. $selected = true;
  4402. } else {
  4403. $selected = false;
  4404. }
  4405.  
  4406. $view_params['parameters']['settings']['incoming_order_state']['preorder']['options'][$id_order_state]['name'] = $orderState['name'];
  4407. $view_params['parameters']['settings']['incoming_order_state']['preorder']['options'][$id_order_state]['selected'] = $selected;
  4408. }
  4409.  
  4410. // Sent Orders States
  4411. //
  4412. $view_params['parameters']['settings']['sent_order_state'] = array();
  4413. $view_params['parameters']['settings']['sent_order_state']['options'] = array();
  4414. $view_params['parameters']['settings']['sent_order_state']['title'] = $this->l('Orders Sent');
  4415.  
  4416. foreach ($orderStates as $orderState) {
  4417. $id_order_state = (int)$orderState['id_order_state'];
  4418.  
  4419. if ($id_order_state == $this->config['send_state']) {
  4420. $selected = true;
  4421. } else {
  4422. $selected = false;
  4423. }
  4424.  
  4425. $view_params['parameters']['settings']['sent_order_state']['options'][$id_order_state]['name'] = $orderState['name'];
  4426. $view_params['parameters']['settings']['sent_order_state']['options'][$id_order_state]['selected'] = $selected;
  4427. }
  4428.  
  4429. // Canceled Orders States
  4430. //
  4431. $view_params['parameters']['settings']['canceled_order_state'] = array();
  4432. $view_params['parameters']['settings']['canceled_order_state']['options'] = array();
  4433. $view_params['parameters']['settings']['canceled_order_state']['title'] = $this->l('Canceled Orders ');
  4434.  
  4435. foreach ($orderStates as $orderState) {
  4436. $id_order_state = (int)$orderState['id_order_state'];
  4437.  
  4438. if ($id_order_state == $this->config['canceled_state']) {
  4439. $selected = true;
  4440. } else {
  4441. $selected = false;
  4442. }
  4443.  
  4444. $view_params['parameters']['settings']['canceled_order_state']['options'][$id_order_state]['name'] = $orderState['name'];
  4445. $view_params['parameters']['settings']['canceled_order_state']['options'][$id_order_state]['selected'] = $selected;
  4446. }
  4447.  
  4448. $view_params['parameters']['settings']['employee'] = array();
  4449.  
  4450. // Employee::getEmployees is displayed as deprecated in PS 1.4 ... but not in PS 1.5
  4451. foreach (@Employee::getEmployees() as $employee) {
  4452. $id_employee = (int)$employee['id_employee'];
  4453.  
  4454. if ($id_employee == $this->config['employee']) {
  4455. $selected = true;
  4456. } else {
  4457. $selected = false;
  4458. }
  4459.  
  4460. $view_params['parameters']['settings']['employee'][$id_employee]['name'] = (isset($employee['name']) ? $employee['name'] : sprintf('%s %s', $employee['firstname'], $employee['lastname']));
  4461. $view_params['parameters']['settings']['employee'][$id_employee]['selected'] = $selected;
  4462. }
  4463.  
  4464. //
  4465. // Customer groups
  4466. //
  4467. $view_params['parameters']['settings']['customer_groups'] = array();
  4468. $view_params['parameters']['settings']['business'] = $this->amazon_features['business'];
  4469.  
  4470. foreach (Group::getGroups($this->context->language->id, true) as $customer_group) {
  4471. $id_group = (int)$customer_group['id_group'];
  4472.  
  4473. if ($id_group == $this->config['id_group']) {
  4474. $selected = true;
  4475. } else {
  4476. $selected = false;
  4477. }
  4478.  
  4479. $view_params['parameters']['settings']['customer_groups'][$id_group]['name'] = $customer_group['name'];
  4480. $view_params['parameters']['settings']['customer_groups'][$id_group]['selected'] = $selected;
  4481.  
  4482. if ($this->amazon_features['business']) {
  4483. if ($id_group == $this->config['id_business_group']) {
  4484. $business_selected = true;
  4485. } else {
  4486. $business_selected = false;
  4487. }
  4488.  
  4489. $view_params['parameters']['settings']['customer_groups'][$id_group]['business_selected'] = $business_selected;
  4490. }
  4491. }
  4492.  
  4493.  
  4494.  
  4495. //
  4496. // Advanced Stock
  4497. //
  4498.  
  4499. if (version_compare(_PS_VERSION_, '1.5', '>=') && Configuration::get('PS_ADVANCED_STOCK_MANAGEMENT')) {
  4500. $view_params['parameters']['settings']['warehouse'] = array();
  4501.  
  4502. foreach (Warehouse::getWarehouses(true) as $warehouse) {
  4503. $id_warehouse = (int)$warehouse['id_warehouse'];
  4504.  
  4505. if ($id_warehouse == $this->config['warehouse']) {
  4506. $selected = true;
  4507. } else {
  4508. $selected = false;
  4509. }
  4510.  
  4511. $view_params['parameters']['settings']['warehouse'][$id_warehouse]['name'] = $warehouse['name'];
  4512. $view_params['parameters']['settings']['warehouse'][$id_warehouse]['selected'] = $selected;
  4513. }
  4514. } else {
  4515. $view_params['parameters']['settings']['warehouse'] = null;
  4516. }
  4517.  
  4518. //
  4519. // Products State/Condition
  4520. //
  4521. // Check for the condition field (Prestashop < 1.4 doesn't have this field)
  4522. if (($conditionFields = AmazonTools::getConditionField())) {
  4523. $view_params['parameters']['settings']['product_condition'] = true;
  4524.  
  4525. // For i18n
  4526. //
  4527. $default_conditions = array($this->l('new'), $this->l('used'), $this->l('refurbished'));
  4528.  
  4529. // Fetch columns names
  4530. //
  4531. preg_match_all("/'([\w ]*)'/", $conditionFields['Type'], $ps_conditions);
  4532.  
  4533. $view_params['parameters']['settings']['product_conditions'] = array();
  4534.  
  4535. $index = 1;
  4536. foreach (self::$conditions as $condition) {
  4537. $view_params['parameters']['settings']['product_conditions'][$condition] = array();
  4538. $view_params['parameters']['settings']['product_conditions'][$condition]['index'] = $index++;
  4539. $view_params['parameters']['settings']['product_conditions'][$condition]['selector'] = array();
  4540.  
  4541. foreach ($ps_conditions[1] as $ps_condition) {
  4542. if (isset($this->config['condition_map'][$condition]) && !empty($this->config['condition_map'][$condition]) && $this->config['condition_map'][$condition] === $ps_condition) {
  4543. $selected = true;
  4544. } elseif ($condition === 'New' && $ps_condition === 'new' && $this->config['condition_map'][$condition] === null) {
  4545. // default config
  4546.  
  4547. $selected = true;
  4548. } else {
  4549. $selected = false;
  4550. }
  4551.  
  4552. $view_params['parameters']['settings']['product_conditions'][$condition]['selector'][$ps_condition] = array();
  4553. $view_params['parameters']['settings']['product_conditions'][$condition]['selector'][$ps_condition]['selected'] = $selected;
  4554. $view_params['parameters']['settings']['product_conditions'][$condition]['selector'][$ps_condition]['name'] = AmazonTools::ucfirst($this->l($ps_condition));
  4555. }
  4556. }
  4557. } else {
  4558. $view_params['parameters']['settings']['product_condition'] = false;
  4559. }
  4560.  
  4561. //
  4562. // Amazon Europe
  4563. //
  4564.  
  4565. $view_params['parameters']['settings']['europe'] = array();
  4566. $view_params['parameters']['settings']['europe']['tutorial'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_AMAZON_EUROPE);
  4567.  
  4568. foreach ($this->_platforms as $iso_code => $platform) {
  4569. $view_params['parameters']['settings']['europe']['selector'][$iso_code]['selected'] = ($iso_code === $this->config['marketplace_master'] ? true : false);
  4570. $view_params['parameters']['settings']['europe']['selector'][$iso_code]['iso_code'] = $iso_code;
  4571. $view_params['parameters']['settings']['europe']['selector'][$iso_code]['name'] = $platform;
  4572. }
  4573.  
  4574. $old_amazon_europe = (bool)AmazonConfiguration::get('EUROPE'); // retro compat
  4575.  
  4576. if ($this->config['features']['amazon_europe'] || $old_amazon_europe) {
  4577. $view_params['parameters']['settings']['europe']['active'] = true;
  4578. $view_params['parameters']['settings']['europe']['disabled'] = false;
  4579. $view_params['parameters']['settings']['europe']['class'] = 'master-enabled';
  4580. } else {
  4581. $view_params['parameters']['settings']['europe']['active'] = false;
  4582. $view_params['parameters']['settings']['europe']['disabled'] = true;
  4583. $view_params['parameters']['settings']['europe']['class'] = 'master-disabled';
  4584. }
  4585.  
  4586. return ($view_params);
  4587. }
  4588.  
  4589. private function _categories(&$view_params)
  4590. {
  4591. $view_params['categories'] = array();
  4592. $view_params['categories']['settings'] = array();
  4593. $view_params['categories']['tutorial'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_CATEGORIES);
  4594.  
  4595. $view_params['categories']['images_url'] = $this->images;
  4596. $view_params['categories']['selected_tab'] = ($this->selectedTab() === 'categories' ? 'selected' : '');
  4597. $view_params['categories']['expert_mode'] = (bool)$this->config['features']['expert_mode'];
  4598. $view_params['categories']['validation'] = $this->_validate(true);
  4599.  
  4600. $index = array();
  4601.  
  4602. $html = '';
  4603.  
  4604. $categories = Category::getCategories((int)$this->id_lang, false);
  4605.  
  4606. if (version_compare(_PS_VERSION_, '1.5', '>=')) {
  4607. $id_shop = (int)$this->context->shop->id;
  4608. $shop = new Shop($id_shop);
  4609.  
  4610. $first = null;
  4611. $root = Category::getRootCategory(null, $shop)->id_category;
  4612.  
  4613. foreach ($categories as $categories1) {
  4614. foreach ($categories1 as $category) {
  4615. if ($category['infos']['id_category'] == $root) {
  4616. $first = $category;
  4617. break;
  4618. }
  4619. }
  4620. if ($first) {
  4621. break;
  4622. }
  4623. }
  4624.  
  4625. $default_category = $shop->id_category;
  4626. } else {
  4627. foreach ($categories as $first1 => $categories_array) {
  4628. break;
  4629. }
  4630. foreach ($categories_array as $first2 => $categories_array2) {
  4631. break;
  4632. }
  4633. $first = $categories[$first1][$first2];
  4634. $default_category = 1;
  4635. }
  4636.  
  4637. //$html_categories = self::recurseCategoryForInclude($index, $categories, $first, $default_category, null, $this->config['categories'], $this->config['profiles_to_categories'], true);
  4638.  
  4639. $view_params['categories']['expert_mode'] = (bool)$this->config['features']['expert_mode'];
  4640. $view_params['categories']['brute_force'] = $this->config['brute_force'];
  4641. //$view_params['categories']['html_categories'] = $html_categories;
  4642.  
  4643. $html_categories = self::recurseCategoryForInclude($index, $categories, $first, $default_category, null, $this->config['categories'], $this->config['profiles_to_categories'], false);
  4644.  
  4645. $view_params['categories']['list'] = $html_categories;
  4646. $view_params['categories']['profiles'] = &$this->profiles;
  4647. }
  4648.  
  4649.  
  4650. /**
  4651. * @param $indexedCategories
  4652. * @param $categories
  4653. * @param $current
  4654. * @param int $id_category
  4655. * @param null $id_category_default
  4656. * @param array $default_categories
  4657. * @param array $default_profiles
  4658. * @param bool|false $next
  4659. *
  4660. * @return string
  4661. */
  4662. public function recurseCategoryForInclude($indexedCategories, $categories, $current, $id_category = 1, $id_category_default = null, $default_categories = array(), $default_profiles = array(), $next = false)
  4663. {
  4664. static $done;
  4665. static $irow;
  4666. static $categories_table;
  4667.  
  4668. $categories_table = isset($categories_table) ? $categories_table : array();
  4669.  
  4670. if (is_array($default_categories) && in_array($id_category, $default_categories)) {
  4671. $checked = ' checked="checked"';
  4672. } elseif (!is_array($default_categories) || !count($default_categories)) {
  4673. $checked = ' checked="checked"';
  4674. } else {
  4675. $checked = '';
  4676. }
  4677.  
  4678. if (!isset($done[$current['infos']['id_parent']])) {
  4679. $done[$current['infos']['id_parent']] = 0;
  4680. }
  4681. $done[$current['infos']['id_parent']] += 1;
  4682.  
  4683. $todo = count($categories[$current['infos']['id_parent']]);
  4684. $doneC = $done[$current['infos']['id_parent']];
  4685.  
  4686. $level = $current['infos']['level_depth'] + 1;
  4687. $img = ($next === false) ? 'lv1.gif' : 'lv'.$level.'_'.($todo == $doneC ? 'f' : 'b').'.gif';
  4688. $selected_profile = null;
  4689. $saved_profiles = &$this->profiles['name'];
  4690.  
  4691. if (is_array($saved_profiles) && count($saved_profiles)) {
  4692. if (is_array($saved_profiles) && count($saved_profiles) === 1 && !empty($checked)) {
  4693. $default_profile = true;
  4694. } else {
  4695. $default_profile = false;
  4696. }
  4697.  
  4698. foreach ($saved_profiles as $profile) {
  4699. if (!isset($profile) || empty($profile)) {
  4700. continue;
  4701. }
  4702.  
  4703. if (isset($default_profiles[$id_category]) && $default_profiles[$id_category] == $profile || $default_profile) {
  4704. $selected_profile = $profile;
  4705. }
  4706. }
  4707. }
  4708.  
  4709. $categories_table[$id_category] = array(
  4710. 'level' => $level,
  4711. 'img_level' => $this->images.$img,
  4712. 'alt_row' => $irow++ % 2,
  4713. 'id_category_default' => $id_category_default == $id_category,
  4714. 'checked' => $checked,
  4715. 'name' => Tools::stripslashes($current['infos']['name']),
  4716. 'profile' => $selected_profile,
  4717. 'disabled' => !$next
  4718. );
  4719.  
  4720. if (isset($categories[$id_category])) {
  4721. if ($categories[$id_category]) {
  4722. foreach (array_keys($categories[$id_category]) as $key) {
  4723. if ($key != 'infos') {
  4724. self::recurseCategoryForInclude($indexedCategories, $categories, $categories[$id_category][$key], $key, $id_category_default, $default_categories, $default_profiles, true);
  4725. }
  4726. }
  4727. }
  4728. }
  4729.  
  4730. return ($categories_table);
  4731. }
  4732.  
  4733. private function _profiles(&$view_params)
  4734. {
  4735. $view_params['profiles'] = array();
  4736. $view_params['profiles']['config'] = array();
  4737.  
  4738. $view_params['profiles']['module_path'] = $this->path;
  4739. $view_params['profiles']['images_url'] = $this->images;
  4740. $view_params['profiles']['selected_tab'] = ($this->selectedTab() === 'profiles' ? 'selected' : '');
  4741. $view_params['profiles']['expert_mode'] = (bool)$this->config['features']['expert_mode'];
  4742. $view_params['profiles']['validation'] = $this->_validate(true);
  4743. $view_params['profiles']['tutorial'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_PROFILES);
  4744.  
  4745.  
  4746. $view_params['profiles']['xsd_path'] = str_replace('\\', '/', realpath(dirname(__FILE__))).'/xsd/';
  4747. $view_params['profiles']['xsd_operations_url'] = $this->url.'functions/xsd_operations.php';
  4748. $view_params['profiles']['xsd_ajax_error'] = $this->l('An unexpected server side error occured').$this->l('In most cases, this is a permission problem. Please apply write permission (777) to amazon/validate/xsd directory.');
  4749. $view_params['profiles']['error_profile_name'] = $this->l('First, you must enter a profile name');
  4750.  
  4751. $html = null;
  4752.  
  4753. $exemptions = array();
  4754. $exemptions['none'] = self::EXEMPTION_NONE;
  4755. $exemptions['compatibility'] = self::EXEMPTION_COMPATIBILITY;
  4756. $exemptions['model_number'] = self::EXEMPTION_MODEL_NUMBER;
  4757. $exemptions['model_name'] = self::EXEMPTION_MODEL_NAME;
  4758. $exemptions['mfr_part_number'] = self::EXEMPTION_MFR_PART_NUMBER;
  4759. $exemptions['catalog_number'] = self::EXEMPTION_CATALOG_NUMBER;
  4760. $exemptions['style_number'] = self::EXEMPTION_STYLE_NUMBER;
  4761. $exemptions['attr_ean'] = self::EXEMPTION_ATTR_EAN;
  4762. $exemptions['generic'] = self::EXEMPTION_GENERIC;
  4763.  
  4764. $view_params['profiles']['exemptions'] = $exemptions;
  4765.  
  4766. // Only Used to Fetch the XSD Files ;
  4767. //
  4768. AmazonXSD::getCategories();
  4769.  
  4770. $view_params['profiles']['categories_english'] = (Tools::strtolower(Language::getIsoById($this->id_lang)) === 'fr') ? true : false;
  4771.  
  4772. $view_params['profiles']['marketplaces'] = array();
  4773. $view_params['profiles']['marketplaces']['countries'] = $marketplace_countries = AmazonSpecificField::countrySelector();
  4774. $view_params['profiles']['marketplaces']['show'] = count($marketplace_countries) > 1;
  4775.  
  4776. $current_currency = Currency::getDefaultCurrency();
  4777.  
  4778. $profiles = is_array($this->profiles) && count($this->profiles) ? $this->profiles : array('name' => null);
  4779.  
  4780. $profiles = AmazonSpecificField::migrateProfilesFromV3($profiles);
  4781.  
  4782. $view_params['profiles']['bullet_point_strategy_a'] = self::BULLET_POINT_STRATEGY_ATTRIBUTES;
  4783. $view_params['profiles']['bullet_point_strategy_af'] = self::BULLET_POINT_STRATEGY_ATTRIBUTES_FEATURES;
  4784. $view_params['profiles']['bullet_point_strategy_f'] = self::BULLET_POINT_STRATEGY_FEATURES;
  4785. $view_params['profiles']['bullet_point_strategy_d'] = self::BULLET_POINT_STRATEGY_DESC;
  4786. $view_params['profiles']['bullet_point_strategy_daf'] = self::BULLET_POINT_STRATEGY_DESC_ATTRIBUTES_FEATURES;
  4787. $view_params['profiles']['bullet_point_strategy_df'] = self::BULLET_POINT_STRATEGY_DESC_FEATURES;
  4788.  
  4789. $current_description_strategy = Configuration::get('AMAZON_DESCRIPTION_FIELD');
  4790.  
  4791. if ($current_description_strategy && !in_array($current_description_strategy, array(Amazon::FIELD_DESCRIPTION_SHORT, Amazon::FIELD_DESCRIPTION_BOTH))) {
  4792. $view_params['profiles']['bullet_point_strategy_shortd'] = true;
  4793. } else {
  4794. $view_params['profiles']['bullet_point_strategy_shortd'] = false;
  4795. }
  4796.  
  4797.  
  4798. $view_params['profiles']['universes'] = array();
  4799.  
  4800. $view_params['profiles']['empty_profile_header'] = array();
  4801. $view_params['profiles']['empty_profile_header']['name'] = null;
  4802. $view_params['profiles']['empty_profile_header']['profile_id'] = 0;
  4803.  
  4804. $empty_price_rule = array();
  4805. $empty_price_rule['currency_sign'] = isset($current_currency->sign) ? $current_currency->sign : null;
  4806. $empty_price_rule['type'] = 'percent';
  4807. $empty_price_rule['rule']['from'][0] = '';
  4808. $empty_price_rule['rule']['to'][0] = '';
  4809. $empty_price_rule['rule']['percent'][0] = '';
  4810. $empty_price_rule['rule']['value'][0] = '';
  4811.  
  4812. $languages = AmazonTools::languages();
  4813.  
  4814.  
  4815. foreach ($languages as $language) {
  4816. $id_lang = $language['id_lang'];
  4817.  
  4818. if (isset($this->config['regions']) && is_array($this->config['regions']) && array_key_exists($id_lang, $this->config['regions'])) {
  4819. $region = $this->config['regions'][$id_lang];
  4820. } else {
  4821. $region = null;
  4822. }
  4823.  
  4824. if (!(isset($this->config['actives'][$id_lang]) && (int)$this->config['actives'][$id_lang])) {
  4825. continue;
  4826. }
  4827.  
  4828. // Repricing Strategies
  4829. $strategies = $this->getStrategies($id_lang);
  4830.  
  4831. $view_params['profiles']['universes'][$id_lang] = AmazonSpecificField::universes($region);
  4832.  
  4833. $view_params['profiles']['empty_profile'][$id_lang] = array();
  4834. $view_params['profiles']['empty_profile'][$id_lang]['universe'] = null;
  4835. $view_params['profiles']['empty_profile'][$id_lang]['product_type'] = null;
  4836. $view_params['profiles']['empty_profile'][$id_lang]['product_type_translation'] = null;
  4837. $view_params['profiles']['empty_profile'][$id_lang]['price_rule'] = $empty_price_rule;
  4838. $view_params['profiles']['empty_profile'][$id_lang]['latency'] = null;
  4839.  
  4840. if (!isset($profiles['name'])) {
  4841. $profiles['name'] = array();
  4842. }
  4843.  
  4844. $profile_index = 0;
  4845.  
  4846. foreach ($profiles['name'] as $profile_id => $profile_name) {
  4847. if (!Tools::strlen($profile_key = AmazonTools::toKey($profile_name)) && $profile_id != 65535) {
  4848. continue;
  4849. }
  4850.  
  4851. // Skip empty entries
  4852. if (empty($profile_name) && (!isset($profiles['master'][$profile_id]) || !$profiles['master'][$profile_id])) {
  4853. continue;
  4854. }
  4855.  
  4856. $profile_index++;
  4857.  
  4858. $view_params['profiles']['header'][$profile_key] = array();
  4859. $view_params['profiles']['header'][$profile_key]['profile_id'] = $profile_id;
  4860. $view_params['profiles']['header'][$profile_key]['name'] = $profiles['name'][$profile_id];
  4861.  
  4862. $p_universe = isset($profiles['universe'][$profile_id][$id_lang]) ? $profiles['universe'][$profile_id][$id_lang] : '';
  4863. $p_product_type = isset($profiles['product_type'][$profile_id][$id_lang]) ? $profiles['product_type'][$profile_id][$id_lang] : '';
  4864. $p_extra = isset($profiles['extra'][$profile_key][$id_lang]) ? $profiles['extra'][$profile_key][$id_lang] : '';
  4865.  
  4866. if (!$product_type_translation = AmazonSettings::getProductTypeTranslation($region, $p_universe, $p_product_type)) {
  4867. $product_type_translation = $p_product_type;
  4868. }
  4869.  
  4870. if ($p_universe && $p_product_type) {
  4871. $type = sprintf('%s&nbsp;&gt;&nbsp;%s', $p_universe, $p_product_type);
  4872. } else {
  4873. $type = $this->l('ERROR');
  4874. }
  4875.  
  4876. $view_params['profiles']['config'][$profile_key][$id_lang] = array();
  4877. $view_params['profiles']['config'][$profile_key][$id_lang]['universe'] = $p_universe;
  4878. $view_params['profiles']['config'][$profile_key][$id_lang]['product_type'] = $p_product_type;
  4879. $view_params['profiles']['config'][$profile_key][$id_lang]['product_type_translation'] = $product_type_translation;
  4880. $view_params['profiles']['config'][$profile_key][$id_lang]['type'] = $type;
  4881.  
  4882.  
  4883. $view_params['profiles']['config'][$profile_key][$id_lang]['latency'] = isset($profiles['latency'][$profile_id][$id_lang]) ? $profiles['latency'][$profile_id][$id_lang] : '';
  4884. $view_params['profiles']['config'][$profile_key][$id_lang]['combinations'] = isset($profiles['combinations'][$profile_id][$id_lang]) ? $profiles['combinations'][$profile_id][$id_lang] : '';
  4885.  
  4886. $view_params['profiles']['config'][$profile_key][$id_lang]['code_exemption'] = isset($profiles['code_exemption'][$profile_id][$id_lang]) ? $profiles['code_exemption'][$profile_id][$id_lang] : self::EXEMPTION_NONE;
  4887.  
  4888. if (isset($profiles['code_exemption'][$profile_id][$id_lang]) && $profiles['code_exemption'][$profile_id][$id_lang] == self::EXEMPTION_COMPATIBILITY) {
  4889. $view_params['profiles']['config'][$profile_key][$id_lang]['code_exemption_options'] = array('private_label' => true);
  4890. } else {
  4891. $view_params['profiles']['config'][$profile_key][$id_lang]['code_exemption_options'] = isset($profiles['code_exemption_options'][$profile_id][$id_lang]) ? $profiles['code_exemption_options'][$profile_id][$id_lang] : null;
  4892. }
  4893.  
  4894. $view_params['profiles']['config'][$profile_key][$id_lang]['sku_as_supplier_reference'] = isset($profiles['sku_as_supplier_reference'][$profile_id][$id_lang]) ? $profiles['sku_as_supplier_reference'][$profile_id][$id_lang] : 0;
  4895. $view_params['profiles']['config'][$profile_key][$id_lang]['sku_as_sup_ref_unconditionnaly'] = isset($profiles['sku_as_sup_ref_unconditionnaly'][$profile_id][$id_lang]) ? $profiles['sku_as_sup_ref_unconditionnaly'][$profile_id][$id_lang] : 0;
  4896.  
  4897. $view_params['profiles']['config'][$profile_key][$id_lang]['item_type'] = isset($profiles['item_type'][$profile_id][$id_lang]) ? $profiles['item_type'][$profile_id][$id_lang] : '';
  4898.  
  4899. if (isset($profiles['price_rule'][$profile_id][$id_lang]) && is_array($profiles['price_rule'][$profile_id][$id_lang]) && isset($profiles['price_rule'][$profile_id][$id_lang]['rule']['from']) && is_array($profiles['price_rule'][$profile_id][$id_lang]['rule']['from']) && isset($profiles['price_rule'][$profile_id][$id_lang]['rule']['to']) && is_array($profiles['price_rule'][$profile_id][$id_lang]['rule']['to'])) {
  4900. $view_params['profiles']['config'][$profile_key][$id_lang]['price_rule']['currency_sign'] = isset($current_currency->sign) ? $current_currency->sign : null;
  4901. $view_params['profiles']['config'][$profile_key][$id_lang]['price_rule']['type'] = isset($profiles['price_rule'][$profile_id][$id_lang]['type']) ? $profiles['price_rule'][$profile_id][$id_lang]['type'] : 'percent';
  4902.  
  4903. if (isset($profiles['price_rule'][$profile_id][$id_lang]['rule']['from']) && is_array($profiles['price_rule'][$profile_id][$id_lang]['rule']['from']) && isset($profiles['price_rule'][$profile_id][$id_lang]['rule']['to']) && is_array($profiles['price_rule'][$profile_id][$id_lang]['rule']['to'])) {
  4904. $view_params['profiles']['config'][$profile_key][$id_lang]['price_rule']['rule'] = $profiles['price_rule'][$profile_id][$id_lang]['rule'];
  4905. if (!count($profiles['price_rule'][$profile_id][$id_lang]['rule']['from']) && !count($profiles['price_rule'][$profile_id][$id_lang]['rule']['to']) && !count($profiles['price_rule'][$profile_id][$id_lang]['rule']['value'])) {
  4906. $view_params['profiles']['config'][$profile_key][$id_lang]['price_rule']['rule']['from'][0] = '';
  4907. $view_params['profiles']['config'][$profile_key][$id_lang]['price_rule']['rule']['to'][0] = '';
  4908. $view_params['profiles']['config'][$profile_key][$id_lang]['price_rule']['rule']['percent'][0] = '';
  4909. $view_params['profiles']['config'][$profile_key][$id_lang]['price_rule']['rule']['value'][0] = '';
  4910. }
  4911. }
  4912. } else {
  4913. // first use
  4914. $view_params['profiles']['config'][$profile_key][$id_lang]['price_rule'] = $empty_price_rule;
  4915. }
  4916.  
  4917. $view_params['profiles']['config'][$profile_key][$id_lang]['universe'] = $p_universe;
  4918.  
  4919. if ($profile_index < self::MAX_PROFILES) {
  4920. $view_params['profiles']['config'][$profile_key][$id_lang]['specifics'] = AmazonSpecificField::displayFields($id_lang, $profile_name, $p_extra);
  4921. } else {
  4922. $view_params['profiles']['config'][$profile_key][$id_lang]['specifics'] = array();
  4923. $view_params['profiles']['config'][$profile_key][$id_lang]['specifics']['has_data'] = is_array($p_extra) && count($p_extra) ? true : false;
  4924. $view_params['profiles']['config'][$profile_key][$id_lang]['specifics']['id_lang'] = $id_lang;
  4925. $view_params['profiles']['config'][$profile_key][$id_lang]['specifics']['profile_key'] = $profile_key;
  4926. }
  4927.  
  4928. $view_params['profiles']['config'][$profile_key][$id_lang]['bullet_point_strategy'] = isset($profiles['bullet_point_strategy'][$profile_id][$id_lang]) ? $profiles['bullet_point_strategy'][$profile_id][$id_lang] : null;
  4929. $view_params['profiles']['config'][$profile_key][$id_lang]['bullet_point_labels'] = isset($profiles['bullet_point_labels'][$profile_id][$id_lang]) ? $profiles['bullet_point_labels'][$profile_id][$id_lang] : null;
  4930.  
  4931. $p_browsenode = isset($profiles['browsenode'][$profile_id][$id_lang]) ? $profiles['browsenode'][$profile_id][$id_lang] : null;
  4932.  
  4933. $view_params['profiles']['config'][$profile_key][$id_lang]['browse_node'] = str_replace(array(
  4934. ';',
  4935. ':',
  4936. '-',
  4937. ','
  4938. ), ', ', $p_browsenode);
  4939.  
  4940. $view_params['profiles']['config'][$profile_key][$id_lang]['strategies'] = $strategies;
  4941. $view_params['profiles']['config'][$profile_key][$id_lang]['repricing'] = isset($profiles['repricing'][$profile_id][$id_lang]) ? $profiles['repricing'][$profile_id][$id_lang] : '';
  4942. ;
  4943.  
  4944. if ($this->config['features']['shipping']) {
  4945. // Shipping Templates
  4946. $view_params['profiles']['config'][$profile_key][$id_lang]['shipping_group'] = isset($profiles['shipping_group'][$profile_id][$id_lang]) ? $profiles['shipping_group'][$profile_id][$id_lang] : null;
  4947.  
  4948. $view_params['profiles']['shipping_templates']['enabled'] = $shipping_templates = is_array($this->config['shipping']) && isset($this->config['shipping']['shipping_templates']) && (bool)$this->config['shipping']['shipping_templates'];
  4949. $view_params['profiles']['shipping_templates']['groups'][$id_lang] = array();
  4950.  
  4951. if ($shipping_templates) {
  4952. $configured_group_names = unserialize(AmazonConfiguration::get('shipping_groups'));
  4953.  
  4954. if (is_array($configured_group_names) && count($configured_group_names)) {
  4955. foreach ($configured_group_names as $group_region => $group_names) {
  4956. if ($group_region != $region) {
  4957. continue;
  4958. }
  4959.  
  4960. $view_params['profiles']['shipping_templates']['groups'][$id_lang] = array();
  4961.  
  4962. if (is_array($group_names) && count($group_names)) {
  4963. foreach ($group_names as $group_key => $group_name) {
  4964. $view_params['profiles']['shipping_templates']['groups'][$id_lang][$group_key] = $group_name;
  4965. }
  4966. }
  4967. }
  4968. }
  4969. }
  4970. }
  4971.  
  4972. $view_params['profiles']['ptc'][$id_lang]= AmazonTaxes::getPtcList($region);
  4973. $view_params['profiles']['config'][$profile_key][$id_lang]['ptc_selected'] = isset($profiles['ptc'][$profile_id][$id_lang]) ? $profiles['ptc'][$profile_id][$id_lang] : null;
  4974. }
  4975. }
  4976.  
  4977. return ($view_params);
  4978. }
  4979.  
  4980. private function _mapping(&$view_params)
  4981. {
  4982. $selected_tab = $this->selectedTab();
  4983.  
  4984. $languages = AmazonTools::languages();
  4985. $lang_admin = Language::getIsoById($this->id_lang);
  4986.  
  4987. $view_params['mapping'] = array();
  4988. $view_params['mapping']['tutorial'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_MAPPINGS);
  4989. $view_params['mapping']['selected_tab'] = $selected_tab === 'mapping' ? true : false;
  4990. $view_params['mapping']['validation'] = $this->_validate(true);
  4991. $view_params['mapping']['images_url'] = $this->images;
  4992. $view_params['mapping']['attributes'] = array();
  4993. $view_params['mapping']['lang'] = array();
  4994. $view_params['mapping']['ungroup'] = $ungroup = (isset($this->config['mapping']['ungroup']) && (bool)$this->config['mapping']['ungroup'] ? true : false);
  4995. $view_params['mapping']['feature'] = array();
  4996. $view_params['mapping']['fixed'] = array();
  4997. $view_params['mapping']['attribute'] = array();
  4998.  
  4999. $valid_values = array();
  5000.  
  5001. if (is_array($this->config['mapping']) && count($this->config['mapping'])) {
  5002. $mapping = &$this->config['mapping'];
  5003. } else {
  5004. $mapping = array();
  5005. }
  5006.  
  5007. //
  5008. // Amazon Attributes Mapping
  5009. //
  5010. foreach ($languages as $language) {
  5011. $id_lang = $language['id_lang'];
  5012. $iso_lang = $language['iso_code'];
  5013. $id_attribute_group = null;
  5014.  
  5015. $matching_entries = AmazonSpecificField::getMatchingEntries($this->profiles, $id_lang);
  5016.  
  5017. if (!(isset($this->config['actives'][$id_lang]) && (int)$this->config['actives'][$id_lang])) {
  5018. continue;
  5019. }
  5020.  
  5021. if (isset($this->config['regions']) && is_array($this->config['regions']) && isset($this->config['regions'][$id_lang])) {
  5022. $region = $this->config['regions'][$id_lang];
  5023. } else {
  5024. $region = null;
  5025. }
  5026.  
  5027. if (isset(self::$attributes_groups[$id_lang])) {
  5028. $attributes_groups = &self::$attributes_groups[$id_lang];
  5029. } else {
  5030. //TODO: Preserve the reference
  5031. $attributes_groups = array();
  5032. }
  5033.  
  5034. if (isset(self::$attributes[$id_lang])) {
  5035. $attributes = &self::$attributes[$id_lang];
  5036. } else {
  5037. $attributes = array();
  5038. }
  5039.  
  5040. if (is_array(self::$features) && isset(self::$features[$id_lang])) {
  5041. $features = &self::$features[$id_lang];
  5042. } else {
  5043. $features = array();
  5044. }
  5045.  
  5046. if (is_array(self::$features_values) && isset(self::$features_values[$id_lang])) {
  5047. $features_values = &self::$features_values[$id_lang];
  5048. } else {
  5049. $features_values = array();
  5050. }
  5051.  
  5052. //
  5053. // 2014-11-24 International Valid Color Map
  5054. //
  5055. $standard_colors = array();
  5056.  
  5057. foreach (AmazonXSD::$langColorMap as $color => $langColorMap) {
  5058. if (!isset($langColorMap[$iso_lang])) {
  5059. continue;
  5060. }
  5061. $color_key = AmazonTools::toKey($langColorMap[$iso_lang]);
  5062. if (isset(AmazonXSD::$langColorMap[$color][$iso_lang])) {
  5063. $standard_colors[$color_key] = AmazonXSD::$langColorMap[$color][$iso_lang];
  5064. } elseif (isset(AmazonXSD::$langColorMap[$color]['en']) && is_array(AmazonXSD::$langColorMap[$color]['en'])) {
  5065. $standard_colors[$color_key] = AmazonXSD::$langColorMap[$color]['en'];
  5066. } else {
  5067. $standard_colors[$color_key] = AmazonTools::ucfirst($color);
  5068. }
  5069. $standard_colors[$color_key] = AmazonXSD::$langColorMap[$color][$iso_lang];
  5070. }
  5071.  
  5072. $view_params['mapping']['lang'][$id_lang] = array();
  5073. $view_params['mapping']['lang'][$id_lang]['name'] = $language['name'];
  5074. $view_params['mapping']['lang'][$id_lang]['iso_code'] = $language['iso_code'];
  5075. $view_params['mapping']['lang'][$id_lang]['flag'] = $this->images.'geo_flags/'.$this->geoFlag($language['id_lang']).'.gif';
  5076.  
  5077. $view_params['mapping']['feature'][$id_lang] = array();
  5078.  
  5079. // Matching Entry: Features
  5080. //
  5081. foreach ($matching_entries as $matching_entry) {
  5082. if ($matching_entry['prestashop_type'] != 'feature') {
  5083. continue;
  5084. }
  5085.  
  5086. if (!is_array($features) || !count($features) || !is_array($features_values) || !count($features_values)) {
  5087. continue;
  5088. }
  5089.  
  5090. if (!($id_feature = (int)$matching_entry['prestashop_id'])) {
  5091. continue;
  5092. }
  5093.  
  5094. if (!isset($features[$id_feature]) || !count($features[$id_feature]) || !isset($features_values[$id_feature]) || !count($features_values[$id_feature])) {
  5095. continue;
  5096. }
  5097.  
  5098. $profile_key = $matching_entry['profile_key'];
  5099. $profile_name = $matching_entry['profile_name'];
  5100.  
  5101. $amazon_attr_label = trim(preg_replace('/([A-Z])/', ' \1', $matching_entry['amazon_attribute']));
  5102.  
  5103. if ($ungroup) {
  5104. $title = sprintf('%s, %s &gt; %s', $profile_name, $amazon_attr_label, $features[$id_feature]['name']);
  5105. $mapping_key = $profile_key;
  5106. } else {
  5107. $title = sprintf('%s, %s &gt; %s', $matching_entry['universe'], $amazon_attr_label, $features[$id_feature]['name']);
  5108. $mapping_key = sprintf('%s/%s', $matching_entry['universe'], $matching_entry['amazon_attribute']);
  5109. }
  5110.  
  5111. $view_params['mapping']['feature'][$id_lang][$mapping_key][$id_feature] = array();
  5112. $view_params['mapping']['feature'][$id_lang][$mapping_key][$id_feature]['name'] = $title;
  5113. $view_params['mapping']['feature'][$id_lang][$mapping_key][$id_feature]['left'] = array();
  5114. $view_params['mapping']['feature'][$id_lang][$mapping_key][$id_feature]['right'] = array();
  5115. $view_params['mapping']['feature'][$id_lang][$mapping_key][$id_feature]['mandatory'] = $matching_entry['mandatory'];
  5116.  
  5117.  
  5118. $target_mapping = (is_array($mapping) && isset($mapping['features']) && isset($mapping['features']['free']) && isset($mapping['features']['free'][$id_lang])) ? $mapping['features']['free'][$id_lang] : array();
  5119. $constrained_mapping = false;
  5120.  
  5121. if ($this->config['features']['creation'] && Tools::strlen($matching_entry['universe']) && Tools::strlen($matching_entry['product_type']) && $region) {
  5122. $valid_values = AmazonValidValues::getValidValues($matching_entry['universe'], $matching_entry['amazon_attribute'], $region);
  5123.  
  5124. if (is_array($valid_values) && count($valid_values)) {
  5125. foreach ($valid_values as $valid_value_key => $valid_value) {
  5126. if (!Tools::strlen($valid_value)) {
  5127. continue;
  5128. }
  5129.  
  5130. $view_params['mapping']['feature'][$id_lang][$mapping_key][$id_feature]['right'][$valid_value_key] = $valid_value;
  5131. }
  5132. $target_mapping = (is_array($mapping) && isset($mapping['features']) && isset($mapping['features']['const']) && isset($mapping['features']['const'][$id_lang])) ? $mapping['features']['const'][$id_lang] : array();
  5133. $constrained_mapping = true;
  5134. }
  5135. }
  5136. $view_params['mapping']['feature'][$id_lang][$mapping_key][$id_feature]['has_valid_values'] = count($view_params['mapping']['feature'][$id_lang][$mapping_key][$id_feature]['right']) ? true : false;
  5137.  
  5138. $matched = array();
  5139.  
  5140. foreach ($features_values[$id_feature] as $id_feature_value => $feature_value) {
  5141. $feature_value['mapping'] = null;
  5142.  
  5143. $has_key = is_array($target_mapping) && isset($target_mapping[$mapping_key]);
  5144. $has_feature = $has_key && isset($target_mapping[$mapping_key][$id_feature]);
  5145. $has_feature_value = $has_feature && isset($target_mapping[$mapping_key][$id_feature][$id_feature_value]);
  5146.  
  5147. $feature_key = AmazonTools::toKey($feature_value['value']);
  5148.  
  5149. if ($constrained_mapping && count($target_mapping) && $has_feature_value) {
  5150. $feature_value['mapping'] = AmazonTools::toKey($target_mapping[$mapping_key][$id_feature][$id_feature_value]);
  5151. } elseif ($constrained_mapping) {
  5152. $feature_value['mapping'] = null;
  5153. } elseif (count($target_mapping) && $has_feature_value) {
  5154. $feature_value['mapping'] = $target_mapping[$mapping_key][$id_feature][$id_feature_value];
  5155. }
  5156.  
  5157. if ($matching_entry['is_color'] && count($valid_values) && isset($valid_values[$feature_key])) {
  5158. $matched[] = $feature_value['value'];
  5159. continue;
  5160. } elseif ($matching_entry['is_color'] && isset($standard_colors[$feature_key])) {
  5161. $matched[] = $feature_value['value'];
  5162. continue;
  5163. }
  5164.  
  5165. $view_params['mapping']['feature'][$id_lang][$mapping_key][$id_feature]['left'][$id_feature_value] = $feature_value;
  5166. }
  5167.  
  5168. if (is_array($matched) && count($matched)) {
  5169. $matching_list = implode(', ', array_unique($matched));
  5170.  
  5171. if (Tools::strlen($matching_list) > 64) {
  5172. preg_replace('/(?<=^.{64}).{4,}(?=.{64}$)/', '...', $matching_list);
  5173. }
  5174.  
  5175. $view_params['mapping']['feature'][$id_lang][$mapping_key][$id_feature]['match_list'] = $matching_list;
  5176. $view_params['mapping']['feature'][$id_lang][$mapping_key][$id_feature]['mandatory'] = false;
  5177. }
  5178.  
  5179. if (!count($view_params['mapping']['feature'][$id_lang][$mapping_key])) {
  5180. unset($view_params['mapping']['feature'][$id_lang][$mapping_key]);
  5181. }
  5182. }
  5183. if ($iso_lang === $lang_admin) {
  5184. $view_params['mapping']['lang'][$id_lang]['feat_collapsed'] = true;
  5185. } else {
  5186. $view_params['mapping']['lang'][$id_lang]['feat_collapsed'] = false;
  5187. }
  5188.  
  5189. $view_params['mapping']['attribute'][$id_lang] = array();
  5190.  
  5191. // Matching Entry: Attributes
  5192. //
  5193. foreach ($matching_entries as $matching_entry) {
  5194. if ($matching_entry['prestashop_type'] != 'attribute') {
  5195. continue;
  5196. }
  5197.  
  5198. if (!is_array($attributes) || !count($attributes) || !is_array($attributes_groups) || !count($attributes_groups)) {
  5199. continue;
  5200. }
  5201.  
  5202. if (!($id_attribute_group = (int)$matching_entry['prestashop_id'])) {
  5203. continue;
  5204. }
  5205.  
  5206. if (!isset($attributes_groups[$id_attribute_group]) || !count($attributes_groups[$id_attribute_group])) {
  5207. continue;
  5208. }
  5209.  
  5210. $first_attribute = reset($attributes[$id_attribute_group]);
  5211.  
  5212. $profile_key = $matching_entry['profile_key'];
  5213. $profile_name = $matching_entry['profile_name'];
  5214. $amazon_attr_label = trim(preg_replace('/([A-Z])/', ' \1', $matching_entry['amazon_attribute']));
  5215.  
  5216. if ($ungroup) {
  5217. $title = sprintf('%s, %s &gt; %s', $profile_name, $amazon_attr_label, $first_attribute['attribute_group']);
  5218. $mapping_key = $profile_key;
  5219. } else {
  5220. $title = sprintf('%s, %s &gt; %s', $matching_entry['universe'], $amazon_attr_label, $first_attribute['attribute_group']);
  5221. $mapping_key = sprintf('%s/%s', $matching_entry['universe'], $matching_entry['amazon_attribute']);
  5222. }
  5223.  
  5224. $view_params['mapping']['attribute'][$id_lang][$mapping_key][$id_attribute_group] = array();
  5225. $view_params['mapping']['attribute'][$id_lang][$mapping_key][$id_attribute_group]['name'] = $title;
  5226. $view_params['mapping']['attribute'][$id_lang][$mapping_key][$id_attribute_group]['left'] = array();
  5227. $view_params['mapping']['attribute'][$id_lang][$mapping_key][$id_attribute_group]['right'] = array();
  5228. $view_params['mapping']['attribute'][$id_lang][$mapping_key][$id_attribute_group]['mandatory'] = $matching_entry['mandatory'];
  5229.  
  5230. $target_mapping = (is_array($mapping) && isset($mapping['attributes']) && isset($mapping['attributes']['free']) && isset($mapping['attributes']['free'][$id_lang])) ? $mapping['attributes']['free'][$id_lang] : array();
  5231.  
  5232. $constrained_mapping = false;
  5233.  
  5234. if ($this->config['features']['creation'] && Tools::strlen($matching_entry['universe']) && Tools::strlen($matching_entry['product_type']) && $region) {
  5235. $valid_values = AmazonValidValues::getValidValues($matching_entry['universe'], $matching_entry['amazon_attribute'], $region);
  5236.  
  5237. if (is_array($valid_values) && count($valid_values)) {
  5238. foreach ($valid_values as $valid_value_key => $valid_value) {
  5239. if (!Tools::strlen($valid_value)) {
  5240. continue;
  5241. }
  5242.  
  5243. $view_params['mapping']['attribute'][$id_lang][$mapping_key][$id_attribute_group]['right'][$valid_value_key] = $valid_value;
  5244. }
  5245. $target_mapping = (is_array($mapping) && isset($mapping['attributes']) && isset($mapping['attributes']['const']) && isset($mapping['attributes']['const'][$id_lang])) ? $mapping['attributes']['const'][$id_lang] : array();
  5246. $constrained_mapping = true;
  5247. }
  5248. }
  5249.  
  5250. $view_params['mapping']['attribute'][$id_lang][$mapping_key][$id_attribute_group]['has_valid_values'] = $has_valid_values = count($view_params['mapping']['attribute'][$id_lang][$mapping_key][$id_attribute_group]['right']) ? true : false;
  5251.  
  5252. $matched = array();
  5253.  
  5254. foreach ($attributes[$id_attribute_group] as $id_attribute => $attribute) {
  5255. $attribute['mapping'] = null;
  5256. $attribute_key = AmazonTools::toKey($attribute['name']);
  5257.  
  5258. $has_key = is_array($target_mapping) && isset($target_mapping[$mapping_key]);
  5259. $has_attribute_group = $has_key && isset($target_mapping[$mapping_key][$id_attribute_group]);
  5260. $has_attribute = $has_attribute_group && isset($target_mapping[$mapping_key][$id_attribute_group][$id_attribute]);
  5261.  
  5262. if ($constrained_mapping && count($target_mapping) && $has_attribute) {
  5263. $attribute['mapping'] = AmazonTools::toKey($target_mapping[$mapping_key][$id_attribute_group][$id_attribute]);
  5264. } elseif ($constrained_mapping) {
  5265. $attribute['mapping'] = null;
  5266. } elseif (count($target_mapping) && $has_attribute) {
  5267. $attribute['mapping'] = $target_mapping[$mapping_key][$id_attribute_group][$id_attribute];
  5268. }
  5269.  
  5270. if ($matching_entry['is_color'] && count($valid_values) && isset($valid_values[$attribute_key])) {
  5271. $matched[] = $attribute['name'];
  5272. continue;
  5273. } elseif ($matching_entry['is_color'] && isset($valid_values[$attribute_key])) {
  5274. $matched[] = $attribute['name'];
  5275. continue;
  5276. } elseif ($matching_entry['is_color'] && isset($standard_colors[$attribute_key])) {
  5277. $matched[] = $attribute['name'];
  5278. continue;
  5279. } elseif ($matching_entry['amazon_attribute'] == 'Size' && isset($valid_values[$attribute_key])) {
  5280. $matched[] = $attribute['name'];
  5281. continue;
  5282. }
  5283.  
  5284. $view_params['mapping']['attribute'][$id_lang][$mapping_key][$id_attribute_group]['left'][$id_attribute] = $attribute;
  5285. }
  5286.  
  5287. if (is_array($matched) && count($matched)) {
  5288. $matching_list = implode(', ', array_unique($matched));
  5289.  
  5290. if (Tools::strlen($matching_list) > 64) {
  5291. preg_replace('/(?<=^.{64}).{4,}(?=.{64}$)/', '...', $matching_list);
  5292. }
  5293.  
  5294. $view_params['mapping']['attribute'][$id_lang][$mapping_key][$id_attribute_group]['match_list'] = $matching_list;
  5295. $view_params['mapping']['attribute'][$id_lang][$mapping_key][$id_attribute_group]['mandatory'] = false;
  5296. }
  5297.  
  5298. if (!count($view_params['mapping']['attribute'][$id_lang][$mapping_key])) {
  5299. unset($view_params['mapping']['attribute'][$id_lang][$mapping_key]);
  5300. }
  5301. }
  5302.  
  5303.  
  5304. if ($iso_lang === $lang_admin) {
  5305. $view_params['mapping']['lang'][$id_lang]['attr_collapsed'] = true;
  5306. } else {
  5307. $view_params['mapping']['lang'][$id_lang]['attr_collapsed'] = false;
  5308. }
  5309.  
  5310. $view_params['mapping']['fixed'][$id_lang] = array();
  5311.  
  5312. // Matching Entry: Fixed Values
  5313. //
  5314. foreach ($matching_entries as $matching_entry) {
  5315. if (!$matching_entry['fixed_value']) {
  5316. continue;
  5317. }
  5318.  
  5319. $amazon_attribute = $matching_entry['amazon_attribute'];
  5320. $profile_key = $matching_entry['profile_key'];
  5321. $profile_name = $matching_entry['profile_name'];
  5322.  
  5323. $amazon_attr_label = trim(preg_replace('/([A-Z])/', ' \1', $amazon_attribute));
  5324.  
  5325. if ($ungroup) {
  5326. $title = sprintf('%s, %s', $profile_name, $amazon_attr_label);
  5327. $mapping_key = $profile_key;
  5328. } else {
  5329. $title = sprintf('%s, %s', $matching_entry['universe'], $amazon_attr_label);
  5330. $mapping_key = sprintf('%s/%s', $matching_entry['universe'], $matching_entry['amazon_attribute']);
  5331. }
  5332.  
  5333. if (is_array($mapping) && isset($mapping['fixed']) && isset($mapping['fixed'][$id_lang]) && isset($mapping['fixed'][$id_lang][$mapping_key]) && isset($mapping['fixed'][$id_lang][$mapping_key][$amazon_attribute])) {
  5334. $value = $mapping['fixed'][$id_lang][$mapping_key][$amazon_attribute];
  5335. } else {
  5336. $value = null;
  5337. }
  5338.  
  5339. $view_params['mapping']['fixed'][$id_lang][$mapping_key][$amazon_attribute] = array();
  5340. $view_params['mapping']['fixed'][$id_lang][$mapping_key][$amazon_attribute]['name'] = $title;
  5341. $view_params['mapping']['fixed'][$id_lang][$mapping_key][$amazon_attribute]['value'] = $value;
  5342. }
  5343.  
  5344. if ($iso_lang === $lang_admin) {
  5345. $view_params['mapping']['lang'][$id_lang]['fixed_collapsed'] = true;
  5346. } else {
  5347. $view_params['mapping']['lang'][$id_lang]['fixed_collapsed'] = false;
  5348. }
  5349.  
  5350. $view_params['mapping']['add_mapping'][$id_lang] = array();
  5351. $view_params['mapping']['add_mapping_lang'][$id_lang] = array();
  5352.  
  5353. if (is_array($matching_entries) && count($matching_entries)) {
  5354. $used_universes_attributes = array();
  5355.  
  5356. foreach ($matching_entries as $matching_entry) {
  5357. if (array_key_exists('fixed_value', $matching_entry) && (bool)$matching_entry['fixed_value']) {
  5358. continue;
  5359. }
  5360.  
  5361. $valid_values = AmazonValidValues::getValidValues($matching_entry['universe'], $matching_entry['amazon_attribute'], $region);
  5362.  
  5363. if (!count($valid_values)) {
  5364. continue;
  5365. }
  5366.  
  5367. $universe = $matching_entry['universe'];
  5368. $attr_key = AmazonTools::toKey($matching_entry['amazon_attribute']);
  5369.  
  5370. $used_universes_attributes[$universe][$attr_key] = $matching_entry['amazon_attribute'];
  5371. }
  5372. $additionnal_mapping_values = array();
  5373.  
  5374. if (is_array($used_universes_attributes) && count($used_universes_attributes)) {
  5375. asort($used_universes_attributes);
  5376.  
  5377. foreach ($used_universes_attributes as $universe => $mappings) {
  5378. if (!is_array($mappings)) {
  5379. continue;
  5380. }
  5381.  
  5382. $additionnal_mapping_values[$universe] = array();
  5383.  
  5384. foreach ($mappings as $attribute_key => $amazon_attribute) {
  5385. $result = AmazonValidValues::getCustomMapping($universe, $amazon_attribute, $region);
  5386.  
  5387. if (is_array($result) && count($result)) {
  5388. $additionnal_mapping_values[$universe][$amazon_attribute] = implode(',', $result);
  5389. }
  5390. }
  5391. }
  5392. }
  5393.  
  5394. $view_params['mapping']['add_mapping'][$id_lang] = $used_universes_attributes;
  5395. $view_params['mapping']['add_mapping_values'][$id_lang] = $additionnal_mapping_values;
  5396.  
  5397. $view_params['mapping']['add_mapping_lang'][$id_lang] = array();
  5398. $view_params['mapping']['add_mapping_lang'][$id_lang]['name'] = $language['name'];
  5399. $view_params['mapping']['add_mapping_lang'][$id_lang]['flag'] = $this->images.'geo_flags/'.$this->geoFlag($language['id_lang']).'.gif';
  5400. $view_params['mapping']['add_mapping_lang'][$id_lang]['iso_code'] = $language['iso_code'];
  5401. $view_params['mapping']['add_mapping_lang'][$id_lang]['region'] = $region;
  5402.  
  5403. if ($iso_lang === $lang_admin) {
  5404. $view_params['mapping']['add_mapping_lang'][$id_lang]['attr_collapsed'] = true;
  5405. } else {
  5406. $view_params['mapping']['add_mapping_lang'][$id_lang]['attr_collapsed'] = false;
  5407. }
  5408. }
  5409.  
  5410. if (!count($view_params['mapping']['add_mapping_lang'][$id_lang])) {
  5411. unset($view_params['mapping']['add_mapping_lang'][$id_lang]);
  5412. }
  5413.  
  5414. if (!count($view_params['mapping']['add_mapping'][$id_lang])) {
  5415. unset($view_params['mapping']['add_mapping'][$id_lang]);
  5416. }
  5417.  
  5418. if (!count($view_params['mapping']['fixed'][$id_lang])) {
  5419. unset($view_params['mapping']['fixed'][$id_lang]);
  5420. }
  5421.  
  5422. if (!count($view_params['mapping']['feature'][$id_lang])) {
  5423. unset($view_params['mapping']['feature'][$id_lang]);
  5424. }
  5425.  
  5426. if (!count($view_params['mapping']['attribute'][$id_lang])) {
  5427. unset($view_params['mapping']['attribute'][$id_lang]);
  5428. }
  5429. }
  5430. $count_fixed = count($view_params['mapping']['fixed']);
  5431. $count_feature = count($view_params['mapping']['feature']);
  5432. $count_attribute = count($view_params['mapping']['attribute']);
  5433. $count_all = $count_fixed + $count_feature + $count_attribute;
  5434.  
  5435. if (!$count_fixed) {
  5436. unset($view_params['mapping']['fixed']);
  5437. }
  5438.  
  5439. if (!$count_feature) {
  5440. unset($view_params['mapping']['feature']);
  5441. }
  5442.  
  5443. if (!$count_attribute) {
  5444. unset($view_params['mapping']['attribute']);
  5445. }
  5446.  
  5447. $view_params['mapping']['count'] = $count_all;
  5448.  
  5449. return ($view_params);
  5450. }
  5451.  
  5452. private function _filters(&$view_params)
  5453. {
  5454. $view_params['filters']['selected_tab'] = $this->selectedTab() === 'filters' ? true : false;
  5455. $view_params['filters']['images_url'] = $this->images;
  5456. $view_params['filters']['url'] = $this->url;
  5457. $view_params['filters']['validation'] = $this->_validate(true);
  5458. $view_params['filters']['tutorial'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_FILTERS);
  5459.  
  5460. $price_filter = $this->config['price_filter'];
  5461.  
  5462. // Price Filtering
  5463. //
  5464. $view_params['filters']['prices'] = array();
  5465. $view_params['filters']['prices']['currency_sign'] = Currency::getDefaultCurrency()->sign;
  5466. $view_params['filters']['prices']['gt'] = null;
  5467. $view_params['filters']['prices']['lt'] = null;
  5468.  
  5469. if (is_array($price_filter) && isset($price_filter['gt']) && (float)$price_filter['gt']) {
  5470. $view_params['filters']['prices']['gt'] = sprintf('%.02f', $price_filter['gt']);
  5471. }
  5472.  
  5473. if (is_array($price_filter) && isset($price_filter['lt']) && (float)$price_filter['lt']) {
  5474. $view_params['filters']['prices']['lt'] = sprintf('%.02f', $price_filter['lt']);
  5475. }
  5476.  
  5477. // Manufacturers Filtering
  5478. //
  5479. $manufacturers = Manufacturer::getManufacturers(false, $this->id_lang);
  5480.  
  5481. $selected_manufacturers = $this->config['excluded_manufacturers'];
  5482.  
  5483. $filtered_manufacturers = array();
  5484. $available_manufacturers = array();
  5485.  
  5486. if (is_array($manufacturers) && count($manufacturers)) {
  5487. foreach ($manufacturers as $manufacturer) {
  5488. if (is_array($selected_manufacturers) && in_array((string)$manufacturer['id_manufacturer'], $selected_manufacturers)) {
  5489. continue;
  5490. }
  5491.  
  5492. $available_manufacturers[$manufacturer['id_manufacturer']] = $manufacturer['name'];
  5493. }
  5494. if (is_array($selected_manufacturers) && count($selected_manufacturers)) {
  5495. foreach ($manufacturers as $manufacturer) {
  5496. if (is_array($selected_manufacturers) && !in_array((string)$manufacturer['id_manufacturer'], $selected_manufacturers)) {
  5497. continue;
  5498. }
  5499.  
  5500. $filtered_manufacturers[$manufacturer['id_manufacturer']] = $manufacturer['name'];
  5501. }
  5502. }
  5503. }
  5504. $view_params['filters']['manufacturers'] = array();
  5505. $view_params['filters']['manufacturers']['available'] = $available_manufacturers;
  5506. $view_params['filters']['manufacturers']['filtered'] = $filtered_manufacturers;
  5507.  
  5508. // Suppliers Filtering
  5509. //
  5510. $suppliers = Supplier::getSuppliers(false, $this->id_lang);
  5511.  
  5512. $selected_suppliers = $this->config['excluded_suppliers'];
  5513. $filtered_suppliers = array();
  5514. $available_suppliers = array();
  5515.  
  5516. if (is_array($suppliers) && count($suppliers)) {
  5517. foreach ($suppliers as $supplier) {
  5518. if (is_array($selected_suppliers) && in_array((string)$supplier['id_supplier'], $selected_suppliers)) {
  5519. continue;
  5520. }
  5521.  
  5522. $available_suppliers[$supplier['id_supplier']] = $supplier['name'];
  5523. }
  5524. if (is_array($selected_suppliers) && count($selected_suppliers)) {
  5525. foreach ($suppliers as $supplier) {
  5526. if (is_array($selected_suppliers) && !in_array((string)$supplier['id_supplier'], $selected_suppliers)) {
  5527. continue;
  5528. }
  5529.  
  5530. $filtered_suppliers[$supplier['id_supplier']] = $supplier['name'];
  5531. }
  5532. }
  5533. }
  5534. $view_params['filters']['suppliers'] = array();
  5535. $view_params['filters']['suppliers']['available'] = $available_suppliers;
  5536. $view_params['filters']['suppliers']['filtered'] = $filtered_suppliers;
  5537. }
  5538.  
  5539. private function _shipping(&$view_params)
  5540. {
  5541. $view_params['shipping'] = array();
  5542. $view_params['shipping']['selected_tab'] = $this->selectedTab() === 'shipping' ? true : false;
  5543. $view_params['shipping']['images_url'] = $this->images;
  5544. $view_params['shipping']['url'] = $this->url;
  5545. $view_params['shipping']['validation'] = $this->_validate(true);
  5546. $view_params['shipping']['shipping_url'] = $this->url.'functions/download_reports.php?instant_token='.$this->config['instant_token'].'&context_key='.AmazonContext::getKey($this->context->shop);
  5547. $view_params['shipping']['tutorial'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_SHIPPING);
  5548. $view_params['shipping']['expert_mode'] = (bool)$this->config['features']['expert_mode'];
  5549.  
  5550. $view_params['shipping']['carriers'] = array();
  5551. $view_params['shipping']['smart_shipping'] = array();
  5552. $view_params['shipping']['smart_shipping']['mapping'] = array();
  5553.  
  5554. $view_params['shipping']['smart_shipping']['kind'] = array();
  5555. $view_params['shipping']['smart_shipping']['kind']['additive'] = self::SHIPPING_OVERRIDE_ADDITIVE;
  5556. $view_params['shipping']['smart_shipping']['kind']['exclusive'] = self::SHIPPING_OVERRIDE_EXCLUSIVE;
  5557. $view_params['shipping']['smart_shipping']['kind']['value'] = null;
  5558.  
  5559. if (!is_array($this->config['shipping'])) {
  5560. $this->config['shipping'] = array();
  5561. }
  5562.  
  5563. if (isset($this->config['shipping']['allow_overrides'])) {
  5564. $view_params['shipping']['allow_overrides'] = (bool)$this->config['shipping']['allow_overrides'];
  5565. } else {
  5566. $view_params['shipping']['allow_overrides'] = false;
  5567. }
  5568.  
  5569. if (isset($this->config['shipping']['tare']) && (float)$this->config['shipping']['tare']) {
  5570. $view_params['shipping']['tare'] = sprintf('%.02f', (float)$this->config['shipping']['tare']);
  5571. } else {
  5572. $view_params['shipping']['tare'] = 0;
  5573. }
  5574.  
  5575. if (isset($this->config['shipping']['gauge']) && (float)$this->config['shipping']['gauge']) {
  5576. $view_params['shipping']['gauge'] = sprintf('%.02f', (float)$this->config['shipping']['gauge']);
  5577. } else {
  5578. $view_params['shipping']['gauge'] = 0;
  5579. }
  5580.  
  5581. $view_params['shipping']['marketplaces'] = array();
  5582. $view_params['shipping']['marketplaces']['countries'] = $marketplace_countries = AmazonSpecificField::countrySelector();
  5583. $view_params['shipping']['marketplaces']['show'] = count($marketplace_countries) > 1;
  5584.  
  5585. $view_params['shipping']['shipping_templates'] = array();
  5586.  
  5587. if ($this->config['features']['shipping']) {
  5588. // Shipping Templates
  5589. $view_params['shipping']['shipping_templates']['enabled'] = $shipping_templates = is_array($this->config['shipping']) && isset($this->config['shipping']['shipping_templates']) && (bool)$this->config['shipping']['shipping_templates'];
  5590. $view_params['shipping']['shipping_templates']['groups'] = array();
  5591.  
  5592. if ($shipping_templates) {
  5593. $configured_group_names = unserialize(AmazonConfiguration::get('shipping_groups'));
  5594.  
  5595. if (is_array($configured_group_names) && count($configured_group_names)) {
  5596. foreach ($configured_group_names as $region => $group_names) {
  5597. $view_params['shipping']['shipping_templates']['groups'][$region] = array();
  5598.  
  5599. if (is_array($group_names) && count($group_names)) {
  5600. foreach ($group_names as $group_key => $group_name) {
  5601. $view_params['shipping']['shipping_templates']['groups'][$region][$group_key] = $group_name;
  5602. }
  5603. }
  5604. }
  5605. }
  5606. }
  5607. } else {
  5608. $view_params['shipping']['shipping_templates']['enabled'] = false;
  5609. $view_params['shipping']['shipping_templates']['groups'] = array();
  5610. }
  5611.  
  5612. if (isset($this->config['shipping']['smart_shipping']) && is_array($this->config['shipping']['smart_shipping'])) {
  5613. $view_params['shipping']['smart_shipping'] = $this->config['shipping']['smart_shipping'];
  5614. }
  5615.  
  5616. $view_params['shipping']['smart_shipping']['kind'] = array();
  5617. $view_params['shipping']['smart_shipping']['kind']['additive'] = self::SHIPPING_OVERRIDE_ADDITIVE;
  5618. $view_params['shipping']['smart_shipping']['kind']['exclusive'] = self::SHIPPING_OVERRIDE_EXCLUSIVE;
  5619. $view_params['shipping']['smart_shipping']['kind']['value'] = null;
  5620.  
  5621. if (!isset($view_params['shipping']['smart_shipping']['active'])) {
  5622. $view_params['shipping']['smart_shipping']['active'] = false;
  5623. }
  5624.  
  5625. $carriers = &self::$carriers;
  5626.  
  5627. foreach ($carriers as $carrier) {
  5628. $view_params['shipping']['carriers'][$carrier['id_carrier']] = $carrier['name'];
  5629. }
  5630.  
  5631. if (isset($this->config['shipping_methods']) && is_array($this->config['shipping_methods'])) {
  5632. if (isset($this->config['shipping']['smart_shipping']['kind'])) {
  5633. $view_params['shipping']['smart_shipping']['kind']['value'] = $this->config['shipping']['smart_shipping']['kind'];
  5634. }
  5635.  
  5636. foreach ($this->config['shipping_methods'] as $shipping_method) {
  5637. if (empty($shipping_method)) {
  5638. continue;
  5639. }
  5640.  
  5641. if (isset($this->config['shipping']['smart_shipping']['prestashop'][$shipping_method]) && $this->config['shipping']['smart_shipping']['prestashop'][$shipping_method]) {
  5642. $selected = $this->config['shipping']['smart_shipping']['prestashop'][$shipping_method];
  5643. } else {
  5644. $selected = null;
  5645. }
  5646.  
  5647. $view_params['shipping']['smart_shipping']['mapping'][$shipping_method] = $selected;
  5648. }
  5649. }
  5650. }
  5651.  
  5652. /*Sets initial data form new SHOP when data si duplicated form Main shop - added for multistore comaptibility - Apr/6/2014 - ERT*/
  5653. /*
  5654. public function hookActionShopDataDuplication($params){
  5655. $shop = new Shop((int)$params["new_id_shop"]);
  5656. $id_shop_group = $shop->id_shop_group;
  5657. $id_shop = $shop->id;
  5658. foreach ($this->_config as $key => $value)
  5659. {
  5660. if (is_null($value))
  5661. $value = '';
  5662.  
  5663. if (is_array($value))
  5664. $value = AmazonTools::encode(serialize($value));
  5665.  
  5666. if (!self::configurationUpdateValue($key, $value, $id_shop_group, $id_shop))
  5667. {
  5668. $this->_errors[] = sprintf('%s - key: %s, value: %s', $this->l('Unable to duplicate data for Shop ID '. $params["new_id_shop"] .' : Some configuration values'), $key, nl2br(print_r($value, true)));
  5669. }
  5670. }
  5671. }
  5672. */
  5673.  
  5674. private function _messaging(&$view_params)
  5675. {
  5676. require_once(dirname(__FILE__).'/classes/amazon.messaging.class.php');
  5677.  
  5678. $mail_invoice = $this->config['mail_invoice'];
  5679. $mail_review = $this->config['mail_review'];
  5680. $mail_customer_thread = $this->config['mail_customer_thread'];
  5681.  
  5682. $pass = true;
  5683. $lang = Language::getIsoById($this->id_lang);
  5684.  
  5685. $mail_templates = null;
  5686. $mail_add_files = null;
  5687.  
  5688. $view_params['messaging'] = array();
  5689.  
  5690. $view_params['messaging']['selected_tab'] = $this->selectedTab() === 'messaging' ? true : false;
  5691. $view_params['messaging']['images_url'] = $this->images;
  5692. $view_params['messaging']['is_ps15'] = version_compare(_PS_VERSION_, '1.5', '>=');
  5693. $view_params['messaging']['url'] = $this->url;
  5694. $view_params['messaging']['validation'] = $this->_validate(true);
  5695. $view_params['messaging']['account_type_is_global'] = (bool)($this->config['account_type'] == self::ACCOUNT_TYPE_GLOBAL);
  5696.  
  5697. $view_params['messaging']['tutorial'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_MESSAGING);
  5698. // Order State
  5699. //
  5700. $orderStates = OrderState::getOrderStates($this->id_lang);
  5701.  
  5702. $view_params['messaging']['order_states'] = array();
  5703.  
  5704. $c = 0;
  5705. foreach ($orderStates as $orderState) {
  5706. if (!(int)$orderState['id_order_state']) {
  5707. continue;
  5708. }
  5709.  
  5710. if (!$orderState['invoice'] || $orderState['send_email']) {
  5711. continue;
  5712. }
  5713.  
  5714. $view_params['messaging']['order_states'][$c]['value'] = (int)$orderState['id_order_state'];
  5715. $view_params['messaging']['order_states'][$c]['name'] = $orderState['name'];
  5716. $c++;
  5717. }
  5718.  
  5719. if (!is_dir($this->path_mail.$lang)) {
  5720. $lang = 'en';
  5721. }
  5722.  
  5723. $mailDir = sprintf('%s%s/*.html', $this->path_mail, $lang);
  5724.  
  5725. // Mail Template
  5726. //
  5727. if (is_dir($this->path_mail.$lang)) {
  5728. $files = glob($mailDir);
  5729.  
  5730. if ($files) {
  5731. $result = preg_replace('#.*/(\w*)\.html#', '$1', $files);
  5732.  
  5733. if (is_array($result)) {
  5734. $mail_templates = array_unique($result);
  5735. } else {
  5736. $pass = false;
  5737. }
  5738. } else {
  5739. $pass = false;
  5740. }
  5741. } else {
  5742. $pass = false;
  5743. }
  5744.  
  5745. // Optionnal Additionnal File
  5746. //
  5747. if (is_dir($this->path_pdf)) {
  5748. $files = glob($this->path_pdf.'*.pdf');
  5749.  
  5750. if ($files) {
  5751. $result = preg_replace('#.*/(\w*)#', '$1', $files);
  5752.  
  5753. if (is_array($result)) {
  5754. $mail_add_files = array_unique($result);
  5755. }
  5756. }
  5757. }
  5758.  
  5759. if ($pass) {
  5760. $view_params['messaging']['problem'] = false;
  5761. } else {
  5762. $view_params['messaging']['problem'] = true;
  5763. }
  5764.  
  5765. // Testing feature
  5766. if (AmazonTools::tableExists(_DB_PREFIX_.self::TABLE_MARKETPLACE_ORDERS)) {
  5767. $sql = 'SELECT o.`id_order`, concat(c.`firstname`, " ", c.`lastname`) as customer from `'._DB_PREFIX_.self::TABLE_MARKETPLACE_ORDERS.'` mo
  5768. LEFT JOIN `'._DB_PREFIX_.'orders` o on (o.`id_order` = mo.`id_order`)
  5769. LEFT JOIN `'._DB_PREFIX_.'customer` c on (o.`id_customer` = c.`id_customer`)
  5770. ORDER BY o.`id_order` DESC LIMIT 10';
  5771.  
  5772. $results = Db::getInstance()->ExecuteS($sql);
  5773.  
  5774. if (is_array($results) && count($results)) {
  5775. $view_params['messaging']['test'] = array();
  5776. foreach ($results as $order) {
  5777. $id_order = $order['id_order'];
  5778. $view_params['messaging']['test'][$id_order] = array();
  5779. $view_params['messaging']['test'][$id_order]['id_order'] = $order['id_order'];
  5780. $view_params['messaging']['test'][$id_order]['customer'] = $order['customer'];
  5781. }
  5782. }
  5783. }
  5784.  
  5785. $view_params['messaging']['mail_templates'] = $mail_templates;
  5786. $view_params['messaging']['mail_add_files'] = $mail_add_files;
  5787. $view_params['messaging']['experimental'] = self::ENABLE_EXPERIMENTAL_FEATURES;
  5788.  
  5789. $view_params['messaging']['mail_invoice'] = array();
  5790. $view_params['messaging']['mail_invoice']['active'] = isset($mail_invoice['active']) ? $mail_invoice['active'] : false;
  5791. $view_params['messaging']['mail_invoice']['template'] = isset($mail_invoice['template']) ? $mail_invoice['template'] : null;
  5792. $view_params['messaging']['mail_invoice']['additionnal'] = isset($mail_invoice['additionnal']) ? $mail_invoice['additionnal'] : null;
  5793. $view_params['messaging']['mail_invoice']['order_state'] = isset($mail_invoice['order_state']) && $mail_invoice['order_state'] ? $mail_invoice['order_state'] : null;
  5794.  
  5795. $view_params['messaging']['mail_review'] = array();
  5796. $view_params['messaging']['mail_review']['active'] = isset($mail_review['active']) ? $mail_review['active'] : false;
  5797. $view_params['messaging']['mail_review']['template'] = isset($mail_review['template']) ? $mail_review['template'] : null;
  5798. $view_params['messaging']['mail_review']['delay'] = isset($mail_review['delay']) ? $mail_review['delay'] : null;
  5799. $view_params['messaging']['mail_review']['order_state'] = isset($mail_review['order_state']) && $mail_review['order_state'] ? $mail_review['order_state'] : null;
  5800.  
  5801. $email_providers = AmazonMessaging::$email_providers;
  5802. $default_email_provider = key($email_providers);
  5803.  
  5804. $view_params['messaging']['customer_thread'] = array();
  5805. $view_params['messaging']['customer_thread']['labels'] = array();
  5806.  
  5807. $labels_count = 0;
  5808. foreach ($this->config['actives'] as $id_lang => $active) {
  5809. if (!$active) {
  5810. continue;
  5811. }
  5812. $regions = &$this->config['regions'];
  5813. if (is_array($regions) && isset($regions[$id_lang]) && !empty($regions[$id_lang])) {
  5814. $view_params['messaging']['customer_thread']['labels'][$id_lang] = sprintf('Amazon-%s', AmazonTools::ucfirst($regions[$id_lang]));
  5815. $labels_count++;
  5816. }
  5817. }
  5818. $view_params['messaging']['customer_thread']['labels_count'] = $labels_count;
  5819. $view_params['messaging']['customer_thread']['active'] = isset($mail_customer_thread['active']) ? $mail_customer_thread['active'] : false;
  5820. $view_params['messaging']['customer_thread']['login'] = isset($mail_customer_thread['login']) ? $mail_customer_thread['login'] : null;
  5821. $view_params['messaging']['customer_thread']['password'] = isset($mail_customer_thread['password']) ? $mail_customer_thread['password'] : null;
  5822.  
  5823. $view_params['messaging']['customer_thread']['template'] = isset($mail_customer_thread['template']) ? $mail_customer_thread['template'] : 'reply_msg';
  5824. $view_params['messaging']['customer_thread']['mail_provider'] = isset($mail_customer_thread['mail_provider']) ? $mail_customer_thread['mail_provider'] : $default_email_provider;
  5825. $view_params['messaging']['customer_thread']['mail_providers'] = $email_providers;
  5826. $view_params['messaging']['customer_thread']['imap_open'] = function_exists('imap_open');
  5827. }
  5828.  
  5829. private function _tools(&$view_params)
  5830. {
  5831. $view_params['tools']['request_uri'] = Tools::htmlentitiesUTF8($_SERVER['REQUEST_URI']);
  5832. $view_params['tools']['selected_tab'] = $this->selectedTab() === 'tools' ? true : false;
  5833. $view_params['tools']['images_url'] = $this->images;
  5834. $view_params['tools']['url'] = $this->url;
  5835. $view_params['tools']['tutorial'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_TOOLS);
  5836.  
  5837. $context_key = AmazonContext::getKey($this->context->shop);
  5838.  
  5839. $view_params['tools']['tools_url'] = $this->url.'functions/tools.php?instant_token='.$this->config['instant_token'].'&context_key='.$context_key;
  5840.  
  5841. // Current Queue
  5842. //
  5843. $languages = AmazonTools::languages();
  5844. $action_queues = AmazonProduct::getCurrentQueue();
  5845.  
  5846. if (is_array($action_queues) && count($action_queues)) {
  5847. foreach ($action_queues as $key => $action_queue) {
  5848. if (isset($languages[$action_queue['id_lang']])) {
  5849. $action_queues[$key]['lang'] = $languages[$action_queue['id_lang']]['name'];
  5850. $action_queues[$key]['lang_iso_code'] = $languages[$action_queue['id_lang']]['iso_code'];
  5851.  
  5852. $action_queues[$key]['flag'] = $this->images.'geo_flags/'.$this->geoFlag($action_queue['id_lang']).'.gif';
  5853. } else {
  5854. $action_queues[$key]['lang'] = $this->l('Inactive');
  5855. $action_queues[$key]['flag'] = null;
  5856. }
  5857. $action_queues[$key]['date_min'] = AmazonTools::displayDate($action_queue['date_min'], $this->id_lang, true);
  5858. $action_queues[$key]['date_max'] = AmazonTools::displayDate($action_queue['date_max'], $this->id_lang, true);
  5859.  
  5860. switch ($action_queue['action']) {
  5861. case self::ADD:
  5862. $action_queues[$key]['action_name'] = $this->l('Add');
  5863. break;
  5864. case self::REMOVE:
  5865. $action_queues[$key]['action_name'] = $this->l('Delete');
  5866. break;
  5867. case self::UPDATE:
  5868. $action_queues[$key]['action_name'] = $this->l('Update');
  5869. break;
  5870. case self::REPRICE:
  5871. $action_queues[$key]['action_name'] = $this->l('Repricing');
  5872. break;
  5873. }
  5874. }
  5875. } elseif ($action_queues === false) {
  5876. $view_params['tools']['action_queue_missing'] = true;
  5877. }
  5878.  
  5879. $view_params['tools']['action_queue'] = $action_queues;
  5880.  
  5881. $view_params['tools']['valid_values'] = true;
  5882.  
  5883. if ($this->config['features']['creation']) {
  5884. if (AmazonValidValues::tableExists()) {
  5885. $view_params['tools']['valid_values_action'] = $this->l('Refresh');
  5886.  
  5887. $last_import = AmazonValidValues::lastImport();
  5888.  
  5889. if ($last_import) {
  5890. $view_params['tools']['valid_values_last_import'] = sprintf('%s: %s', $this->l('Last Import'), AmazonTools::displayDate($last_import, $this->id_lang, true));
  5891. } else {
  5892. $view_params['tools']['valid_values_last_import'] = sprintf('%s: %s', $this->l('Last Import'), $this->l('Never'));
  5893. }
  5894. } else {
  5895. $view_params['tools']['valid_values_action'] = $this->l('Import');
  5896. }
  5897. }
  5898.  
  5899.  
  5900. $view_params['tools']['maintenance'] = true;
  5901. }
  5902.  
  5903. private function _fba(&$view_params)
  5904. {
  5905. $view_params['fba'] = array();
  5906. $view_params['fba']['selected_tab'] = $this->selectedTab() === 'fba' ? true : false;
  5907. $view_params['fba']['images_url'] = $this->images;
  5908. $view_params['fba']['validation'] = $this->_validate(true);
  5909. $view_params['fba']['tutorial'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_FBA);
  5910. $view_params['fba']['init_stock_url'] = $this->url.'functions/fba_inventory.php?instant_token='.$this->config['instant_token'].'&context_key='.AmazonContext::getKey($this->context->shop);
  5911.  
  5912. // Order State
  5913. //
  5914. $orderStates = OrderState::getOrderStates($this->id_lang);
  5915.  
  5916. $view_params['fba']['order_states'] = array();
  5917.  
  5918. $c = 0;
  5919. foreach ($orderStates as $orderState) {
  5920. if (!(int)$orderState['id_order_state']) {
  5921. continue;
  5922. }
  5923.  
  5924. $view_params['fba']['order_states'][$c]['value'] = (int)$orderState['id_order_state'];
  5925. $view_params['fba']['order_states'][$c]['name'] = $orderState['name'];
  5926. $c++;
  5927. }
  5928.  
  5929. $view_params['fba']['formula'] = $this->config['fba_formula'];
  5930. $view_params['fba']['multichannel'] = $this->config['fba_multichannel'];
  5931. $view_params['fba']['multichannel_auto'] = $this->config['fba_multichannel_auto'];
  5932. $view_params['fba']['order_state'] = $this->config['fba_order_state'];
  5933. $view_params['fba']['multichannel_state'] = $this->config['fba_multichannel_state'];
  5934. $view_params['fba']['multichannel_sent_state'] = $this->config['fba_multichannel_sent_state'];
  5935. $view_params['fba']['multichannel_done_state'] = $this->config['fba_multichannel_done_state'];
  5936. $view_params['fba']['decrease_stock'] = $this->config['fba_decrease_stock'];
  5937.  
  5938. $view_params['fba']['stock_behaviour'] = $this->config['fba_stock_behaviour'];
  5939. $view_params['fba']['stock_behaviour_synch'] = self::FBA_STOCK_SYNCH;
  5940. $view_params['fba']['stock_behaviour_switch'] = self::FBA_STOCK_SWITCH;
  5941.  
  5942. $view_params['fba']['notification'] = $this->config['fba_notification'];
  5943. $view_params['fba']['notification_both'] = self::FBA_NOTIFICATION_BOTH;
  5944. $view_params['fba']['notification_shop'] = self::FBA_NOTIFICATION_SHOP;
  5945. $view_params['fba']['notification_customer'] = self::FBA_NOTIFICATION_CUSTOMER;
  5946.  
  5947.  
  5948.  
  5949. if ($this->config['fba_stock_behaviour'] == self::FBA_STOCK_SYNCH) {
  5950. $view_params['fba']['stock_init'] = array();
  5951. $view_params['fba']['stock_init']['enabled'] = true;
  5952.  
  5953. $view_params['fba']['marketplaces'] = array();
  5954. $view_params['fba']['marketplaces']['countries'] = $marketplace_countries = AmazonSpecificField::countrySelector($this->amazon_features['amazon_europe']);
  5955. $view_params['fba']['marketplaces']['show'] = count($marketplace_countries) > 1;
  5956. } else {
  5957. $view_params['fba']['stock_init']['enabled'] = false;
  5958. $view_params['fba']['stock_init']['groups'] = array();
  5959. }
  5960. }
  5961.  
  5962.  
  5963. private function _repricing(&$view_params)
  5964. {
  5965. $view_params['repricing'] = array();
  5966. $view_params['repricing']['selected_tab'] = $this->selectedTab() === 'repricing' ? true : false;
  5967. $view_params['repricing']['images_url'] = $this->images;
  5968. $view_params['repricing']['module_path'] = $this->path;
  5969. $view_params['repricing']['validation'] = $this->_validate(true);
  5970. $view_params['repricing']['tutorial'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_REPRICING);
  5971. $view_params['repricing']['repricing_url'] = $this->url.'functions/repricing.php?instant_token='.$this->config['instant_token'].'&context_key='.AmazonContext::getKey($this->context->shop);
  5972.  
  5973. $view_params['repricing']['method'] = array();
  5974. $view_params['repricing']['method']['wholesale'] = AmazonRepricing::REPRICING_WHOLESALE_PRICE;
  5975. $view_params['repricing']['method']['regular'] = AmazonRepricing::REPRICING_REGULAR_PRICE;
  5976.  
  5977. $repricing = &$this->config['repricing'];
  5978.  
  5979. if (!is_array($repricing)) {
  5980. $repricing = array();
  5981. }
  5982.  
  5983. $view_params['repricing']['awsKeyId'] = isset($repricing['awsKeyId']) ? $repricing['awsKeyId'] : null;
  5984. $view_params['repricing']['awsSecretKey'] = isset($repricing['awsSecretKey']) ? $repricing['awsSecretKey'] : null;
  5985.  
  5986. if (!Tools::strlen(trim($view_params['repricing']['awsKeyId']))) {
  5987. $view_params['repricing']['awsKeyId_required'] = true;
  5988. } else {
  5989. $view_params['repricing']['awsKeyId_required'] = false;
  5990. }
  5991.  
  5992. if (!Tools::strlen(trim($view_params['repricing']['awsKeyId']))) {
  5993. $view_params['repricing']['awsSecretKey_required'] = true;
  5994. } else {
  5995. $view_params['repricing']['awsSecretKey_required'] = false;
  5996. }
  5997.  
  5998. $view_params['repricing']['marketplaces'] = array();
  5999. $view_params['repricing']['marketplaces']['countries'] = $marketplace_countries = AmazonSpecificField::countrySelector();
  6000. $view_params['repricing']['marketplaces']['show'] = count($marketplace_countries) > 1;
  6001.  
  6002. $model_strategy = array_fill_keys(array(
  6003. 'name',
  6004. 'active',
  6005. 'key',
  6006. 'agressivity',
  6007. 'delta_min',
  6008. 'delta_max',
  6009. 'limit',
  6010. 'base',
  6011. 'show',
  6012. 'master'
  6013. ), null);
  6014. $empty_strategy = $model_strategy;
  6015. $empty_strategy['key'] = '_key_';
  6016. $empty_strategy['show'] = false;
  6017. $empty_strategy['active'] = true;
  6018. $empty_strategy['master'] = true;
  6019. $empty_strategy['base'] = 1;
  6020.  
  6021. $view_params['repricing']['strategies']['empty'] = $empty_strategy;
  6022.  
  6023. foreach (AmazonTools::languages() as $language) {
  6024. $id_lang = $language['id_lang'];
  6025.  
  6026. if (!(isset($this->config['actives'][$id_lang]) && (int)$this->config['actives'][$id_lang])) {
  6027. continue;
  6028. }
  6029. $view_params['repricing']['strategies']['strategy'][$id_lang] = $this->getStrategies($id_lang);
  6030. }
  6031. }
  6032.  
  6033. protected function getStrategies($id_lang)
  6034. {
  6035. static $strategies = null;
  6036. static $default_strategies = null;
  6037.  
  6038. $strategies_table = array();
  6039. $model_strategy = array_fill_keys(array(
  6040. 'name',
  6041. 'active',
  6042. 'key',
  6043. 'agressivity',
  6044. 'delta_min',
  6045. 'delta_max',
  6046. 'limit',
  6047. 'base',
  6048. 'show',
  6049. 'master'
  6050. ), null);
  6051.  
  6052. if ($strategies === null) {
  6053. $strategies = AmazonConfiguration::get('strategies');
  6054. $default_strategies = AmazonConfiguration::get('default_strategies');
  6055. }
  6056.  
  6057. if (!is_array($strategies) || !count($strategies)) {
  6058. return ($strategies_table);
  6059. }
  6060.  
  6061. $strategies_have_names = is_array($strategies) && isset($strategies['name']) && is_array($strategies['name']) && count($strategies['name']);
  6062. $strategies_have_items = $strategies_have_names && isset($strategies['name'][$id_lang]) && is_array($strategies['name'][$id_lang]) && count($strategies['name'][$id_lang]);
  6063.  
  6064. if ($strategies_have_items) {
  6065. $has_active = isset($strategies['active']) && is_array($strategies['active']) && isset($strategies['active'][$id_lang]) && is_array($strategies['active'][$id_lang]);
  6066. $has_agressivity = isset($strategies['agressivity']) && is_array($strategies['agressivity']) && isset($strategies['agressivity'][$id_lang]) && is_array($strategies['agressivity'][$id_lang]);
  6067. $has_base = isset($strategies['base']) && is_array($strategies['base']) && isset($strategies['base'][$id_lang]) && is_array($strategies['base'][$id_lang]);
  6068. $has_limit = isset($strategies['limit']) && is_array($strategies['limit']) && isset($strategies['limit'][$id_lang]) && is_array($strategies['limit'][$id_lang]);
  6069. $has_delta_min = isset($strategies['delta_min']) && is_array($strategies['delta_min']) && isset($strategies['delta_min'][$id_lang]) && is_array($strategies['delta_min'][$id_lang]);
  6070. $has_delta_max = isset($strategies['delta_max']) && is_array($strategies['delta_max']) && isset($strategies['delta_max'][$id_lang]) && is_array($strategies['delta_max'][$id_lang]);
  6071.  
  6072.  
  6073. foreach ($strategies['name'][$id_lang] as $index => $strategy_name) {
  6074. $strategy = $model_strategy;
  6075. $strategy['show'] = true;
  6076. $strategy['name'] = $strategy_name;
  6077. $strategy['key'] = $key = AmazonTools::toKey($strategy_name);
  6078. $strategy['active'] = $has_active && isset($strategies['active'][$id_lang][$index]) ? $strategies['active'][$id_lang][$index] : null;
  6079. $strategy['agressivity'] = $has_agressivity && isset($strategies['agressivity'][$id_lang][$index]) ? $strategies['agressivity'][$id_lang][$index] : null;
  6080. $strategy['base'] = $has_base && isset($strategies['base'][$id_lang][$index]) ? $strategies['base'][$id_lang][$index] : null;
  6081. $strategy['limit'] = $has_limit && isset($strategies['limit'][$id_lang][$index]) ? $strategies['limit'][$id_lang][$index] : null;
  6082. $strategy['delta_min'] = $has_delta_min && isset($strategies['delta_min'][$id_lang][$index]) ? $strategies['delta_min'][$id_lang][$index] : null;
  6083. $strategy['delta_max'] = $has_delta_max && isset($strategies['delta_max'][$id_lang][$index]) ? $strategies['delta_max'][$id_lang][$index] : null;
  6084.  
  6085. if (is_array($default_strategies) && count($default_strategies) && isset($default_strategies[$id_lang]) && !empty($default_strategies[$id_lang]) && $strategy['key'] == $default_strategies[$id_lang]) {
  6086. $strategy['default'] = true;
  6087. } else {
  6088. $strategy['default'] = false;
  6089. }
  6090.  
  6091. $strategies_table[$key] = $strategy;
  6092. }
  6093. }
  6094.  
  6095. return ($strategies_table);
  6096. }
  6097.  
  6098. private function _cron(&$view_params)
  6099. {
  6100. $view_params['cron'] = array();
  6101. $view_params['cron']['selected_tab'] = $this->selectedTab() === 'cron' ? true : false;
  6102. $view_params['cron']['images_url'] = $this->images;
  6103. $view_params['cron']['url'] = $this->url;
  6104. $view_params['cron']['validation'] = $this->_validate(true);
  6105. $view_params['cron']['tutorial'] = AmazonSupport::gethreflink(AmazonSupport::TUTORIAL_CRON);
  6106. $view_params['cron']['display'] = false;
  6107.  
  6108. $base_url = AmazonTools::getHttpHost(true, true).__PS_BASE_URI__.basename(_PS_MODULE_DIR_).'/'.$this->name;
  6109. $marketPlaceIds = $this->config['amazon_marketplace_ids'];
  6110. $marketPlaceMaster = $this->config['marketplace_master'];
  6111. $actives = $this->config['actives'];
  6112. $regions = $this->config['regions'];
  6113.  
  6114. $view_params['cron']['prestashop'] = array();
  6115. $view_params['cron']['prestashop']['exists'] = is_dir(_PS_MODULE_DIR_.'cronjobs/');
  6116. $view_params['cron']['prestashop']['installed'] = (bool)AmazonTools::moduleIsInstalled('cronjobs');
  6117.  
  6118. $view_params['cron']['products'] = array();
  6119. $view_params['cron']['products']['synch'] = array();
  6120.  
  6121. $view_params['cron']['orders'] = array();
  6122. $view_params['cron']['orders']['status'] = array();
  6123. $view_params['cron']['orders']['import'] = array();
  6124. $view_params['cron']['orders']['canceled'] = array();
  6125. $view_params['cron']['orders']['report'] = array();
  6126.  
  6127. $view_params['cron']['fba']['status'] = array();
  6128. $view_params['cron']['fba']['cancel'] = array();
  6129. $view_params['cron']['fba']['stocks'] = array();
  6130.  
  6131. $view_params['cron']['repricing'] = array();
  6132. $view_params['cron']['repricing']['reprice'] = array();
  6133. $view_params['cron']['repricing']['update'] = array();
  6134. $view_params['cron']['repricing']['export'] = array();
  6135.  
  6136. $view_params['cron']['messaging'] = array();
  6137. $view_params['cron']['messaging']['grab'] = array();
  6138.  
  6139. $languages = AmazonTools::languages();
  6140.  
  6141. if (version_compare(_PS_VERSION_, '1.5', '>=')) {
  6142. $context_key = AmazonContext::getKey($this->context->shop);
  6143. $context_param = '&context_key='.$context_key;
  6144. } else {
  6145. $context_param = null;
  6146. }
  6147. $view_params['cron']['context_key'] = $context_key;
  6148.  
  6149. // Cron for Amazon Europe
  6150. //
  6151. if (is_array($marketPlaceIds) && count($marketPlaceIds)) {
  6152. foreach ($languages as $langkey => $language) {
  6153. $id_lang = $language['id_lang'];
  6154.  
  6155. if (!(isset($actives[$id_lang]) && (int)$actives[$id_lang])) {
  6156. continue;
  6157. }
  6158.  
  6159. if (!isset($marketPlaceIds[$id_lang]) || !AmazonTools::isEuropeMarketplaceId($marketPlaceIds[$id_lang])) {
  6160. continue;
  6161. }
  6162.  
  6163. $view_params['cron']['display'] = true;
  6164.  
  6165. $flag = $this->images.'geo_flags/'.$this->geoFlag($language['id_lang']).'.gif';
  6166. $lang = $language['iso_code'];
  6167.  
  6168. $params = '/functions/products.php?cron_token='.$this->config['tokens'][$id_lang].$context_param.'&cron=1&action=update&lang='.$regions[$id_lang];
  6169.  
  6170. $view_params['cron']['products']['synch'][$id_lang]['id_lang'] = $id_lang;
  6171. $view_params['cron']['products']['synch'][$id_lang]['lang'] = $regions[$id_lang];
  6172. $view_params['cron']['products']['synch'][$id_lang]['flag'] = $flag;
  6173. $view_params['cron']['products']['synch'][$id_lang]['lang'] = $lang;
  6174. $view_params['cron']['products']['synch'][$id_lang]['url'] = $base_url.$params;
  6175. $view_params['cron']['products']['synch'][$id_lang]['short_url'] = preg_replace('/(?<=^.{64}).{4,}(?=.{24}$)/', '...', $base_url.$params);
  6176. $view_params['cron']['products']['synch'][$id_lang]['title'] = $this->l('Synchronization');
  6177. $view_params['cron']['products']['synch'][$id_lang]['frequency'] = -1;
  6178.  
  6179. $europe = ($marketPlaceMaster === $regions[$id_lang] || $marketPlaceMaster === 'uk');
  6180. $pass = !$europe && $marketPlaceMaster;
  6181.  
  6182. if (isset($regions[$id_lang]) && Tools::strlen($regions[$id_lang]) && !$pass) {
  6183. $params = '/functions/import.php?cron_token='.$this->config['tokens'][$id_lang].$context_param.'&cron=1&lang='.$regions[$id_lang].'&europe='.$europe;
  6184. $view_params['cron']['orders']['import'][$id_lang]['id_lang'] = $id_lang;
  6185. $view_params['cron']['orders']['import'][$id_lang]['lang'] = $regions[$id_lang];
  6186. $view_params['cron']['orders']['import'][$id_lang]['flag'] = $flag;
  6187. $view_params['cron']['orders']['import'][$id_lang]['lang'] = $lang;
  6188. $view_params['cron']['orders']['import'][$id_lang]['url'] = $base_url.$params;
  6189. $view_params['cron']['orders']['import'][$id_lang]['short_url'] = preg_replace('/(?<=^.{64}).{4,}(?=.{24}$)/', '...', $base_url.$params);
  6190. $view_params['cron']['orders']['import'][$id_lang]['title'] = $this->l('Orders Import');
  6191. $view_params['cron']['orders']['import'][$id_lang]['frequency'] = -1;
  6192.  
  6193. $params = '/functions/status.php?cron_token='.$this->config['tokens'][$id_lang].$context_param.'&cron=1&lang='.$regions[$id_lang].'&europe='.$europe;
  6194. $view_params['cron']['orders']['status'][$id_lang]['id_lang'] = $id_lang;
  6195. $view_params['cron']['orders']['status'][$id_lang]['lang'] = $regions[$id_lang];
  6196. $view_params['cron']['orders']['status'][$id_lang]['flag'] = $flag;
  6197. $view_params['cron']['orders']['status'][$id_lang]['lang'] = $lang;
  6198. $view_params['cron']['orders']['status'][$id_lang]['url'] = $base_url.$params;
  6199. $view_params['cron']['orders']['status'][$id_lang]['short_url'] = preg_replace('/(?<=^.{64}).{4,}(?=.{24}$)/', '...', $base_url.$params);
  6200. $view_params['cron']['orders']['status'][$id_lang]['title'] = $this->l('Orders Status');
  6201. $view_params['cron']['orders']['status'][$id_lang]['frequency'] = 4;
  6202.  
  6203. if (isset($this->config['canceled_state']) && (int)$this->config['canceled_state'] && $this->amazon_features['cancel_orders']) {
  6204. $params = '/functions/canceled.php?cron_token='.$this->config['tokens'][$id_lang].$context_param.'&cron=1&lang='.$regions[$id_lang].'&europe='.$europe;
  6205. $view_params['cron']['orders']['canceled'][$id_lang]['id_lang'] = $id_lang;
  6206. $view_params['cron']['orders']['canceled'][$id_lang]['lang'] = $regions[$id_lang];
  6207. $view_params['cron']['orders']['canceled'][$id_lang]['flag'] = $flag;
  6208. $view_params['cron']['orders']['canceled'][$id_lang]['lang'] = $lang;
  6209. $view_params['cron']['orders']['canceled'][$id_lang]['url'] = $base_url.$params;
  6210. $view_params['cron']['orders']['canceled'][$id_lang]['short_url'] = preg_replace('/(?<=^.{64}).{4,}(?=.{24}$)/', '...', $base_url.$params);
  6211. $view_params['cron']['orders']['canceled'][$id_lang]['title'] = $this->l('Canceled Orders');
  6212. $view_params['cron']['orders']['canceled'][$id_lang]['frequency'] = 2;
  6213. }
  6214.  
  6215. if ($this->config['fba_multichannel']) {
  6216. $params = '/functions/fbaorder.php?cron_token='.$this->config['tokens'][$id_lang].$context_param.'&cron=1&action=status&europe='.$europe;
  6217. $view_params['cron']['fba']['status'][$id_lang]['id_lang'] = $id_lang;
  6218. $view_params['cron']['fba']['status'][$id_lang]['lang'] = $regions[$id_lang];
  6219. $view_params['cron']['fba']['status'][$id_lang]['flag'] = $flag;
  6220. $view_params['cron']['fba']['status'][$id_lang]['lang'] = $lang;
  6221. $view_params['cron']['fba']['status'][$id_lang]['url'] = $base_url.$params;
  6222. $view_params['cron']['fba']['status'][$id_lang]['short_url'] = preg_replace('/(?<=^.{64}).{4,}(?=.{24}$)/', '...', $base_url.$params);
  6223. $view_params['cron']['fba']['status'][$id_lang]['title'] = $this->l('FBA Orders Status');
  6224. $view_params['cron']['fba']['status'][$id_lang]['frequency'] = 2;
  6225. }
  6226.  
  6227. if ($this->config['features']['fba']) {
  6228. $script = null;
  6229.  
  6230. if ($this->config['fba_stock_behaviour'] == self::FBA_STOCK_SWITCH) {
  6231. $script = 'fbamanager';
  6232. } elseif ($this->config['fba_stock_behaviour'] == self::FBA_STOCK_SYNCH) {
  6233. $script = 'fbastocksynch';
  6234. }
  6235. if ($script) {
  6236. $params = '/functions/'.$script.'.php?cron_token='.$this->config['tokens'][$id_lang].$context_param.'&cron=1&action=stocks&europe='.$europe;
  6237. $view_params['cron']['fba']['stocks'][$id_lang]['id_lang'] = $id_lang;
  6238. $view_params['cron']['fba']['stocks'][$id_lang]['lang'] = $regions[$id_lang];
  6239. $view_params['cron']['fba']['stocks'][$id_lang]['flag'] = $flag;
  6240. $view_params['cron']['fba']['stocks'][$id_lang]['lang'] = $lang;
  6241. $view_params['cron']['fba']['stocks'][$id_lang]['url'] = $base_url.$params;
  6242. $view_params['cron']['fba']['stocks'][$id_lang]['short_url'] = preg_replace('/(?<=^.{64}).{4,}(?=.{24}$)/', '...', $base_url.$params);
  6243. $view_params['cron']['fba']['stocks'][$id_lang]['title'] = $this->l('FBA Manager');
  6244. $view_params['cron']['fba']['stocks'][$id_lang]['frequency'] = 2;
  6245. }
  6246. }
  6247.  
  6248. if ($this->config['features']['expert_mode']) {
  6249. $params = '/functions/check_stock.php?cron_token='.$this->config['tokens'][$id_lang].$context_param.'&cron=1&lang='.$regions[$id_lang];
  6250. $view_params['cron']['products']['fetch'][$id_lang]['id_lang'] = $id_lang;
  6251. $view_params['cron']['products']['fetch'][$id_lang]['lang'] = $regions[$id_lang];
  6252. $view_params['cron']['products']['fetch'][$id_lang]['flag'] = $flag;
  6253. $view_params['cron']['products']['fetch'][$id_lang]['lang'] = $lang;
  6254. $view_params['cron']['products']['fetch'][$id_lang]['url'] = $base_url.$params;
  6255. $view_params['cron']['products']['fetch'][$id_lang]['short_url'] = preg_replace('/(?<=^.{64}).{4,}(?=.{24}$)/', '...', $base_url.$params);
  6256. $view_params['cron']['products']['fetch'][$id_lang]['title'] = $this->l('Fix Stock Issues');
  6257. $view_params['cron']['products']['fetch'][$id_lang]['frequency'] = 0;
  6258.  
  6259. $params = '/functions/check_stock.php?cron_token='.$this->config['tokens'][$id_lang].$context_param.'&cron=1&lang='.$regions[$id_lang].'&fix=1';
  6260. $view_params['cron']['products']['fix'][$id_lang]['id_lang'] = $id_lang;
  6261. $view_params['cron']['products']['fix'][$id_lang]['lang'] = $regions[$id_lang];
  6262. $view_params['cron']['products']['fix'][$id_lang]['flag'] = $flag;
  6263. $view_params['cron']['products']['fix'][$id_lang]['lang'] = $lang;
  6264. $view_params['cron']['products']['fix'][$id_lang]['url'] = $base_url.$params;
  6265. $view_params['cron']['products']['fix'][$id_lang]['short_url'] = preg_replace('/(?<=^.{64}).{4,}(?=.{24}$)/', '...', $base_url.$params);
  6266. $view_params['cron']['products']['fix'][$id_lang]['title'] = $this->l('Fix Stock Issues');
  6267. $view_params['cron']['products']['fix'][$id_lang]['frequency'] = 0;
  6268. }
  6269.  
  6270. if ($this->config['features']['orders_reports']) {
  6271. $params = '/functions/orders_reports.php?amazon_token='.$this->config['tokens'][$id_lang].$context_param.'&cron=1&amazon_lang='.$id_lang.'&action=report&europe='.$europe;
  6272. $view_params['cron']['orders']['report'][$id_lang]['id_lang'] = $id_lang;
  6273. $view_params['cron']['orders']['report'][$id_lang]['lang'] = $regions[$id_lang];
  6274. $view_params['cron']['orders']['report'][$id_lang]['flag'] = $flag;
  6275. $view_params['cron']['orders']['report'][$id_lang]['lang'] = $lang;
  6276. $view_params['cron']['orders']['report'][$id_lang]['url'] = $base_url.$params;
  6277. $view_params['cron']['orders']['report'][$id_lang]['short_url'] = preg_replace('/(?<=^.{64}).{4,}(?=.{24}$)/', '...', $base_url.$params);
  6278. $view_params['cron']['orders']['report'][$id_lang]['title'] = $this->l('Orders Reports');
  6279. $view_params['cron']['orders']['report'][$id_lang]['frequency'] = 1;
  6280. }
  6281. } elseif ($regions[$id_lang] === 'uk') {
  6282. // UK exception
  6283.  
  6284. $params = '/functions/import.php?cron_token='.$this->config['tokens'][$id_lang].$context_param.'&cron=1&lang='.$regions[$id_lang];
  6285. $view_params['cron']['orders']['import'][$id_lang]['id_lang'] = $id_lang;
  6286. $view_params['cron']['orders']['import'][$id_lang]['lang'] = $regions[$id_lang];
  6287. $view_params['cron']['orders']['import'][$id_lang]['flag'] = $flag;
  6288. $view_params['cron']['orders']['import'][$id_lang]['url'] = $base_url.$params;
  6289. $view_params['cron']['orders']['import'][$id_lang]['short_url'] = preg_replace('/(?<=^.{64}).{4,}(?=.{24}$)/', '...', $base_url.$params);
  6290. $view_params['cron']['orders']['import'][$id_lang]['title'] = $this->l('Orders Import');
  6291. $view_params['cron']['orders']['import'][$id_lang]['frequency'] = -1;
  6292.  
  6293. $params = '/functions/status.php?cron_token='.$this->config['tokens'][$id_lang].$context_param.'&cron=1&lang='.$regions[$id_lang].'&europe=1';
  6294. $view_params['cron']['orders']['status'][$id_lang]['id_lang'] = $id_lang;
  6295. $view_params['cron']['orders']['status'][$id_lang]['lang'] = $regions[$id_lang];
  6296. $view_params['cron']['orders']['status'][$id_lang]['flag'] = $flag;
  6297. $view_params['cron']['orders']['status'][$id_lang]['lang'] = $lang;
  6298. $view_params['cron']['orders']['status'][$id_lang]['url'] = $base_url.$params;
  6299. $view_params['cron']['orders']['status'][$id_lang]['short_url'] = preg_replace('/(?<=^.{64}).{4,}(?=.{24}$)/', '...', $base_url.$params);
  6300. $view_params['cron']['orders']['status'][$id_lang]['title'] = $this->l('Orders Status');
  6301. $view_params['cron']['orders']['status'][$id_lang]['frequency'] = 4;
  6302.  
  6303.  
  6304. if ($this->config['features']['expert_mode']) {
  6305. $params = '/functions/check_stock.php?cron_token='.$this->config['tokens'][$id_lang].$context_param.'&cron=1&lang='.$regions[$id_lang];
  6306. $view_params['cron']['products']['fetch'][$id_lang]['id_lang'] = $id_lang;
  6307. $view_params['cron']['products']['fetch'][$id_lang]['lang'] = $regions[$id_lang];
  6308. $view_params['cron']['products']['fetch'][$id_lang]['flag'] = $flag;
  6309. $view_params['cron']['products']['fetch'][$id_lang]['lang'] = $lang;
  6310. $view_params['cron']['products']['fetch'][$id_lang]['url'] = $base_url.$params;
  6311. $view_params['cron']['products']['fetch'][$id_lang]['short_url'] = preg_replace('/(?<=^.{64}).{4,}(?=.{24}$)/', '...', $base_url.$params);
  6312. $view_params['cron']['products']['fetch'][$id_lang]['title'] = $this->l('Fix Stock Issues');
  6313. $view_params['cron']['products']['fetch'][$id_lang]['frequency'] = 0;
  6314.  
  6315. $params = '/functions/check_stock.php?cron_token='.$this->config['tokens'][$id_lang].$context_param.'&cron=1&lang='.$regions[$id_lang].'&fix=1';
  6316. $view_params['cron']['products']['fix'][$id_lang]['id_lang'] = $id_lang;
  6317. $view_params['cron']['products']['fix'][$id_lang]['lang'] = $regions[$id_lang];
  6318. $view_params['cron']['products']['fix'][$id_lang]['flag'] = $flag;
  6319. $view_params['cron']['products']['fix'][$id_lang]['lang'] = $lang;
  6320. $view_params['cron']['products']['fix'][$id_lang]['url'] = $base_url.$params;
  6321. $view_params['cron']['products']['fix'][$id_lang]['short_url'] = preg_replace('/(?<=^.{64}).{4,}(?=.{24}$)/', '...', $base_url.$params);
  6322. $view_params['cron']['products']['fix'][$id_lang]['title'] = $this->l('Fix Stock Issues');
  6323. $view_params['cron']['products']['fix'][$id_lang]['frequency'] = 0;
  6324. }
  6325.  
  6326. if ($this->config['features']['orders_reports']) {
  6327. $params = '/functions/orders_reports.php?amazon_token='.$this->config['tokens'][$id_lang].$context_param.'&cron=1&amazon_lang='.$id_lang.'&action=report';
  6328. $view_params['cron']['orders']['report'][$id_lang]['id_lang'] = $id_lang;
  6329. $view_params['cron']['orders']['report'][$id_lang]['lang'] = $regions[$id_lang];
  6330. $view_params['cron']['orders']['report'][$id_lang]['flag'] = $flag;
  6331. $view_params['cron']['orders']['report'][$id_lang]['lang'] = $lang;
  6332. $view_params['cron']['orders']['report'][$id_lang]['url'] = $base_url.$params;
  6333. $view_params['cron']['orders']['report'][$id_lang]['short_url'] = preg_replace('/(?<=^.{64}).{4,}(?=.{24}$)/', '...', $base_url.$params);
  6334. $view_params['cron']['orders']['report'][$id_lang]['title'] = $this->l('Orders Reports');
  6335. $view_params['cron']['orders']['report'][$id_lang]['frequency'] = 1;
  6336. }
  6337. }
  6338.  
  6339. if ($this->config['features']['repricing']) {
  6340. $params = '/functions/repricing.php?cron_token='.$this->config['tokens'][$id_lang].$context_param.'&cron=1&action=reprice&lang='.$regions[$id_lang];
  6341. $view_params['cron']['repricing']['reprice'][$id_lang]['id_lang'] = $id_lang;
  6342. $view_params['cron']['repricing']['reprice'][$id_lang]['lang'] = $regions[$id_lang];
  6343. $view_params['cron']['repricing']['reprice'][$id_lang]['flag'] = $flag;
  6344. $view_params['cron']['repricing']['reprice'][$id_lang]['lang'] = $lang;
  6345. $view_params['cron']['repricing']['reprice'][$id_lang]['url'] = $base_url.$params;
  6346. $view_params['cron']['repricing']['reprice'][$id_lang]['short_url'] = preg_replace('/(?<=^.{64}).{4,}(?=.{24}$)/', '...', $base_url.$params);
  6347. $view_params['cron']['repricing']['reprice'][$id_lang]['title'] = $this->l('Repricing (Analysis)');
  6348. $view_params['cron']['repricing']['reprice'][$id_lang]['frequency'] = -1;
  6349.  
  6350. $params = '/functions/repricing.php?cron_token='.$this->config['tokens'][$id_lang].$context_param.'&cron=1&action=push&lang='.$regions[$id_lang];
  6351. $view_params['cron']['repricing']['update'][$id_lang]['id_lang'] = $id_lang;
  6352. $view_params['cron']['repricing']['update'][$id_lang]['lang'] = $regions[$id_lang];
  6353. $view_params['cron']['repricing']['update'][$id_lang]['flag'] = $flag;
  6354. $view_params['cron']['repricing']['update'][$id_lang]['lang'] = $lang;
  6355. $view_params['cron']['repricing']['update'][$id_lang]['url'] = $base_url.$params;
  6356. $view_params['cron']['repricing']['update'][$id_lang]['short_url'] = preg_replace('/(?<=^.{64}).{4,}(?=.{24}$)/', '...', $base_url.$params);
  6357. $view_params['cron']['repricing']['update'][$id_lang]['title'] = $this->l('Repricing (Updates)');
  6358. $view_params['cron']['repricing']['update'][$id_lang]['frequency'] = -1;
  6359.  
  6360. $params = '/functions/repricing.php?cron_token='.$this->config['tokens'][$id_lang].$context_param.'&cron=1&action=export&lang='.$regions[$id_lang];
  6361. $view_params['cron']['repricing']['export'][$id_lang]['id_lang'] = $id_lang;
  6362. $view_params['cron']['repricing']['export'][$id_lang]['lang'] = $regions[$id_lang];
  6363. $view_params['cron']['repricing']['export'][$id_lang]['flag'] = $flag;
  6364. $view_params['cron']['repricing']['export'][$id_lang]['lang'] = $lang;
  6365. $view_params['cron']['repricing']['export'][$id_lang]['url'] = $base_url.$params;
  6366. $view_params['cron']['repricing']['export'][$id_lang]['short_url'] = preg_replace('/(?<=^.{64}).{4,}(?=.{24}$)/', '...', $base_url.$params);
  6367. $view_params['cron']['repricing']['export'][$id_lang]['title'] = $this->l('Repricing (Export)');
  6368. $view_params['cron']['repricing']['export'][$id_lang]['frequency'] = -1;
  6369. }
  6370.  
  6371. if ($this->customerThreadIsActive()) {
  6372. $params = '/functions/imap.php?cron_token='.$this->config['tokens'][$id_lang].$context_param.'&cron=1&lang='.$regions[$id_lang];
  6373. $view_params['cron']['messaging']['grab'][$id_lang]['id_lang'] = $id_lang;
  6374. $view_params['cron']['messaging']['grab'][$id_lang]['flag'] = $flag;
  6375. $view_params['cron']['messaging']['grab'][$id_lang]['lang'] = $regions[$id_lang];
  6376. ;
  6377. $view_params['cron']['messaging']['grab'][$id_lang]['url'] = $base_url.$params;
  6378. $view_params['cron']['messaging']['grab'][$id_lang]['short_url'] = preg_replace('/(?<=^.{64}).{4,}(?=.{24}$)/', '...', $base_url.$params);
  6379. $view_params['cron']['messaging']['grab'][$id_lang]['title'] = $this->l('Messaging');
  6380. $view_params['cron']['messaging']['grab'][$id_lang]['frequency'] = -1;
  6381. }
  6382.  
  6383. if (!$this->amazon_features['orders']) {
  6384. unset($view_params['cron']['orders']);
  6385. }
  6386.  
  6387. unset($languages[$langkey]);
  6388. }
  6389. }
  6390.  
  6391. // Remaining platforms (except Europe)
  6392. //
  6393. foreach ($languages as $langkey => $language) {
  6394. $id_lang = $language['id_lang'];
  6395.  
  6396. if (!isset($regions[$id_lang])) {
  6397. continue;
  6398. }
  6399. if (!(isset($actives[$id_lang]) && (int)$actives[$id_lang])) {
  6400. continue;
  6401. }
  6402.  
  6403. if (AmazonTools::isEuropeMarketplaceId($marketPlaceIds[$id_lang]) || empty($marketPlaceIds[$id_lang])) {
  6404. continue;
  6405. }
  6406.  
  6407. $view_params['cron']['display'] = true;
  6408.  
  6409. $flag = $this->images.'geo_flags/'.$this->geoFlag($language['id_lang']).'.gif';
  6410. $lang = $language['iso_code'];
  6411.  
  6412. $params = '/functions/products.php?cron_token='.$this->config['tokens'][$id_lang].$context_param.'&cron=1&action=update&lang='.$regions[$id_lang];
  6413. $view_params['cron']['products']['synch'][$id_lang]['id_lang'] = $id_lang;
  6414. $view_params['cron']['products']['synch'][$id_lang]['lang'] = $regions[$id_lang];
  6415. $view_params['cron']['products']['synch'][$id_lang]['flag'] = $flag;
  6416. $view_params['cron']['products']['synch'][$id_lang]['lang'] = $lang;
  6417. $view_params['cron']['products']['synch'][$id_lang]['url'] = $base_url.$params;
  6418. $view_params['cron']['products']['synch'][$id_lang]['short_url'] = preg_replace('/(?<=^.{64}).{4,}(?=.{24}$)/', '...', $base_url.$params);
  6419. $view_params['cron']['products']['synch'][$id_lang]['title'] = $this->l('Synchronization');
  6420. $view_params['cron']['products']['synch'][$id_lang]['frequency'] = 1;
  6421.  
  6422. $params = '/functions/import.php?cron_token='.$this->config['tokens'][$id_lang].$context_param.'&cron=1&lang='.$regions[$id_lang];
  6423. $view_params['cron']['orders']['import'][$id_lang]['id_lang'] = $id_lang;
  6424. $view_params['cron']['orders']['import'][$id_lang]['lang'] = $regions[$id_lang];
  6425. $view_params['cron']['orders']['import'][$id_lang]['flag'] = $flag;
  6426. $view_params['cron']['orders']['import'][$id_lang]['lang'] = $lang;
  6427. $view_params['cron']['orders']['import'][$id_lang]['url'] = $base_url.$params;
  6428. $view_params['cron']['orders']['import'][$id_lang]['short_url'] = preg_replace('/(?<=^.{64}).{4,}(?=.{24}$)/', '...', $base_url.$params);
  6429. $view_params['cron']['orders']['import'][$id_lang]['title'] = $this->l('Orders Import');
  6430. $view_params['cron']['orders']['import'][$id_lang]['frequency'] = 1;
  6431.  
  6432. $params = '/functions/status.php?&cron_token='.$this->config['tokens'][$id_lang].$context_param.'&cron=1&lang='.$regions[$id_lang];
  6433. $view_params['cron']['orders']['status'][$id_lang]['id_lang'] = $id_lang;
  6434. $view_params['cron']['orders']['status'][$id_lang]['lang'] = $regions[$id_lang];
  6435. $view_params['cron']['orders']['status'][$id_lang]['flag'] = $flag;
  6436. $view_params['cron']['orders']['status'][$id_lang]['lang'] = $lang;
  6437. $view_params['cron']['orders']['status'][$id_lang]['url'] = $base_url.$params;
  6438. $view_params['cron']['orders']['status'][$id_lang]['short_url'] = preg_replace('/(?<=^.{64}).{4,}(?=.{24}$)/', '...', $base_url.$params);
  6439. $view_params['cron']['orders']['status'][$id_lang]['title'] = $this->l('Orders Status');
  6440. $view_params['cron']['orders']['status'][$id_lang]['frequency'] = 4;
  6441.  
  6442. if (isset($this->config['canceled_state']) && (int)$this->config['canceled_state'] && $this->amazon_features['cancel_orders']) {
  6443. $params = '/functions/canceled.php?&cron_token='.$this->config['tokens'][$id_lang].$context_param.'&cron=1&lang='.$regions[$id_lang];
  6444. $view_params['cron']['orders']['canceled'][$id_lang]['id_lang'] = $id_lang;
  6445. $view_params['cron']['orders']['canceled'][$id_lang]['lang'] = $regions[$id_lang];
  6446. $view_params['cron']['orders']['canceled'][$id_lang]['flag'] = $flag;
  6447. $view_params['cron']['orders']['canceled'][$id_lang]['lang'] = $lang;
  6448. $view_params['cron']['orders']['canceled'][$id_lang]['url'] = $base_url.$params;
  6449. $view_params['cron']['orders']['canceled'][$id_lang]['short_url'] = preg_replace('/(?<=^.{64}).{4,}(?=.{24}$)/', '...', $base_url.$params);
  6450. $view_params['cron']['orders']['canceled'][$id_lang]['title'] = $this->l('Canceled Orders');
  6451. $view_params['cron']['orders']['canceled'][$id_lang]['frequency'] = 2;
  6452. }
  6453.  
  6454. if ($this->config['fba_multichannel']) {
  6455. $params = '/functions/fbaorder.php?cron_token='.$this->config['tokens'][$id_lang].$context_param.'&cron=1&lang='.$regions[$id_lang].'&action=status';
  6456. $view_params['cron']['fba']['status'][$id_lang]['id_lang'] = $id_lang;
  6457. $view_params['cron']['fba']['status'][$id_lang]['lang'] = $regions[$id_lang];
  6458. $view_params['cron']['fba']['status'][$id_lang]['flag'] = $flag;
  6459. $view_params['cron']['fba']['status'][$id_lang]['lang'] = $lang;
  6460. $view_params['cron']['fba']['status'][$id_lang]['url'] = $base_url.$params;
  6461. $view_params['cron']['fba']['status'][$id_lang]['short_url'] = preg_replace('/(?<=^.{64}).{4,}(?=.{24}$)/', '...', $base_url.$params);
  6462. $view_params['cron']['fba']['status'][$id_lang]['title'] = $this->l('FBA Orders Status');
  6463. $view_params['cron']['fba']['status'][$id_lang]['frequency'] = 2;
  6464. }
  6465.  
  6466. if ($this->config['features']['fba']) {
  6467. $script = null;
  6468.  
  6469. if ($this->config['fba_stock_behaviour'] == self::FBA_STOCK_SWITCH) {
  6470. $script = 'fbamanager';
  6471. } elseif ($this->config['fba_stock_behaviour'] == self::FBA_STOCK_SYNCH) {
  6472. $script = 'fbastocksynch';
  6473. }
  6474.  
  6475. if ($script) {
  6476. $params = '/functions/'.$script.'.php?cron_token='.$this->config['tokens'][$id_lang].$context_param.'&cron=1&lang='.$regions[$id_lang].'&action=stocks';
  6477. $view_params['cron']['fba']['stocks'][$id_lang]['id_lang'] = $id_lang;
  6478. $view_params['cron']['fba']['stocks'][$id_lang]['lang'] = $regions[$id_lang];
  6479. $view_params['cron']['fba']['stocks'][$id_lang]['flag'] = $flag;
  6480. $view_params['cron']['fba']['stocks'][$id_lang]['lang'] = $lang;
  6481. $view_params['cron']['fba']['stocks'][$id_lang]['url'] = $base_url.$params;
  6482. $view_params['cron']['fba']['stocks'][$id_lang]['short_url'] = preg_replace('/(?<=^.{64}).{4,}(?=.{24}$)/', '...', $base_url.$params);
  6483. $view_params['cron']['fba']['stocks'][$id_lang]['title'] = $this->l('FBA Manager');
  6484. $view_params['cron']['fba']['stocks'][$id_lang]['frequency'] = 2;
  6485. }
  6486. }
  6487.  
  6488.  
  6489. if ($this->config['features']['repricing']) {
  6490. $params = '/functions/repricing.php?cron_token='.$this->config['tokens'][$id_lang].$context_param.'&cron=1&action=reprice&lang='.$regions[$id_lang];
  6491. $view_params['cron']['repricing']['reprice'][$id_lang]['id_lang'] = $id_lang;
  6492. $view_params['cron']['repricing']['reprice'][$id_lang]['lang'] = $regions[$id_lang];
  6493. $view_params['cron']['repricing']['reprice'][$id_lang]['flag'] = $flag;
  6494. $view_params['cron']['repricing']['reprice'][$id_lang]['lang'] = $lang;
  6495. $view_params['cron']['repricing']['reprice'][$id_lang]['url'] = $base_url.$params;
  6496. $view_params['cron']['repricing']['reprice'][$id_lang]['short_url'] = preg_replace('/(?<=^.{64}).{4,}(?=.{24}$)/', '...', $base_url.$params);
  6497. $view_params['cron']['repricing']['reprice'][$id_lang]['title'] = $this->l('Repricing (Analysis)');
  6498. $view_params['cron']['repricing']['reprice'][$id_lang]['frequency'] = 1;
  6499.  
  6500. $params = '/functions/repricing.php?cron_token='.$this->config['tokens'][$id_lang].$context_param.'&cron=1&action=push&lang='.$regions[$id_lang];
  6501. $view_params['cron']['repricing']['update'][$id_lang]['id_lang'] = $id_lang;
  6502. $view_params['cron']['repricing']['update'][$id_lang]['lang'] = $regions[$id_lang];
  6503. $view_params['cron']['repricing']['update'][$id_lang]['flag'] = $flag;
  6504. $view_params['cron']['repricing']['update'][$id_lang]['lang'] = $lang;
  6505. $view_params['cron']['repricing']['update'][$id_lang]['url'] = $base_url.$params;
  6506. $view_params['cron']['repricing']['update'][$id_lang]['short_url'] = preg_replace('/(?<=^.{64}).{4,}(?=.{24}$)/', '...', $base_url.$params);
  6507. $view_params['cron']['repricing']['update'][$id_lang]['title'] = $this->l('Repricing (Updates)');
  6508. $view_params['cron']['repricing']['update'][$id_lang]['frequency'] = -1;
  6509.  
  6510. $params = '/functions/repricing.php?cron_token='.$this->config['tokens'][$id_lang].$context_param.'&cron=1&action=export&lang='.$regions[$id_lang];
  6511. $view_params['cron']['repricing']['export'][$id_lang]['id_lang'] = $id_lang;
  6512. $view_params['cron']['repricing']['export'][$id_lang]['lang'] = $regions[$id_lang];
  6513. $view_params['cron']['repricing']['export'][$id_lang]['flag'] = $flag;
  6514. $view_params['cron']['repricing']['export'][$id_lang]['lang'] = $lang;
  6515. $view_params['cron']['repricing']['export'][$id_lang]['url'] = $base_url.$params;
  6516. $view_params['cron']['repricing']['export'][$id_lang]['short_url'] = preg_replace('/(?<=^.{64}).{4,}(?=.{24}$)/', '...', $base_url.$params);
  6517. $view_params['cron']['repricing']['export'][$id_lang]['title'] = $this->l('Repricing (Export)');
  6518. $view_params['cron']['repricing']['export'][$id_lang]['frequency'] = 1;
  6519. }
  6520.  
  6521. if ($this->customerThreadIsActive()) {
  6522. $params = '/functions/imap.php?cron_token='.$this->config['tokens'][$id_lang].$context_param.'&cron=1&lang='.$regions[$id_lang];
  6523. $view_params['cron']['messaging']['grab'][$id_lang]['id_lang'] = $id_lang;
  6524. $view_params['cron']['messaging']['grab'][$id_lang]['lang'] = $lang;
  6525. $view_params['cron']['messaging']['grab'][$id_lang]['flag'] = $flag;
  6526. $view_params['cron']['messaging']['grab'][$id_lang]['url'] = $base_url.$params;
  6527. $view_params['cron']['messaging']['grab'][$id_lang]['short_url'] = preg_replace('/(?<=^.{64}).{4,}(?=.{24}$)/', '...', $base_url.$params);
  6528. $view_params['cron']['messaging']['grab'][$id_lang]['title'] = $this->l('Messaging');
  6529. $view_params['cron']['messaging']['grab'][$id_lang]['frequency'] = -1;
  6530. }
  6531.  
  6532. if ($this->config['features']['expert_mode']) {
  6533. $params = '/functions/check_stock.php?cron_token='.$this->config['tokens'][$id_lang].$context_param.'&cron=1&lang='.$regions[$id_lang];
  6534. $view_params['cron']['products']['fetch'][$id_lang]['id_lang'] = $id_lang;
  6535. $view_params['cron']['products']['fetch'][$id_lang]['lang'] = $regions[$id_lang];
  6536. $view_params['cron']['products']['fetch'][$id_lang]['flag'] = $flag;
  6537. $view_params['cron']['products']['fetch'][$id_lang]['lang'] = $lang;
  6538. $view_params['cron']['products']['fetch'][$id_lang]['url'] = $base_url.$params;
  6539. $view_params['cron']['products']['fetch'][$id_lang]['short_url'] = preg_replace('/(?<=^.{64}).{4,}(?=.{24}$)/', '...', $base_url.$params);
  6540. $view_params['cron']['products']['fetch'][$id_lang]['title'] = $this->l('Fix Stock Issues');
  6541. $view_params['cron']['products']['fetch'][$id_lang]['frequency'] = 0;
  6542.  
  6543. $params = '/functions/check_stock.php?cron_token='.$this->config['tokens'][$id_lang].$context_param.'&cron=1&lang='.$regions[$id_lang].'&fix=1';
  6544. $view_params['cron']['products']['fix'][$id_lang]['id_lang'] = $id_lang;
  6545. $view_params['cron']['products']['fix'][$id_lang]['lang'] = $regions[$id_lang];
  6546. $view_params['cron']['products']['fix'][$id_lang]['flag'] = $flag;
  6547. $view_params['cron']['products']['fix'][$id_lang]['lang'] = $lang;
  6548. $view_params['cron']['products']['fix'][$id_lang]['url'] = $base_url.$params;
  6549. $view_params['cron']['products']['fix'][$id_lang]['short_url'] = preg_replace('/(?<=^.{64}).{4,}(?=.{24}$)/', '...', $base_url.$params);
  6550. $view_params['cron']['products']['fix'][$id_lang]['title'] = $this->l('Fix Stock Issues');
  6551. $view_params['cron']['products']['fix'][$id_lang]['frequency'] = 0;
  6552. }
  6553. }
  6554. }
  6555.  
  6556.  
  6557. protected static function loadAttributes($inactives = false)
  6558. {
  6559. $actives = AmazonConfiguration::get('ACTIVE');
  6560. $languages = AmazonTools::languages();
  6561.  
  6562. self::$attributes_groups = array();
  6563. self::$attributes = array();
  6564.  
  6565. if (!AmazonConfiguration::combinationIsFeatureActive()) {
  6566. return;
  6567. }
  6568.  
  6569. foreach ($languages as $language) {
  6570. $id_lang = $language['id_lang'];
  6571.  
  6572. if (!$inactives && !(isset($actives) || !(isset($actives[$id_lang]) || !(int)$actives[$id_lang]))) {
  6573. continue;
  6574. }
  6575.  
  6576. $attributes_groups = AttributeGroup::getAttributesGroups($id_lang);
  6577.  
  6578. if (is_array($attributes_groups) && count($attributes_groups)) {
  6579. self::$attributes_groups[$id_lang] = array();
  6580.  
  6581. foreach ($attributes_groups as $attribute_group) {
  6582. $id_attribute_group = (int)$attribute_group['id_attribute_group'];
  6583.  
  6584. self::$attributes_groups[$id_lang][$id_attribute_group] = $attribute_group;
  6585. }
  6586. } else {
  6587. self::$attributes_groups[$id_lang] = array();
  6588. }
  6589.  
  6590. $attributes = Attribute::getAttributes($id_lang, true);
  6591.  
  6592. if (is_array($attributes) && count($attributes)) {
  6593. self::$attributes[$id_lang] = array();
  6594.  
  6595. foreach ($attributes as $attribute) {
  6596. $id_attribute_group = (int)$attribute['id_attribute_group'];
  6597. $id_attribute = (int)$attribute['id_attribute'];
  6598.  
  6599. self::$attributes[$id_lang][$id_attribute_group][$id_attribute] = $attribute;
  6600. }
  6601. } else {
  6602. self::$attributes[$id_lang] = array();
  6603. }
  6604. }
  6605. }
  6606.  
  6607. protected static function loadFeatures($inactives = false, $custom = false)
  6608. {
  6609. $features = array();
  6610.  
  6611. if (!AmazonConfiguration::featureIsFeatureActive()) {
  6612. return;
  6613. }
  6614. $actives = AmazonConfiguration::get('ACTIVE');
  6615. $languages = AmazonTools::languages();
  6616.  
  6617. foreach ($languages as $language) {
  6618. $id_lang = $language['id_lang'];
  6619.  
  6620. if (!$inactives && !(isset($actives) || !(isset($actives[$id_lang]) || !(int)$actives[$id_lang]))) {
  6621. continue;
  6622. }
  6623.  
  6624. $features = Feature::getFeatures($id_lang);
  6625.  
  6626. if (is_array($features) && count($features)) {
  6627. foreach ($features as $feature) {
  6628. $id_feature = (int)$feature['id_feature'];
  6629.  
  6630. $features_values = FeatureValue::getFeatureValuesWithLang($id_lang, $id_feature, $custom);
  6631.  
  6632. if (is_array($features_values) && count($features_values)) {
  6633. $feature['is_color_feature'] = false; // Used by Profiles and Mapping
  6634.  
  6635. self::$features[$id_lang][$id_feature] = $feature;
  6636.  
  6637. foreach ($features_values as $feature_value) {
  6638. $feature_value['name'] = $feature['name'];
  6639. self::$features_values[$id_lang][$id_feature][$feature_value['id_feature_value']] = $feature_value;
  6640. }
  6641. }
  6642. }
  6643. } else {
  6644. self::$features_values[$id_lang] = array();
  6645. }
  6646. }
  6647. }
  6648.  
  6649. public function hookPostUpdateOrderStatus($params)
  6650. {
  6651. $this->hookActionOrderStatusPostUpdate($params);
  6652. }
  6653.  
  6654. public function hookActionOrderStatusPostUpdate($params)
  6655. {
  6656. // Manage Messaging with customer (invoice)
  6657. //
  6658. $this->manageInvoiceOrderState($params);
  6659.  
  6660. // Manage Messaging with customer (Seller Review Incentive)
  6661. //
  6662. $this->manageReviewIncentiveOrderState($params);
  6663.  
  6664. // Manage Order Cancelations
  6665. //
  6666. $this->manageOrderCancelation($params);
  6667.  
  6668. if (Amazon::$debug_mode && Tools::getValue('id_order')) {
  6669. CommonTools::d(sprintf('%s:#%d hookActionOrderStatusPostUpdate - module is in debug mode, operation stopped'."\n", basename(__FILE__), __LINE__));
  6670. }
  6671. }
  6672.  
  6673. public function hookActionEmailAddAfterContent($params)
  6674. {
  6675. if (!$this->customerThreadIsActive($params)) {
  6676. return;
  6677. }
  6678. require_once(dirname(__FILE__).'/classes/amazon.messaging.class.php');
  6679.  
  6680. $messaging = new AmazonMessaging();
  6681. $messaging->overrideCustomerThreadEmail($params);
  6682. }
  6683.  
  6684. public function customerThreadIsActive($params = false)
  6685. {
  6686. if (!function_exists('imap_open')) {
  6687. return(false);
  6688. }
  6689.  
  6690. if (!$this->amazon_features['messaging']) {
  6691. return(false);
  6692. }
  6693.  
  6694. $customer_thread_settings = AmazonConfiguration::get('CUSTOMER_THREAD');
  6695.  
  6696. if (!is_array($customer_thread_settings) && !count($customer_thread_settings)) {
  6697. return(false);
  6698. }
  6699.  
  6700. if (is_array($customer_thread_settings) && (!isset($customer_thread_settings['active']) || !(bool)$customer_thread_settings['active'])) {
  6701. return(false);
  6702. }
  6703.  
  6704. if (is_array($params) && $params['template'] == $customer_thread_settings['template']) {
  6705. return(true);
  6706. } elseif ($params != false && is_array($params)) {
  6707. return(false);
  6708. }
  6709.  
  6710. return(true);
  6711. }
  6712.  
  6713. protected function manageInvoiceOrderState($params)
  6714. {
  6715. $id_order = (int)$params['id_order'];
  6716. $test_mode = isset($params['test_mode']) && $params['test_mode'];
  6717.  
  6718. // Mail/Invoice is Active ?
  6719. //
  6720. $mail_invoice = AmazonConfiguration::get('MAIL_INVOICE');
  6721.  
  6722. if (!isset($mail_invoice['active']) || !(int)$mail_invoice['active'] || !isset($mail_invoice['order_state'])) {
  6723. if (Amazon::$debug_mode) {
  6724. printf('%s:#%d Amazon_Messaging::sendInvoice(%d) invoice by email is inactive'."\n", basename(__FILE__), __LINE__, $id_order);
  6725. }
  6726.  
  6727. return (false);
  6728. }
  6729.  
  6730. $order = new Order($id_order);
  6731.  
  6732. if (!Validate::isLoadedObject($order)) {
  6733. if (Amazon::$debug_mode) {
  6734. printf('%s:#%d Amazon_Messaging::sendInvoice(%d) invoice by email: unable to load order'."\n", basename(__FILE__), __LINE__, $id_order);
  6735. }
  6736.  
  6737. return (false);
  6738. }
  6739.  
  6740. // Not an amazon order
  6741. //
  6742. if (Tools::strtolower($order->module) != Tools::strtolower($this->name)) {
  6743. if (Amazon::$debug_mode) {
  6744. printf('%s:#%d Amazon_Messaging::sendInvoice(%d) invoice by email: not an Amazon order'."\n", basename(__FILE__), __LINE__, $id_order);
  6745. }
  6746.  
  6747. return(false);
  6748. }
  6749.  
  6750. if (!$test_mode) {
  6751. // Matching Order Status
  6752. //
  6753. if ($params['newOrderStatus']->id != (int)$mail_invoice['order_state']) {
  6754. if (Amazon::$debug_mode) {
  6755. printf('%s:#%d Amazon_Messaging::sendInvoice(%d) invoice by email: status mismatch: %d/%d'."\n", basename(__FILE__), __LINE__, $id_order, $params['newOrderStatus']->id, (int)$mail_invoice['order_state']);
  6756. }
  6757.  
  6758. return (false);
  6759. }
  6760. }
  6761.  
  6762. // Starting Mail/Invoice sending
  6763. //
  6764. require_once(dirname(__FILE__).'/classes/amazon.messaging.class.php');
  6765.  
  6766. $messaging = new AmazonMessaging(Amazon::$debug_mode, $test_mode);
  6767. $result = $messaging->sendInvoice($id_order);
  6768.  
  6769. if (Amazon::$debug_mode && !$result) {
  6770. printf('%s:#%d AmazonMessaging::sendInvoice(%d) failed'."\n", basename(__FILE__), __LINE__, $id_order);
  6771. }
  6772.  
  6773. return ($result);
  6774. }
  6775.  
  6776. protected function manageReviewIncentiveOrderState($params)
  6777. {
  6778. $id_order = (int)$params['id_order'];
  6779. $test_mode = isset($params['test_mode']) && $params['test_mode'];
  6780.  
  6781. // Mail/Invoice is Active ?
  6782. //
  6783. $mail_review = AmazonConfiguration::get('MAIL_REVIEW');
  6784.  
  6785. if (!isset($mail_review['active']) || !(int)$mail_review['active'] || !isset($mail_review['order_state'])) {
  6786. return (false);
  6787. }
  6788.  
  6789. if (!($order = new Order($id_order))) {
  6790. return (false);
  6791. }
  6792.  
  6793. // Not an amazon order
  6794. //
  6795. if (Tools::strtolower($order->module) != Tools::strtolower($this->name)) {
  6796. return (false);
  6797. }
  6798.  
  6799. // Matching Order Status
  6800. //
  6801. if (!$test_mode && $params['newOrderStatus']->id != (int)$mail_review['order_state']) {
  6802. return (false);
  6803. }
  6804.  
  6805. // Starting Mail/Invoice sending
  6806. //
  6807. require_once(dirname(__FILE__).'/classes/amazon.messaging.class.php');
  6808.  
  6809. $messaging = new AmazonMessaging(Amazon::$debug_mode, $test_mode);
  6810. $result = $messaging->sendReviewIncentive($id_order);
  6811.  
  6812. if (!$result && Amazon::$debug_mode) {
  6813. printf('%s:#%d AmazonMessaging::manageReviewIncentiveOrderState(%d) failed'."\n", basename(__FILE__), __LINE__, $id_order);
  6814. }
  6815.  
  6816. return ($result);
  6817. }
  6818.  
  6819. protected function manageOrderCancelation($params)
  6820. {
  6821. $id_order = (int)$params['id_order'];
  6822.  
  6823. if (!($order = new Order($id_order))) {
  6824. return (false);
  6825. }
  6826.  
  6827. // Not an amazon order
  6828. //
  6829. if (Tools::strtolower($order->module) != Tools::strtolower($this->name)) {
  6830. return (false);
  6831. }
  6832.  
  6833. // Matching Order Status
  6834. //
  6835. $canceled_state = AmazonConfiguration::get('CANCELED_STATE');
  6836.  
  6837. if (!$canceled_state || (int)$params['newOrderStatus']->id != (int)$canceled_state) {
  6838. return (false);
  6839. }
  6840.  
  6841. require_once(dirname(__FILE__).'/classes/amazon.order_info.class.php');
  6842. require_once(dirname(__FILE__).'/classes/amazon.order.class.php');
  6843. require_once(dirname(__FILE__).'/classes/amazon.order_cancel.class.php');
  6844.  
  6845. $order_cancel = new AmazonOrderCancel();
  6846. $result = $order_cancel->changeOrderStatus($id_order, AmazonOrder::TO_CANCEL);
  6847.  
  6848. if (!$result && Amazon::$debug_mode) {
  6849. printf('%s:#%d AmazonMessaging::manageOrderCancelation(%d) failed'."\n", basename(__FILE__), __LINE__, $id_order);
  6850. }
  6851.  
  6852. return ($result);
  6853. }
  6854.  
  6855.  
  6856. /* HOOKS FOR BACKWARD COMPATIBILITY - PRESTASHOP 1.3 and 1.4 */
  6857.  
  6858. public function hookbackOfficeHeader($params)
  6859. {
  6860. return ($this->hookDisplayBackOfficeHeader($params));
  6861. }
  6862.  
  6863. public function hookDisplayBackOfficeHeader($params)
  6864. {
  6865. $html = '';
  6866. $amazonTab = null;
  6867.  
  6868. if (version_compare(_PS_VERSION_, '1.5', '<')) {
  6869. $context_param = null;
  6870. $amazonTab = Tools::strtolower(Tools::getValue('tab')) === 'admincatalog';
  6871. }
  6872.  
  6873. if ($amazonTab && Tools::getValue('id_product') && (Tools::getValue('addproduct') !== false || Tools::getValue('updateproduct') !== false)) {
  6874. $context_param = '?amazon_token='.Configuration::get('AMAZON_INSTANT_TOKEN', null, 0, 0);
  6875. $html .= html_entity_decode('&lt;meta name="amazon-options" content="'.$this->url.'functions/product_options.php'.$context_param.'" /&gt;');
  6876. $html .= $this->_autoAddJS($this->url.'views/js/product_options.js');
  6877. $html .= $this->_autoAddCSS($this->url.'views/css/product_options.css');
  6878. }
  6879.  
  6880. return ($html);
  6881. }
  6882.  
  6883. public function hookActionProductAttributeDelete($params)
  6884. {
  6885. if (isset($params['product']->id)) {
  6886. $id_product = $params['product']->id;
  6887. } elseif (isset($params['id_product'])) {
  6888. $id_product = $params['id_product'];
  6889. } elseif (isset($params['product'])) {
  6890. $id_product = $params['product']['id_product'];
  6891. } else {
  6892. return (false);
  6893. }
  6894.  
  6895. return (AmazonProduct::marketplaceActionRemoveAllCombinations(self::REMOVE, $id_product));
  6896. }
  6897.  
  6898. public function hookDeleteProductAttribute($params)
  6899. {
  6900. if (isset($params['product']->id_product_attribute)) {
  6901. $id_product_attribute = $params['product']->id_product_attribute;
  6902. $id_product = $params['product']->id_product;
  6903. } elseif (isset($params['id_product_attribute'])) {
  6904. $id_product_attribute = $params['id_product_attribute'];
  6905. $id_product = $params['id_product'];
  6906. } elseif (isset($params['product'])) {
  6907. $id_product_attribute = $params['product']['id_product_attribute'];
  6908. $id_product = $params['product']['id_product'];
  6909. } else {
  6910. return (false);
  6911. }
  6912.  
  6913. return (AmazonProduct::marketplaceActionRemoveCombination($id_product, $id_product_attribute));
  6914. }
  6915.  
  6916. public function hookActionProductSave($params)
  6917. {
  6918. if (isset($params['product']->id)) {
  6919. $id_product = $params['product']->id;
  6920. } elseif (isset($params['id_product'])) {
  6921. $id_product = $params['id_product'];
  6922. } elseif (isset($params['product'])) {
  6923. $id_product = $params['product']['id_product'];
  6924. } else {
  6925. return (false);
  6926. }
  6927.  
  6928. return (AmazonProduct::marketplaceActionSet(self::UPDATE, $id_product));
  6929. }
  6930.  
  6931. public function hookActionOrderHistoryAddAfter($params)
  6932. {
  6933. // Manage FBA MultiChannel Orders
  6934. //
  6935. return ($this->_manageFbaIncomingOrder($params));
  6936. }
  6937.  
  6938. public function _manageFbaIncomingOrder($params)
  6939. {
  6940. if (!isset($params['order_history'])) {
  6941. return (false);
  6942. }
  6943.  
  6944. $order_status = new OrderState((int)$params['order_history']->id_order_state);
  6945.  
  6946. if (!Validate::isLoadedObject($order_status)) {
  6947. return(false);
  6948. }
  6949. if (!$order_status->paid) {
  6950. return(false);
  6951. }
  6952. if ($order_status->shipped) {
  6953. return(false);
  6954. }
  6955. if ($order_status->delivery) {
  6956. return(false);
  6957. }
  6958.  
  6959. // Only if FBA MultiChannel is active
  6960. if (!(bool)Configuration::get('AMAZON_FBA_MULTICHANNEL')) {
  6961. return (false);
  6962. }
  6963.  
  6964. if (!(bool)Configuration::get('AMAZON_FBA_MULTICHANNEL_AUTO')) {
  6965. return (false);
  6966. }
  6967.  
  6968. if (!isset($params['order_history']->id_order)) {
  6969. return (false);
  6970. }
  6971.  
  6972. $id_order = (int)$params['order_history']->id_order;
  6973.  
  6974. require_once(dirname(__FILE__).'/classes/amazon.multichannel.class.php');
  6975. require_once(dirname(__FILE__).'/classes/amazon.mail.logger.class.php');
  6976.  
  6977. $debug = (bool)Configuration::get('AMAZON_DEBUG_MODE');
  6978. $send_email = (bool)Configuration::get('AMAZON_EMAIL');
  6979. $message = null;
  6980.  
  6981. if ($debug && $send_email) {
  6982. $caller = AmazonTools::callingFunction();
  6983. $message .= sprintf('%s : %s'.self::LF, $caller, 'Testing FBA Eligibility');
  6984. }
  6985.  
  6986. if (!($order = AmazonMultiChannel::isEligible($id_order))) {
  6987. if ($debug && $send_email) {
  6988. $caller = AmazonTools::callingFunction();
  6989. $message .= sprintf('%s : %s'.self::LF, $caller, 'Order is not eligible');
  6990. AmazonMailLogger::message($message);
  6991. }
  6992.  
  6993. return (false);
  6994. }
  6995.  
  6996. if (!isset($order->id_lang) || !$order->id_lang) {
  6997. if ($debug && $send_email) {
  6998. $caller = AmazonTools::callingFunction();
  6999. $message .= sprintf('%s : %s'.self::LF, $caller, 'Missing ID Lang');
  7000. AmazonMailLogger::message($message);
  7001.  
  7002. return (false);
  7003. }
  7004. }
  7005.  
  7006. // TODO: FBA Matrix to identify the closest fullfilment center
  7007. $id_lang = $order->id_lang;
  7008.  
  7009. // Eligibility Check passed, place a new FBA Order
  7010. //
  7011. $amazonMultiChannelOrder = new AmazonMultiChannel($id_order);
  7012.  
  7013. if (!Validate::isLoadedObject($amazonMultiChannelOrder)) {
  7014. if ($debug && $send_email) {
  7015. $caller = AmazonTools::callingFunction();
  7016. $message .= sprintf('%s : %s'.self::LF, $caller, 'Unable to read object');
  7017. AmazonMailLogger::message($message);
  7018. }
  7019.  
  7020. // abnormal
  7021. return (false);
  7022. }
  7023. // Module itself
  7024. if (Tools::strtolower($amazonMultiChannelOrder->module) === $this->name) {
  7025. return (false);
  7026. }
  7027.  
  7028. // Already ordered, shipped or canceled
  7029. //
  7030. if (Tools::strlen($amazonMultiChannelOrder->marketPlaceChannelStatus)) {
  7031. return (false);
  7032. }
  7033.  
  7034. if (!($AmazonFBAOrder = $amazonMultiChannelOrder->createFulfillmentOrder($id_lang, $debug))) {
  7035. if ($debug && $send_email) {
  7036. $caller = AmazonTools::callingFunction();
  7037. $message .= sprintf('%s : %s'.self::LF, $caller, 'CreateFulfillmentOrder Failed');
  7038.  
  7039. if (AmazonMultiChannel::$errors) {
  7040. $message .= print_r(AmazonMultiChannel::$errors, true);
  7041. }
  7042.  
  7043. $message .= print_r($AmazonFBAOrder, true);
  7044. AmazonMailLogger::message($message);
  7045. } elseif ($debug) {
  7046. echo nl2br(print_r($AmazonFBAOrder, true));
  7047. }
  7048.  
  7049. return (false);
  7050. }
  7051.  
  7052. if ($send_email) {
  7053. $mailtemplate = array();
  7054. $mailtemplate['{order}'] = sprintf('%s : %s
  7055. %s : %s
  7056. %s : %s', $this->l('Order ID'), $id_order, $this->l('Date'), $AmazonFBAOrder['DisplayableOrderDateTime'], $this->l('Shipping'), $AmazonFBAOrder['ShippingSpeedCategory']);
  7057. $mailtemplate['{order}'] = nl2br($mailtemplate['{order}']);
  7058.  
  7059. $mailtemplate['{customer_address}'] = sprintf('
  7060. %s
  7061. %s
  7062. %s
  7063. %s
  7064. %s %s (%s)
  7065. %s', $AmazonFBAOrder['DestinationAddress']['Name'], $AmazonFBAOrder['DestinationAddress']['Line1'], $AmazonFBAOrder['DestinationAddress']['Line2'], $AmazonFBAOrder['DestinationAddress']['Line3'], $AmazonFBAOrder['DestinationAddress']['PostalCode'], $AmazonFBAOrder['DestinationAddress']['City'], $AmazonFBAOrder['DestinationAddress']['CountryCode'], $AmazonFBAOrder['DestinationAddress']['PhoneNumber']);
  7066. $mailtemplate['{customer_address}'] = nl2br($mailtemplate['{customer_address}']);
  7067.  
  7068. $mailtemplate['{ordered_items}'] = null;
  7069.  
  7070. if (is_array($AmazonFBAOrder['Items'])) {
  7071. foreach ($AmazonFBAOrder['Items'] as $Item) {
  7072. $mailtemplate['{ordered_items}'] .= sprintf('%d x %s - %s'."\n", $Item['Quantity'], $Item['SKU'], $Item['DisplayableComment']);
  7073. }
  7074.  
  7075. $mailtemplate['{ordered_items}'] = nl2br($mailtemplate['{ordered_items}']);
  7076.  
  7077. $mailtemplate['{amazon_info}'] = sprintf($this->l('Order #%s submitted on %s Amazon response ID: %s'), $AmazonFBAOrder['DisplayableOrderId'], $AmazonFBAOrder['DisplayableOrderDateTime'], $AmazonFBAOrder['Response']);
  7078. }
  7079.  
  7080. $email_address = Configuration::get('PS_SHOP_EMAIL');
  7081.  
  7082. if ($debug) {
  7083. $caller = AmazonTools::callingFunction();
  7084. $message .= sprintf('%s : %s'.self::LF, $caller, 'Amazon FBA Order Complete');
  7085. $message .= print_r($AmazonFBAOrder, true);
  7086. AmazonMailLogger::message($message);
  7087. }
  7088. Mail::Send(
  7089. $id_lang, // id_lang
  7090. 'fba_multichannel', // template
  7091. $this->l('Amazon FBA: A new multichannel order has been processed'), // subject
  7092. $mailtemplate, // templateVars
  7093. $email_address, // to
  7094. null, // To Name
  7095. null, // From
  7096. null, // From Name
  7097. null, // Attachment
  7098. null, // SMTP
  7099. $this->path.'mails/'
  7100. );
  7101. }
  7102.  
  7103. if ($debug && !$send_email) {
  7104. echo nl2br(print_r($AmazonFBAOrder, true));
  7105. }
  7106.  
  7107. return (false);
  7108. }
  7109.  
  7110. public function hookUpdateQuantity($params)
  7111. {
  7112. return ($this->hookActionUpdateQuantity($params));
  7113. }
  7114.  
  7115. public function hookActionUpdateQuantity($params)
  7116. {
  7117. if (isset($params['product']->id)) {
  7118. $id_product = $params['product']->id;
  7119. } elseif (isset($params['id_product'])) {
  7120. $id_product = $params['id_product'];
  7121. } elseif (isset($params['product'])) {
  7122. $id_product = $params['product']['id_product'];
  7123. } else {
  7124. return (false);
  7125. }
  7126.  
  7127. $id_product_attribute = isset($params['id_product_attribute']) ? $params['id_product_attribute'] : null;
  7128.  
  7129. AmazonProduct::marketplaceActionSet(self::UPDATE, $id_product, $id_product_attribute);
  7130. }
  7131.  
  7132. public function hookUpdateProduct($params)
  7133. {
  7134. $this->hookActionProductUpdate($params);
  7135. }
  7136.  
  7137. public function hookActionProductUpdate($params)
  7138. {
  7139. if (isset($params['product']->id)) {
  7140. $id_product = $params['product']->id;
  7141. } elseif (isset($params['id_product'])) {
  7142. $id_product = $params['id_product'];
  7143. } elseif (isset($params['product'])) {
  7144. $id_product = $params['product']['id_product'];
  7145. } else {
  7146. return (false);
  7147. }
  7148.  
  7149. AmazonProduct::marketplaceActionSet(self::UPDATE, $id_product);
  7150. }
  7151.  
  7152. public function hookAfterSaveProduct($params)
  7153. {
  7154. return ($this->hookActionProductUpdate($params));
  7155. }
  7156.  
  7157. public function actionObjectStockAvailableUpdateAfter($params)
  7158. {
  7159. if (!isset($params['object']) || !$params['object']->id_product) {
  7160. return (false);
  7161. }
  7162.  
  7163. $obj = new stdClass;
  7164. $obj->id = (int)$params['object']->id_product;
  7165.  
  7166. return ($this->hookActionProductUpdate(array('product' => $obj)));
  7167. }
  7168.  
  7169. public function hookActionObjectProductUpdateAfter($params)
  7170. {
  7171. if (!isset($params['object']) || !$params['object']->id) {
  7172. return (false);
  7173. }
  7174.  
  7175. $obj = new stdClass;
  7176. $obj->id = $params['object']->id;
  7177.  
  7178. return ($this->hookActionProductUpdate(array('product' => $obj)));
  7179. }
  7180.  
  7181. public function hookUpdateProductAttribute($params)
  7182. {
  7183. return ($this->hookActionProductAttributeUpdate($params));
  7184. }
  7185.  
  7186. public function hookActionProductAttributeUpdate($params)
  7187. {
  7188. if (!isset($params['id_product_attribute'])) {
  7189. return (false);
  7190. }
  7191.  
  7192. return (AmazonProduct::marketplaceActionUpdateCombination($params['id_product_attribute']));
  7193. }
  7194.  
  7195. public function hookDeleteProduct($params)
  7196. {
  7197. return ($this->hookActionProductDelete($params));
  7198. }
  7199.  
  7200. public function hookActionProductDelete($params)
  7201. {
  7202. if (isset($params['product']->id)) {
  7203. $id_product = $params['product']->id;
  7204. } elseif (isset($params['id_product'])) {
  7205. $id_product = $params['id_product'];
  7206. } elseif (isset($params['product'])) {
  7207. $id_product = $params['product']['id_product'];
  7208. } else {
  7209. return (false);
  7210. }
  7211.  
  7212. if (!isset($params['product']->reference)) {
  7213. return (false);
  7214. }
  7215.  
  7216. return (AmazonProduct::marketplaceActionSet(self::REMOVE, $id_product, null, $params['product']->reference));
  7217. }
  7218.  
  7219. public function hookAddProduct($params)
  7220. {
  7221. return ($this->hookActionProductAdd($params));
  7222. }
  7223.  
  7224. public function hookActionProductAdd($params)
  7225. {
  7226. if (isset($params['product']->id)) {
  7227. $id_product = $params['product']->id;
  7228. } elseif (isset($params['id_product'])) {
  7229. $id_product = $params['id_product'];
  7230. } elseif (isset($params['product'])) {
  7231. $id_product = $params['product']['id_product'];
  7232. } else {
  7233. return (false);
  7234. }
  7235.  
  7236. return (AmazonProduct::marketplaceActionSet(self::ADD, $id_product));
  7237. }
  7238.  
  7239. public function hookActionCarrierUpdate($params)
  7240. {
  7241. $this->hookUpdateCarrier($params);
  7242. }
  7243.  
  7244. public function hookUpdateCarrier($params)
  7245. {
  7246. if (version_compare(_PS_VERSION_, '1.5', '>=') && Shop::isFeatureActive()) {
  7247. //
  7248. $shops = Shop::getShops(true, null, false);
  7249. } else {
  7250. $shops = array(
  7251. 0 => array(
  7252. 'id_shop' => null,
  7253. 'id_shop_group' => null
  7254. )
  7255. );
  7256. }
  7257.  
  7258. foreach ($shops as $shop) {
  7259. // Amazon Carrier Mapping
  7260. $carriers = AmazonConfiguration::get('CARRIER', null, $shop['id_shop_group'], $shop['id_shop']);
  7261.  
  7262. if ($carriers && is_array($carriers)) {
  7263. foreach ($carriers as $id_lang => $ps_carriers) {
  7264. if ($ps_carriers && is_array($ps_carriers)) {
  7265. foreach ($ps_carriers as $index => $carrier) {
  7266. if ($carriers[$id_lang][$index] == $params['id_carrier']) {
  7267. $carriers[$id_lang][$index] = $params['carrier']->id;
  7268. }
  7269. }
  7270. }
  7271. }
  7272. }
  7273.  
  7274. AmazonConfiguration::updateValue('CARRIER', $carriers, false, $shop['id_shop_group'], $shop['id_shop']);
  7275.  
  7276. // Amazon FBA MultiChannel Carrier Mapping
  7277. $carriers_multichannel = AmazonConfiguration::get('CARRIER_MULTICHANNEL', null, $shop['id_shop_group'], $shop['id_shop']);
  7278.  
  7279. if ($carriers_multichannel && is_array($carriers_multichannel)) {
  7280. foreach ($carriers_multichannel as $id_lang => $mapping) {
  7281. if (isset($mapping['prestashop']) && is_array($mapping['prestashop'])) {
  7282. foreach ($mapping['prestashop'] as $key => $id_carrier) {
  7283. if ($id_carrier == $params['id_carrier']) {
  7284. $carriers_multichannel[$id_lang]['prestashop'][$key] = $params['carrier']->id;
  7285. }
  7286. }
  7287. }
  7288. }
  7289. }
  7290.  
  7291. AmazonConfiguration::updateValue('CARRIER_MULTICHANNEL', $carriers_multichannel, false, $shop['id_shop_group'], $shop['id_shop']);
  7292.  
  7293. // Amazon Outgoing Orders Carrier Mapping
  7294. $carriers_default = AmazonConfiguration::get('CARRIER_DEFAULT', null, $shop['id_shop_group'], $shop['id_shop']);
  7295.  
  7296. if ($carriers_default && is_array($carriers_default)) {
  7297. foreach ($carriers_default as $id_lang => $mapping) {
  7298. if (isset($mapping['prestashop']) && is_array($mapping['prestashop'])) {
  7299. foreach ($mapping['prestashop'] as $key => $id_carrier) {
  7300. if ($id_carrier == $params['id_carrier']) {
  7301. $carriers_default[$id_lang]['prestashop'][$key] = $params['carrier']->id;
  7302. }
  7303. }
  7304. }
  7305. }
  7306. }
  7307.  
  7308. AmazonConfiguration::updateValue('CARRIER_DEFAULT', $carriers_default, false, $shop['id_shop_group'], $shop['id_shop']);
  7309.  
  7310. // Amazon Smart Shipping
  7311. $smart_shipping = AmazonConfiguration::get('SHIPPING', null, $shop['id_shop_group'], $shop['id_shop']);
  7312.  
  7313. if (is_array($smart_shipping) && isset($smart_shipping['smart_shipping']) && isset($smart_shipping['smart_shipping']['prestashop']) && is_array($smart_shipping['smart_shipping']['prestashop'])) {
  7314. foreach ($smart_shipping['smart_shipping']['prestashop'] as $amazonShippingOption => $id_carrier) {
  7315. if ($id_carrier == $params['id_carrier']) {
  7316. $smart_shipping['smart_shipping']['prestashop'][$amazonShippingOption] = $params['carrier']->id;
  7317. }
  7318. }
  7319. }
  7320.  
  7321. AmazonConfiguration::updateValue('SHIPPING', $smart_shipping, false, $shop['id_shop_group'], $shop['id_shop']);
  7322. }
  7323. }
  7324.  
  7325. public function hookAdminOrder($params)
  7326. {
  7327. return ($this->hookDisplayAdminOrder($params));
  7328. }
  7329.  
  7330. public function hookDisplayAdminOrder($params)
  7331. {
  7332. require_once(_PS_MODULE_DIR_.$this->name.'/classes/amazon.admin_order.class.php');
  7333.  
  7334. $adminOrder = new AmazonAdminOrder();
  7335. $this->_html = $adminOrder->marketplaceOrderDisplay($params);
  7336.  
  7337. return ($this->_html);
  7338. }
  7339.  
  7340. public function hookDisplayAdminProductsExtra($params)
  7341. {
  7342. require_once(_PS_MODULE_DIR_.$this->name.'/classes/amazon.product_tab.class.php');
  7343.  
  7344. $adminProductTab = new AmazonProductTab();
  7345.  
  7346. $html = $adminProductTab->marketplaceProductTabContent($params);
  7347.  
  7348. if (Tools::strlen($html)) {
  7349. return ($html);
  7350. } else {
  7351. return (nl2br(Amazon::LF));
  7352. } // Prevents error: "A server error occurred while loading the tabs: some tabs could not be loaded."
  7353. }
  7354.  
  7355. public function hookActionAdminOrdersListingFieldsModifier($params)
  7356. {
  7357. if (!isset($params['fields']['mp_order_id'])) {
  7358. $params['fields']['mp_order_id'] = array(
  7359. 'title' => 'Marketplace Order ID',
  7360. "align" => "text-center",
  7361. "class" => "fixed-width-xs",
  7362. "filter_key" => "amo!mp_order_id"
  7363. );
  7364. }
  7365. if (isset($params['select'])) {
  7366. $params['select'] .= ", amo.mp_order_id";
  7367. }
  7368.  
  7369. if (isset($params['join'])) {
  7370. $params['join'] .= 'LEFT JOIN `' . _DB_PREFIX_ . 'marketplace_orders` amo ON (a.`id_order` = amo.`id_order`)';
  7371. }
  7372. }
  7373.  
  7374. public function hookDisplayPDFInvoice($object)
  7375. {
  7376. require_once(_PS_MODULE_DIR_.$this->name.'/classes/amazon.admin_order.class.php');
  7377.  
  7378. /** @var OrderInvoice $order_invoice */
  7379. $order_invoice = $object['object'];
  7380. $marketplace_order = AmazonAdminOrder::getByOrderId($order_invoice->id_order);
  7381. if ($marketplace_order) {
  7382. return sprintf('Marketplace Order ID: %s', $marketplace_order['mp_order_id']);
  7383. }
  7384. return '';
  7385. }
  7386.  
  7387. /**
  7388. * GDPR compliant: Export customer data
  7389. * @param string|array $customer
  7390. * @return string
  7391. * @throws PrestaShopDatabaseException
  7392. */
  7393. public function hookActionExportGDPRData($customer)
  7394. {
  7395. $customer_data = $this->_extractCustomerDataForGDPR($customer);
  7396.  
  7397. $mp_order_ids = AmazonTools::getAllCustomerMpOrderIds($customer_data['email'], $customer_data['name']);
  7398.  
  7399. if (count($mp_order_ids)) {
  7400. $result = AmazonTools::getAllCustomerDataByMpOrderIds($mp_order_ids);
  7401. return json_encode($result);
  7402. }
  7403.  
  7404. return json_encode(array());
  7405. }
  7406.  
  7407. /**
  7408. * GDPR compliant: Delete customer data
  7409. * @param string|array $customer
  7410. * @return string
  7411. * @throws PrestaShopDatabaseException
  7412. */
  7413. public function hookActionDeleteGDPRCustomer($customer)
  7414. {
  7415. $customer_data = $this->_extractCustomerDataForGDPR($customer);
  7416.  
  7417. $mp_order_ids = AmazonTools::getAllCustomerMpOrderIds($customer_data['email'], $customer_data['name']);
  7418.  
  7419. if (count($mp_order_ids)) {
  7420. $result = AmazonTools::deleteAllCustomerDataByMpOrderId($mp_order_ids);
  7421. if ($result) {
  7422. return json_encode(true);
  7423. } else {
  7424. return json_encode($this->l('Amazon: Unable to delete customer data.'));
  7425. }
  7426. }
  7427.  
  7428. return json_encode(true);
  7429. }
  7430.  
  7431. /**
  7432. * Parse customer input to email and name
  7433. * @param $customer
  7434. * @return array
  7435. */
  7436. private function _extractCustomerDataForGDPR($customer)
  7437. {
  7438. // Include needed classes
  7439. require_once(_PS_MODULE_DIR_.'/amazon/classes/amazon.address.class.php');
  7440. require_once(_PS_MODULE_DIR_.'/amazon/classes/amazon.order.class.php');
  7441. require_once(_PS_MODULE_DIR_.'/amazon/classes/amazon.order_item.class.php');
  7442. require_once(_PS_MODULE_DIR_.'/amazon/classes/amazon.stat.class.php');
  7443.  
  7444. $email = $first_name = $last_name = '';
  7445. if (is_string($customer)) {
  7446. // This is email
  7447. $email = $customer;
  7448. } elseif (is_array($customer)) {
  7449. // Customer data in array
  7450. if (isset($customer['email'])) {
  7451. $email = $customer['email'];
  7452. }
  7453. if (isset($customer['firstname'])) {
  7454. $first_name = $customer['firstname'];
  7455. }
  7456. if (isset($customer['lastname'])) {
  7457. $last_name = $customer['lastname'];
  7458. }
  7459. }
  7460.  
  7461. $email = trim($email);
  7462.  
  7463. if ($first_name && $last_name && Tools::strlen($first_name) && Tools::strlen($last_name)) {
  7464. $name = array(trim($first_name.' '.$last_name), trim($last_name.' '.$first_name));
  7465. } else {
  7466. $name = trim($first_name.' '.$last_name);
  7467. }
  7468.  
  7469. return array('email' => $email, 'name' => $name);
  7470. }
  7471. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement