From a564a5f5ea4103c4a435d97ae699a2bb860684b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thoma=20Bigue=CC=80res?= Date: Thu, 26 Nov 2015 17:02:54 +0100 Subject: [PATCH 1/6] [*] MO mondialrelay : taking account weight coefficiency [*] MO mondialrelay : spanish phone format [*] MO mondialrelay : assurance level [*] MO mondialrelay : OPC [*] MO mondialrelay : alert if javascript is not enabled --- AdminMondialRelay.php | 274 +- ajax.php | 146 +- classes/IMondialRelayWSMethod.php | 40 +- classes/MRCreateTickets.php | 1184 ++++---- classes/MRDownloadPDF.php | 288 +- classes/MRGetRelayPoint.php | 480 ++-- classes/MRGetTickets.php | 430 +-- classes/MRManagement.php | 268 +- classes/MRRelayDetail.php | 448 +-- classes/MRTools.php | 444 +-- classes/index.php | 4 +- config.xml | 20 +- connexion.php | 54 +- cron.php | 66 +- css/index.php | 6 +- css/style.css | 0 de.php | 0 docs/index.php | 6 +- docs/install.pdf | Bin en.php | 0 errorCode.php | 144 +- es.php | 0 fr.php | 2 + img/AdminMondialRelay.gif | Bin img/details.gif | Bin img/error2.png | Bin img/getTickets.gif | Bin img/help.png | Bin img/icones/account_detail.png | Bin img/icones/help.png | Bin img/icones/index.php | 4 +- img/icones/info.png | Bin img/icones/settings.png | Bin img/icones/supplier.png | Bin img/index.php | 4 +- img/loader.gif | Bin img/logo.gif | Bin img/logo_hd.png | Bin img/pdf_icon.jpg | Bin img/selectRelayPoint.png | Bin index.php | 4 +- it.php | 0 js/common.js | 64 + js/gmap.js | 0 js/index.php | 4 +- js/jquery-1.6.4.min.js | 0 ...gin.mondialrelay.parcelshoppicker.2.0.0.js | 0 js/mondialrelay.js | 19 +- js/mondialrelay_widget.js | 13 - logo.gif | Bin 678 -> 1035 bytes logo.png | Bin 3262 -> 2305 bytes mails/en/index.php | 4 +- mails/en/mr_new_order.html | 0 mails/en/mr_new_order.txt | 0 mails/fr/index.php | 4 +- mails/fr/mr_new_order.html | 0 mails/fr/mr_new_order.txt | 0 mails/index.php | 4 +- mondialrelay.php | 2432 ++++++++--------- nl.php | 0 sql/index.php | 4 +- sql/mrInstall.sql | 0 upgrade/index.php | 4 +- upgrade/install-1.8.0.php | 190 +- upgrade/install-1.8.3.php | 14 +- upgrade/install-2.0.6.php | 22 +- views/index.php | 4 +- views/templates/admin/bo-header.tpl | 0 views/templates/admin/configuration.tpl | 0 views/templates/admin/generate_tickets.tpl | 0 views/templates/admin/history.tpl | 0 views/templates/admin/index.php | 4 +- views/templates/admin/post_action.tpl | 0 views/templates/admin/settings.tpl | 0 views/templates/front/checkout_process.tpl | 6 +- .../front/checkout_process_widget.tpl | 9 +- views/templates/front/header.tpl | 1 + views/templates/front/header_widget.tpl | 3 +- views/templates/front/index.php | 4 +- views/templates/front/jquery-overload.tpl | 0 views/templates/front/order_detail.tpl | 0 views/templates/index.php | 4 +- 82 files changed, 3591 insertions(+), 3538 deletions(-) mode change 100644 => 100755 AdminMondialRelay.php mode change 100644 => 100755 ajax.php mode change 100644 => 100755 classes/IMondialRelayWSMethod.php mode change 100644 => 100755 classes/MRCreateTickets.php mode change 100644 => 100755 classes/MRDownloadPDF.php mode change 100644 => 100755 classes/MRGetRelayPoint.php mode change 100644 => 100755 classes/MRGetTickets.php mode change 100644 => 100755 classes/MRManagement.php mode change 100644 => 100755 classes/MRRelayDetail.php mode change 100644 => 100755 classes/MRTools.php mode change 100644 => 100755 classes/index.php mode change 100644 => 100755 config.xml mode change 100644 => 100755 connexion.php mode change 100644 => 100755 cron.php mode change 100644 => 100755 css/index.php mode change 100644 => 100755 css/style.css mode change 100644 => 100755 de.php mode change 100644 => 100755 docs/index.php mode change 100644 => 100755 docs/install.pdf mode change 100644 => 100755 en.php mode change 100644 => 100755 errorCode.php mode change 100644 => 100755 es.php mode change 100644 => 100755 fr.php mode change 100644 => 100755 img/AdminMondialRelay.gif mode change 100644 => 100755 img/details.gif mode change 100644 => 100755 img/error2.png mode change 100644 => 100755 img/getTickets.gif mode change 100644 => 100755 img/help.png mode change 100644 => 100755 img/icones/account_detail.png mode change 100644 => 100755 img/icones/help.png mode change 100644 => 100755 img/icones/index.php mode change 100644 => 100755 img/icones/info.png mode change 100644 => 100755 img/icones/settings.png mode change 100644 => 100755 img/icones/supplier.png mode change 100644 => 100755 img/index.php mode change 100644 => 100755 img/loader.gif mode change 100644 => 100755 img/logo.gif mode change 100644 => 100755 img/logo_hd.png mode change 100644 => 100755 img/pdf_icon.jpg mode change 100644 => 100755 img/selectRelayPoint.png mode change 100644 => 100755 index.php mode change 100644 => 100755 it.php create mode 100755 js/common.js mode change 100644 => 100755 js/gmap.js mode change 100644 => 100755 js/index.php mode change 100644 => 100755 js/jquery-1.6.4.min.js mode change 100644 => 100755 js/jquery.plugin.mondialrelay.parcelshoppicker.2.0.0.js mode change 100644 => 100755 js/mondialrelay.js mode change 100644 => 100755 js/mondialrelay_widget.js mode change 100644 => 100755 logo.gif mode change 100644 => 100755 logo.png mode change 100644 => 100755 mails/en/index.php mode change 100644 => 100755 mails/en/mr_new_order.html mode change 100644 => 100755 mails/en/mr_new_order.txt mode change 100644 => 100755 mails/fr/index.php mode change 100644 => 100755 mails/fr/mr_new_order.html mode change 100644 => 100755 mails/fr/mr_new_order.txt mode change 100644 => 100755 mails/index.php mode change 100644 => 100755 mondialrelay.php mode change 100644 => 100755 nl.php mode change 100644 => 100755 sql/index.php mode change 100644 => 100755 sql/mrInstall.sql mode change 100644 => 100755 upgrade/index.php mode change 100644 => 100755 upgrade/install-1.8.0.php mode change 100644 => 100755 upgrade/install-1.8.3.php mode change 100644 => 100755 upgrade/install-2.0.6.php mode change 100644 => 100755 views/index.php mode change 100644 => 100755 views/templates/admin/bo-header.tpl mode change 100644 => 100755 views/templates/admin/configuration.tpl mode change 100644 => 100755 views/templates/admin/generate_tickets.tpl mode change 100644 => 100755 views/templates/admin/history.tpl mode change 100644 => 100755 views/templates/admin/index.php mode change 100644 => 100755 views/templates/admin/post_action.tpl mode change 100644 => 100755 views/templates/admin/settings.tpl mode change 100644 => 100755 views/templates/front/checkout_process.tpl mode change 100644 => 100755 views/templates/front/checkout_process_widget.tpl mode change 100644 => 100755 views/templates/front/header.tpl mode change 100644 => 100755 views/templates/front/header_widget.tpl mode change 100644 => 100755 views/templates/front/index.php mode change 100644 => 100755 views/templates/front/jquery-overload.tpl mode change 100644 => 100755 views/templates/front/order_detail.tpl mode change 100644 => 100755 views/templates/index.php diff --git a/AdminMondialRelay.php b/AdminMondialRelay.php old mode 100644 new mode 100755 index 8005fcd..37ac44c --- a/AdminMondialRelay.php +++ b/AdminMondialRelay.php @@ -30,141 +30,141 @@ class AdminMondialRelay extends AdminTab { - private $mondialrelay = null; - - public $post_errors = array(); - - public function __construct() - { - $this->mondialrelay = new MondialRelay(); - - $this->table = 'mr_selected'; - - parent::__construct(); - $this->context = Context::getContext(); - $datas = array( - 'display_header' => true, - 'display_header_javascript' => true, - 'display_footer' => true, - ); - - $this->context->smarty->assign($datas); - } - - private function displayOrdersTable() - { - $order_state = new OrderState((int)(Configuration::get('MONDIAL_RELAY_ORDER_STATE')), $this->context->language->id); - $orders = MondialRelay::getOrders(array(), MondialRelay::NO_FILTER, $this->mondialrelay->account_shop['MR_WEIGHT_COEFFICIENT']); - - // Simulate a ticket generation - $MRCreateTicket = new MRCreateTickets(array( - 'orderIdList' => null, - 'totalOrder' => null, - 'weightList' => null - ), - $this->mondialrelay - ); - if (is_array($orders) && count($orders)) - foreach ($orders as &$order) - { - $order['display_total_price'] = Tools::displayPrice($order['total'], new Currency($order['id_currency'])); - $order['display_shipping_price'] = Tools::displayPrice($order['shipping'], new Currency($order['id_currency'])); - if (version_compare(_PS_VERSION_, '1.5.5', '<')) - $order['display_date'] = Tools::displayDate($order['date'], $this->context->language->id); - else - $order['display_date'] = Tools::displayDate($order['date']); - $order['weight'] = (!empty($order['mr_weight']) && $order['mr_weight'] > 0) ? $order['mr_weight'] : $order['order_weight']; - } - - $controller = (_PS_VERSION_ < '1.5') ? 'AdminContact' : 'AdminStores'; - - $this->context->smarty->assign(array( - 'MR_token_admin_module' => Tools::getAdminToken('AdminModules'.(int)(Tab::getIdFromClassName('AdminModules')).(int)$this->context->employee->id), - 'MR_token_admin_contact' => array( - 'controller_name' => $controller, - 'token' => Tools::getAdminToken($controller.(int)(Tab::getIdFromClassName($controller)).(int)$this->context->employee->id)), - 'MR_token_admin_orders' => Tools::getAdminToken('AdminOrders'.(int)(Tab::getIdFromClassName('AdminOrders')).(int)$this->context->employee->id), - 'MR_order_state_name' => $order_state->name, - 'MR_orders' => $orders, - 'MR_PS_IMG_DIR_' => _PS_IMG_DIR_, - 'MR_errors_type' => $MRCreateTicket->checkPreValidation()) - ); - - unset($order_state); - echo $this->mondialrelay->fetchTemplate('/views/templates/admin/', 'generate_tickets'); - } - - public function displayhistoriqueForm() - { - $query = 'SELECT * FROM `'._DB_PREFIX_.'mr_history` ORDER BY `id` DESC ;'; - $history = Db::getInstance()->executeS($query); - - foreach ($history as &$item) - $item['url_10x15'] = str_replace('format=A4', 'format=10x15', $item['url_a4']); - - $this->context->smarty->assign(array( - 'MR_histories' => $history) - ); - echo $this->mondialrelay->fetchTemplate('/views/templates/admin/', 'history'); - } - - public function displaySettings($post_action) - { - $curr_order_state = new OrderState((int)$this->mondialrelay->account_shop['MR_ORDER_STATE']); - $order_state = array( - 'id_order_state' => $this->mondialrelay->account_shop['MR_ORDER_STATE'], - 'name' => $curr_order_state->name[$this->context->language->id] - ); - - $this->context->smarty->assign(array( - 'MR_token_admin_mondialrelay' => Tools::getAdminToken('AdminMondialRelay'.(int)(Tab::getIdFromClassName('AdminMondialRelay')).(int)$this->context->employee->id), - 'MR_account_set' => MondialRelay::isAccountSet(), - 'MR_order_state' => $order_state, - 'MR_orders_states_list' => OrderState::getOrderStates($this->context->language->id), - 'MR_form_action' => $post_action, - 'MR_error_list' => $this->post_errors - )); - - echo $this->mondialrelay->fetchTemplate('/views/templates/admin/', 'settings'); - } - - public function postProcess() - { - $post_action = array( - 'type' => Tools::getValue('MR_action_name'), - 'message_success' => $this->l('Action Succeed'), - 'had_errors' => false - ); - - parent::postProcess(); - - if (Tools::isSubmit('submit_order_state')) - if (($order_state = (int)Tools::getValue('id_order_state'))) - { - $this->mondialrelay->account_shop['MR_ORDER_STATE'] = $order_state; - - if ($this->mondialrelay->updateAccountShop()) - $post_action['message_success'] = $this->l('Order State has been updated'); - else - $this->post_errors[] = $this->l('Cannot Update the account shop'); - } - - if (count($this->post_errors)) - $post_action['had_errors'] = true; - - return $post_action; - } - - public function display() - { - - $post_action = count($_POST) ? $this->postProcess() : null; - - $this->displaySettings($post_action); - if (MondialRelay::isAccountSet() && (int)$this->mondialrelay->account_shop['MR_ORDER_STATE']) - { - $this->displayOrdersTable(); - $this->displayhistoriqueForm(); - } - } + private $mondialrelay = null; + + public $post_errors = array(); + + public function __construct() + { + $this->mondialrelay = new MondialRelay(); + + $this->table = 'mr_selected'; + + parent::__construct(); + $this->context = Context::getContext(); + $datas = array( + 'display_header' => true, + 'display_header_javascript' => true, + 'display_footer' => true, + ); + + $this->context->smarty->assign($datas); + } + + private function displayOrdersTable() + { + $order_state = new OrderState((int)(Configuration::get('MONDIAL_RELAY_ORDER_STATE')), $this->context->language->id); + $orders = MondialRelay::getOrders(array(), MondialRelay::NO_FILTER, $this->mondialrelay->account_shop['MR_WEIGHT_COEFFICIENT']); + + // Simulate a ticket generation + $MRCreateTicket = new MRCreateTickets(array( + 'orderIdList' => null, + 'totalOrder' => null, + 'weightList' => null + ), + $this->mondialrelay + ); + if (is_array($orders) && count($orders)) + foreach ($orders as &$order) + { + $order['display_total_price'] = Tools::displayPrice($order['total'], new Currency($order['id_currency'])); + $order['display_shipping_price'] = Tools::displayPrice($order['shipping'], new Currency($order['id_currency'])); + if (version_compare(_PS_VERSION_, '1.5.5', '<')) + $order['display_date'] = Tools::displayDate($order['date'], $this->context->language->id); + else + $order['display_date'] = Tools::displayDate($order['date']); + $order['weight'] = (!empty($order['mr_weight']) && $order['mr_weight'] > 0) ? $order['mr_weight'] : $order['order_weight']; + } + + $controller = (_PS_VERSION_ < '1.5') ? 'AdminContact' : 'AdminStores'; + + $this->context->smarty->assign(array( + 'MR_token_admin_module' => Tools::getAdminToken('AdminModules'.(int)(Tab::getIdFromClassName('AdminModules')).(int)$this->context->employee->id), + 'MR_token_admin_contact' => array( + 'controller_name' => $controller, + 'token' => Tools::getAdminToken($controller.(int)(Tab::getIdFromClassName($controller)).(int)$this->context->employee->id)), + 'MR_token_admin_orders' => Tools::getAdminToken('AdminOrders'.(int)(Tab::getIdFromClassName('AdminOrders')).(int)$this->context->employee->id), + 'MR_order_state_name' => $order_state->name, + 'MR_orders' => $orders, + 'MR_PS_IMG_DIR_' => _PS_IMG_DIR_, + 'MR_errors_type' => $MRCreateTicket->checkPreValidation()) + ); + + unset($order_state); + echo $this->mondialrelay->fetchTemplate('/views/templates/admin/', 'generate_tickets'); + } + + public function displayhistoriqueForm() + { + $query = 'SELECT * FROM `'._DB_PREFIX_.'mr_history` ORDER BY `id` DESC ;'; + $history = Db::getInstance()->executeS($query); + + foreach ($history as &$item) + $item['url_10x15'] = str_replace('format=A4', 'format=10x15', $item['url_a4']); + + $this->context->smarty->assign(array( + 'MR_histories' => $history) + ); + echo $this->mondialrelay->fetchTemplate('/views/templates/admin/', 'history'); + } + + public function displaySettings($post_action) + { + $curr_order_state = new OrderState((int)$this->mondialrelay->account_shop['MR_ORDER_STATE']); + $order_state = array( + 'id_order_state' => $this->mondialrelay->account_shop['MR_ORDER_STATE'], + 'name' => $curr_order_state->name[$this->context->language->id] + ); + + $this->context->smarty->assign(array( + 'MR_token_admin_mondialrelay' => Tools::getAdminToken('AdminMondialRelay'.(int)(Tab::getIdFromClassName('AdminMondialRelay')).(int)$this->context->employee->id), + 'MR_account_set' => MondialRelay::isAccountSet(), + 'MR_order_state' => $order_state, + 'MR_orders_states_list' => OrderState::getOrderStates($this->context->language->id), + 'MR_form_action' => $post_action, + 'MR_error_list' => $this->post_errors + )); + + echo $this->mondialrelay->fetchTemplate('/views/templates/admin/', 'settings'); + } + + public function postProcess() + { + $post_action = array( + 'type' => Tools::getValue('MR_action_name'), + 'message_success' => $this->l('Action Succeed'), + 'had_errors' => false + ); + + parent::postProcess(); + + if (Tools::isSubmit('submit_order_state')) + if (($order_state = (int)Tools::getValue('id_order_state'))) + { + $this->mondialrelay->account_shop['MR_ORDER_STATE'] = $order_state; + + if ($this->mondialrelay->updateAccountShop()) + $post_action['message_success'] = $this->l('Order State has been updated'); + else + $this->post_errors[] = $this->l('Cannot Update the account shop'); + } + + if (count($this->post_errors)) + $post_action['had_errors'] = true; + + return $post_action; + } + + public function display() + { + + $post_action = count($_POST) ? $this->postProcess() : null; + + $this->displaySettings($post_action); + if (MondialRelay::isAccountSet() && (int)$this->mondialrelay->account_shop['MR_ORDER_STATE']) + { + $this->displayOrdersTable(); + $this->displayhistoriqueForm(); + } + } } diff --git a/ajax.php b/ajax.php old mode 100644 new mode 100755 index 753a007..fba0f0d --- a/ajax.php +++ b/ajax.php @@ -32,19 +32,19 @@ */ /* -* Clean displayed content for Admin ajax query +* Clean displayed content for Admin ajax query */ @ob_clean(); /* -* Front Ajax query, need the front cookie and MR class -* When it's back query, the PS core made the work +* Front Ajax query, need the front cookie and MR class +* When it's back query, the PS core made the work */ if (!defined('_PS_ADMIN_DIR_')) { - require_once(realpath(dirname(__FILE__).'/../../config/config.inc.php')); - require_once(realpath(dirname(__FILE__).'/../../init.php')); - require_once(dirname(__FILE__).'/mondialrelay.php'); + require_once(realpath(dirname(__FILE__).'/../../config/config.inc.php')); + require_once(realpath(dirname(__FILE__).'/../../init.php')); + require_once(dirname(__FILE__).'/mondialrelay.php'); } $mondialrelay = isset($this) ? $this : new Mondialrelay(); @@ -62,18 +62,18 @@ /* Access page List liable to the generated token*/ $accessPageList = array( - MondialRelay::getToken('front') => array( - 'MRGetRelayPoint', - 'addSelectedCarrierToDB' - ), - MondialRelay::getToken('back') => array( - 'MRGetTickets', - 'MRCreateTickets', - 'MRDeleteHistory', - 'uninstallDetail', - 'DeleteHistory', - 'MRDownloadPDF' - ) + MondialRelay::getToken('front') => array( + 'MRGetRelayPoint', + 'addSelectedCarrierToDB' + ), + MondialRelay::getToken('back') => array( + 'MRGetTickets', + 'MRCreateTickets', + 'MRDeleteHistory', + 'uninstallDetail', + 'DeleteHistory', + 'MRDownloadPDF' + ) ); $params = array(); @@ -82,73 +82,73 @@ /* If the method name associated to the token received doesn't match with*/ /* the list, then we kill the request*/ if (!isset($accessPageList[$token]) || !in_array($method, $accessPageList[$token])) - exit(); + exit(); /* Method name allow to instanciate his object to properly call the*/ /* implemented interface method and do his job*/ switch ($method) { - case 'MRCreateTickets': - $params['orderIdList'] = Tools::getValue('order_id_list'); - $params['totalOrder'] = Tools::getValue('numSelected'); - $params['weightList'] = Tools::getValue('weight_list'); - $params['insuranceList'] = Tools::getValue('insurance_list'); - break; - case 'MRGetTickets': - $params['detailedExpeditionList'] = Tools::getValue('detailedExpeditionList'); - break; - case 'MRDownloadPDF': - $params['Expeditions'] = Tools::getValue('detailedExpeditionList'); - break; - case 'DeleteHistory': - $params['historyIdList'] = Tools::getValue('history_id_list'); - break; - case 'uninstallDetail': - $params['action'] = Tools::getValue('action'); - break; - case 'MRGetRelayPoint': - $params['id_carrier'] = Tools::getValue('id_carrier'); - $params['weight'] = Context::getContext()->cart->getTotalWeight(); - $params['id_address_delivery'] = Context::getContext()->cart->id_address_delivery; - break; - case 'addSelectedCarrierToDB': - $params['id_carrier'] = Tools::getValue('id_carrier'); - $params['id_cart'] = Context::getContext()->cart->id; - $params['id_customer'] = Context::getContext()->customer->id; - $params['id_mr_method'] = Tools::getValue('id_mr_method'); - $params['relayPointInfo'] = Tools::getValue('relayPointInfo'); - break; - default: + case 'MRCreateTickets': + $params['orderIdList'] = Tools::getValue('order_id_list'); + $params['totalOrder'] = Tools::getValue('numSelected'); + $params['weightList'] = Tools::getValue('weight_list'); + $params['insuranceList'] = Tools::getValue('insurance_list'); + break; + case 'MRGetTickets': + $params['detailedExpeditionList'] = Tools::getValue('detailedExpeditionList'); + break; + case 'MRDownloadPDF': + $params['Expeditions'] = Tools::getValue('detailedExpeditionList'); + break; + case 'DeleteHistory': + $params['historyIdList'] = Tools::getValue('history_id_list'); + break; + case 'uninstallDetail': + $params['action'] = Tools::getValue('action'); + break; + case 'MRGetRelayPoint': + $params['id_carrier'] = Tools::getValue('id_carrier'); + $params['weight'] = Context::getContext()->cart->getTotalWeight(); + $params['id_address_delivery'] = Context::getContext()->cart->id_address_delivery; + break; + case 'addSelectedCarrierToDB': + $params['id_carrier'] = Tools::getValue('id_carrier'); + $params['id_cart'] = Context::getContext()->cart->id; + $params['id_customer'] = Context::getContext()->customer->id; + $params['id_mr_method'] = Tools::getValue('id_mr_method'); + $params['relayPointInfo'] = Tools::getValue('relayPointInfo'); + break; + default: } - + /* Try to instanciate the method object name and call the necessaries method*/ try { - if (class_exists($method, false)) - { - /* $this is the current mondialrelay object loaded when use in BO. Use for perf*/ - $obj = new $method($params, $mondialrelay); - - /* Verify that the class implement correctly the interface*/ - /* Else use a Management class to do some ajax stuff*/ - if (($obj instanceof IMondialRelayWSMethod)) - { - $obj->init(); - $obj->send(); - $result = $obj->getResult(); - } - unset($obj); - } - else if (($management = new MRManagement($params)) && method_exists($management, $method)) - $result = $management->{$method}(); - else - throw new Exception('Method Class : '.$method.' can\'t be found'); - unset($management); + if (class_exists($method, false)) + { + /* $this is the current mondialrelay object loaded when use in BO. Use for perf*/ + $obj = new $method($params, $mondialrelay); + + /* Verify that the class implement correctly the interface*/ + /* Else use a Management class to do some ajax stuff*/ + if (($obj instanceof IMondialRelayWSMethod)) + { + $obj->init(); + $obj->send(); + $result = $obj->getResult(); + } + unset($obj); + } + else if (($management = new MRManagement($params)) && method_exists($management, $method)) + $result = $management->{$method}(); + else + throw new Exception('Method Class : '.$method.' can\'t be found'); + unset($management); } catch(Exception $e) { - echo MRTools::jsonEncode(array('other' => array('error' => array($e->getMessage())))); - exit(-1); + echo MRTools::jsonEncode(array('other' => array('error' => array($e->getMessage())))); + exit(-1); } echo MRTools::jsonEncode($result); exit(0); diff --git a/classes/IMondialRelayWSMethod.php b/classes/IMondialRelayWSMethod.php old mode 100644 new mode 100755 index 0b0e82e..30d19da --- a/classes/IMondialRelayWSMethod.php +++ b/classes/IMondialRelayWSMethod.php @@ -33,25 +33,25 @@ */ interface IMondialRelayWSMethod { - /* - * Initiate the data needed to be send properly - * Can manage a list of data for multiple request - */ - public function init(); - - /* - * Send one or multiple request to the webservice - */ - public function send(); - - /* - * Get the values with associated fields name - */ - public function getFieldsList(); - - /* - * Get the result of one or multiple send request - */ - public function getResult(); + /* + * Initiate the data needed to be send properly + * Can manage a list of data for multiple request + */ + public function init(); + + /* + * Send one or multiple request to the webservice + */ + public function send(); + + /* + * Get the values with associated fields name + */ + public function getFieldsList(); + + /* + * Get the result of one or multiple send request + */ + public function getResult(); } ?> \ No newline at end of file diff --git a/classes/MRCreateTickets.php b/classes/MRCreateTickets.php old mode 100644 new mode 100755 index ba9e257..be03729 --- a/classes/MRCreateTickets.php +++ b/classes/MRCreateTickets.php @@ -35,597 +35,597 @@ */ class MRCreateTickets implements IMondialRelayWSMethod { - public $class_name = __CLASS__; - - private $_fields = array( - 'id_mr_selected' => 0, - 'list' => array( - 'Enseigne' => array( - 'required' => true, - 'value' => '', - 'regexValidation' => '#^[0-9A-Z]{2}[0-9A-Z ]{6}$#'), - 'ModeCol' => array( - 'required' => true, - 'value' => '', - 'regexValidation' => '#^(CCC|CDR|CDS|REL)$#'), - 'ModeLiv' => array( - 'required' => true, - 'value' => '', - 'regexValidation' => '#^(LCC|LD1|LDS|24R|ESP|DRI|HOM)$#'), - 'NDossier' => array( - 'required' => false, - 'value' => '', - 'regexValidation' => '#^(|[0-9A-Z_ -]{0,15})$#'), - 'NClient' => array( - 'required' => false, - 'value' => '', - 'regexValidation' => '#^(|[0-9A-Z]{0,9})$#'), - 'Expe_Langage' => array( - 'required' => true, - 'value' => '', - 'regexValidation' => '#^[A-Z]{2}$#'), - 'Expe_Ad1' => array( - 'required' => true, - 'value' => '', - 'regexValidation' => '#^[0-9A-Z_\-\'., /]{2,32}$#'), - 'Expe_Ad2' => array( - 'required' => false, - 'value' => '', - 'regexValidation' => '#^[0-9A-Z_\-\'., /]{0,32}$#'), - 'Expe_Ad3' => array( - 'required' => true, - 'value' => '', - 'regexValidation' => '#^[0-9A-Z_\-\'., /]{0,32}$#'), - 'Expe_Ad4' => array( - 'required' => false, - 'value' => '', - 'regexValidation' => '#^[0-9A-Z]{2}[0-9A-Z ]{6}$#'), - 'Expe_Ville' => array( - 'required' => true, - 'value' => '', - 'regexValidation' => '#^[A-Z_\-\' 0-9]{2,26}$#'), - 'Expe_CP' => array( - 'required' => true, - 'value' => '', - 'params' => array(), - 'methodValidation' => 'checkZipcodeByCountry'), - 'Expe_Pays' => array( - 'required' => true, - 'value' => '', - 'regexValidation' => '#^[A-Z]{2}$#'), - 'Expe_Tel1' => array( - 'required' => true, - 'value' => '', - 'regexValidation' => '#^((00|\+)[1-9]{2}|0)[0-9][0-9]{7,8}$#'), - 'Expe_Tel2' => array( - 'required' => false, - 'value' => '', - 'regexValidation' => '#^((00|\+)[1-9]{2}|0)[0-9][0-9]{7,8}$#'), - 'Expe_Mail' => array( - 'required' => false, - 'value' => '', - 'regexValidation' => '#^[\w\-\.\@_]{0,70}$#'), - 'Dest_Langage' => array( - 'required' => true, - 'value' => '', - 'regexValidation' => '#^[A-Z]{2}$#'), - 'Dest_Ad1' => array( - 'required' => true, - 'value' => '', - 'regexValidation' => '#^[0-9A-Z_\-\'., /]{2,32}$#'), - 'Dest_Ad2' => array( - 'required' => false, - 'value' => '', - 'regexValidation' => '#^[0-9A-Z_\-\'., /]{2,32}$#'), - 'Dest_Ad3' => array( - 'required' => true, - 'value' => '', - 'regexValidation' => '#^[0-9A-Z_\-\'., /]{2,32}$#'), - 'Dest_Ad4' => array( - 'required' => false, - 'value' => '', - 'regexValidation' => '#^[0-9A-Z_\-\'., /]{0,32}$#'), - 'Dest_Ville' => array( - 'required' => true, - 'value' => '', - 'regexValidation' => '#^[A-Z_\-\' 0-9]{2,26}$#'), - 'Dest_CP' => array( - 'required' => true, - 'value' => '', - 'params' => array(), - 'methodValidation' => 'checkZipcodeByCountry'), - 'Dest_Pays' => array( - 'required' => true, - 'value' => '', - 'regexValidation' => '#^[A-Z]{2}$#'), - 'Dest_Tel1' => array( - 'required' => false, - 'value' => '', - 'regexValidation' => '#^((00|\+)[1-9]{2}|0)[0-9][0-9]{7,8}$#'), - 'Dest_Tel2' => array( - 'required' => false, - 'value' => '', - 'regexValidation' => '#^((00|\+)[1-9]{2}|0)[0-9][0-9]{7,8}$#'), - 'Dest_Mail' => array( - 'required' => false, - 'value' => '', - 'regexValidation' => '#^[\w\-\.\@_]{0,70}$#'), - 'Poids' => array( - 'required' => true, - 'value' => '', - 'regexValidation' => '#^[0-9]{3,7}$#'), - 'Longueur' => array( - 'required' => false, - 'value' => '', - 'regexValidation' => '#^[0-9]{0,3}$#'), - 'Taille' => array( - 'required' => false, - 'value' => '', - 'regexValidation' => '#^(XS|S|M|L|XL|XXL|3XL)$#'), - 'NbColis' => array( - 'required' => true, - 'value' => '', - 'regexValidation' => '#^[0-9]{1,2}$#'), - 'CRT_Valeur' => array( - 'required' => true, - 'value' => '', - 'regexValidation' => '#^[0-9]{1,7}$#'), - 'CRT_Devise' => array( - 'required' => false, - 'value' => '', - 'regexValidation' => '#^(|EUR)$#'), - 'Exp_Valeur' => array( - 'required' => false, - 'value' => '', - 'regexValidation' => '#^[0-9]{0,7}$#'), - 'Exp_Devise' => array( - 'required' => false, - 'value' => '', - 'regexValidation' => '#^(|EUR)$#'), - 'COL_Rel_Pays' => array( - 'required' => false, - 'value' => '', - 'regexValidation' => '#^[A-Z]{2}$#'), - 'COL_Rel' => array( - 'required' => false, - 'value' => '', - 'regexValidation' => '#^(|[0-9]{6})$#'), - 'LIV_Rel_Pays' => array( - 'required' => false, - 'value' => '', - 'regexValidation' => '#^[A-Z]{2}$#'), - 'LIV_Rel' => array( - 'required' => false, - 'value' => '', - 'regexValidation' => '#^(|[0-9]{6})$#'), - 'TAvisage' => array( - 'required' => false, - 'value' => '', - 'regexValidation' => '#^(|O|N)$#'), - 'TReprise' => array( - 'required' => false, - 'value' => '', - 'regexValidation' => '#^(|O|N)$#'), - 'Montage' => array( - 'required' => false, - 'value' => '', - 'regexValidation' => '#^(|[0-9]{1,3})$#'), - 'TRDV' => array( - 'required' => false, - 'value' => '', - 'regexValidation' => '#^(|O|N)$#'), - 'Assurance' => array( - 'required' => false, - 'value' => '', - 'regexValidation' => '#^(|[0-9A-Z]{1})$#'), - 'Instructions' => array( - 'required' => false, - 'value' => '', - 'regexValidation' => '#^[0-9A-Z_\-\'., /]{0,31}#'), - 'Security' => array( - 'required' => true, - 'value' => '', - 'regexValidation' => '#^[0-9A-Z]{32}$#'), - 'Texte' => array( - 'required' => false, - 'value' => '', - 'regexValidation' => '#^([^<>&\']{3,30})(\(cr\)[^<>&\']{0,30}){0,9}$#'))); - - private $_orderListId = null; - private $_totalOrder = 0; - private $_weightList = null; - private $_insuranceList = null; - private $_mondialrelay = null; - private $_fieldsList = array(); - private $_webServiceKey = ''; - private $_markCode = ''; - - private $_resultList = array( - 'error' => array(), - 'success' => array()); - - private $_webserviceURL = ''; - - public function __construct($params, $object) - { - $this->_orderListId = $params['orderIdList']; - $this->_totalOrder = $params['totalOrder']; - $this->_weightList = $params['weightList']; - $this->_insuranceList = isset($params['insuranceList']) ? $params['insuranceList'] : ''; - $this->_mondialrelay = $object; - $this->_webServiceKey = $this->_mondialrelay->account_shop['MR_KEY_WEBSERVICE']; - $this->_markCode = $this->_mondialrelay->account_shop['MR_CODE_MARQUE']; - $this->class_name = Tools::strtolower($this->class_name); - - $this->_webserviceURL = MondialRelay::MR_URL.'webservice/Web_Services.asmx?WSDL'; - } - - public function __destruct() - { - unset($this->_mondialrelay); - } - - /* - * Build a correct weight format (NNNNN) - */ - private function _weightFormat($weight) - { - return sprintf("%05s", $weight); - } - - /* - * Set the default value to the order paramaters - */ - private function _setRequestDefaultValue() - { - $this->_fields['list']['Enseigne']['value'] = $this->_mondialrelay->account_shop['MR_ENSEIGNE_WEBSERVICE']; - $this->_fields['list']['Expe_Langage']['value'] = $this->_mondialrelay->account_shop['MR_LANGUAGE']; - $this->_fields['list']['Expe_Ad1']['value'] = Configuration::get('PS_SHOP_NAME'); - $this->_fields['list']['Expe_Ad3']['value'] = Configuration::get('PS_SHOP_ADDR1'); - // Deleted, cause to many failed for the process - // $this->_fields['list']['Expe_Ad4']['value'] = Configuration::get('PS_SHOP_ADDR2'); - $this->_fields['list']['Expe_Ville']['value'] = Configuration::get('PS_SHOP_CITY'); - $this->_fields['list']['Expe_CP']['value'] = Configuration::get('PS_SHOP_CODE'); - $this->_fields['list']['Expe_CP']['params']['id_country'] = Configuration::get('PS_COUNTRY_DEFAULT'); - - if (version_compare(_PS_VERSION_, '1.4', '>=')) - { - $this->_fields['list']['Expe_Pays']['value'] = Country::getIsoById(Configuration::get('PS_SHOP_COUNTRY_ID')); - $this->_fields['list']['Expe_CP']['params']['id_country'] = Configuration::get('PS_SHOP_COUNTRY_ID'); - } - else - $this->_fields['list']['Expe_Pays']['value'] = Tools::substr(Configuration::get('PS_SHOP_COUNTRY'), 0, 2); - $this->_fields['list']['Expe_Tel1']['value'] = MRTools::getFormatedPhone(Configuration::get('PS_SHOP_PHONE')); - $this->_fields['list']['Expe_Mail']['value'] = Configuration::get('PS_SHOP_EMAIL'); - $this->_fields['list']['NbColis']['value'] = 1; - $this->_fields['list']['CRT_Valeur']['value'] = 0; - $this->_fields['list']['CRT_Devise']['value'] = 'EUR'; - } - - /* - * Initiate the data needed to be send properly - * Can manage a list of data for multiple request - */ - public function init() - { - if ($this->_totalOrder == 0) - throw new Exception($this->_mondialrelay->l('Please select at least one order', $this->class_name)); - - $this->_setRequestDefaultValue(); - if (count($orderListDetails = $this->_mondialrelay->getOrders($this->_orderListId))) - { - foreach ($orderListDetails as $orderDetail) - { - // Storage temporary - $base = $this->_fields; - $tmp = &$base['list']; - - $deliveriesAddress = new Address($orderDetail['id_address_delivery']); - $customer = new Customer($orderDetail['id_customer']); - - // Store the weight order set by the user - - foreach ($this->_weightList as $orderWeightInfos) - { - $detail = explode('-', $orderWeightInfos); - if (count($detail) == 2 && $detail[1] == $orderDetail['id_order']) - $tmp['Poids']['value'] = (float)$this->_weightFormat($detail[0]); - } - foreach ($this->_insuranceList as $insurance) - { - $detail = explode('-', $insurance); - if (count($detail) == 2 && $detail[1] == $orderDetail['id_order']) - $tmp['Assurance']['value'] = (int)($detail[0]); - else - $tmp['Assurance']['value'] = $orderDetail['mr_ModeAss']; - } - $dest_tel = (!empty($deliveriesAddress->phone)) ? MRTools::getFormatedPhone($deliveriesAddress->phone) : ''; - $dest_tel2 = (!empty($deliveriesAddress->phone_mobile)) ? MRTools::getFormatedPhone($deliveriesAddress->phone_mobile) : ''; - $destIsoCode = Country::getIsoById($deliveriesAddress->id_country); - $tmp['ModeCol']['value'] = $orderDetail['mr_ModeCol']; - $tmp['ModeLiv']['value'] = $orderDetail['mr_ModeLiv']; - $tmp['NDossier']['value'] = $orderDetail['id_order']; - $tmp['NClient']['value'] = $orderDetail['id_customer']; - $tmp['Dest_Langage']['value'] = 'FR'; //Language::getIsoById($orderDetail['id_lang']); - $tmp['Dest_Ad1']['value'] = preg_replace(MRTools::REGEX_CLEAN_ADDR, '', Tools::substr(MRTools::removeAccents($deliveriesAddress->firstname.' '.$deliveriesAddress->lastname), 0, 32)); - $tmp['Dest_Ad2']['value'] = preg_replace(MRTools::REGEX_CLEAN_ADDR, '', Tools::substr(MRTools::removeAccents($deliveriesAddress->address2), 0, 32)); - $tmp['Dest_Ad3']['value'] = preg_replace(MRTools::REGEX_CLEAN_ADDR, '', Tools::substr(MRTools::removeAccents($deliveriesAddress->address1), 0, 32)); - $tmp['Dest_Ville']['value'] = $deliveriesAddress->city; - $tmp['Dest_CP']['value'] = $deliveriesAddress->postcode; - $tmp['Dest_CP']['params']['id_country'] = $deliveriesAddress->id_country; - $tmp['Dest_Pays']['value'] = $destIsoCode; - $tmp['Dest_Tel1']['value'] = $dest_tel; - $tmp['Dest_Tel2']['value'] = $dest_tel2; - $tmp['Dest_Mail']['value'] = $customer->email; - if ($orderDetail['mr_ModeLiv'] != 'LD1' && $orderDetail['mr_ModeLiv'] != 'LDS' && $orderDetail['mr_ModeLiv'] != 'HOM') - { - $tmp['LIV_Rel_Pays']['value'] = $orderDetail['MR_Selected_Pays']; - $tmp['LIV_Rel']['value'] = $orderDetail['MR_Selected_Num']; - } - - // Store the necessary information to the root case table - $base['id_mr_selected'] = $orderDetail['id_mr_selected']; - - // Add the temporary values to a field list for multiple request - $this->_fieldsList[] = $base; - unset($deliveriesAddress); - unset($customer); - } - $this->_generateMD5SecurityKey(); - } - } - - /* - * Generate the MD5 key for each param list - */ - private function _generateMD5SecurityKey() - { - // RootCase is the array case where the main information are stored - // it's an array containing id_mr_selected and an array with the necessary fields - foreach ($this->_fieldsList as &$rootCase) - { - $concatenationValue = ''; - foreach ($rootCase['list'] as $paramName => &$valueDetailed) - if ($paramName != 'Texte' && $paramName != 'Security') - { - // Mac server make an empty string instead of a cleaned string - // TODO : test on windows and linux server - $cleanedString = MRTools::removeAccents($valueDetailed['value']); - $valueDetailed['value'] = !empty($cleanedString) ? Tools::strtoupper($cleanedString) : Tools::strtoupper($valueDetailed['value']); - - // Call a pointer function if exist to do different test - if (isset($valueDetailed['methodValidation']) && method_exists('MRTools', $valueDetailed['methodValidation']) && isset($valueDetailed['params']) && MRTools::$valueDetailed['methodValidation']($valueDetailed['value'], $valueDetailed['params'])) - $concatenationValue .= $valueDetailed['value']; - // Use simple Regex test given by MondialRelay - else if (isset($valueDetailed['regexValidation']) && preg_match($valueDetailed['regexValidation'], $valueDetailed['value'], $matches)) - $concatenationValue .= $valueDetailed['value']; - // If the key is required, we set an error, else it's skipped - else if ((!Tools::strlen($valueDetailed['value']) && $valueDetailed['required']) || Tools::strlen($valueDetailed['value'])) - { - if (empty($valueDetailed['value'])) - $error = $this->_mondialrelay->l('This key', $this->class_name).' ['.$paramName.'] '.$this->_mondialrelay->l('is empty and need to be filled', $this->class_name); - else - $error = 'This key ['.$paramName.'] hasn not a valid value format : '.$valueDetailed['value']; - $this->_resultList['error'][$rootCase['list']['NDossier']['value']][] = $error; - } - } - $concatenationValue .= $this->_webServiceKey; - $rootCase['list']['Security']['value'] = Tools::strtoupper(md5($concatenationValue)); - } - } - - /* - * Update the tables used and send mail with the order history - */ - private function _updateTable($params, $expeditionNum, $ticketURL, $trackingURL, $id_mr_selected) - { - $sql = ' - UPDATE `'._DB_PREFIX_.'mr_selected` - SET `MR_poids` = \''.pSQL($params['Poids']).'\', - `MR_insurance` = \''.pSQL($params['Assurance']).'\', - `exp_number` = \''.pSQL($expeditionNum).'\', - `url_etiquette` = \''.pSQL($ticketURL).'\', - `url_suivi` = \''.pSQL($trackingURL).'\' - WHERE id_mr_selected = '.(int)$id_mr_selected; - Db::getInstance()->execute($sql); - - // NDossier contains the id_order - $order = new Order($params['NDossier']); - - // Update the database for order and orderHistory - $order->shipping_number = $expeditionNum; - $order->update(); - - if (version_compare(_PS_VERSION_, '1.5', '>=')) - { - //Retrieve Order Carrier - $sql = 'SELECT `id_order_carrier` - FROM `'._DB_PREFIX_.'order_carrier` - WHERE `id_order` = '.(int)$order->id; - - $id_order_carrier = Db::getInstance()->getValue($sql); - - if($id_order_carrier) - { - $order_carrier = new OrderCarrier((int)$id_order_carrier); - if(Validate::isLoadedObject($order_carrier)) - { - $order_carrier->tracking_number = pSQL($expeditionNum); - $order_carrier->update(); - } - } - } - - $templateVars = array('{followup}' => $trackingURL); - $orderState = (Configuration::get('PS_OS_SHIPPING')) ? - Configuration::get('PS_OS_SHIPPING') : - _PS_OS_SHIPPING_; - - $history = new OrderHistory(); - $history->id_order = (int)$params['NDossier']; - if (version_compare(_PS_VERSION_, '1.5.2', '>=')) - $history->changeIdOrderState((int)$orderState, $order); - else - $history->changeIdOrderState((int)$orderState, (int)($params['NDossier'])); - $history->id_employee = (isset(Context::getContext()->employee->id) ? (int)Context::getContext()->employee->id : ''); - $history->addWithemail(true, $templateVars); - unset($order); - unset($order_carrier); - unset($history); - } - - /* - * Manage the return value of the webservice, handle the errors or build the - * succeed message - */ - private function _parseResult($client, $result, $params, $id_mr_selected) - { - $errors = &$this->_resultList['error'][$params['NDossier']]; - $success = &$this->_resultList['success'][$params['NDossier']]; - $result = $result->WSI2_CreationEtiquetteResult; - if (($errorNumber = $result->STAT) != 0) - { - $errors[] = $this->_mondialrelay->l('There is an error number : ', $this->class_name).$errorNumber; - $errors[] = $this->_mondialrelay->l('Details : ', $this->class_name). - $this->_mondialrelay->getErrorCodeDetail($errorNumber); - } - else - { - $baseURL = MondialRelay::MR_URL; - $expedition = $result->ExpeditionNum; - $securityKey = Tools::strtoupper(md5('<'.$params['Enseigne'].$this->_markCode. - '>'.$expedition.'<'.$this->_webServiceKey.'>')); - $ticketURL = $baseURL.$result->URL_Etiquette; - $trackingURL = $baseURL. - 'public/permanent/tracking.aspx?ens='.$params['Enseigne'].$this->_markCode.'&exp='.$expedition.'&language='.Configuration::get('PS_LANG_DEFAULT').'&crc='.$securityKey; - - $success['displayExpedition'] = $this->_mondialrelay->l('Expedition Number : ', $this->class_name).$expedition; - $success['displayTicketURL'] = $this->_mondialrelay->l('Ticket URL : ', $this->class_name).$ticketURL; - $success['displayTrackingURL'] = $this->_mondialrelay->l('Tracking URL: ', $this->class_name).$trackingURL; - $success['expeditionNumber'] = $expedition; - - $this->_updateTable($params, $expedition, $ticketURL, $trackingURL, $id_mr_selected); - } - } - - /* - * Send one or multiple request to the webservice - */ - public function send() - { - if ($client = new SoapClient($this->_webserviceURL)) - { - $client->soap_defencoding = 'UTF-8'; - $client->decode_utf8 = false; - - foreach ($this->_fieldsList as $rootCase) - { - $params = $this->_getSimpleParamArray($rootCase['list']); - $result = $client->WSI2_CreationEtiquette($params); - $this->_parseResult($client, $result, $params, $rootCase['id_mr_selected']); - } - unset($client); - Configuration::updateValue('MONDIALRELAY_CONFIGURATION_OK', true); - } - else - throw new Exception($this->_mondialrelay->l('The Mondial Relay webservice is not currently reliable', $this->class_name)); - } - - /* - ** Check if the shop parameter are currently well configured - */ - public function checkPreValidation() - { - $errorList = array('error' => array(), 'warn' => array()); - - $list = array( - 'Expe_Langage' => array( - 'value' => $this->_mondialrelay->account_shop['MR_LANGUAGE'], - 'error' => $this->_mondialrelay->l('Please check your language configuration', $this->class_name)), - 'Expe_Ad1' => array( - 'value' => Configuration::get('PS_SHOP_NAME'), - 'error' => $this->_mondialrelay->l('Please check your shop name configuration', $this->class_name)), - 'Expe_Ad3' => array( - 'value' => Configuration::get('PS_SHOP_ADDR1'), - 'error' => $this->_mondialrelay->l('Please check your address 1 configuration', $this->class_name)), - 'Expe_Ville' => array( - 'value' => Configuration::get('PS_SHOP_CITY'), - 'error' => $this->_mondialrelay->l('Please check your city configuration', $this->class_name)), - 'Expe_CP' => array( - 'value' => Configuration::get('PS_SHOP_CODE'), - 'error' => $this->_mondialrelay->l('Please check your zipcode configuration', $this->class_name)), - 'Expe_Pays' => array( - 'value' => ((version_compare(_PS_VERSION_, '1.4', '>=')) ? - Country::getIsoById(Configuration::get('PS_SHOP_COUNTRY_ID')) : - Tools::substr(Configuration::get('PS_SHOP_COUNTRY'), 0, 2)), - 'error' => $this->_mondialrelay->l('Please check your country configuration', $this->class_name)), - 'Expe_Tel1' => array( - 'value' => MRTools::getFormatedPhone(Configuration::get('PS_SHOP_PHONE')), - 'error' => $this->_mondialrelay->l('Please check your Phone configuration', $this->class_name)), - 'Expe_Mail' => array( - 'value' => Configuration::get('PS_SHOP_EMAIL'), - 'error' => $this->_mondialrelay->l('Please check your mail configuration', $this->class_name))); - - foreach ($list as $name => $tab) - { - // Mac server make an empty string instead of a cleaned string - // TODO : test on windows and linux server - $cleanedString = MRTools::removeAccents($tab['value']); - $tab['value'] = !empty($cleanedString) ? Tools::strtoupper($cleanedString) : Tools::strtoupper($tab['value']); - - if ($name == 'Expe_CP') - { - if (version_compare(_PS_VERSION_, '1.4', '>=')) - { - if (!(MRTools::checkZipcodeByCountry($tab['value'], array( - 'id_country' => Configuration::get('PS_SHOP_COUNTRY_ID'))))) - $errorList['error'][$name] = $tab['error']; - } - else - $errorList['warn'][$name] = $this->_mondialrelay->l('Post code cannot be validated with PrestaShop versions older than 1.4', $this->class_name); - } - else if (isset($this->_fields['list'][$name]['regexValidation']) && - (!preg_match($this->_fields['list'][$name]['regexValidation'], $tab['value'], $matches))) - $errorList['error'][$name] = $tab['error']; - } - return $errorList; - } - - /* - * Get the values with associated fields name - * @fields : array containing multiple values information - */ - private function _getSimpleParamArray($fields) - { - $params = array(); - - foreach ($fields as $keyName => $valueDetailed) - $params[$keyName] = $valueDetailed['value']; - return $params; - } - - /* - * Return the fields list - */ - public function getFieldsList() - { - return $this->_fieldsList['list']; - } - - /* - * Return the result of one or multiple sent requests - */ - public function getResult() - { - return $this->_resultList; - } - - /* - * Return which number order of the list is currently managed - */ - public static function getCurrentRequestUnderTraitment() - { - // TODO: Build a SQL Query to know how many request have been executed - } + public $class_name = __CLASS__; + + private $_fields = array( + 'id_mr_selected' => 0, + 'list' => array( + 'Enseigne' => array( + 'required' => true, + 'value' => '', + 'regexValidation' => '#^[0-9A-Z]{2}[0-9A-Z ]{6}$#'), + 'ModeCol' => array( + 'required' => true, + 'value' => '', + 'regexValidation' => '#^(CCC|CDR|CDS|REL)$#'), + 'ModeLiv' => array( + 'required' => true, + 'value' => '', + 'regexValidation' => '#^(LCC|LD1|LDS|24R|ESP|DRI|HOM)$#'), + 'NDossier' => array( + 'required' => false, + 'value' => '', + 'regexValidation' => '#^(|[0-9A-Z_ -]{0,15})$#'), + 'NClient' => array( + 'required' => false, + 'value' => '', + 'regexValidation' => '#^(|[0-9A-Z]{0,9})$#'), + 'Expe_Langage' => array( + 'required' => true, + 'value' => '', + 'regexValidation' => '#^[A-Z]{2}$#'), + 'Expe_Ad1' => array( + 'required' => true, + 'value' => '', + 'regexValidation' => '#^[0-9A-Z_\-\'., /]{2,32}$#'), + 'Expe_Ad2' => array( + 'required' => false, + 'value' => '', + 'regexValidation' => '#^[0-9A-Z_\-\'., /]{0,32}$#'), + 'Expe_Ad3' => array( + 'required' => true, + 'value' => '', + 'regexValidation' => '#^[0-9A-Z_\-\'., /]{0,32}$#'), + 'Expe_Ad4' => array( + 'required' => false, + 'value' => '', + 'regexValidation' => '#^[0-9A-Z]{2}[0-9A-Z ]{6}$#'), + 'Expe_Ville' => array( + 'required' => true, + 'value' => '', + 'regexValidation' => '#^[A-Z_\-\' 0-9]{2,26}$#'), + 'Expe_CP' => array( + 'required' => true, + 'value' => '', + 'params' => array(), + 'methodValidation' => 'checkZipcodeByCountry'), + 'Expe_Pays' => array( + 'required' => true, + 'value' => '', + 'regexValidation' => '#^[A-Z]{2}$#'), + 'Expe_Tel1' => array( + 'required' => true, + 'value' => '', + 'regexValidation' => '#^((00|\+)[1-9]{2}|0)[0-9][0-9]{7,8}$#'), + 'Expe_Tel2' => array( + 'required' => false, + 'value' => '', + 'regexValidation' => '#^((00|\+)[1-9]{2}|0)[0-9][0-9]{7,8}$#'), + 'Expe_Mail' => array( + 'required' => false, + 'value' => '', + 'regexValidation' => '#^[\w\-\.\@_]{0,70}$#'), + 'Dest_Langage' => array( + 'required' => true, + 'value' => '', + 'regexValidation' => '#^[A-Z]{2}$#'), + 'Dest_Ad1' => array( + 'required' => true, + 'value' => '', + 'regexValidation' => '#^[0-9A-Z_\-\'., /]{2,32}$#'), + 'Dest_Ad2' => array( + 'required' => false, + 'value' => '', + 'regexValidation' => '#^[0-9A-Z_\-\'., /]{2,32}$#'), + 'Dest_Ad3' => array( + 'required' => true, + 'value' => '', + 'regexValidation' => '#^[0-9A-Z_\-\'., /]{2,32}$#'), + 'Dest_Ad4' => array( + 'required' => false, + 'value' => '', + 'regexValidation' => '#^[0-9A-Z_\-\'., /]{0,32}$#'), + 'Dest_Ville' => array( + 'required' => true, + 'value' => '', + 'regexValidation' => '#^[A-Z_\-\' 0-9]{2,26}$#'), + 'Dest_CP' => array( + 'required' => true, + 'value' => '', + 'params' => array(), + 'methodValidation' => 'checkZipcodeByCountry'), + 'Dest_Pays' => array( + 'required' => true, + 'value' => '', + 'regexValidation' => '#^[A-Z]{2}$#'), + 'Dest_Tel1' => array( + 'required' => false, + 'value' => '', + 'regexValidation' => '#^((00|\+)[1-9]{2}|0)[0-9][0-9]{7,8}$#'), + 'Dest_Tel2' => array( + 'required' => false, + 'value' => '', + 'regexValidation' => '#^((00|\+)[1-9]{2}|0)[0-9][0-9]{7,8}$#'), + 'Dest_Mail' => array( + 'required' => false, + 'value' => '', + 'regexValidation' => '#^[\w\-\.\@_]{0,70}$#'), + 'Poids' => array( + 'required' => true, + 'value' => '', + 'regexValidation' => '#^[0-9]{3,7}$#'), + 'Longueur' => array( + 'required' => false, + 'value' => '', + 'regexValidation' => '#^[0-9]{0,3}$#'), + 'Taille' => array( + 'required' => false, + 'value' => '', + 'regexValidation' => '#^(XS|S|M|L|XL|XXL|3XL)$#'), + 'NbColis' => array( + 'required' => true, + 'value' => '', + 'regexValidation' => '#^[0-9]{1,2}$#'), + 'CRT_Valeur' => array( + 'required' => true, + 'value' => '', + 'regexValidation' => '#^[0-9]{1,7}$#'), + 'CRT_Devise' => array( + 'required' => false, + 'value' => '', + 'regexValidation' => '#^(|EUR)$#'), + 'Exp_Valeur' => array( + 'required' => false, + 'value' => '', + 'regexValidation' => '#^[0-9]{0,7}$#'), + 'Exp_Devise' => array( + 'required' => false, + 'value' => '', + 'regexValidation' => '#^(|EUR)$#'), + 'COL_Rel_Pays' => array( + 'required' => false, + 'value' => '', + 'regexValidation' => '#^[A-Z]{2}$#'), + 'COL_Rel' => array( + 'required' => false, + 'value' => '', + 'regexValidation' => '#^(|[0-9]{6})$#'), + 'LIV_Rel_Pays' => array( + 'required' => false, + 'value' => '', + 'regexValidation' => '#^[A-Z]{2}$#'), + 'LIV_Rel' => array( + 'required' => false, + 'value' => '', + 'regexValidation' => '#^(|[0-9]{6})$#'), + 'TAvisage' => array( + 'required' => false, + 'value' => '', + 'regexValidation' => '#^(|O|N)$#'), + 'TReprise' => array( + 'required' => false, + 'value' => '', + 'regexValidation' => '#^(|O|N)$#'), + 'Montage' => array( + 'required' => false, + 'value' => '', + 'regexValidation' => '#^(|[0-9]{1,3})$#'), + 'TRDV' => array( + 'required' => false, + 'value' => '', + 'regexValidation' => '#^(|O|N)$#'), + 'Assurance' => array( + 'required' => false, + 'value' => '', + 'regexValidation' => '#^(|[0-9A-Z]{1})$#'), + 'Instructions' => array( + 'required' => false, + 'value' => '', + 'regexValidation' => '#^[0-9A-Z_\-\'., /]{0,31}#'), + 'Security' => array( + 'required' => true, + 'value' => '', + 'regexValidation' => '#^[0-9A-Z]{32}$#'), + 'Texte' => array( + 'required' => false, + 'value' => '', + 'regexValidation' => '#^([^<>&\']{3,30})(\(cr\)[^<>&\']{0,30}){0,9}$#'))); + + private $_orderListId = null; + private $_totalOrder = 0; + private $_weightList = null; + private $_insuranceList = null; + private $_mondialrelay = null; + private $_fieldsList = array(); + private $_webServiceKey = ''; + private $_markCode = ''; + + private $_resultList = array( + 'error' => array(), + 'success' => array()); + + private $_webserviceURL = ''; + + public function __construct($params, $object) + { + $this->_orderListId = $params['orderIdList']; + $this->_totalOrder = $params['totalOrder']; + $this->_weightList = $params['weightList']; + $this->_insuranceList = isset($params['insuranceList']) ? $params['insuranceList'] : ''; + $this->_mondialrelay = $object; + $this->_webServiceKey = $this->_mondialrelay->account_shop['MR_KEY_WEBSERVICE']; + $this->_markCode = $this->_mondialrelay->account_shop['MR_CODE_MARQUE']; + $this->class_name = Tools::strtolower($this->class_name); + + $this->_webserviceURL = MondialRelay::MR_URL.'webservice/Web_Services.asmx?WSDL'; + } + + public function __destruct() + { + unset($this->_mondialrelay); + } + + /* + * Build a correct weight format (NNNNN) + */ + private function _weightFormat($weight) + { + return sprintf("%05s", $weight); + } + + /* + * Set the default value to the order paramaters + */ + private function _setRequestDefaultValue() + { + $this->_fields['list']['Enseigne']['value'] = $this->_mondialrelay->account_shop['MR_ENSEIGNE_WEBSERVICE']; + $this->_fields['list']['Expe_Langage']['value'] = $this->_mondialrelay->account_shop['MR_LANGUAGE']; + $this->_fields['list']['Expe_Ad1']['value'] = Configuration::get('PS_SHOP_NAME'); + $this->_fields['list']['Expe_Ad3']['value'] = Configuration::get('PS_SHOP_ADDR1'); + // Deleted, cause to many failed for the process + // $this->_fields['list']['Expe_Ad4']['value'] = Configuration::get('PS_SHOP_ADDR2'); + $this->_fields['list']['Expe_Ville']['value'] = Configuration::get('PS_SHOP_CITY'); + $this->_fields['list']['Expe_CP']['value'] = Configuration::get('PS_SHOP_CODE'); + $this->_fields['list']['Expe_CP']['params']['id_country'] = Configuration::get('PS_COUNTRY_DEFAULT'); + + if (version_compare(_PS_VERSION_, '1.4', '>=')) + { + $this->_fields['list']['Expe_Pays']['value'] = Country::getIsoById(Configuration::get('PS_SHOP_COUNTRY_ID')); + $this->_fields['list']['Expe_CP']['params']['id_country'] = Configuration::get('PS_SHOP_COUNTRY_ID'); + } + else + $this->_fields['list']['Expe_Pays']['value'] = Tools::substr(Configuration::get('PS_SHOP_COUNTRY'), 0, 2); + $this->_fields['list']['Expe_Tel1']['value'] = MRTools::getFormatedPhone(Configuration::get('PS_SHOP_PHONE')); + $this->_fields['list']['Expe_Mail']['value'] = Configuration::get('PS_SHOP_EMAIL'); + $this->_fields['list']['NbColis']['value'] = 1; + $this->_fields['list']['CRT_Valeur']['value'] = 0; + $this->_fields['list']['CRT_Devise']['value'] = 'EUR'; + } + + /* + * Initiate the data needed to be send properly + * Can manage a list of data for multiple request + */ + public function init() + { + if ($this->_totalOrder == 0) + throw new Exception($this->_mondialrelay->l('Please select at least one order', $this->class_name)); + + $this->_setRequestDefaultValue(); + if (count($orderListDetails = $this->_mondialrelay->getOrders($this->_orderListId))) + { + foreach ($orderListDetails as $orderDetail) + { + // Storage temporary + $base = $this->_fields; + $tmp = &$base['list']; + + $deliveriesAddress = new Address($orderDetail['id_address_delivery']); + $customer = new Customer($orderDetail['id_customer']); + + // Store the weight order set by the user + + foreach ($this->_weightList as $orderWeightInfos) + { + $detail = explode('-', $orderWeightInfos); + if (count($detail) == 2 && $detail[1] == $orderDetail['id_order']) + $tmp['Poids']['value'] = (float)$this->_weightFormat($detail[0]); + } + foreach ($this->_insuranceList as $insurance) + { + $detail = explode('-', $insurance); + if ($detail[1] == $orderDetail['id_order']) { + $tmp['Assurance']['value'] = (count($detail) == 2) ? (int)($detail[0]) : $orderDetail['mr_ModeAss']; + } + + } + $dest_tel = (!empty($deliveriesAddress->phone)) ? MRTools::getFormatedPhone($deliveriesAddress->phone) : ''; + $dest_tel2 = (!empty($deliveriesAddress->phone_mobile)) ? MRTools::getFormatedPhone($deliveriesAddress->phone_mobile) : ''; + $destIsoCode = Country::getIsoById($deliveriesAddress->id_country); + $tmp['ModeCol']['value'] = $orderDetail['mr_ModeCol']; + $tmp['ModeLiv']['value'] = $orderDetail['mr_ModeLiv']; + $tmp['NDossier']['value'] = $orderDetail['id_order']; + $tmp['NClient']['value'] = $orderDetail['id_customer']; + $tmp['Dest_Langage']['value'] = 'FR'; //Language::getIsoById($orderDetail['id_lang']); + $tmp['Dest_Ad1']['value'] = preg_replace(MRTools::REGEX_CLEAN_ADDR, '', Tools::substr(MRTools::removeAccents($deliveriesAddress->firstname.' '.$deliveriesAddress->lastname), 0, 32)); + $tmp['Dest_Ad2']['value'] = preg_replace(MRTools::REGEX_CLEAN_ADDR, '', Tools::substr(MRTools::removeAccents($deliveriesAddress->address2), 0, 32)); + $tmp['Dest_Ad3']['value'] = preg_replace(MRTools::REGEX_CLEAN_ADDR, '', Tools::substr(MRTools::removeAccents($deliveriesAddress->address1), 0, 32)); + $tmp['Dest_Ville']['value'] = $deliveriesAddress->city; + $tmp['Dest_CP']['value'] = $deliveriesAddress->postcode; + $tmp['Dest_CP']['params']['id_country'] = $deliveriesAddress->id_country; + $tmp['Dest_Pays']['value'] = $destIsoCode; + $tmp['Dest_Tel1']['value'] = $dest_tel; + $tmp['Dest_Tel2']['value'] = $dest_tel2; + $tmp['Dest_Mail']['value'] = $customer->email; + if ($orderDetail['mr_ModeLiv'] != 'LD1' && $orderDetail['mr_ModeLiv'] != 'LDS' && $orderDetail['mr_ModeLiv'] != 'HOM') + { + $tmp['LIV_Rel_Pays']['value'] = $orderDetail['MR_Selected_Pays']; + $tmp['LIV_Rel']['value'] = $orderDetail['MR_Selected_Num']; + } + + // Store the necessary information to the root case table + $base['id_mr_selected'] = $orderDetail['id_mr_selected']; + + // Add the temporary values to a field list for multiple request + $this->_fieldsList[] = $base; + unset($deliveriesAddress); + unset($customer); + } + $this->_generateMD5SecurityKey(); + } + } + + /* + * Generate the MD5 key for each param list + */ + private function _generateMD5SecurityKey() + { + // RootCase is the array case where the main information are stored + // it's an array containing id_mr_selected and an array with the necessary fields + foreach ($this->_fieldsList as &$rootCase) + { + $concatenationValue = ''; + foreach ($rootCase['list'] as $paramName => &$valueDetailed) + if ($paramName != 'Texte' && $paramName != 'Security') + { + // Mac server make an empty string instead of a cleaned string + // TODO : test on windows and linux server + $cleanedString = MRTools::removeAccents($valueDetailed['value']); + $valueDetailed['value'] = !empty($cleanedString) ? Tools::strtoupper($cleanedString) : Tools::strtoupper($valueDetailed['value']); + + // Call a pointer function if exist to do different test + if (isset($valueDetailed['methodValidation']) && method_exists('MRTools', $valueDetailed['methodValidation']) && isset($valueDetailed['params']) && MRTools::$valueDetailed['methodValidation']($valueDetailed['value'], $valueDetailed['params'])) + $concatenationValue .= $valueDetailed['value']; + // Use simple Regex test given by MondialRelay + else if (isset($valueDetailed['regexValidation']) && preg_match($valueDetailed['regexValidation'], $valueDetailed['value'], $matches)) + $concatenationValue .= $valueDetailed['value']; + // If the key is required, we set an error, else it's skipped + else if ((!Tools::strlen($valueDetailed['value']) && $valueDetailed['required']) || Tools::strlen($valueDetailed['value'])) + { + if (empty($valueDetailed['value'])) + $error = $this->_mondialrelay->l('This key', $this->class_name).' ['.$paramName.'] '.$this->_mondialrelay->l('is empty and need to be filled', $this->class_name); + else + $error = 'This key ['.$paramName.'] hasn not a valid value format : '.$valueDetailed['value']; + $this->_resultList['error'][$rootCase['list']['NDossier']['value']][] = $error; + } + } + $concatenationValue .= $this->_webServiceKey; + $rootCase['list']['Security']['value'] = Tools::strtoupper(md5($concatenationValue)); + } + } + + /* + * Update the tables used and send mail with the order history + */ + private function _updateTable($params, $expeditionNum, $ticketURL, $trackingURL, $id_mr_selected) + { + $sql = ' + UPDATE `'._DB_PREFIX_.'mr_selected` + SET `MR_poids` = \''.pSQL($params['Poids']).'\', + `MR_insurance` = \''.pSQL($params['Assurance']).'\', + `exp_number` = \''.pSQL($expeditionNum).'\', + `url_etiquette` = \''.pSQL($ticketURL).'\', + `url_suivi` = \''.pSQL($trackingURL).'\' + WHERE id_mr_selected = '.(int)$id_mr_selected; + Db::getInstance()->execute($sql); + + // NDossier contains the id_order + $order = new Order($params['NDossier']); + + // Update the database for order and orderHistory + $order->shipping_number = $expeditionNum; + $order->update(); + + if (version_compare(_PS_VERSION_, '1.5', '>=')) + { + //Retrieve Order Carrier + $sql = 'SELECT `id_order_carrier` + FROM `'._DB_PREFIX_.'order_carrier` + WHERE `id_order` = '.(int)$order->id; + + $id_order_carrier = Db::getInstance()->getValue($sql); + + if($id_order_carrier) + { + $order_carrier = new OrderCarrier((int)$id_order_carrier); + if(Validate::isLoadedObject($order_carrier)) + { + $order_carrier->tracking_number = pSQL($expeditionNum); + $order_carrier->update(); + } + } + } + + $templateVars = array('{followup}' => $trackingURL); + $orderState = (Configuration::get('PS_OS_SHIPPING')) ? + Configuration::get('PS_OS_SHIPPING') : + _PS_OS_SHIPPING_; + + $history = new OrderHistory(); + $history->id_order = (int)$params['NDossier']; + if (version_compare(_PS_VERSION_, '1.5.2', '>=')) + $history->changeIdOrderState((int)$orderState, $order); + else + $history->changeIdOrderState((int)$orderState, (int)($params['NDossier'])); + $history->id_employee = (isset(Context::getContext()->employee->id) ? (int)Context::getContext()->employee->id : ''); + $history->addWithemail(true, $templateVars); + unset($order); + unset($order_carrier); + unset($history); + } + + /* + * Manage the return value of the webservice, handle the errors or build the + * succeed message + */ + private function _parseResult($client, $result, $params, $id_mr_selected) + { + $errors = &$this->_resultList['error'][$params['NDossier']]; + $success = &$this->_resultList['success'][$params['NDossier']]; + $result = $result->WSI2_CreationEtiquetteResult; + if (($errorNumber = $result->STAT) != 0) + { + $errors[] = $this->_mondialrelay->l('There is an error number : ', $this->class_name).$errorNumber; + $errors[] = $this->_mondialrelay->l('Details : ', $this->class_name). + $this->_mondialrelay->getErrorCodeDetail($errorNumber); + } + else + { + $baseURL = MondialRelay::MR_URL; + $expedition = $result->ExpeditionNum; + $securityKey = Tools::strtoupper(md5('<'.$params['Enseigne'].$this->_markCode. + '>'.$expedition.'<'.$this->_webServiceKey.'>')); + $ticketURL = $baseURL.$result->URL_Etiquette; + $trackingURL = $baseURL. + 'public/permanent/tracking.aspx?ens='.$params['Enseigne'].$this->_markCode.'&exp='.$expedition.'&language='.Configuration::get('PS_LANG_DEFAULT').'&crc='.$securityKey; + + $success['displayExpedition'] = $this->_mondialrelay->l('Expedition Number : ', $this->class_name).$expedition; + $success['displayTicketURL'] = $this->_mondialrelay->l('Ticket URL : ', $this->class_name).$ticketURL; + $success['displayTrackingURL'] = $this->_mondialrelay->l('Tracking URL: ', $this->class_name).$trackingURL; + $success['expeditionNumber'] = $expedition; + + $this->_updateTable($params, $expedition, $ticketURL, $trackingURL, $id_mr_selected); + } + } + + /* + * Send one or multiple request to the webservice + */ + public function send() + { + if ($client = new SoapClient($this->_webserviceURL)) + { + $client->soap_defencoding = 'UTF-8'; + $client->decode_utf8 = false; + + foreach ($this->_fieldsList as $rootCase) + { + $params = $this->_getSimpleParamArray($rootCase['list']); + $result = $client->WSI2_CreationEtiquette($params); + $this->_parseResult($client, $result, $params, $rootCase['id_mr_selected']); + } + unset($client); + Configuration::updateValue('MONDIALRELAY_CONFIGURATION_OK', true); + } + else + throw new Exception($this->_mondialrelay->l('The Mondial Relay webservice is not currently reliable', $this->class_name)); + } + + /* + ** Check if the shop parameter are currently well configured + */ + public function checkPreValidation() + { + $errorList = array('error' => array(), 'warn' => array()); + + $list = array( + 'Expe_Langage' => array( + 'value' => $this->_mondialrelay->account_shop['MR_LANGUAGE'], + 'error' => $this->_mondialrelay->l('Please check your language configuration', $this->class_name)), + 'Expe_Ad1' => array( + 'value' => Configuration::get('PS_SHOP_NAME'), + 'error' => $this->_mondialrelay->l('Please check your shop name configuration', $this->class_name)), + 'Expe_Ad3' => array( + 'value' => Configuration::get('PS_SHOP_ADDR1'), + 'error' => $this->_mondialrelay->l('Please check your address 1 configuration', $this->class_name)), + 'Expe_Ville' => array( + 'value' => Configuration::get('PS_SHOP_CITY'), + 'error' => $this->_mondialrelay->l('Please check your city configuration', $this->class_name)), + 'Expe_CP' => array( + 'value' => Configuration::get('PS_SHOP_CODE'), + 'error' => $this->_mondialrelay->l('Please check your zipcode configuration', $this->class_name)), + 'Expe_Pays' => array( + 'value' => ((version_compare(_PS_VERSION_, '1.4', '>=')) ? + Country::getIsoById(Configuration::get('PS_SHOP_COUNTRY_ID')) : + Tools::substr(Configuration::get('PS_SHOP_COUNTRY'), 0, 2)), + 'error' => $this->_mondialrelay->l('Please check your country configuration', $this->class_name)), + 'Expe_Tel1' => array( + 'value' => MRTools::getFormatedPhone(Configuration::get('PS_SHOP_PHONE')), + 'error' => $this->_mondialrelay->l('Please check your Phone configuration', $this->class_name)), + 'Expe_Mail' => array( + 'value' => Configuration::get('PS_SHOP_EMAIL'), + 'error' => $this->_mondialrelay->l('Please check your mail configuration', $this->class_name))); + + foreach ($list as $name => $tab) + { + // Mac server make an empty string instead of a cleaned string + // TODO : test on windows and linux server + $cleanedString = MRTools::removeAccents($tab['value']); + $tab['value'] = !empty($cleanedString) ? Tools::strtoupper($cleanedString) : Tools::strtoupper($tab['value']); + + if ($name == 'Expe_CP') + { + if (version_compare(_PS_VERSION_, '1.4', '>=')) + { + if (!(MRTools::checkZipcodeByCountry($tab['value'], array( + 'id_country' => Configuration::get('PS_SHOP_COUNTRY_ID'))))) + $errorList['error'][$name] = $tab['error']; + } + else + $errorList['warn'][$name] = $this->_mondialrelay->l('Post code cannot be validated with PrestaShop versions older than 1.4', $this->class_name); + } + else if (isset($this->_fields['list'][$name]['regexValidation']) && + (!preg_match($this->_fields['list'][$name]['regexValidation'], $tab['value'], $matches))) + $errorList['error'][$name] = $tab['error']; + } + return $errorList; + } + + /* + * Get the values with associated fields name + * @fields : array containing multiple values information + */ + private function _getSimpleParamArray($fields) + { + $params = array(); + + foreach ($fields as $keyName => $valueDetailed) + $params[$keyName] = $valueDetailed['value']; + return $params; + } + + /* + * Return the fields list + */ + public function getFieldsList() + { + return $this->_fieldsList['list']; + } + + /* + * Return the result of one or multiple sent requests + */ + public function getResult() + { + return $this->_resultList; + } + + /* + * Return which number order of the list is currently managed + */ + public static function getCurrentRequestUnderTraitment() + { + // TODO: Build a SQL Query to know how many request have been executed + } } ?> diff --git a/classes/MRDownloadPDF.php b/classes/MRDownloadPDF.php old mode 100644 new mode 100755 index ebd3bd3..9e3a147 --- a/classes/MRDownloadPDF.php +++ b/classes/MRDownloadPDF.php @@ -32,160 +32,160 @@ */ class MRDownloadPDF implements IMondialRelayWSMethod { - public $class_name = __CLASS__; + public $class_name = __CLASS__; - private $_fields = array( - 'list' => array( - 'Enseigne' => array( - 'required' => true, - 'value' => '', - 'regexValidation' => '#^[0-9A-Z]{2}[0-9A-Z ]{6}$#'), - 'Expeditions' => array( - 'required' => true, - 'value' => '', - 'regexValidation' => '#^[0-9]{8}(;[0-9]{8})*$#'), - 'Langue' => array( - 'required' => true, - 'value' => '', - 'regexValidation' => '#^[A-Z]{2}$#'), - 'Security' => array( - 'required' => true, - 'value' => '', - 'regexValidation' => '#^[0-9A-Z]{32}$#'))); + private $_fields = array( + 'list' => array( + 'Enseigne' => array( + 'required' => true, + 'value' => '', + 'regexValidation' => '#^[0-9A-Z]{2}[0-9A-Z ]{6}$#'), + 'Expeditions' => array( + 'required' => true, + 'value' => '', + 'regexValidation' => '#^[0-9]{8}(;[0-9]{8})*$#'), + 'Langue' => array( + 'required' => true, + 'value' => '', + 'regexValidation' => '#^[A-Z]{2}$#'), + 'Security' => array( + 'required' => true, + 'value' => '', + 'regexValidation' => '#^[0-9A-Z]{32}$#'))); - private $_mondialrelay = null; - private $_fieldsList = array(); - private $_webServiceKey = ''; - private $_markCode = ''; - private $Expeditions = ''; + private $_mondialrelay = null; + private $_fieldsList = array(); + private $_webServiceKey = ''; + private $_markCode = ''; + private $Expeditions = ''; - private $_resultList = array( - 'error' => array(), - 'success' => array()); + private $_resultList = array( + 'error' => array(), + 'success' => array()); - private $_webserviceURL = ''; + private $_webserviceURL = ''; - public function __construct($params, $object) - { - $this->Expeditions = $params['Expeditions']; - $this->_mondialrelay = $object; - $this->_webServiceKey = $this->_mondialrelay->account_shop['MR_KEY_WEBSERVICE']; - $this->_markCode = $this->_mondialrelay->account_shop['MR_CODE_MARQUE']; - $this->class_name = Tools::strtolower($this->class_name); - $this->_webserviceURL = MondialRelay::MR_URL.'webservice/Web_Services.asmx?WSDL'; - } + public function __construct($params, $object) + { + $this->Expeditions = $params['Expeditions']; + $this->_mondialrelay = $object; + $this->_webServiceKey = $this->_mondialrelay->account_shop['MR_KEY_WEBSERVICE']; + $this->_markCode = $this->_mondialrelay->account_shop['MR_CODE_MARQUE']; + $this->class_name = Tools::strtolower($this->class_name); + $this->_webserviceURL = MondialRelay::MR_URL.'webservice/Web_Services.asmx?WSDL'; + } - public function __destruct() - { - unset($this->_mondialrelay); - } + public function __destruct() + { + unset($this->_mondialrelay); + } - /* - * Initiate the data needed to be send properly - * Can manage a list of data for multiple request - */ - public function init() - { - $this->_fields['list']['Enseigne']['value'] = $this->_mondialrelay->account_shop['MR_ENSEIGNE_WEBSERVICE']; - $this->_fields['list']['Expeditions']['value'] = $this->Expeditions; - $this->_fields['list']['Langue']['value'] = $this->_mondialrelay->account_shop['MR_LANGUAGE']; - $this->_fieldsList[] = $this->_fields; - $this->_generateMD5SecurityKey(); - } + /* + * Initiate the data needed to be send properly + * Can manage a list of data for multiple request + */ + public function init() + { + $this->_fields['list']['Enseigne']['value'] = $this->_mondialrelay->account_shop['MR_ENSEIGNE_WEBSERVICE']; + $this->_fields['list']['Expeditions']['value'] = $this->Expeditions; + $this->_fields['list']['Langue']['value'] = $this->_mondialrelay->account_shop['MR_LANGUAGE']; + $this->_fieldsList[] = $this->_fields; + $this->_generateMD5SecurityKey(); + } - /* - * Generate the MD5 key for each param list - */ - private function _generateMD5SecurityKey() - { - foreach ($this->_fieldsList as &$rootCase) - { - $concatenationValue = ''; - foreach ($rootCase['list'] as $paramName => &$valueDetailed) - if ($paramName != 'Texte' && $paramName != 'Security') - { - $valueDetailed['value'] = Tools::strtoupper($valueDetailed['value']); - if (preg_match($valueDetailed['regexValidation'], $valueDetailed['value'], $matches)) - $concatenationValue .= $valueDetailed['value']; - elseif ((!Tools::strlen($valueDetailed['value']) && $valueDetailed['required']) || Tools::strlen($valueDetailed['value'])) - { - $error = $this->_mondialrelay->l('This key').' ['.$paramName.'] '.$this->_mondialrelay->l('hasn\'t a valide value format').' : '.$valueDetailed['value']; - $this->_resultList['error'][] = $error; - } - } - $concatenationValue .= $this->_webServiceKey; - $rootCase['list']['Security']['value'] = Tools::strtoupper(md5($concatenationValue)); - } - } + /* + * Generate the MD5 key for each param list + */ + private function _generateMD5SecurityKey() + { + foreach ($this->_fieldsList as &$rootCase) + { + $concatenationValue = ''; + foreach ($rootCase['list'] as $paramName => &$valueDetailed) + if ($paramName != 'Texte' && $paramName != 'Security') + { + $valueDetailed['value'] = Tools::strtoupper($valueDetailed['value']); + if (preg_match($valueDetailed['regexValidation'], $valueDetailed['value'], $matches)) + $concatenationValue .= $valueDetailed['value']; + elseif ((!Tools::strlen($valueDetailed['value']) && $valueDetailed['required']) || Tools::strlen($valueDetailed['value'])) + { + $error = $this->_mondialrelay->l('This key').' ['.$paramName.'] '.$this->_mondialrelay->l('hasn\'t a valide value format').' : '.$valueDetailed['value']; + $this->_resultList['error'][] = $error; + } + } + $concatenationValue .= $this->_webServiceKey; + $rootCase['list']['Security']['value'] = Tools::strtoupper(md5($concatenationValue)); + } + } - /* - * Manage the return value of the webservice, handle the errors or build the - * succeed message - */ - private function _parseResult($client, $result, $params) - { - $errors = &$this->_resultList['error'][]; - $success = &$this->_resultList['success'][]; - $result = $result->WSI2_GetEtiquettesResult; - if (($errorNumber = $result->STAT) != 0) - { - $errors[] = $this->_mondialrelay->l('There is an error number : ', $this->class_name).$errorNumber; - $errors[] = $this->_mondialrelay->l('Details : ', $this->class_name). - $this->_mondialrelay->getErrorCodeDetail($errorNumber); - } - else - { - $baseURL = 'http://www.mondialrelay.fr'; - $success['URL_PDF_A4'] = $baseURL.$result->URL_PDF_A4; - $success['URL_PDF_A5'] = $baseURL.$result->URL_PDF_A5; - $success['URL_PDF_10x15'] = $baseURL.str_replace('format=A4', 'format=10x15', $result->URL_PDF_A4); - } - } + /* + * Manage the return value of the webservice, handle the errors or build the + * succeed message + */ + private function _parseResult($client, $result, $params) + { + $errors = &$this->_resultList['error'][]; + $success = &$this->_resultList['success'][]; + $result = $result->WSI2_GetEtiquettesResult; + if (($errorNumber = $result->STAT) != 0) + { + $errors[] = $this->_mondialrelay->l('There is an error number : ', $this->class_name).$errorNumber; + $errors[] = $this->_mondialrelay->l('Details : ', $this->class_name). + $this->_mondialrelay->getErrorCodeDetail($errorNumber); + } + else + { + $baseURL = 'http://www.mondialrelay.fr'; + $success['URL_PDF_A4'] = $baseURL.$result->URL_PDF_A4; + $success['URL_PDF_A5'] = $baseURL.$result->URL_PDF_A5; + $success['URL_PDF_10x15'] = $baseURL.str_replace('format=A4', 'format=10x15', $result->URL_PDF_A4); + } + } - /* - * Send one or multiple request to the webservice - */ - public function send() - { - if ($client = new SoapClient($this->_webserviceURL)) - { - $client->soap_defencoding = 'UTF-8'; - $client->decode_utf8 = false; - foreach ($this->_fieldsList as $rootCase) - { - $params = $this->_getSimpleParamArray($rootCase['list']); - $result = $client->WSI2_GetEtiquettes($params); - $this->_parseResult($client, $result, $params); - } - unset($client); - } - else - throw new Exception($this->_mondialrelay->l('The Mondial Relay webservice isn\'t currently reliable')); - } - - /* - * Return the fields list - */ - public function getFieldsList() - { - return $this->_fieldsList['list']; - } + /* + * Send one or multiple request to the webservice + */ + public function send() + { + if ($client = new SoapClient($this->_webserviceURL)) + { + $client->soap_defencoding = 'UTF-8'; + $client->decode_utf8 = false; + foreach ($this->_fieldsList as $rootCase) + { + $params = $this->_getSimpleParamArray($rootCase['list']); + $result = $client->WSI2_GetEtiquettes($params); + $this->_parseResult($client, $result, $params); + } + unset($client); + } + else + throw new Exception($this->_mondialrelay->l('The Mondial Relay webservice isn\'t currently reliable')); + } + + /* + * Return the fields list + */ + public function getFieldsList() + { + return $this->_fieldsList['list']; + } - /* - * Return the result of one or multiple sent requests - */ - public function getResult() - { - return $this->_resultList; - } - - private function _getSimpleParamArray($fields) - { - $params = array(); - - foreach ($fields as $keyName => $valueDetailed) - $params[$keyName] = $valueDetailed['value']; - return $params; - } + /* + * Return the result of one or multiple sent requests + */ + public function getResult() + { + return $this->_resultList; + } + + private function _getSimpleParamArray($fields) + { + $params = array(); + + foreach ($fields as $keyName => $valueDetailed) + $params[$keyName] = $valueDetailed['value']; + return $params; + } } diff --git a/classes/MRGetRelayPoint.php b/classes/MRGetRelayPoint.php old mode 100644 new mode 100755 index f25a0af..927041a --- a/classes/MRGetRelayPoint.php +++ b/classes/MRGetRelayPoint.php @@ -35,248 +35,248 @@ */ class MRGetRelayPoint implements IMondialRelayWSMethod { - /*Params is required if you use a pointer function*/ - private $_fields = array( - 'list' => array( - 'Enseigne' => array( - 'required' => true, - 'value' => '', - 'regexValidation' => '#^[0-9A-Z]{2}[0-9A-Z ]{6}$#'), - 'Pays' => array( - 'required' => true, - 'value' => '', - 'regexValidation' => '#^[A-Z]{2}$#'), - 'Ville' => array( - 'required' => false, - 'value' => '', - 'regexValidation' => '#^[A-Z_\-\' 0-9]{2,25}$#'), - 'CP' => array( - 'required' => false, - 'value' => '', - 'params' => array(), - 'methodValidation' => 'checkZipcodeByCountry'), - 'Taille' => array( - 'required' => false, - 'value' => '', - 'regexValidation' => '#^(XS|S|M|L|XL|XXL|3XL)$#'), - 'Poids' => array( - 'required' => false, - 'value' => '', - 'regexValidation' => '#^[0-9]{3,7}$#'), - 'Action' => array( - 'required' => false, - 'value' => '', - 'regexValidation' => '#^(REL|24R|ESP|DRI)$#'), - 'Security' => array( - 'required' => true, - 'value' => '', - 'regexValidation' => '#^[0-9A-Z]{32}$#'))); - - private $_id_address_delivery = 0; - private $_weight = 0; - private $_webServiceKey = ''; - private $_mondialRelay = null; - private $_id_carrier = 0; - private $_id_delivery_country = 0; - - private $_resultList = array( - 'error' => array(), - 'success' => array()); - - private $_webserviceURL; - - public function __construct($params, $object) - { - $this->_mondialRelay = $object; - $this->_id_address_delivery = (int)($params['id_address_delivery']); - $this->_id_carrier = (int)($params['id_carrier']); - $this->_weight = (float)($params['weight']); - $this->_webServiceKey = $this->_mondialRelay->account_shop['MR_KEY_WEBSERVICE']; - $this->_webserviceURL = MondialRelay::MR_URL.'webservice/Web_Services.asmx?WSDL'; - } - - public function __destruct() - { - unset($this->_mondialRelay); - } - - public function init() - { - $address = new Address($this->_id_address_delivery); - $weight = $this->_mondialRelay->account_shop['MR_WEIGHT_COEFFICIENT'] * $this->_weight; - - if (!$address) - throw new Exception($this->_mondialrelay->l('Customer address can\'t be found')); - - $this->_fields['list']['Enseigne']['value'] = $this->_mondialRelay->account_shop['MR_ENSEIGNE_WEBSERVICE']; - $this->_fields['list']['Poids']['value'] = ($weight < 100) ? 100 : $weight; - $this->_fields['list']['Pays']['value'] = trim(Country::getIsoById($address->id_country)); - $this->_fields['list']['Ville']['value'] = trim($address->city); - $this->_fields['list']['CP']['value'] = trim($address->postcode); - $this->_fields['list']['CP']['params']['id_country'] = $address->id_country; - - $this->_generateMD5SecurityKey(); - unset($address); - } - - /* - * Generate the MD5 key for each param list - */ - private function _generateMD5SecurityKey() - { - $concatenationValue = ''; - foreach ($this->_fields['list'] as $paramName => &$valueDetailed) - if ($paramName != 'Texte' && $paramName != 'Security') - { - // Mac server make an empty string instead of a cleaned string - // TODO : test on windows and linux server - $cleanedString = MRTools::removeAccents($valueDetailed['value']); - $valueDetailed['value'] = !empty($cleanedString) ? Tools::strtoupper($cleanedString) : Tools::strtoupper($valueDetailed['value']); + /*Params is required if you use a pointer function*/ + private $_fields = array( + 'list' => array( + 'Enseigne' => array( + 'required' => true, + 'value' => '', + 'regexValidation' => '#^[0-9A-Z]{2}[0-9A-Z ]{6}$#'), + 'Pays' => array( + 'required' => true, + 'value' => '', + 'regexValidation' => '#^[A-Z]{2}$#'), + 'Ville' => array( + 'required' => false, + 'value' => '', + 'regexValidation' => '#^[A-Z_\-\' 0-9]{2,25}$#'), + 'CP' => array( + 'required' => false, + 'value' => '', + 'params' => array(), + 'methodValidation' => 'checkZipcodeByCountry'), + 'Taille' => array( + 'required' => false, + 'value' => '', + 'regexValidation' => '#^(XS|S|M|L|XL|XXL|3XL)$#'), + 'Poids' => array( + 'required' => false, + 'value' => '', + 'regexValidation' => '#^[0-9]{3,7}$#'), + 'Action' => array( + 'required' => false, + 'value' => '', + 'regexValidation' => '#^(REL|24R|ESP|DRI)$#'), + 'Security' => array( + 'required' => true, + 'value' => '', + 'regexValidation' => '#^[0-9A-Z]{32}$#'))); + + private $_id_address_delivery = 0; + private $_weight = 0; + private $_webServiceKey = ''; + private $_mondialRelay = null; + private $_id_carrier = 0; + private $_id_delivery_country = 0; + + private $_resultList = array( + 'error' => array(), + 'success' => array()); + + private $_webserviceURL; + + public function __construct($params, $object) + { + $this->_mondialRelay = $object; + $this->_id_address_delivery = (int)($params['id_address_delivery']); + $this->_id_carrier = (int)($params['id_carrier']); + $this->_weight = (float)($params['weight']); + $this->_webServiceKey = $this->_mondialRelay->account_shop['MR_KEY_WEBSERVICE']; + $this->_webserviceURL = MondialRelay::MR_URL.'webservice/Web_Services.asmx?WSDL'; + } + + public function __destruct() + { + unset($this->_mondialRelay); + } + + public function init() + { + $address = new Address($this->_id_address_delivery); + $weight = $this->_mondialRelay->account_shop['MR_WEIGHT_COEFFICIENT'] * $this->_weight; + + if (!$address) + throw new Exception($this->_mondialrelay->l('Customer address can\'t be found')); + + $this->_fields['list']['Enseigne']['value'] = $this->_mondialRelay->account_shop['MR_ENSEIGNE_WEBSERVICE']; + $this->_fields['list']['Poids']['value'] = ($weight < 100) ? 100 : $weight; + $this->_fields['list']['Pays']['value'] = trim(Country::getIsoById($address->id_country)); + $this->_fields['list']['Ville']['value'] = trim($address->city); + $this->_fields['list']['CP']['value'] = trim($address->postcode); + $this->_fields['list']['CP']['params']['id_country'] = $address->id_country; + + $this->_generateMD5SecurityKey(); + unset($address); + } + + /* + * Generate the MD5 key for each param list + */ + private function _generateMD5SecurityKey() + { + $concatenationValue = ''; + foreach ($this->_fields['list'] as $paramName => &$valueDetailed) + if ($paramName != 'Texte' && $paramName != 'Security') + { + // Mac server make an empty string instead of a cleaned string + // TODO : test on windows and linux server + $cleanedString = MRTools::removeAccents($valueDetailed['value']); + $valueDetailed['value'] = !empty($cleanedString) ? Tools::strtoupper($cleanedString) : Tools::strtoupper($valueDetailed['value']); - $valueDetailed['value'] = Tools::strtoupper($valueDetailed['value']); - // Call a pointer function if exist to do different test - if (isset($valueDetailed['methodValidation']) && method_exists('MRTools', $valueDetailed['methodValidation']) && isset($valueDetailed['params']) && MRTools::$valueDetailed['methodValidation']($valueDetailed['value'], $valueDetailed['params'])) - $concatenationValue .= $valueDetailed['value']; - // Use simple Regex test given by MondialRelay - else if (isset($valueDetailed['regexValidation']) && preg_match($valueDetailed['regexValidation'], $valueDetailed['value'], $matches)) - $concatenationValue .= $valueDetailed['value']; - // If the key is required, we set an error, else it's skipped - elseif ((!Tools::strlen($valueDetailed['value']) && $valueDetailed['required']) || Tools::strlen($valueDetailed['value'])) - { - $error = $this->_mondialRelay->l('This key').' ['.$paramName.'] '. - $this->_mondialRelay->l('hasn\'t a valide value format').' : '.$valueDetailed['value']; - $this->_resultList['error'][] = $error; - } - } - $concatenationValue .= $this->_webServiceKey; - $this->_fields['list']['Security']['value'] = Tools::strtoupper(md5($concatenationValue)); - } + $valueDetailed['value'] = Tools::strtoupper($valueDetailed['value']); + // Call a pointer function if exist to do different test + if (isset($valueDetailed['methodValidation']) && method_exists('MRTools', $valueDetailed['methodValidation']) && isset($valueDetailed['params']) && MRTools::$valueDetailed['methodValidation']($valueDetailed['value'], $valueDetailed['params'])) + $concatenationValue .= $valueDetailed['value']; + // Use simple Regex test given by MondialRelay + else if (isset($valueDetailed['regexValidation']) && preg_match($valueDetailed['regexValidation'], $valueDetailed['value'], $matches)) + $concatenationValue .= $valueDetailed['value']; + // If the key is required, we set an error, else it's skipped + elseif ((!Tools::strlen($valueDetailed['value']) && $valueDetailed['required']) || Tools::strlen($valueDetailed['value'])) + { + $error = $this->_mondialRelay->l('This key').' ['.$paramName.'] '. + $this->_mondialRelay->l('hasn\'t a valide value format').' : '.$valueDetailed['value']; + $this->_resultList['error'][] = $error; + } + } + $concatenationValue .= $this->_webServiceKey; + $this->_fields['list']['Security']['value'] = Tools::strtoupper(md5($concatenationValue)); + } - /* - * Get the values with associated fields name - * @fields : array containing multiple values information - */ - private function _getSimpleParamArray($fields) - { - $params = array(); - - foreach ($fields as $keyName => $valueDetailed) - $params[$keyName] = $valueDetailed['value']; - return $params; - } - - /* - ** Get detail information for each relay - */ - private function _getRelayPointDetails($relayPointList) - { - $relayPointNumList = array(); - foreach ($relayPointList as $relayPoint) - $relayPointNumList[] = $relayPoint['Num']; - $MRRelayDetail = new MRRelayDetail(array('relayPointNumList' => $relayPointNumList, 'id_address_delivery' => $this->_id_address_delivery)); - $MRRelayDetail->init(); - $MRRelayDetail->send(); - return $MRRelayDetail->getResult(); - } + /* + * Get the values with associated fields name + * @fields : array containing multiple values information + */ + private function _getSimpleParamArray($fields) + { + $params = array(); + + foreach ($fields as $keyName => $valueDetailed) + $params[$keyName] = $valueDetailed['value']; + return $params; + } + + /* + ** Get detail information for each relay + */ + private function _getRelayPointDetails($relayPointList) + { + $relayPointNumList = array(); + foreach ($relayPointList as $relayPoint) + $relayPointNumList[] = $relayPoint['Num']; + $MRRelayDetail = new MRRelayDetail(array('relayPointNumList' => $relayPointNumList, 'id_address_delivery' => $this->_id_address_delivery)); + $MRRelayDetail->init(); + $MRRelayDetail->send(); + return $MRRelayDetail->getResult(); + } - /* - ** Generate a perman link to view relay detail on their website - */ - private function _addLinkHoursDetail(&$relayPointList) - { - $relayPointNumList = array(); - foreach ($relayPointList as $relayPoint) - $relayPointNumList[] = $relayPoint->Num; - $permaList = MRRelayDetail::getPermaLink($relayPointNumList, $this->_id_address_delivery); - foreach ($relayPointList as &$relayPoint) - { - $relayPoint->permaLinkDetail = ''; - if (array_key_exists($relayPoint->Num, $permaList)) - $relayPoint->permaLinkDetail = $permaList[$relayPoint->Num]; - } - return $relayPointList; - } - - /* - * Manage the return value of the webservice, handle the errors or build the - * succeed message - */ - private function _parseResult($client, $result, $params) - { - $errors = array(); - $success = array(); - $result = $result->WSI2_RecherchePointRelaisResult; - if (($errorNumber = $result->STAT) != 0) - { - $errors[] = $this->_mondialRelay->l('There is an error number : ').$errorNumber; - $errors[] = $this->_mondialRelay->l('Details : '). - $this->_mondialRelay->getErrorCodeDetail($errorNumber); - } - else - { - unset($result->STAT); - - // Clean Content - foreach ($result as $num => $relayPoint) - { - $totalEmptyFields = 0; - foreach ($relayPoint as &$value) - { - $value = trim($value); - if (empty($value)) - ++$totalEmptyFields; - } - if ($totalEmptyFields == count($relayPoint)) - unset($result[$num]); - } - if (!count($result)) - $errors[] = $this->_mondialRelay->l('MondialRelay can\'t find any relay point near your address. Maybe your address isn\'t properly filled ?'); - else - { - $this->_addLinkHoursDetail($result); + /* + ** Generate a perman link to view relay detail on their website + */ + private function _addLinkHoursDetail(&$relayPointList) + { + $relayPointNumList = array(); + foreach ($relayPointList as $relayPoint) + $relayPointNumList[] = $relayPoint->Num; + $permaList = MRRelayDetail::getPermaLink($relayPointNumList, $this->_id_address_delivery); + foreach ($relayPointList as &$relayPoint) + { + $relayPoint->permaLinkDetail = ''; + if (array_key_exists($relayPoint->Num, $permaList)) + $relayPoint->permaLinkDetail = $permaList[$relayPoint->Num]; + } + return $relayPointList; + } + + /* + * Manage the return value of the webservice, handle the errors or build the + * succeed message + */ + private function _parseResult($client, $result, $params) + { + $errors = array(); + $success = array(); + $result = $result->WSI2_RecherchePointRelaisResult; + if (($errorNumber = $result->STAT) != 0) + { + $errors[] = $this->_mondialRelay->l('There is an error number : ').$errorNumber; + $errors[] = $this->_mondialRelay->l('Details : '). + $this->_mondialRelay->getErrorCodeDetail($errorNumber); + } + else + { + unset($result->STAT); + + // Clean Content + foreach ($result as $num => $relayPoint) + { + $totalEmptyFields = 0; + foreach ($relayPoint as &$value) + { + $value = trim($value); + if (empty($value)) + ++$totalEmptyFields; + } + if ($totalEmptyFields == count($relayPoint)) + unset($result[$num]); + } + if (!count($result)) + $errors[] = $this->_mondialRelay->l('MondialRelay can\'t find any relay point near your address. Maybe your address isn\'t properly filled ?'); + else + { + $this->_addLinkHoursDetail($result); - // Fetch detail info using webservice (not used anymore) - // $this->_generateLinkHoursDetail($result); - // $result = (count($relayDetail['success'])) ? $relayDetail['success'] : $result; - } - $success = $result; - } - $this->_resultList['error'] = $errors; - $this->_resultList['success'] = $success; - } - - /* - * Send one or multiple request to the webservice - */ - public function send() - { - if ($client = new SoapClient($this->_webserviceURL)) - { - $client->soap_defencoding = 'UTF-8'; - $client->decode_utf8 = false; - - $params = $this->_getSimpleParamArray($this->_fields['list']); - $result = $client->WSI2_RecherchePointRelais($params); - $this->_parseResult($client, $result, $params); - unset($client); - } - else - throw new Exception($this->_mondialRelay->l('The Mondial Relay webservice isn\'t currently reliable')); - } - - /* - * Get the values with associated fields name - */ - public function getFieldsList() - { - return $this->_fieldsList['list']; - } - - /* - * Get the result of one or multiple send request - */ - public function getResult() - { - return $this->_resultList; - } + // Fetch detail info using webservice (not used anymore) + // $this->_generateLinkHoursDetail($result); + // $result = (count($relayDetail['success'])) ? $relayDetail['success'] : $result; + } + $success = $result; + } + $this->_resultList['error'] = $errors; + $this->_resultList['success'] = $success; + } + + /* + * Send one or multiple request to the webservice + */ + public function send() + { + if ($client = new SoapClient($this->_webserviceURL)) + { + $client->soap_defencoding = 'UTF-8'; + $client->decode_utf8 = false; + + $params = $this->_getSimpleParamArray($this->_fields['list']); + $result = $client->WSI2_RecherchePointRelais($params); + $this->_parseResult($client, $result, $params); + unset($client); + } + else + throw new Exception($this->_mondialRelay->l('The Mondial Relay webservice isn\'t currently reliable')); + } + + /* + * Get the values with associated fields name + */ + public function getFieldsList() + { + return $this->_fieldsList['list']; + } + + /* + * Get the result of one or multiple send request + */ + public function getResult() + { + return $this->_resultList; + } } diff --git a/classes/MRGetTickets.php b/classes/MRGetTickets.php old mode 100644 new mode 100755 index da0f638..5ff43e0 --- a/classes/MRGetTickets.php +++ b/classes/MRGetTickets.php @@ -35,221 +35,221 @@ */ class MRGetTickets implements IMondialRelayWSMethod { - private $_fields = array( - 'list' => array( - 'Enseigne' => array( - 'required' => true, - 'value' => '', - 'regexValidation' => '#^[0-9A-Z]{2}[0-9A-Z ]{6}$#'), - 'Expeditions' => array( - 'required' => true, - 'value' => '', - 'regexValidation' => '#^[0-9]{8}(;[0-9]{8})*$#'), - 'Langue' => array( - 'required' => true, - 'value' => '', - 'regexValidation' => '#^[A-Z]{2}$#'), - 'Security' => array( - 'required' => true, - 'value' => '', - 'regexValidation' => '#^[0-9A-Z]{32}$#'))); - - private $_detailedExpeditionList = array(); - private $_webServiceKey = ''; - private $_mondialrelay = null; - - private $_resultList = array( - 'error' => array(), - 'success' => array()); - - private $_webserviceURL; - - public function __construct($params, $object) - { - $this->_mondialrelay = $object; - $this->_detailedExpeditionList = $params['detailedExpeditionList']; - $this->_webServiceKey = $this->_mondialrelay->account_shop['MR_KEY_WEBSERVICE']; - $this->_webserviceURL = MondialRelay::MR_URL.'webservice/Web_Services.asmx?WSDL'; - } - - public function __destruct() - { - unset($this->_mondialrelay); - } - - public function init() - { - $this->_fields['list']['Enseigne']['value'] = $this->_mondialrelay->account_shop['MR_ENSEIGNE_WEBSERVICE']; - $this->_fields['list']['Langue']['value'] = $this->_mondialrelay->account_shop['MR_LANGUAGE']; - - foreach ($this->_detailedExpeditionList as $detailedExpedition) - { - // Storage temporary - $base = $this->_fields; - $tmp = &$base['list']; - - $tmp['Expeditions']['value'] = $detailedExpedition['expeditionNumber']; - $this->_fieldsList[] = $base; - } - $this->_generateMD5SecurityKey(); - } - - /* - * Generate the MD5 key for each param list - */ - private function _generateMD5SecurityKey() - { - // RootCase is the array case where the main information are stored - // it's an array containing id_mr_selected and an array with the necessary fields - foreach ($this->_fieldsList as &$rootCase) - { - $concatenationValue = ''; - foreach ($rootCase['list'] as $paramName => &$valueDetailed) - if ($paramName != 'Texte' && $paramName != 'Security') - { - $valueDetailed['value'] = Tools::strtoupper($valueDetailed['value']); - if (preg_match($valueDetailed['regexValidation'], $valueDetailed['value'], $matches)) - $concatenationValue .= $valueDetailed['value']; - elseif ((!Tools::strlen($valueDetailed['value']) && $valueDetailed['required']) || Tools::strlen($valueDetailed['value'])) - { - $error = $this->_mondialrelay->l('This key').' ['.$paramName.'] '.$this->_mondialrelay->l('hasn\'t a valide value format').' : '.$valueDetailed['value']; - $id_order = $this->_getOrderIdWithExpeditionNumber($rootCase['list']['Expeditions']['value']); - $this->_resultList['error'][$id_order][] = $error; - } - } - $concatenationValue .= $this->_webServiceKey; - $rootCase['list']['Security']['value'] = Tools::strtoupper(md5($concatenationValue)); - } - } + private $_fields = array( + 'list' => array( + 'Enseigne' => array( + 'required' => true, + 'value' => '', + 'regexValidation' => '#^[0-9A-Z]{2}[0-9A-Z ]{6}$#'), + 'Expeditions' => array( + 'required' => true, + 'value' => '', + 'regexValidation' => '#^[0-9]{8}(;[0-9]{8})*$#'), + 'Langue' => array( + 'required' => true, + 'value' => '', + 'regexValidation' => '#^[A-Z]{2}$#'), + 'Security' => array( + 'required' => true, + 'value' => '', + 'regexValidation' => '#^[0-9A-Z]{32}$#'))); + + private $_detailedExpeditionList = array(); + private $_webServiceKey = ''; + private $_mondialrelay = null; + + private $_resultList = array( + 'error' => array(), + 'success' => array()); + + private $_webserviceURL; + + public function __construct($params, $object) + { + $this->_mondialrelay = $object; + $this->_detailedExpeditionList = $params['detailedExpeditionList']; + $this->_webServiceKey = $this->_mondialrelay->account_shop['MR_KEY_WEBSERVICE']; + $this->_webserviceURL = MondialRelay::MR_URL.'webservice/Web_Services.asmx?WSDL'; + } + + public function __destruct() + { + unset($this->_mondialrelay); + } + + public function init() + { + $this->_fields['list']['Enseigne']['value'] = $this->_mondialrelay->account_shop['MR_ENSEIGNE_WEBSERVICE']; + $this->_fields['list']['Langue']['value'] = $this->_mondialrelay->account_shop['MR_LANGUAGE']; + + foreach ($this->_detailedExpeditionList as $detailedExpedition) + { + // Storage temporary + $base = $this->_fields; + $tmp = &$base['list']; + + $tmp['Expeditions']['value'] = $detailedExpedition['expeditionNumber']; + $this->_fieldsList[] = $base; + } + $this->_generateMD5SecurityKey(); + } + + /* + * Generate the MD5 key for each param list + */ + private function _generateMD5SecurityKey() + { + // RootCase is the array case where the main information are stored + // it's an array containing id_mr_selected and an array with the necessary fields + foreach ($this->_fieldsList as &$rootCase) + { + $concatenationValue = ''; + foreach ($rootCase['list'] as $paramName => &$valueDetailed) + if ($paramName != 'Texte' && $paramName != 'Security') + { + $valueDetailed['value'] = Tools::strtoupper($valueDetailed['value']); + if (preg_match($valueDetailed['regexValidation'], $valueDetailed['value'], $matches)) + $concatenationValue .= $valueDetailed['value']; + elseif ((!Tools::strlen($valueDetailed['value']) && $valueDetailed['required']) || Tools::strlen($valueDetailed['value'])) + { + $error = $this->_mondialrelay->l('This key').' ['.$paramName.'] '.$this->_mondialrelay->l('hasn\'t a valide value format').' : '.$valueDetailed['value']; + $id_order = $this->_getOrderIdWithExpeditionNumber($rootCase['list']['Expeditions']['value']); + $this->_resultList['error'][$id_order][] = $error; + } + } + $concatenationValue .= $this->_webServiceKey; + $rootCase['list']['Security']['value'] = Tools::strtoupper(md5($concatenationValue)); + } + } - /* - * Get the values with associated fields name - * @fields : array containing multiple values information - */ - private function _getSimpleParamArray($fields) - { - $params = array(); - - foreach ($fields as $keyName => $valueDetailed) - $params[$keyName] = $valueDetailed['value']; - return $params; - } - - /* - * Update the history tables - */ - private function _updateTable($id_order, $expeditionNumber, $URLA4, $URLA5, &$success) - { - $query = ' - SELECT id FROM `'._DB_PREFIX_.'mr_history` - WHERE `order`='.(int)$id_order; - - $row = Db::getInstance()->getRow($query); - if ($row) - { - $query = ' - UPDATE `'._DB_PREFIX_.'mr_history` - SET - `exp` = \''.(int)$expeditionNumber.'\', - `url_a4` = \''.pSQL((string)$URLA4).'\', - `url_a5` = \''.pSQL((string)$URLA5).'\' - WHERE `order` = '.(int)$id_order; - } - else - { - $query = ' - INSERT INTO '._DB_PREFIX_.'mr_history - (`order`, `exp`, `url_a4`, `url_a5`) - VALUES ( - '.(int)$id_order.', - '.(int)$expeditionNumber.', - \''.pSQL((string)$URLA4).'\', - \''.pSQL((string)$URLA5).'\')'; - } - Db::getInstance()->execute($query); - $success['id_mr_history'] = isset($row['id']) ? $row['id'] : Db::getInstance()->Insert_ID(); - } - - /* - * Manage the return value of the webservice, handle the errors or build the - * succeed message - */ - private function _parseResult($client, $result, $params) - { - $errors = array(); - $success = array(); - - $id_order = $this->_getOrderIdWithExpeditionNumber($params['Expeditions']); - $result = $result->WSI2_GetEtiquettesResult; - if (($errorNumber = $result->STAT) != 0) - { - $errors[] = $this->_mondialrelay->l('There is an error number : ').$errorNumber; - $errors[] = $this->_mondialrelay->l('Details : '). - $this->_mondialrelay->getErrorCodeDetail($errorNumber); - } - else - { - $baseURL = 'http://www.mondialrelay.fr'; - $URLPDF_A4 = $baseURL.$result->URL_PDF_A4; - $URLPDF_A5 = $baseURL.$result->URL_PDF_A5; + /* + * Get the values with associated fields name + * @fields : array containing multiple values information + */ + private function _getSimpleParamArray($fields) + { + $params = array(); + + foreach ($fields as $keyName => $valueDetailed) + $params[$keyName] = $valueDetailed['value']; + return $params; + } + + /* + * Update the history tables + */ + private function _updateTable($id_order, $expeditionNumber, $URLA4, $URLA5, &$success) + { + $query = ' + SELECT id FROM `'._DB_PREFIX_.'mr_history` + WHERE `order`='.(int)$id_order; + + $row = Db::getInstance()->getRow($query); + if ($row) + { + $query = ' + UPDATE `'._DB_PREFIX_.'mr_history` + SET + `exp` = \''.(int)$expeditionNumber.'\', + `url_a4` = \''.pSQL((string)$URLA4).'\', + `url_a5` = \''.pSQL((string)$URLA5).'\' + WHERE `order` = '.(int)$id_order; + } + else + { + $query = ' + INSERT INTO '._DB_PREFIX_.'mr_history + (`order`, `exp`, `url_a4`, `url_a5`) + VALUES ( + '.(int)$id_order.', + '.(int)$expeditionNumber.', + \''.pSQL((string)$URLA4).'\', + \''.pSQL((string)$URLA5).'\')'; + } + Db::getInstance()->execute($query); + $success['id_mr_history'] = isset($row['id']) ? $row['id'] : Db::getInstance()->Insert_ID(); + } + + /* + * Manage the return value of the webservice, handle the errors or build the + * succeed message + */ + private function _parseResult($client, $result, $params) + { + $errors = array(); + $success = array(); + + $id_order = $this->_getOrderIdWithExpeditionNumber($params['Expeditions']); + $result = $result->WSI2_GetEtiquettesResult; + if (($errorNumber = $result->STAT) != 0) + { + $errors[] = $this->_mondialrelay->l('There is an error number : ').$errorNumber; + $errors[] = $this->_mondialrelay->l('Details : '). + $this->_mondialrelay->getErrorCodeDetail($errorNumber); + } + else + { + $baseURL = 'http://www.mondialrelay.fr'; + $URLPDF_A4 = $baseURL.$result->URL_PDF_A4; + $URLPDF_A5 = $baseURL.$result->URL_PDF_A5; - $success['id_order'] = $id_order; - $success['expeditionNumber'] = $params['Expeditions']; - $success['URLPDF_A4'] = $URLPDF_A4; - $success['URLPDF_A5'] = $URLPDF_A5; - $success['URLPDF_10x15'] = $baseURL.str_replace('format=A4', 'format=10x15', $result->URL_PDF_A4); - $this->_updateTable($id_order, $params['Expeditions'], $URLPDF_A4, $URLPDF_A5, $success); - } - $this->_resultList['error'][$id_order] = $errors; - $this->_resultList['success'][$id_order] = $success; - } - - /* - * Get the order id using the expedition number - */ - private function _getOrderIdWithExpeditionNumber($expeditionNumber) - { - foreach ($this->_detailedExpeditionList as $detailedExpedition) - if ($detailedExpedition['expeditionNumber'] == $expeditionNumber) - return $detailedExpedition['id_order']; - return 0; - } - - /* - * Send one or multiple request to the webservice - */ - public function send() - { - if ($client = new SoapClient($this->_webserviceURL)) - { - $client->soap_defencoding = 'UTF-8'; - $client->decode_utf8 = false; - - foreach ($this->_fieldsList as $rootCase) - { - $params = $this->_getSimpleParamArray($rootCase['list']); - $result = $client->WSI2_GetEtiquettes($params); - $this->_parseResult($client, $result, $params); - } - unset($client); - } - else - throw new Exception($this->_mondialrelay->l('The Mondial Relay webservice isn\'t currently reliable')); - } - - /* - * Get the values with associated fields name - */ - public function getFieldsList() - { - return $this->_fieldsList['list']; - } - - /* - * Get the result of one or multiple send request - */ - public function getResult() - { - return $this->_resultList; - } + $success['id_order'] = $id_order; + $success['expeditionNumber'] = $params['Expeditions']; + $success['URLPDF_A4'] = $URLPDF_A4; + $success['URLPDF_A5'] = $URLPDF_A5; + $success['URLPDF_10x15'] = $baseURL.str_replace('format=A4', 'format=10x15', $result->URL_PDF_A4); + $this->_updateTable($id_order, $params['Expeditions'], $URLPDF_A4, $URLPDF_A5, $success); + } + $this->_resultList['error'][$id_order] = $errors; + $this->_resultList['success'][$id_order] = $success; + } + + /* + * Get the order id using the expedition number + */ + private function _getOrderIdWithExpeditionNumber($expeditionNumber) + { + foreach ($this->_detailedExpeditionList as $detailedExpedition) + if ($detailedExpedition['expeditionNumber'] == $expeditionNumber) + return $detailedExpedition['id_order']; + return 0; + } + + /* + * Send one or multiple request to the webservice + */ + public function send() + { + if ($client = new SoapClient($this->_webserviceURL)) + { + $client->soap_defencoding = 'UTF-8'; + $client->decode_utf8 = false; + + foreach ($this->_fieldsList as $rootCase) + { + $params = $this->_getSimpleParamArray($rootCase['list']); + $result = $client->WSI2_GetEtiquettes($params); + $this->_parseResult($client, $result, $params); + } + unset($client); + } + else + throw new Exception($this->_mondialrelay->l('The Mondial Relay webservice isn\'t currently reliable')); + } + + /* + * Get the values with associated fields name + */ + public function getFieldsList() + { + return $this->_fieldsList['list']; + } + + /* + * Get the result of one or multiple send request + */ + public function getResult() + { + return $this->_resultList; + } } \ No newline at end of file diff --git a/classes/MRManagement.php b/classes/MRManagement.php old mode 100644 new mode 100755 index f7e28db..1702cb8 --- a/classes/MRManagement.php +++ b/classes/MRManagement.php @@ -29,142 +29,142 @@ class MRManagement extends MondialRelay { - private $_params = array(); - - private $_resultList = array( - 'error' => array(), - 'success' => array()); - - public function __construct($params) - { - $this->_params = $params; - - parent::__construct(); - } - - /* - ** This method fill the database with the selected carrier - */ - public function addSelectedCarrierToDB() - { - $db = Db::getInstance(); - // insutance - $sql = 'SELECT insurance FROM '._DB_PREFIX_.'mr_method WHERE id_mr_method = '.(int)$this->_params['id_mr_method']; - $insurance = $db->getValue($sql); - - $query = 'SELECT `id_mr_selected` FROM `'._DB_PREFIX_.'mr_selected` WHERE `id_cart` = '.(int)$this->_params['id_cart'].' '; + private $_params = array(); + + private $_resultList = array( + 'error' => array(), + 'success' => array()); + + public function __construct($params) + { + $this->_params = $params; + + parent::__construct(); + } + + /* + ** This method fill the database with the selected carrier + */ + public function addSelectedCarrierToDB() + { + $db = Db::getInstance(); + // insutance + $sql = 'SELECT insurance FROM '._DB_PREFIX_.'mr_method WHERE id_mr_method = '.(int)$this->_params['id_mr_method']; + $insurance = $db->getValue($sql); + + $query = 'SELECT `id_mr_selected` FROM `'._DB_PREFIX_.'mr_selected` WHERE `id_cart` = '.(int)$this->_params['id_cart'].' '; - // Not exist and needed for database - unset($this->_params['relayPointInfo']['permaLinkDetail']); - - // Update if Exist else add a new entry - if ($db->getRow($query)) - { - $query = 'UPDATE `'._DB_PREFIX_.'mr_selected` - SET `id_method` = '.(int)$this->_params['id_mr_method'].', - `MR_insurance` = '.(int)$insurance.','; - if (is_array($this->_params['relayPointInfo'])) - foreach ($this->_params['relayPointInfo'] as $nameKey => $value) - $query .= '`MR_Selected_'.MRTools::bqSQL($nameKey).'` = "'.pSQL($value).'", '; - else // Clean the existing relay point data - $query .= ' - MR_Selected_Num = NULL, - MR_Selected_LgAdr1 = NULL, - MR_Selected_LgAdr2 = NULL, - MR_Selected_LgAdr3 = NULL, - MR_Selected_LgAdr4 = NULL, - MR_Selected_CP = NULL, - MR_Selected_Pays = NULL, - MR_Selected_Ville = NULL, '; - $query = rtrim($query, ', ').' WHERE `id_cart` = '.(int)$this->_params['id_cart']; - } - else - { - $query = 'INSERT INTO `'._DB_PREFIX_.'mr_selected` - (`id_customer`, `id_method`, `id_cart`, MR_insurance, '; - if (is_array($this->_params['relayPointInfo'])) - foreach ($this->_params['relayPointInfo'] as $nameKey => $value) - $query .= '`MR_Selected_'.MRTools::bqSQL($nameKey).'`, '; - $query = rtrim($query, ', ').') VALUES ( - '.(int)$this->_params['id_customer'].', - '.(int)$this->_params['id_mr_method'].', - '.(int)$this->_params['id_cart'].', - '.(int)$insurance.', '; + // Not exist and needed for database + unset($this->_params['relayPointInfo']['permaLinkDetail']); + + // Update if Exist else add a new entry + if ($db->getRow($query)) + { + $query = 'UPDATE `'._DB_PREFIX_.'mr_selected` + SET `id_method` = '.(int)$this->_params['id_mr_method'].', + `MR_insurance` = '.(int)$insurance.','; + if (is_array($this->_params['relayPointInfo'])) + foreach ($this->_params['relayPointInfo'] as $nameKey => $value) + $query .= '`MR_Selected_'.MRTools::bqSQL($nameKey).'` = "'.pSQL($value).'", '; + else // Clean the existing relay point data + $query .= ' + MR_Selected_Num = NULL, + MR_Selected_LgAdr1 = NULL, + MR_Selected_LgAdr2 = NULL, + MR_Selected_LgAdr3 = NULL, + MR_Selected_LgAdr4 = NULL, + MR_Selected_CP = NULL, + MR_Selected_Pays = NULL, + MR_Selected_Ville = NULL, '; + $query = rtrim($query, ', ').' WHERE `id_cart` = '.(int)$this->_params['id_cart']; + } + else + { + $query = 'INSERT INTO `'._DB_PREFIX_.'mr_selected` + (`id_customer`, `id_method`, `id_cart`, MR_insurance, '; + if (is_array($this->_params['relayPointInfo'])) + foreach ($this->_params['relayPointInfo'] as $nameKey => $value) + $query .= '`MR_Selected_'.MRTools::bqSQL($nameKey).'`, '; + $query = rtrim($query, ', ').') VALUES ( + '.(int)$this->_params['id_customer'].', + '.(int)$this->_params['id_mr_method'].', + '.(int)$this->_params['id_cart'].', + '.(int)$insurance.', '; - if (is_array($this->_params['relayPointInfo'])) - foreach ($this->_params['relayPointInfo'] as $nameKey => $value) - $query .= '"'.pSQL($value).'", '; - $query = rtrim($query, ', ').')'; - } - $db->execute($query); - } + if (is_array($this->_params['relayPointInfo'])) + foreach ($this->_params['relayPointInfo'] as $nameKey => $value) + $query .= '"'.pSQL($value).'", '; + $query = rtrim($query, ', ').')'; + } + $db->execute($query); + } - public function uninstallDetail() - { - $html = ''; - - switch ($this->_params['action']) - { - case 'showFancy': - $html .= ' -
-

'.$this->l('Uninstalling Mondial Relay').'

-
- '.$this->l('You\'re about to uninstall the module, do you want to remove the database').' ? -

- -
- -
- -
-

-
-
- '; - $this->_resultList['html'] = $html; - break; - case 'backupAndUninstall': - - break; - default: - } - return $this->_resultList; - } + public function uninstallDetail() + { + $html = ''; + + switch ($this->_params['action']) + { + case 'showFancy': + $html .= ' +
+

'.$this->l('Uninstalling Mondial Relay').'

+
+ '.$this->l('You\'re about to uninstall the module, do you want to remove the database').' ? +

+ +
+ +
+ +
+

+
+
+ '; + $this->_resultList['html'] = $html; + break; + case 'backupAndUninstall': + + break; + default: + } + return $this->_resultList; + } - public function DeleteHistory() - { - $success = array(); - $error = array(); - - if (is_array($this->_params['historyIdList']) && count($this->_params['historyIdList'])) - { - $query = ' - DELETE FROM `'._DB_PREFIX_.'mr_history` - WHERE id IN('; - foreach ($this->_params['historyIdList'] as $id) - $query .= (int)$id.', '; - $query = trim($query, ', ').')'; - - $success['deletedListId'] = $this->_params['historyIdList']; - $totalDeleted = Db::getInstance()->execute($query); - if (count($success['deletedListId']) != $totalDeleted) - { - $error[] = $this->l('Some items can\'t be removed, please try to remove it again'); - foreach ($success['deletedListId'] as $id) - { - $query = ' - SELECT id FROM `'._DB_PREFIX_.'mr_history` - WHERE id='.(int)$id; - if (Db::getInstance()->getRow($query) && ($key = array_search($id, $success['deletedListId'])) !== false) - unset($success['deletedListId'][$key]); - } - } - $this->_resultList['success'] = $success; - $this->_resultList['other']['error'] = $error; - } - else - throw new Exception($this->l('Please select at least one history element')); - return $this->_resultList; - } + public function DeleteHistory() + { + $success = array(); + $error = array(); + + if (is_array($this->_params['historyIdList']) && count($this->_params['historyIdList'])) + { + $query = ' + DELETE FROM `'._DB_PREFIX_.'mr_history` + WHERE id IN('; + foreach ($this->_params['historyIdList'] as $id) + $query .= (int)$id.', '; + $query = trim($query, ', ').')'; + + $success['deletedListId'] = $this->_params['historyIdList']; + $totalDeleted = Db::getInstance()->execute($query); + if (count($success['deletedListId']) != $totalDeleted) + { + $error[] = $this->l('Some items can\'t be removed, please try to remove it again'); + foreach ($success['deletedListId'] as $id) + { + $query = ' + SELECT id FROM `'._DB_PREFIX_.'mr_history` + WHERE id='.(int)$id; + if (Db::getInstance()->getRow($query) && ($key = array_search($id, $success['deletedListId'])) !== false) + unset($success['deletedListId'][$key]); + } + } + $this->_resultList['success'] = $success; + $this->_resultList['other']['error'] = $error; + } + else + throw new Exception($this->l('Please select at least one history element')); + return $this->_resultList; + } } \ No newline at end of file diff --git a/classes/MRRelayDetail.php b/classes/MRRelayDetail.php old mode 100644 new mode 100755 index 1d2ab9b..412ce84 --- a/classes/MRRelayDetail.php +++ b/classes/MRRelayDetail.php @@ -35,231 +35,231 @@ */ class MRRelayDetail implements IMondialRelayWSMethod { - private $_fields = array( - 'list' => array( - 'Enseigne' => array( - 'required' => true, - 'value' => '', - 'regexValidation' => '#^[0-9A-Z]{2}[0-9A-Z ]{6}$#'), - 'Num' => array( - 'required' => true, - 'value' => '', - 'regexValidation' => '#^[0-9]{6}$#'), - 'Pays' => array( - 'required' => true, - 'value' => '', - 'regexValidation' => '#^[A-Z]{2}$#'), - 'Security' => array( - 'required' => true, - 'value' => '', - 'regexValidation' => '#^[0-9A-Z]{32}$#'))); - - private $_relayPointNumList = array(); - private $_id_address_delivery = 0; - private $_webServiceKey = ''; - private $_mondialrelay = null; - private $_markCode = ''; - - private $_resultList = array( - 'error' => array(), - 'success' => array()); - - private $_webserviceURL = ''; - - public function __construct($params, $object) - { - $this->_mondialrelay = $object; + private $_fields = array( + 'list' => array( + 'Enseigne' => array( + 'required' => true, + 'value' => '', + 'regexValidation' => '#^[0-9A-Z]{2}[0-9A-Z ]{6}$#'), + 'Num' => array( + 'required' => true, + 'value' => '', + 'regexValidation' => '#^[0-9]{6}$#'), + 'Pays' => array( + 'required' => true, + 'value' => '', + 'regexValidation' => '#^[A-Z]{2}$#'), + 'Security' => array( + 'required' => true, + 'value' => '', + 'regexValidation' => '#^[0-9A-Z]{32}$#'))); + + private $_relayPointNumList = array(); + private $_id_address_delivery = 0; + private $_webServiceKey = ''; + private $_mondialrelay = null; + private $_markCode = ''; + + private $_resultList = array( + 'error' => array(), + 'success' => array()); + + private $_webserviceURL = ''; + + public function __construct($params, $object) + { + $this->_mondialrelay = $object; - $this->_relayPointNumList = $params['relayPointNumList']; - $this->_id_address_delivery = (int)($params['id_address_delivery']); - $this->_webServiceKey = $this->_mondialRelay->account_shop['MR_KEY_WEBSERVICE']; - $this->_markCode = $this->_mondialRelay->account_shop['MR_CODE_MARQUE']; - $this->_webserviceURL = MondialRelay::MR_URL.'webservice/Web_Services.asmx?WSDL'; - } - - public function __destruct() - { - unset($this->_mondialrelay); - } - - public function init() - { - $address = new Address($this->_id_address_delivery); - - if (!$address) - throw new Exception($this->_mondialrelay->l('Customer address can\'t be found')); - - $this->_fields['list']['Enseigne']['value'] = $this->_mondialRelay->account_shop['MR_ENSEIGNE_WEBSERVICE']; - $this->_fields['list']['Pays']['value'] = Country::getIsoById($address->id_country); - - foreach ($this->_relayPointNumList as $num) - { - // Storage temporary - $base = $this->_fields; - $tmp = &$base['list']; - - $tmp['Num']['value'] = $num; - $this->_fieldsList[] = $base; - } - $this->_generateMD5SecurityKey(); - unset($address); - } - - /* - * Generate the MD5 key for each param list - */ - private function _generateMD5SecurityKey() - { - // RootCase is the array case where the main information are stored - // it's an array containing id_mr_selected and an array with the necessary fields - foreach ($this->_fieldsList as &$rootCase) - { - $concatenationValue = ''; - foreach ($rootCase['list'] as $paramName => &$valueDetailed) - if ($paramName != 'Texte' && $paramName != 'Security') - { - // Mac server make an empty string instead of a cleaned string - // TODO : test on windows and linux server - $cleanedString = MRTools::removeAccents($valueDetailed['value']); - $valueDetailed['value'] = !empty($cleanedString) ? Tools::strtoupper($cleanedString) : Tools::strtoupper($valueDetailed['value']); - - // Call a pointer function if exist to do different test - if (isset($valueDetailed['methodValidation']) && method_exists('MRTools', $valueDetailed['methodValidation']) && isset($valueDetailed['params']) && MRTools::$valueDetailed['methodValidation']($valueDetailed['value'], $valueDetailed['params'])) - $concatenationValue .= $valueDetailed['value']; - // Use simple Regex test given by MondialRelay - else if (isset($valueDetailed['regexValidation']) && preg_match($valueDetailed['regexValidation'], $valueDetailed['value'], $matches)) - $concatenationValue .= $valueDetailed['value']; - // If the key is required, we set an error, else it's skipped - elseif ((!Tools::strlen($valueDetailed['value']) && $valueDetailed['required']) || Tools::strlen($valueDetailed['value'])) - { - if (empty($valueDetailed['value'])) - $error = $this->_mondialrelay->l('This key').' ['.$paramName.'] '.$this->_mondialrelay->l('is empty and need to be filled'); - else - $error = 'This key ['.$paramName.'] hasn\'t a valid value format : '.$valueDetailed['value']; - $this->_resultList['error'][$rootCase['list']['Num']['value']] = $error; - } - } - $concatenationValue .= $this->_webServiceKey; - $rootCase['list']['Security']['value'] = Tools::strtoupper(md5($concatenationValue)); - } - } + $this->_relayPointNumList = $params['relayPointNumList']; + $this->_id_address_delivery = (int)($params['id_address_delivery']); + $this->_webServiceKey = $this->_mondialRelay->account_shop['MR_KEY_WEBSERVICE']; + $this->_markCode = $this->_mondialRelay->account_shop['MR_CODE_MARQUE']; + $this->_webserviceURL = MondialRelay::MR_URL.'webservice/Web_Services.asmx?WSDL'; + } + + public function __destruct() + { + unset($this->_mondialrelay); + } + + public function init() + { + $address = new Address($this->_id_address_delivery); + + if (!$address) + throw new Exception($this->_mondialrelay->l('Customer address can\'t be found')); + + $this->_fields['list']['Enseigne']['value'] = $this->_mondialRelay->account_shop['MR_ENSEIGNE_WEBSERVICE']; + $this->_fields['list']['Pays']['value'] = Country::getIsoById($address->id_country); + + foreach ($this->_relayPointNumList as $num) + { + // Storage temporary + $base = $this->_fields; + $tmp = &$base['list']; + + $tmp['Num']['value'] = $num; + $this->_fieldsList[] = $base; + } + $this->_generateMD5SecurityKey(); + unset($address); + } + + /* + * Generate the MD5 key for each param list + */ + private function _generateMD5SecurityKey() + { + // RootCase is the array case where the main information are stored + // it's an array containing id_mr_selected and an array with the necessary fields + foreach ($this->_fieldsList as &$rootCase) + { + $concatenationValue = ''; + foreach ($rootCase['list'] as $paramName => &$valueDetailed) + if ($paramName != 'Texte' && $paramName != 'Security') + { + // Mac server make an empty string instead of a cleaned string + // TODO : test on windows and linux server + $cleanedString = MRTools::removeAccents($valueDetailed['value']); + $valueDetailed['value'] = !empty($cleanedString) ? Tools::strtoupper($cleanedString) : Tools::strtoupper($valueDetailed['value']); + + // Call a pointer function if exist to do different test + if (isset($valueDetailed['methodValidation']) && method_exists('MRTools', $valueDetailed['methodValidation']) && isset($valueDetailed['params']) && MRTools::$valueDetailed['methodValidation']($valueDetailed['value'], $valueDetailed['params'])) + $concatenationValue .= $valueDetailed['value']; + // Use simple Regex test given by MondialRelay + else if (isset($valueDetailed['regexValidation']) && preg_match($valueDetailed['regexValidation'], $valueDetailed['value'], $matches)) + $concatenationValue .= $valueDetailed['value']; + // If the key is required, we set an error, else it's skipped + elseif ((!Tools::strlen($valueDetailed['value']) && $valueDetailed['required']) || Tools::strlen($valueDetailed['value'])) + { + if (empty($valueDetailed['value'])) + $error = $this->_mondialrelay->l('This key').' ['.$paramName.'] '.$this->_mondialrelay->l('is empty and need to be filled'); + else + $error = 'This key ['.$paramName.'] hasn\'t a valid value format : '.$valueDetailed['value']; + $this->_resultList['error'][$rootCase['list']['Num']['value']] = $error; + } + } + $concatenationValue .= $this->_webServiceKey; + $rootCase['list']['Security']['value'] = Tools::strtoupper(md5($concatenationValue)); + } + } - /* - * Get the values with associated fields name - * @fields : array containing multiple values information - */ - private function _getSimpleParamArray($fields) - { - $params = array(); - - foreach ($fields as $keyName => $valueDetailed) - $params[$keyName] = $valueDetailed['value']; - return $params; - } - - /* - * Manage the return value of the webservice, handle the errors or build the - * succeed message - */ - private function _parseResult($client, $result, $params) - { - $errors = array(); - $result = $result->WSI2_DetailPointRelaisResult; - if (($errorNumber = $result->STAT) != 0) - { - $errors[] = $this->_mondialrelay->l('There is an error number : ').$errorNumber; - $errors[] = $this->_mondialrelay->l('Details : '). - $this->_mondialrelay->getErrorCodeDetail($errorNumber); - } - else - { - $HDayList = array( - 'Horaires_Lundi' => $this->_mondialrelay->l('Monday'), - 'Horaires_Mardi' => $this->_mondialrelay->l('Tuesday'), - 'Horaires_Mercredi' => $this->_mondialrelay->l('Wednesday'), - 'Horaires_Jeudi' => $this->_mondialrelay->l('Thursday'), - 'Horaires_Vendredi' => $this->_mondialrelay->l('Friday'), - 'Horaires_Samedi' => $this->_mondialrelay->l('Saturday'), - 'Horaires_Dimanche' => $this->_mondialrelay->l('Sunday')); - - $orderedDate = array(); - // Format hour properly - $priority = 0; - foreach ($HDayList as $day => $tradDayName) - { - $mr_day = $result->{$day}; - foreach ($mr_day['string'] as &$value) - if ($value == '0000') - $value = ''; - else - $value = implode('h', str_split($value, 2)); - $orderedDate[$priority++] = array('name' => $tradDayName, 'list' => $mr_day); - unset($result[$day]); - } - $result->orderedDate = $orderedDate; - $this->_resultList['success'][$result->Num] = $result; - } - $this->_resultList['error'][] = $errors; - } - - /* - * Send one or multiple request to the webservice - */ - public function send() - { - if ($client = new SoapClient($this->_webserviceURL)) - { - $client->soap_defencoding = 'UTF-8'; - $client->decode_utf8 = false; - - foreach ($this->_fieldsList as $rootCase) - { - $params = $this->_getSimpleParamArray($rootCase['list']); - $result = $client->WSI2_DetailPointRelais($params); - $this->_parseResult($client, $result, $params); - } - unset($client); - } - else - throw new Exception($this->_mondialrelay->l('The Mondial Relay webservice isn\'t currently reliable')); - } - - /* - ** Generate a list of perma link - */ - public static function getPermaLink($relayList, $id_address_delivery) - { - if (!($address = new Address($id_address_delivery))) - return array(); + /* + * Get the values with associated fields name + * @fields : array containing multiple values information + */ + private function _getSimpleParamArray($fields) + { + $params = array(); + + foreach ($fields as $keyName => $valueDetailed) + $params[$keyName] = $valueDetailed['value']; + return $params; + } + + /* + * Manage the return value of the webservice, handle the errors or build the + * succeed message + */ + private function _parseResult($client, $result, $params) + { + $errors = array(); + $result = $result->WSI2_DetailPointRelaisResult; + if (($errorNumber = $result->STAT) != 0) + { + $errors[] = $this->_mondialrelay->l('There is an error number : ').$errorNumber; + $errors[] = $this->_mondialrelay->l('Details : '). + $this->_mondialrelay->getErrorCodeDetail($errorNumber); + } + else + { + $HDayList = array( + 'Horaires_Lundi' => $this->_mondialrelay->l('Monday'), + 'Horaires_Mardi' => $this->_mondialrelay->l('Tuesday'), + 'Horaires_Mercredi' => $this->_mondialrelay->l('Wednesday'), + 'Horaires_Jeudi' => $this->_mondialrelay->l('Thursday'), + 'Horaires_Vendredi' => $this->_mondialrelay->l('Friday'), + 'Horaires_Samedi' => $this->_mondialrelay->l('Saturday'), + 'Horaires_Dimanche' => $this->_mondialrelay->l('Sunday')); + + $orderedDate = array(); + // Format hour properly + $priority = 0; + foreach ($HDayList as $day => $tradDayName) + { + $mr_day = $result->{$day}; + foreach ($mr_day['string'] as &$value) + if ($value == '0000') + $value = ''; + else + $value = implode('h', str_split($value, 2)); + $orderedDate[$priority++] = array('name' => $tradDayName, 'list' => $mr_day); + unset($result[$day]); + } + $result->orderedDate = $orderedDate; + $this->_resultList['success'][$result->Num] = $result; + } + $this->_resultList['error'][] = $errors; + } + + /* + * Send one or multiple request to the webservice + */ + public function send() + { + if ($client = new SoapClient($this->_webserviceURL)) + { + $client->soap_defencoding = 'UTF-8'; + $client->decode_utf8 = false; + + foreach ($this->_fieldsList as $rootCase) + { + $params = $this->_getSimpleParamArray($rootCase['list']); + $result = $client->WSI2_DetailPointRelais($params); + $this->_parseResult($client, $result, $params); + } + unset($client); + } + else + throw new Exception($this->_mondialrelay->l('The Mondial Relay webservice isn\'t currently reliable')); + } + + /* + ** Generate a list of perma link + */ + public static function getPermaLink($relayList, $id_address_delivery) + { + if (!($address = new Address($id_address_delivery))) + return array(); - $mondialrelay = new MondialRelay(); - - $list = array(); - $iso = Tools::strtoupper(Country::getIsoById($address->id_country)); - $ens = $mondialrelay->account_shop['MR_ENSEIGNE_WEBSERVICE'].$mondialrelay->account_shop['MR_CODE_MARQUE']; - $url = 'http://www.mondialrelay.com/public/permanent/details_relais.aspx?ens='.$ens; - foreach ($relayList as $relayNum) - { - $crc = Tools::strtoupper(md5('<'.Tools::strtoupper($ens).'>'.$relayNum.$iso.'<'.$mondialrelay->account_shop['MR_KEY_WEBSERVICE'].'>')); - $list[$relayNum] = $url.'&num='.$relayNum.'&pays='.$iso.'&crc='.$crc; - } - unset($address, $mondialrelay); - return $list; - } - - /* - * Get the values with associated fields name - */ - public function getFieldsList() - { - return $this->_fieldsList['list']; - } - - /* - * Get the result of one or multiple send request - */ - public function getResult() - { - return $this->_resultList; - } + $mondialrelay = new MondialRelay(); + + $list = array(); + $iso = Tools::strtoupper(Country::getIsoById($address->id_country)); + $ens = $mondialrelay->account_shop['MR_ENSEIGNE_WEBSERVICE'].$mondialrelay->account_shop['MR_CODE_MARQUE']; + $url = 'http://www.mondialrelay.com/public/permanent/details_relais.aspx?ens='.$ens; + foreach ($relayList as $relayNum) + { + $crc = Tools::strtoupper(md5('<'.Tools::strtoupper($ens).'>'.$relayNum.$iso.'<'.$mondialrelay->account_shop['MR_KEY_WEBSERVICE'].'>')); + $list[$relayNum] = $url.'&num='.$relayNum.'&pays='.$iso.'&crc='.$crc; + } + unset($address, $mondialrelay); + return $list; + } + + /* + * Get the values with associated fields name + */ + public function getFieldsList() + { + return $this->_fieldsList['list']; + } + + /* + * Get the result of one or multiple send request + */ + public function getResult() + { + return $this->_resultList; + } } \ No newline at end of file diff --git a/classes/MRTools.php b/classes/MRTools.php old mode 100644 new mode 100755 index 0747560..1ff2999 --- a/classes/MRTools.php +++ b/classes/MRTools.php @@ -30,241 +30,241 @@ */ class MRTools { - const REGEX_CLEAN_ADDR = '/[^a-zA-Z0-9-\s\'\!\,\|\(\)\.\*\&\#\/\:]/'; + const REGEX_CLEAN_ADDR = '/[^a-zA-Z0-9-\s\'\!\,\|\(\)\.\*\&\#\/\:]/'; - const REGEX_CLEAN_PHONE = '/[^0-9+\(\)]*/'; + const REGEX_CLEAN_PHONE = '/[^0-9+\(\)]*/'; - /** - * Check if a string could be UTF8 one - * - * @static - * @param $str - * @return bool - */ - public static function seemsUTF8($str) - { - $length = strlen($str); + /** + * Check if a string could be UTF8 one + * + * @static + * @param $str + * @return bool + */ + public static function seemsUTF8($str) + { + $length = strlen($str); - for ($i = 0; $i < $length; $i++) - { - $c = ord($str[$i]); - if ($c < 0x80) - $n = 0; # 0bbbbbbb - else if (($c & 0xE0) == 0xC0) - $n = 1; # 110bbbbb - else if (($c & 0xF0) == 0xE0) - $n = 2; # 1110bbbb - else if (($c & 0xF8) == 0xF0) - $n = 3; # 11110bbb - else if (($c & 0xFC) == 0xF8) - $n = 4; # 111110bb - else if (($c & 0xFE) == 0xFC) - $n = 5; # 1111110b - else - return false; # Does not match any model - for ($j = 0; $j < $n; $j++) - { - # n bytes matching 10bbbbbb follow ? - if ((++$i == $length) || ((ord($str[$i]) & 0xC0) != 0x80)) - return false; - } - } - return true; - } + for ($i = 0; $i < $length; $i++) + { + $c = ord($str[$i]); + if ($c < 0x80) + $n = 0; # 0bbbbbbb + else if (($c & 0xE0) == 0xC0) + $n = 1; # 110bbbbb + else if (($c & 0xF0) == 0xE0) + $n = 2; # 1110bbbb + else if (($c & 0xF8) == 0xF0) + $n = 3; # 11110bbb + else if (($c & 0xFC) == 0xF8) + $n = 4; # 111110bb + else if (($c & 0xFE) == 0xFC) + $n = 5; # 1111110b + else + return false; # Does not match any model + for ($j = 0; $j < $n; $j++) + { + # n bytes matching 10bbbbbb follow ? + if ((++$i == $length) || ((ord($str[$i]) & 0xC0) != 0x80)) + return false; + } + } + return true; + } - /** - * Converts all accent characters to ASCII characters. - * - * If there are no accent characters, then the string given is just returned. - * - * @param string $string Text that might have accent characters - * @return string Filtered string with replaced "nice" characters. - */ - public static function removeAccents($string) - { - if (!preg_match('/[\x80-\xff]/', $string)) - return $string; + /** + * Converts all accent characters to ASCII characters. + * + * If there are no accent characters, then the string given is just returned. + * + * @param string $string Text that might have accent characters + * @return string Filtered string with replaced "nice" characters. + */ + public static function removeAccents($string) + { + if (!preg_match('/[\x80-\xff]/', $string)) + return $string; - if (MRTools::seemsUTF8($string)) - { - $chars = array( - // Decompositions for Latin-1 Supplement - chr(195).chr(128) => 'A', chr(195).chr(129) => 'A', - chr(195).chr(130) => 'A', chr(195).chr(131) => 'A', - chr(195).chr(132) => 'A', chr(195).chr(133) => 'A', - chr(195).chr(135) => 'C', chr(195).chr(136) => 'E', - chr(195).chr(137) => 'E', chr(195).chr(138) => 'E', - chr(195).chr(139) => 'E', chr(195).chr(140) => 'I', - chr(195).chr(141) => 'I', chr(195).chr(142) => 'I', - chr(195).chr(143) => 'I', chr(195).chr(145) => 'N', - chr(195).chr(146) => 'O', chr(195).chr(147) => 'O', - chr(195).chr(148) => 'O', chr(195).chr(149) => 'O', - chr(195).chr(150) => 'O', chr(195).chr(153) => 'U', - chr(195).chr(154) => 'U', chr(195).chr(155) => 'U', - chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y', - chr(195).chr(159) => 's', chr(195).chr(160) => 'a', - chr(195).chr(161) => 'a', chr(195).chr(162) => 'a', - chr(195).chr(163) => 'a', chr(195).chr(164) => 'a', - chr(195).chr(165) => 'a', chr(195).chr(167) => 'c', - chr(195).chr(168) => 'e', chr(195).chr(169) => 'e', - chr(195).chr(170) => 'e', chr(195).chr(171) => 'e', - chr(195).chr(172) => 'i', chr(195).chr(173) => 'i', - chr(195).chr(174) => 'i', chr(195).chr(175) => 'i', - chr(195).chr(177) => 'n', chr(195).chr(178) => 'o', - chr(195).chr(179) => 'o', chr(195).chr(180) => 'o', - chr(195).chr(181) => 'o', chr(195).chr(182) => 'o', - chr(195).chr(182) => 'o', chr(195).chr(185) => 'u', - chr(195).chr(186) => 'u', chr(195).chr(187) => 'u', - chr(195).chr(188) => 'u', chr(195).chr(189) => 'y', - chr(195).chr(191) => 'y', - // Decompositions for Latin Extended-A - chr(196).chr(128) => 'A', chr(196).chr(129) => 'a', - chr(196).chr(130) => 'A', chr(196).chr(131) => 'a', - chr(196).chr(132) => 'A', chr(196).chr(133) => 'a', - chr(196).chr(134) => 'C', chr(196).chr(135) => 'c', - chr(196).chr(136) => 'C', chr(196).chr(137) => 'c', - chr(196).chr(138) => 'C', chr(196).chr(139) => 'c', - chr(196).chr(140) => 'C', chr(196).chr(141) => 'c', - chr(196).chr(142) => 'D', chr(196).chr(143) => 'd', - chr(196).chr(144) => 'D', chr(196).chr(145) => 'd', - chr(196).chr(146) => 'E', chr(196).chr(147) => 'e', - chr(196).chr(148) => 'E', chr(196).chr(149) => 'e', - chr(196).chr(150) => 'E', chr(196).chr(151) => 'e', - chr(196).chr(152) => 'E', chr(196).chr(153) => 'e', - chr(196).chr(154) => 'E', chr(196).chr(155) => 'e', - chr(196).chr(156) => 'G', chr(196).chr(157) => 'g', - chr(196).chr(158) => 'G', chr(196).chr(159) => 'g', - chr(196).chr(160) => 'G', chr(196).chr(161) => 'g', - chr(196).chr(162) => 'G', chr(196).chr(163) => 'g', - chr(196).chr(164) => 'H', chr(196).chr(165) => 'h', - chr(196).chr(166) => 'H', chr(196).chr(167) => 'h', - chr(196).chr(168) => 'I', chr(196).chr(169) => 'i', - chr(196).chr(170) => 'I', chr(196).chr(171) => 'i', - chr(196).chr(172) => 'I', chr(196).chr(173) => 'i', - chr(196).chr(174) => 'I', chr(196).chr(175) => 'i', - chr(196).chr(176) => 'I', chr(196).chr(177) => 'i', - chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij', - chr(196).chr(180) => 'J', chr(196).chr(181) => 'j', - chr(196).chr(182) => 'K', chr(196).chr(183) => 'k', - chr(196).chr(184) => 'k', chr(196).chr(185) => 'L', - chr(196).chr(186) => 'l', chr(196).chr(187) => 'L', - chr(196).chr(188) => 'l', chr(196).chr(189) => 'L', - chr(196).chr(190) => 'l', chr(196).chr(191) => 'L', - chr(197).chr(128) => 'l', chr(197).chr(129) => 'L', - chr(197).chr(130) => 'l', chr(197).chr(131) => 'N', - chr(197).chr(132) => 'n', chr(197).chr(133) => 'N', - chr(197).chr(134) => 'n', chr(197).chr(135) => 'N', - chr(197).chr(136) => 'n', chr(197).chr(137) => 'N', - chr(197).chr(138) => 'n', chr(197).chr(139) => 'N', - chr(197).chr(140) => 'O', chr(197).chr(141) => 'o', - chr(197).chr(142) => 'O', chr(197).chr(143) => 'o', - chr(197).chr(144) => 'O', chr(197).chr(145) => 'o', - chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe', - chr(197).chr(148) => 'R',chr(197).chr(149) => 'r', - chr(197).chr(150) => 'R',chr(197).chr(151) => 'r', - chr(197).chr(152) => 'R',chr(197).chr(153) => 'r', - chr(197).chr(154) => 'S',chr(197).chr(155) => 's', - chr(197).chr(156) => 'S',chr(197).chr(157) => 's', - chr(197).chr(158) => 'S',chr(197).chr(159) => 's', - chr(197).chr(160) => 'S', chr(197).chr(161) => 's', - chr(197).chr(162) => 'T', chr(197).chr(163) => 't', - chr(197).chr(164) => 'T', chr(197).chr(165) => 't', - chr(197).chr(166) => 'T', chr(197).chr(167) => 't', - chr(197).chr(168) => 'U', chr(197).chr(169) => 'u', - chr(197).chr(170) => 'U', chr(197).chr(171) => 'u', - chr(197).chr(172) => 'U', chr(197).chr(173) => 'u', - chr(197).chr(174) => 'U', chr(197).chr(175) => 'u', - chr(197).chr(176) => 'U', chr(197).chr(177) => 'u', - chr(197).chr(178) => 'U', chr(197).chr(179) => 'u', - chr(197).chr(180) => 'W', chr(197).chr(181) => 'w', - chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y', - chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z', - chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z', - chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z', - chr(197).chr(190) => 'z', chr(197).chr(191) => 's', - // Euro Sign - chr(226).chr(130).chr(172) => 'E', - // GBP (Pound) Sign - chr(194).chr(163) => ''); + if (MRTools::seemsUTF8($string)) + { + $chars = array( + // Decompositions for Latin-1 Supplement + chr(195).chr(128) => 'A', chr(195).chr(129) => 'A', + chr(195).chr(130) => 'A', chr(195).chr(131) => 'A', + chr(195).chr(132) => 'A', chr(195).chr(133) => 'A', + chr(195).chr(135) => 'C', chr(195).chr(136) => 'E', + chr(195).chr(137) => 'E', chr(195).chr(138) => 'E', + chr(195).chr(139) => 'E', chr(195).chr(140) => 'I', + chr(195).chr(141) => 'I', chr(195).chr(142) => 'I', + chr(195).chr(143) => 'I', chr(195).chr(145) => 'N', + chr(195).chr(146) => 'O', chr(195).chr(147) => 'O', + chr(195).chr(148) => 'O', chr(195).chr(149) => 'O', + chr(195).chr(150) => 'O', chr(195).chr(153) => 'U', + chr(195).chr(154) => 'U', chr(195).chr(155) => 'U', + chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y', + chr(195).chr(159) => 's', chr(195).chr(160) => 'a', + chr(195).chr(161) => 'a', chr(195).chr(162) => 'a', + chr(195).chr(163) => 'a', chr(195).chr(164) => 'a', + chr(195).chr(165) => 'a', chr(195).chr(167) => 'c', + chr(195).chr(168) => 'e', chr(195).chr(169) => 'e', + chr(195).chr(170) => 'e', chr(195).chr(171) => 'e', + chr(195).chr(172) => 'i', chr(195).chr(173) => 'i', + chr(195).chr(174) => 'i', chr(195).chr(175) => 'i', + chr(195).chr(177) => 'n', chr(195).chr(178) => 'o', + chr(195).chr(179) => 'o', chr(195).chr(180) => 'o', + chr(195).chr(181) => 'o', chr(195).chr(182) => 'o', + chr(195).chr(182) => 'o', chr(195).chr(185) => 'u', + chr(195).chr(186) => 'u', chr(195).chr(187) => 'u', + chr(195).chr(188) => 'u', chr(195).chr(189) => 'y', + chr(195).chr(191) => 'y', + // Decompositions for Latin Extended-A + chr(196).chr(128) => 'A', chr(196).chr(129) => 'a', + chr(196).chr(130) => 'A', chr(196).chr(131) => 'a', + chr(196).chr(132) => 'A', chr(196).chr(133) => 'a', + chr(196).chr(134) => 'C', chr(196).chr(135) => 'c', + chr(196).chr(136) => 'C', chr(196).chr(137) => 'c', + chr(196).chr(138) => 'C', chr(196).chr(139) => 'c', + chr(196).chr(140) => 'C', chr(196).chr(141) => 'c', + chr(196).chr(142) => 'D', chr(196).chr(143) => 'd', + chr(196).chr(144) => 'D', chr(196).chr(145) => 'd', + chr(196).chr(146) => 'E', chr(196).chr(147) => 'e', + chr(196).chr(148) => 'E', chr(196).chr(149) => 'e', + chr(196).chr(150) => 'E', chr(196).chr(151) => 'e', + chr(196).chr(152) => 'E', chr(196).chr(153) => 'e', + chr(196).chr(154) => 'E', chr(196).chr(155) => 'e', + chr(196).chr(156) => 'G', chr(196).chr(157) => 'g', + chr(196).chr(158) => 'G', chr(196).chr(159) => 'g', + chr(196).chr(160) => 'G', chr(196).chr(161) => 'g', + chr(196).chr(162) => 'G', chr(196).chr(163) => 'g', + chr(196).chr(164) => 'H', chr(196).chr(165) => 'h', + chr(196).chr(166) => 'H', chr(196).chr(167) => 'h', + chr(196).chr(168) => 'I', chr(196).chr(169) => 'i', + chr(196).chr(170) => 'I', chr(196).chr(171) => 'i', + chr(196).chr(172) => 'I', chr(196).chr(173) => 'i', + chr(196).chr(174) => 'I', chr(196).chr(175) => 'i', + chr(196).chr(176) => 'I', chr(196).chr(177) => 'i', + chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij', + chr(196).chr(180) => 'J', chr(196).chr(181) => 'j', + chr(196).chr(182) => 'K', chr(196).chr(183) => 'k', + chr(196).chr(184) => 'k', chr(196).chr(185) => 'L', + chr(196).chr(186) => 'l', chr(196).chr(187) => 'L', + chr(196).chr(188) => 'l', chr(196).chr(189) => 'L', + chr(196).chr(190) => 'l', chr(196).chr(191) => 'L', + chr(197).chr(128) => 'l', chr(197).chr(129) => 'L', + chr(197).chr(130) => 'l', chr(197).chr(131) => 'N', + chr(197).chr(132) => 'n', chr(197).chr(133) => 'N', + chr(197).chr(134) => 'n', chr(197).chr(135) => 'N', + chr(197).chr(136) => 'n', chr(197).chr(137) => 'N', + chr(197).chr(138) => 'n', chr(197).chr(139) => 'N', + chr(197).chr(140) => 'O', chr(197).chr(141) => 'o', + chr(197).chr(142) => 'O', chr(197).chr(143) => 'o', + chr(197).chr(144) => 'O', chr(197).chr(145) => 'o', + chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe', + chr(197).chr(148) => 'R',chr(197).chr(149) => 'r', + chr(197).chr(150) => 'R',chr(197).chr(151) => 'r', + chr(197).chr(152) => 'R',chr(197).chr(153) => 'r', + chr(197).chr(154) => 'S',chr(197).chr(155) => 's', + chr(197).chr(156) => 'S',chr(197).chr(157) => 's', + chr(197).chr(158) => 'S',chr(197).chr(159) => 's', + chr(197).chr(160) => 'S', chr(197).chr(161) => 's', + chr(197).chr(162) => 'T', chr(197).chr(163) => 't', + chr(197).chr(164) => 'T', chr(197).chr(165) => 't', + chr(197).chr(166) => 'T', chr(197).chr(167) => 't', + chr(197).chr(168) => 'U', chr(197).chr(169) => 'u', + chr(197).chr(170) => 'U', chr(197).chr(171) => 'u', + chr(197).chr(172) => 'U', chr(197).chr(173) => 'u', + chr(197).chr(174) => 'U', chr(197).chr(175) => 'u', + chr(197).chr(176) => 'U', chr(197).chr(177) => 'u', + chr(197).chr(178) => 'U', chr(197).chr(179) => 'u', + chr(197).chr(180) => 'W', chr(197).chr(181) => 'w', + chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y', + chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z', + chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z', + chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z', + chr(197).chr(190) => 'z', chr(197).chr(191) => 's', + // Euro Sign + chr(226).chr(130).chr(172) => 'E', + // GBP (Pound) Sign + chr(194).chr(163) => ''); - $string = strtr($string, $chars); - } - else - { - // Assume ISO-8859-1 if not UTF-8 - $chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158) - .chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194) - .chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202) - .chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210) - .chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218) - .chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227) - .chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235) - .chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243) - .chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251) - .chr(252).chr(253).chr(255); + $string = strtr($string, $chars); + } + else + { + // Assume ISO-8859-1 if not UTF-8 + $chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158) + .chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194) + .chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202) + .chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210) + .chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218) + .chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227) + .chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235) + .chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243) + .chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251) + .chr(252).chr(253).chr(255); - $chars['out'] = 'EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy'; + $chars['out'] = 'EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy'; - $string = strtr($string, $chars['in'], $chars['out']); - $double_chars = array(); - $double_chars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254)); - $double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th'); - $string = str_replace($double_chars['in'], $double_chars['out'], $string); - } - return $string; - } + $string = strtr($string, $chars['in'], $chars['out']); + $double_chars = array(); + $double_chars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254)); + $double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th'); + $string = str_replace($double_chars['in'], $double_chars['out'], $string); + } + return $string; + } - /* Add for 1.3 compatibility and avoid duplicate code */ - public static function jsonEncode($result) - { - return (method_exists('Tools', 'jsonEncode')) ? - Tools::jsonEncode($result) : Tools::jsonEncode($result); - } - - /* - ** Fix security and compatibility for PS < 1.4.5 - */ - public static function bqSQL($string) - { - return str_replace('`', '\`', pSQL($string)); - } - - /* - ** Check zip code by country - */ - public static function checkZipcodeByCountry($zipcode, $params) - { - $id_country = $params['id_country']; - - $zipcodeFormat = Db::getInstance()->getValue(' - SELECT `zip_code_format` - FROM `'._DB_PREFIX_.'country` - WHERE `id_country` = '.(int)$id_country); + /* Add for 1.3 compatibility and avoid duplicate code */ + public static function jsonEncode($result) + { + return (method_exists('Tools', 'jsonEncode')) ? + Tools::jsonEncode($result) : Tools::jsonEncode($result); + } + + /* + ** Fix security and compatibility for PS < 1.4.5 + */ + public static function bqSQL($string) + { + return str_replace('`', '\`', pSQL($string)); + } + + /* + ** Check zip code by country + */ + public static function checkZipcodeByCountry($zipcode, $params) + { + $id_country = $params['id_country']; + + $zipcodeFormat = Db::getInstance()->getValue(' + SELECT `zip_code_format` + FROM `'._DB_PREFIX_.'country` + WHERE `id_country` = '.(int)$id_country); - // -1 to warn user that no layout exist - if (!$zipcodeFormat) - return -1; + // -1 to warn user that no layout exist + if (!$zipcodeFormat) + return -1; - $regxMask = str_replace( - array('N', 'C', 'L'), - array( - '[0-9]', - Country::getIsoById((int)$id_country), - '[a-zA-Z]'), - $zipcodeFormat); - if (preg_match('/'.$regxMask.'/', $zipcode)) - return true; - return false; - } + $regxMask = str_replace( + array('N', 'C', 'L'), + array( + '[0-9]', + Country::getIsoById((int)$id_country), + '[a-zA-Z]'), + $zipcodeFormat); + if (preg_match('/'.$regxMask.'/', $zipcode)) + return true; + return false; + } - public static function getFormatedPhone($phone_number) - { - $begin = Tools::substr($phone_number, 0, 3); - $pad_number = (strpos($begin, '+3') !== false) ? 12 : - (strpos($begin, '00') ? 13 : 10); + public static function getFormatedPhone($phone_number) + { + $begin = Tools::substr($phone_number, 0, 3); + $pad_number = (strpos($begin, '+3') !== false) ? 12 : + (strpos($begin, '00') ? 13 : 10); - return str_pad(Tools::substr(preg_replace(MRTools::REGEX_CLEAN_PHONE, '', $phone_number), 0, $pad_number), $pad_number, '0'); - } + return str_pad(Tools::substr(preg_replace(MRTools::REGEX_CLEAN_PHONE, '', $phone_number), 0, $pad_number), $pad_number, '0', STR_PAD_LEFT); + } } ?> diff --git a/classes/index.php b/classes/index.php old mode 100644 new mode 100755 index dd2cf57..59b98f1 --- a/classes/index.php +++ b/classes/index.php @@ -26,10 +26,10 @@ header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT"); - + header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); - + header("Location: ../"); exit; \ No newline at end of file diff --git a/config.xml b/config.xml old mode 100644 new mode 100755 index f5a659f..4519432 --- a/config.xml +++ b/config.xml @@ -1,12 +1,12 @@ - - mondialrelay - - - - - - 1 - 1 + + mondialrelay + + + + + + 1 + 1 - + \ No newline at end of file diff --git a/connexion.php b/connexion.php old mode 100644 new mode 100755 index 1b794f4..b50c27f --- a/connexion.php +++ b/connexion.php @@ -28,33 +28,33 @@ include_once(dirname(__FILE__).'/mondialrelay.php'); include_once(dirname(__FILE__).'/errorCode.php'); try{ - if (!Tools::getValue('token')) - die('{"error":"Security error"}'); - if (sha1('mr'._COOKIE_KEY_.'Back') != Tools::getValue('token')) - die('{"error":"Security error"}'); - - $webservice = MondialRelay::MR_URL.'webservice/Web_Services.asmx?WSDL'; - $client = new SoapClient($webservice); - $params = array(); - $params['Enseigne'] = Tools::getValue('enseigne'); - $params['Poids'] = ''; - $params['Taille'] = ''; - $params['CP'] = (Configuration::get('PS_SHOP_CODE')) ? Configuration::get('PS_SHOP_CODE') : '75000'; - $params['Ville'] = ''; - $id_country = (Configuration::get('PS_SHOP_COUNTRY_ID')) ? Configuration::get('PS_SHOP_COUNTRY_ID') : Configuration::get('PS_COUNTRY_DEFAULT'); - $params['Pays'] = Country::getIsoById($id_country); - $params['Action'] = ''; - $concat = $params['Enseigne'].$params['Pays'].$params['Ville'].$params['CP'].$params['Poids'].Tools::getValue('key'); - $params['Security'] = Tools::strtoupper(md5($concat)); - $result_mr = $client->WSI2_RecherchePointRelais($params); - if (($errorNumber = $result_mr->WSI2_RecherchePointRelaisResult->STAT) != 0) - { - echo '{"error":"'.str_replace('"', '', $statCode[$errorNumber]).'"}'; - die(); - } - echo '{"success":1}'; + if (!Tools::getValue('token')) + die('{"error":"Security error"}'); + if (sha1('mr'._COOKIE_KEY_.'Back') != Tools::getValue('token')) + die('{"error":"Security error"}'); + + $webservice = MondialRelay::MR_URL.'webservice/Web_Services.asmx?WSDL'; + $client = new SoapClient($webservice); + $params = array(); + $params['Enseigne'] = Tools::getValue('enseigne'); + $params['Poids'] = ''; + $params['Taille'] = ''; + $params['CP'] = (Configuration::get('PS_SHOP_CODE')) ? Configuration::get('PS_SHOP_CODE') : '75000'; + $params['Ville'] = ''; + $id_country = (Configuration::get('PS_SHOP_COUNTRY_ID')) ? Configuration::get('PS_SHOP_COUNTRY_ID') : Configuration::get('PS_COUNTRY_DEFAULT'); + $params['Pays'] = Country::getIsoById($id_country); + $params['Action'] = ''; + $concat = $params['Enseigne'].$params['Pays'].$params['Ville'].$params['CP'].$params['Poids'].Tools::getValue('key'); + $params['Security'] = Tools::strtoupper(md5($concat)); + $result_mr = $client->WSI2_RecherchePointRelais($params); + if (($errorNumber = $result_mr->WSI2_RecherchePointRelaisResult->STAT) != 0) + { + echo '{"error":"'.str_replace('"', '', $statCode[$errorNumber]).'"}'; + die(); + } + echo '{"success":1}'; } catch(Exception $e) { - echo '{"error":"'.str_replace('"', '', $statCode[99]).'"}'; - die(); + echo '{"error":"'.str_replace('"', '', $statCode[99]).'"}'; + die(); } \ No newline at end of file diff --git a/cron.php b/cron.php old mode 100644 new mode 100755 index fb55596..05157f8 --- a/cron.php +++ b/cron.php @@ -28,7 +28,7 @@ include_once('mondialrelay.php'); if (Tools::getValue('secure_key') != Configuration::get('MONDIAL_RELAY_SECURE_KEY')) - exit; + exit; $account_shop = MondialRelay::getAccountDetail(); @@ -39,10 +39,10 @@ WHERE `exp_number` != 0'); if (empty($expeditions)) - die('No order'); + die('No order'); else - echo 'Start progress
'; - + echo 'Start progress
'; + $params = array( 'Enseigne' => $account_shop['MR_ENSEIGNE_WEBSERVICE'], 'Langue' => 'FR' @@ -55,34 +55,34 @@ $i = 0; foreach ($expeditions as $expedition) { - if ($expedition['id_order'] == null) - continue; - $order = new Order((int)($expedition['id_order'])); - if ($order->current_state == Configuration::get('PS_OS_DELIVERED')) - continue; - $params['Expedition'] = $expedition['exp_number']; - $params['Security'] = Tools::strtoupper(md5($params['Enseigne'].$params['Expedition'].'FR'.$account_shop['MR_KEY_WEBSERVICE'])); - - $is_delivered = 0; - $result_mr = $client_mr->WSI2_TracingColisDetaille($params); - - if (isset($result_mr->WSI2_TracingColisDetailleResult->Tracing->ret_WSI2_sub_TracingColisDetaille)) - foreach ($result_mr->WSI2_TracingColisDetailleResult->Tracing->ret_WSI2_sub_TracingColisDetaille as $result) - if (isset($result->Libelle) && $result->Libelle == 'COLIS LIVRÉ') - { - $is_delivered = 1; - break; - } - - if ($is_delivered == 1) - { - $history = new OrderHistory(); - $history->id_order = (int)($expedition['id_order']); - $history->changeIdOrderState((int)(Configuration::get('PS_OS_DELIVERED')), (int)($expedition['id_order'])); - $history->addWithemail(); - } - $i++; - - echo '

'.$i.'

'; + if ($expedition['id_order'] == null) + continue; + $order = new Order((int)($expedition['id_order'])); + if ($order->current_state == Configuration::get('PS_OS_DELIVERED')) + continue; + $params['Expedition'] = $expedition['exp_number']; + $params['Security'] = Tools::strtoupper(md5($params['Enseigne'].$params['Expedition'].'FR'.$account_shop['MR_KEY_WEBSERVICE'])); + + $is_delivered = 0; + $result_mr = $client_mr->WSI2_TracingColisDetaille($params); + + if (isset($result_mr->WSI2_TracingColisDetailleResult->Tracing->ret_WSI2_sub_TracingColisDetaille)) + foreach ($result_mr->WSI2_TracingColisDetailleResult->Tracing->ret_WSI2_sub_TracingColisDetaille as $result) + if (isset($result->Libelle) && $result->Libelle == 'COLIS LIVRÉ') + { + $is_delivered = 1; + break; + } + + if ($is_delivered == 1) + { + $history = new OrderHistory(); + $history->id_order = (int)($expedition['id_order']); + $history->changeIdOrderState((int)(Configuration::get('PS_OS_DELIVERED')), (int)($expedition['id_order'])); + $history->addWithemail(); + } + $i++; + + echo '

'.$i.'

'; } echo 'End progress
'; \ No newline at end of file diff --git a/css/index.php b/css/index.php old mode 100644 new mode 100755 index ce38668..dc40d62 --- a/css/index.php +++ b/css/index.php @@ -24,13 +24,13 @@ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ - + header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT"); - + header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); - + header("Location: ../"); exit; \ No newline at end of file diff --git a/css/style.css b/css/style.css old mode 100644 new mode 100755 diff --git a/de.php b/de.php old mode 100644 new mode 100755 diff --git a/docs/index.php b/docs/index.php old mode 100644 new mode 100755 index 9d353d7..cd81008 --- a/docs/index.php +++ b/docs/index.php @@ -23,13 +23,13 @@ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) * International Registered Trademark & Property of PrestaShop SA */ - + header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT"); - + header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); - + header("Location: ../"); exit; \ No newline at end of file diff --git a/docs/install.pdf b/docs/install.pdf old mode 100644 new mode 100755 diff --git a/en.php b/en.php old mode 100644 new mode 100755 diff --git a/errorCode.php b/errorCode.php old mode 100644 new mode 100755 index 36a55ca..e77b912 --- a/errorCode.php +++ b/errorCode.php @@ -25,77 +25,77 @@ */ $statCode = array( - '1' => 'Enseigne invalide', - '2' => 'Numéro d\'enseigne vide ou inexistant', - '3' => 'Numéro de compte enseigne invalide', - '5' => 'Numéro de dossier enseigne invalide', - '7' => 'Numéro de client enseigne invalide', - '9' => 'Nom de ville non reconnu ou non unique', - '10' => 'Type de collecte invalide ou incorrect (1/D > Domicile -- 3/R > Relais)', - '11' => 'Numéro de Point Relais de collecte invalide', - '12' => 'Pays du Point Relais de collecte invalide', - '13' => 'Type de livraison invalide ou incorrect (1/D > Domicile -- 3/R > Relais)', - '14' => 'Numéro du Point Relais de livraison invalide', - '15' => 'Pays du Point Relais de livraison invalide', - '16' => 'Code pays invalide', - '17' => 'Adresse invalide', - '18' => 'Ville invalide', - '19' => 'Code postal invalide', - '20' => 'Poids du colis invalide', - '21' => 'Taille (Longueur + Hauteur) du colis invalide', - '22' => 'Taille du Colis invalide', - '24' => 'Numéro de Colis Mondial Relay invalide', - '29' => 'Mode de livraison invalide', - '30' => 'Adresse (L1) de l\'expéditeur invalide', - '31' => 'Adresse (L2) de l\'expéditeur invalide', - '33' => 'Adresse (L3) de l\'expéditeur invalide', - '34' => 'Adresse (L4) de l\'expéditeur invalide', - '35' => 'Ville de l\'expéditeur invalide', - '36' => 'Code postal de l\'expéditeur invalide', - '37' => 'Pays de l\'expéditeur invalide', - '38' => 'Numéro de téléphone de l\'expéditeur invalide', - '39' => 'Adresse e-mail de l\'expéditeur invalide', - '40' => 'Action impossible sans ville ni code postal', - '41' => 'Mode de livraison invalide', - '42' => 'Montant CRT invalide', - '43' => 'Devise CRT invalide', - '44' => 'Valeur du colis invalide', - '45' => 'Devise de la valeur du colis invalide', - '46' => 'Plage de numéro d\'expédition épuisée', - '47' => 'Nombre de colis invalide', - '48' => 'Multi-colis en Point Relais Interdit', - '49' => 'Mode de collecte ou de livraison invalide', - '50' => 'Adresse (L1) du destinataire invalide', - '51' => 'Adresse (L2) du destinataire invalide', - '53' => 'Adresse (L3) du destinataire invalide', - '54' => 'Adresse (L4) du destinataire invalide', - '55' => 'Ville du destinataire invalide', - '56' => 'Code postal du destinataire invalide', - '57' => 'Pays du destinataire invalide', - '58' => 'Numéro de téléphone du destinataire invalide', - '59' => 'Adresse e-mail du destinataire invalide', - '60' => 'Champ texte libre invalide', - '61' => 'Top avisage invalide', - '62' => 'Instruction de livraison invalide', - '63' => 'Assurance invalide ou incorrecte', - '64' => 'Temps de montage invalide', - '65' => 'Top rendez-vous invalide', - '66' => 'Top reprise invalide', - '70' => 'Numéro de Point Relais invalide', - '72' => 'Langue expéditeur invalide', - '73' => 'Langue destinataire invalide', - '74' => 'Langue invalide', - '80' => 'Code tracing : Colis enregistré', - '81' => 'Code tracing : Colis en traitement chez Mondial Relay', - '82' => 'Code tracing : Colis livré', - '83' => 'Code tracing : Anomalie', - '90' => 'AS400 indisponible', - '91' => 'Numéro d\'expédition invalide', - '94' => 'Colis Inexistant', - '95' => 'Compte Enseigne non activé', - '96' => 'Type d\'enseigne incorrect en Base', - '97' => 'Clé de sécurité invalide', - '98' => 'Service Indisponible', - '99' => 'Erreur générique du service. Cette erreur peut être dû autant à un problème technique du service qu\'à des données incorrectes ou inexistantes dans la Base de Données. Lorsque vous avez cette erreur veuillez la notifier à Mondial Relay en précisant la date et l\'heure de la connexion ainsi que les informations envoyés au WebService afin d\'effectuer une vérification.'); + '1' => 'Enseigne invalide', + '2' => 'Numéro d\'enseigne vide ou inexistant', + '3' => 'Numéro de compte enseigne invalide', + '5' => 'Numéro de dossier enseigne invalide', + '7' => 'Numéro de client enseigne invalide', + '9' => 'Nom de ville non reconnu ou non unique', + '10' => 'Type de collecte invalide ou incorrect (1/D > Domicile -- 3/R > Relais)', + '11' => 'Numéro de Point Relais de collecte invalide', + '12' => 'Pays du Point Relais de collecte invalide', + '13' => 'Type de livraison invalide ou incorrect (1/D > Domicile -- 3/R > Relais)', + '14' => 'Numéro du Point Relais de livraison invalide', + '15' => 'Pays du Point Relais de livraison invalide', + '16' => 'Code pays invalide', + '17' => 'Adresse invalide', + '18' => 'Ville invalide', + '19' => 'Code postal invalide', + '20' => 'Poids du colis invalide', + '21' => 'Taille (Longueur + Hauteur) du colis invalide', + '22' => 'Taille du Colis invalide', + '24' => 'Numéro de Colis Mondial Relay invalide', + '29' => 'Mode de livraison invalide', + '30' => 'Adresse (L1) de l\'expéditeur invalide', + '31' => 'Adresse (L2) de l\'expéditeur invalide', + '33' => 'Adresse (L3) de l\'expéditeur invalide', + '34' => 'Adresse (L4) de l\'expéditeur invalide', + '35' => 'Ville de l\'expéditeur invalide', + '36' => 'Code postal de l\'expéditeur invalide', + '37' => 'Pays de l\'expéditeur invalide', + '38' => 'Numéro de téléphone de l\'expéditeur invalide', + '39' => 'Adresse e-mail de l\'expéditeur invalide', + '40' => 'Action impossible sans ville ni code postal', + '41' => 'Mode de livraison invalide', + '42' => 'Montant CRT invalide', + '43' => 'Devise CRT invalide', + '44' => 'Valeur du colis invalide', + '45' => 'Devise de la valeur du colis invalide', + '46' => 'Plage de numéro d\'expédition épuisée', + '47' => 'Nombre de colis invalide', + '48' => 'Multi-colis en Point Relais Interdit', + '49' => 'Mode de collecte ou de livraison invalide', + '50' => 'Adresse (L1) du destinataire invalide', + '51' => 'Adresse (L2) du destinataire invalide', + '53' => 'Adresse (L3) du destinataire invalide', + '54' => 'Adresse (L4) du destinataire invalide', + '55' => 'Ville du destinataire invalide', + '56' => 'Code postal du destinataire invalide', + '57' => 'Pays du destinataire invalide', + '58' => 'Numéro de téléphone du destinataire invalide', + '59' => 'Adresse e-mail du destinataire invalide', + '60' => 'Champ texte libre invalide', + '61' => 'Top avisage invalide', + '62' => 'Instruction de livraison invalide', + '63' => 'Assurance invalide ou incorrecte', + '64' => 'Temps de montage invalide', + '65' => 'Top rendez-vous invalide', + '66' => 'Top reprise invalide', + '70' => 'Numéro de Point Relais invalide', + '72' => 'Langue expéditeur invalide', + '73' => 'Langue destinataire invalide', + '74' => 'Langue invalide', + '80' => 'Code tracing : Colis enregistré', + '81' => 'Code tracing : Colis en traitement chez Mondial Relay', + '82' => 'Code tracing : Colis livré', + '83' => 'Code tracing : Anomalie', + '90' => 'AS400 indisponible', + '91' => 'Numéro d\'expédition invalide', + '94' => 'Colis Inexistant', + '95' => 'Compte Enseigne non activé', + '96' => 'Type d\'enseigne incorrect en Base', + '97' => 'Clé de sécurité invalide', + '98' => 'Service Indisponible', + '99' => 'Erreur générique du service. Cette erreur peut être dû autant à un problème technique du service qu\'à des données incorrectes ou inexistantes dans la Base de Données. Lorsque vous avez cette erreur veuillez la notifier à Mondial Relay en précisant la date et l\'heure de la connexion ainsi que les informations envoyés au WebService afin d\'effectuer une vérification.'); ?> diff --git a/es.php b/es.php old mode 100644 new mode 100755 diff --git a/fr.php b/fr.php old mode 100644 new mode 100755 index ba836d1..068ebe1 --- a/fr.php +++ b/fr.php @@ -217,7 +217,9 @@ $_MODULE['<{mondialrelay}prestashop>settings_ca57625685f058f54d82c6e05876a131'] = 'Choississez le statut pour la génération d\'étiquette.'; $_MODULE['<{mondialrelay}prestashop>settings_c9cc8cce247e49bae79f15173ce97354'] = 'Sauvegarder'; $_MODULE['<{mondialrelay}prestashop>settings_f4f70727dc34561dfde1a3c529b6205c'] = 'Paramètres'; +$_MODULE['<{mondialrelay}prestashop>checkout_process_50fa1af2938c04e8fb499c483c1fecb8'] = 'Le JavaScript n\'est pas activé sur votre navigateur, nous vous invitons à l’activer afin de sélectionner un Point Relais® lors de votre commande.'; $_MODULE['<{mondialrelay}prestashop>checkout_process_836f6c949a2f2d61489bf410def82111'] = 'Mondialrelay ne peut récupérer les points relais du à une erreur de Prestashop'; +$_MODULE['<{mondialrelay}prestashop>checkout_process_widget_50fa1af2938c04e8fb499c483c1fecb8'] = 'Le JavaScript n\'est pas activé sur votre navigateur, nous vous invitons à l’activer afin de sélectionner un Point Relais® lors de votre commande.'; $_MODULE['<{mondialrelay}prestashop>checkout_process_widget_ad3d06d03d94223fa652babc913de686'] = 'Valider votre Point Relais®'; $_MODULE['<{mondialrelay}prestashop>checkout_process_widget_b5cdf9b63fda35c33bb5e35cc3716b95'] = 'Point Relais® sélectionné :'; $_MODULE['<{mondialrelay}prestashop>header_e0626222614bdee31951d84c64e5e9ff'] = 'Choisir'; diff --git a/img/AdminMondialRelay.gif b/img/AdminMondialRelay.gif old mode 100644 new mode 100755 diff --git a/img/details.gif b/img/details.gif old mode 100644 new mode 100755 diff --git a/img/error2.png b/img/error2.png old mode 100644 new mode 100755 diff --git a/img/getTickets.gif b/img/getTickets.gif old mode 100644 new mode 100755 diff --git a/img/help.png b/img/help.png old mode 100644 new mode 100755 diff --git a/img/icones/account_detail.png b/img/icones/account_detail.png old mode 100644 new mode 100755 diff --git a/img/icones/help.png b/img/icones/help.png old mode 100644 new mode 100755 diff --git a/img/icones/index.php b/img/icones/index.php old mode 100644 new mode 100755 index 4deda52..9cf60e3 --- a/img/icones/index.php +++ b/img/icones/index.php @@ -27,10 +27,10 @@ header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT"); - + header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); - + header("Location: ../"); exit; \ No newline at end of file diff --git a/img/icones/info.png b/img/icones/info.png old mode 100644 new mode 100755 diff --git a/img/icones/settings.png b/img/icones/settings.png old mode 100644 new mode 100755 diff --git a/img/icones/supplier.png b/img/icones/supplier.png old mode 100644 new mode 100755 diff --git a/img/index.php b/img/index.php old mode 100644 new mode 100755 index 0bfbc8e..fa0395b --- a/img/index.php +++ b/img/index.php @@ -27,10 +27,10 @@ header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT"); - + header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); - + header("Location: ../"); exit; \ No newline at end of file diff --git a/img/loader.gif b/img/loader.gif old mode 100644 new mode 100755 diff --git a/img/logo.gif b/img/logo.gif old mode 100644 new mode 100755 diff --git a/img/logo_hd.png b/img/logo_hd.png old mode 100644 new mode 100755 diff --git a/img/pdf_icon.jpg b/img/pdf_icon.jpg old mode 100644 new mode 100755 diff --git a/img/selectRelayPoint.png b/img/selectRelayPoint.png old mode 100644 new mode 100755 diff --git a/index.php b/index.php old mode 100644 new mode 100755 index 0bfbc8e..fa0395b --- a/index.php +++ b/index.php @@ -27,10 +27,10 @@ header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT"); - + header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); - + header("Location: ../"); exit; \ No newline at end of file diff --git a/it.php b/it.php old mode 100644 new mode 100755 diff --git a/js/common.js b/js/common.js new file mode 100755 index 0000000..ec4d163 --- /dev/null +++ b/js/common.js @@ -0,0 +1,64 @@ +/** +* 2007-2014 Mondial relay +* +* NOTICE OF LICENSE +* +* This source file is subject to the Academic Free License (AFL 3.0) +* that is bundled with this package in the file LICENSE.txt. +* It is also available through the world-wide-web at this URL: +* http://opensource.org/licenses/afl-3.0.php +* If you did not receive a copy of the license and are unable to +* obtain it through the world-wide-web, please send an email +* to Mondial relay so we can send you a copy immediately. +* +* DISCLAIMER +* +* Do not edit or add to this file if you wish to upgrade Mondial relay to newer +* versions in the future. If you wish to customize Mondial relay for your +* needs please refer to Mondial relay for more information. +* +* @author Mondial relay +* @copyright 2007-2014 Mondial relay +* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0) +* International Registered Trademark & Property of Mondial relay +*/ + +function checkMrSelection() { + + if (PS_MRData.PS_VERSION < '1.5') { + var selected_carrier_id = $('input[name=id_carrier]:checked').val(); + } else { + var selected_carrier_id = parseInt($('.delivery_option_radio:checked').val()); + } + /* + console.log(PS_MRData.PS_VERSION); + console.log(selected_carrier_id); + console.log(PS_MRSelectedRelayPoint['carrier_id']); + console.log(PS_MRSelectedRelayPoint['relayPointNum']); + */ + var MR_carrier_selected = (selected_carrier_id==PS_MRSelectedRelayPoint['carrier_id']); // is a mondial relay carrier ? + var MR_relay_selected = (PS_MRSelectedRelayPoint['relayPointNum']>0); // a relay has been selected ? + + if (!MR_carrier_selected) { + return true; + } else if (MR_relay_selected) { + return true; + } else { + alert(PS_MRTranslationList['errorSelection']); + return false; + } +} + +$(document).ready(function() { + + $('#form button[name="processCarrier"], #form input[name="processCarrier"]').click(function(event) { + return checkMrSelection(); + }); + + //OPC Validation - Warn user to select a relay point + $(document).on('click', '.payment_module', function() { + return checkMrSelection(); + }); + +}); + diff --git a/js/gmap.js b/js/gmap.js old mode 100644 new mode 100755 diff --git a/js/index.php b/js/index.php old mode 100644 new mode 100755 index fc4110f..087b026 --- a/js/index.php +++ b/js/index.php @@ -27,10 +27,10 @@ header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT"); - + header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); - + header("Location: ../"); exit; \ No newline at end of file diff --git a/js/jquery-1.6.4.min.js b/js/jquery-1.6.4.min.js old mode 100644 new mode 100755 diff --git a/js/jquery.plugin.mondialrelay.parcelshoppicker.2.0.0.js b/js/jquery.plugin.mondialrelay.parcelshoppicker.2.0.0.js old mode 100644 new mode 100755 diff --git a/js/mondialrelay.js b/js/mondialrelay.js old mode 100644 new mode 100755 index 504d0b7..eaf40d4 --- a/js/mondialrelay.js +++ b/js/mondialrelay.js @@ -1281,20 +1281,7 @@ var PS_MRObject = (function($, undefined) { $('#MR_config_menu').children('ul').css('margin-left', width + 'px'); } - // 1.5 OPC Validation - Warn user to select a relay point - $('.payment_module a').live('click', function() { - if (typeof PS_MRData != 'undefined') - { - if (PS_MRData.PS_VERSION >= '1.5' && PS_MRData.carrier) - { - var _return = !(!PS_MRSelectedRelayPoint['carrier_id'] || !PS_MRSelectedRelayPoint['relayPointNum']); - if (!_return) - alert(PS_MRTranslationList['errorSelection']); - return _return; - } - } - }); - + // If MR carrier selected, check MR relay point is selected too $('input[name=processCarrier], button[name=processCarrier]').click(function(){ var _return = !(PS_MRSelectedRelayPoint['carrier_id'] && !PS_MRSelectedRelayPoint['relayPointNum']); @@ -1358,4 +1345,6 @@ function mr_checkConnexion() { } } }); -} \ No newline at end of file +} + + diff --git a/js/mondialrelay_widget.js b/js/mondialrelay_widget.js old mode 100644 new mode 100755 index 332427f..d7ad3b5 --- a/js/mondialrelay_widget.js +++ b/js/mondialrelay_widget.js @@ -221,19 +221,6 @@ $(document).ready(function() { - // 1.5 OPC Validation - Warn user to select a relay point - $('.payment_module a').live('click', function() { - if (typeof PS_MRData != 'undefined') - { - if (PS_MRData.PS_VERSION >= '1.5' && PS_MRData.carrier && PS_MRSelectedRelayPoint['carrier_id']!=0) - { - var _return = !(!PS_MRSelectedRelayPoint['carrier_id'] || !PS_MRSelectedRelayPoint['relayPointNum']); - if (!_return) - alert(PS_MRTranslationList['errorSelection']); - return _return; - } - } - }); // If MR carrier selected, check MR relay point is selected too $('input[name=processCarrier], button[name=processCarrier]').click(function(){ diff --git a/logo.gif b/logo.gif old mode 100644 new mode 100755 index e1e406a3f28a54901e007127880c923b0239b608..06f847112cfcc82141bafe2d7370007594d1eeba GIT binary patch literal 1035 zcmZ?wbhEHb6krfwc;3RWiNSX>gWqNb|4j@*n;8POFa&R92-?CBx)sC-*$QHWZDR=C z1|q|^gHXga#)$2V;oBJ_wlPI)XNuU$9KM|;avN*J4%VoxY>_)SqPKBJ@8F5u$rHPa zFJUKt{7(LaodOBFKqzsiP~tA(#GN8ZyF`O&4S$DA9EIX512Z94AJeB7($q<`n(u$EJyJ*UEYPDb{g zitIZR*?%;q^IXitvvHHo#ZNw()_XF2%7xTv7qezv$eDF1XU>KE*%u1uTq>M*qGH4<@M%Or@IzjZ(Dt*chmVv%WwB>x;J6Vo$1>j z&fR-{)uv|~PrcZ7?!~TiuMS*(e)!Uxqu1UZz47+U?GI<~y}Nk-%cGay-+cJ_?(^@@ z-~ayp^Y8E9|D%BJA)xqA(77lzu_QG`p**uBL&4qCH-JHh0SG`Dgn{EW1N+O&#jGcJ zh52MEIvi6@Nm@1D)5(}{;b5zQwU$-Jh6nB(?7~id0*36|Ol(T(0X{1)aY$nf3>?GP8*|MC2|=SnR>( zvuR4lp+)Rdgx!~15ojuEV&<{Xc@og*bhuI6$l^xC%?F$^`ju-M3=5W?pJbcGwZr$o z(N+l)$9+5xnwN7(ODI~KJaAm(Dy|T^Oe50p$Z_`VnIZveemEo_Vl!d6DtXz(y^B{= RDMi9i`J|X-0}~U2H2_yJqE7$- literal 678 zcmZ?wbhEHb6krfwI9AHAg27=W2sy4~a9YLSyo$kPHG}JF2DddJfzS}5kmvP1(lbk(fxqHm=_FClcwaVXam$Tot zaJysPLD!1IK6OU}8jb}t91f~K9@um=r15BI)3NZDW8tkQ!rM;9be>G^Ii1pbHhsdG z3?Q1gx1jS})|4|jlh0>Q-B;dsv24zz^0}8PW?!nDd$4Kh<%Y#qJ67K4S$%uj=DRbu z-k-ng!Tg=~7VUnpWbeJD`<`w({(R?|=ey3n*nRHI$^9=6TzUmWhc3N6ee?b0`=4$; z`S$GX_g5c&y#M^45K#PQ=^W(h7~&sfrI4PYn^lmSu25#EXP}@_TAZ1euHfnAuHY5m z>aI{`W~8a3P*|FnlUY)!V5?wZz{Q~WlZBCsp`Jm90SG`5%D{fCp)@1X#ay0?jf+R# z%rzpbG@XTO3KwsT%G4=LnLe|)1hP%%bLqLyXNyh>wx6ZEd@5^7X>z#Zx(!nVO9L6% zICjhuF7;$zvVIm%p4YMYC)k)dS(v3Sax$G=&*>d!5NfLwtFM!0rNMQA*F?fnOiD;X zO^aXqg*&I4bAqO<2TOeZoCBGO`ivryi7f>am>SN_VNPXRki95@twT7<%jRRF@?lnm pV@X>i3ltigSeFRNXdGD9C!=lS6wvVC0AmZ6Tv5I79P-mMQAB1H-LJ_h*$)YNm!Gc$d*u|2|`E_3skZU62l}R86<2XPy{PV zf~g7*QWsQI3^iy}76BK8D#}vPib#bjZWy<+6pKx)c<+yE=Xqwn?|jeuzUO@Bygz13 zc-WUVR*qHx0N5}?=^WzK$N}TxfHI=dNNEC^%9F!Dpis((K_Oc=Zpkr~+lK=oJ3cmgquf_!+LNJ7II>YH$&NJzu2 z_GUwDSumU^3Qd>8k?CPvLAqE#7UKMugH$EOD1g8y4^$#a5(Py`!@bj`826@Q0uFo! zLB%xO-$g~U!@*#w90tAdkcR;Bfj}Q3p6Kc2>+9wG zjM?PE1PX^9@;;X_qTv!zR7N2XQd3j$sh)VLd>w&ECX-DXB$9^_;h{*Apgg6AM6q~U zfetGKa*+%bNhP33k;j*&pfsGZ(!Z~O$UewQ6z|()Y#2ewlM#q`$aJM?Ae;TqPz3pa zR-hdCzxDoKVFfo$1`{~2LYg8M7zdZI*px~}36{e=R4V66rAgCW3{RAzQbnRv1_noZ zgKVBaBr(PB@N71PDN&$2i2!EOX*i<-UL+DyeEfVv7=BO)DbUN4NMsQG7$FdY$e{ap zd;5BM2K!EP=~6)o0!z?ouJ8kw2z``mvH~JAW~Re((FRx;B9|iIyDL*fAFqY}QN8zE z;YVwM7$4;ljKvU4gZ-aDPahfGW7>YOtugpud{|<1yWD8&T}9Xk0KlX$>49A3?dqtE zq{y$Z{=;|rGBPGN9ycJcz&$BANVO|yaC6XA$eEP@xjS9qX9hZ3gljI^hRhvW>{6Kh z{4?yo0&*kf%$ak++_}(YKd838)#{_~-hN6f%IKS{@#16S2Os?@namn6lpAb_ zt>7xTyXzh6Px2P=z}*h#7F!n_e8D7_X#@==zY+;KqM2kz2fv@LMnuu#5_rqXlk)S9 zyo407tY${(?~!~mAfo!{C)<8IGMg_n2QXJz^pbcG_#(Ve)tYcRDf(IeK-jL*uK*El zW856bn#>F{V1rLb2_S6F(4PyR`bD3C?-A$RC`4SEb@`3l z`M``Vr_viHDTDT5U7*_KG_mC*OSk_Z-20%nR1u#CmugAImy(>1;})dH3d}kB8^? zw__Jv6nt;FwiZcWVb(Bo$$RdvvpAOy*Kn%U`)%|)LvXR61?hBW@q|}r_tV(ZF7XFO zEVTOa*I~#W%g0_xr)Hn9j(pbZVWpA}J#O>u^j{-3#0u7bvuR1Y?pboH;e1coL{`7% zO-njW#rRfjF=Tf}9D6&URW5(-IIImxh8slZ>&nVn zIxHVge(DtEJ}X;}OTJIS6xG^0dac*YEZu9@ZV$G%9lhysq^q~?Mgu+ko+l|(RlM&+ z&XL#4x}5o^Mz`O1k+Zd{;v4rXEsd8y@3cQEEVLcGb*Jt79j@g+(VNI_*5A7JZc6LA z`=UBKqaZmsukm<9*z>x1DZ+g^M6y4pw2A8c$~Bqf6TBeaVK}eoV%L_RrM^0MX9 zcRy`lediTHXQ`_5dvt)> zb?4~{WFA+a6&WeWICSa!-LA@IXEq>S+E_mXlRGA*_he5LWCvJKGc)-+qAR}M$kY{# z{!m!%xAb+f8;Dt$W7~N`v8Q*NTU>oi`yV!kYYfqv%6K|<;q^P#TY`D_dKbLdps8+^ z7gg@qTS*%0&dCkETw+s1dXiYr9MY3E798qsw}@pi97awAc4(w;?c;&7L{{~kI@O@* Or-aD}qiciWbN>SPyu``? literal 3262 zcmV;v3_0000*X;fHrLvL+uWo~o;00000LsCUS zR8LYmAZKJPYH(#|Aa*e>Fd!&(b7^j8AW2F`AWBe0M<8}KGAS$|adlyAX>@rYJs>zR z3T9s|cK`qk3`s;mRA}Dqn|*MV)t$#b=XtrW$<6xu&4XUEA7DJL5WS?O@$j*S5ADJG*vwT3tKZmTILG5np&y5h4LYAPEV%H_5%Z z$$foZ&i-*PPZB~%w7DQoe>2bA%z2)ibH2ad@BH4*IYLS)8Ha4s!cH03X%lIfm??vJ zM-Q>qF5+z=673<9oxP;GBcy^6jJ^TP{y5Sex9cHN1X`gFS8+b>(n8#og?Ofx;Hxgf zTT_O=ZVJ9>rD$#)p=&5E4aKdaXzI9Ki?KjP-f5+OUn}urL1IUP#M`<_wueX@?Hf+yn4OUv zs=cImWh2X<`!;&OpAlKlp2GzH^2VeClvotpei`0n7oY?@D0y!58D*5*cXd|6xgtSm z+a7w~Y#CD5)}Q_!1wAJm^)ytCYSqf~Q3Af4u1|qN+kd?@1hRMQJ`}W^43$0-0!0jO z!j2}eqlp}YRO#Ece+Xo{Gn|w4Ay5fFu^qFuCj(RfDT|)(y^wQDD^Q5HoXBVnzyyMx z4^F0}{gxk-cf~wJo{RWP2eA^Vv*Myo;?g(^B+wYxx*wbLu!sgUJSeExq_dhNv+CuU z)bY;>NQp(@!aC|ce;uVO=Hr`If^ccP{go%^e&sDH9$1T=GBXU(RXRWOBz7!)zJQeY zW>qo&kvpmS_>xg?JtYMQuZ}*u0y~ibrMmQyhU&u(vf$F$EPeJ{_@|bfVa*7zW#$2- zJ^9g4?pD7hxb!#Q7!%;gurIfyL%*2-K91dY9@O!03%4G!-*4fJ|B#9T8+Q z4FVKRgGsjbS}q_;T+F$5-KaOmpMQgQA9#xXUCo#zQSl-ag^n8^A4=z>L>ktI8>Gah zcv%B3|4275aJYlFzW6A~_7I?;kqzr?iAj$+X-S)NMQ4q*;vCk6&KgJwAAOMg4di(SQlK!{+(E28_)!L_ za^iQdv;E4i(frtR!=v$!mbwZQVuw0;=kCYYvh>RgcJ?CFbGI^bnraCY!ml^6xoSOu zh8ZZRA3cyK)mH!m`;UJ3BOd8&u*fsKAKOEY1}OguZz?BOk`kNzhUrvXy_k4gH=d~_ zbpG!)lHFk^iYZt;i;|U%gm*O2_ga$!$Tg*isW)HFVAC-|FYQHS)wOW(ED9ITW}vy9 z-Yxr_kph?2W1NVPXv;VzcuucCN7jwX~{ zvlxF>8MD8>p5iMPAhD20Dz0BbprLk{q!cdt$(N}A)~%?1zcZg{>sR8dtC+Av#|0^b zj_T9t{PlJQn~oCv<8C~aMb3nkJU1e3(E98j=zr%Z`E#nB!8Nak;O5;J197xGuQMe( zl_vOyodmbMMZraN4pXFIIW-=MP3aX2Frsmc{y|DEpXVgjwvpZW#+(k&?Tz z2!CA#(RbT1B2fpVtFjO~mckrJfB^r@DGa{Xfk4GuTTY@alnE+?Aka7+p$H;xy>~{d zy-seP07%E02`th`Oe7K&m$MUQV_;(paV7g+pka~1#zI9uW#>$es1islEK+3Z?H)j6 z+p_goTn;mA%xu*iR6OH?R3>V$-BXIV_!sx_59uwemoL-s@E5Q#&&|M8#Q-*0vnSRTOQ_SYb*8le+ua^f)N013~K*rEjP<;e7xgnT-9YrEQ(h& zazk`8Hx6v3a_urs9+;@R`$pEKws2k7Z}H8l8rJ|R6Y-C(k^n1qY+~kytI%}~+qBUA z9t@H!e&!p@y6alp0Uw&Gpek7v&i1UTDypKOC}Knbf~(Wbjlfc&ab=6+`bHfcgH z@8!gcdvN7>sk`GE6qk-(;Ah4iYtUR8txvwd;NjMB>qg`HNt-mY?q5%!ZVHKDm^~XG zVemjZMl?oVRSi>DEhH6*vFo;n7;Nsy45tW^-C-0(A8}UW^!-~*UAG)XQLt?rD{WGD z>nh&dun7#4y&E5z zSBV|zBGnVdTUrEw5g8!f79<_&C)LwW;&?A+fBf{do>M2F=u}>P2|`sk_J6O^_i7Ug zQ2psEGix$3$iA=s9DsS>zmtaVZUkWOo&Pbk&G6TPRM60L4Qbh=Peex4YEDWiZ+azH z?R%W-BTsXE_-QWrpZg~4sJ+!?6fL>{fI|=dioTtP0GR&i)lTf&_Olm=wscXoY5{@i z^&$oiv>}ARwk5r<9KaZeQS*;0uq~VD{-c=# zhf<=KLWI8>J!vZ11Q&Ja`=b8W!l=MR4i|xVtE4qsmLH(FZ~jgH!VW}g1eg8b<=~`h6$ELuPx)6 zJ&#hgb}4WB-Pq|gLV!?}4^&~ufYenOb0nZ>UzkP(r;TGn8|8qnSAE)if7fE*ZId!09 zZ!aA$?51c=4S_{7>D{syBbFlCbPOw*#!eX%(>1p~6uWMocPFu?V`Ew?llZ7m?o?lD zV+^yW5*4@e?a7c$4ojdl;lq@1B-V&;M~-Qu;YFY#u`o$y!#?l06?utG!6o&q-u1(b zBr89$gu_kmjpwXE|AbZ4#-M!7B||P`=EgOM zoE$qlccf}wYHwLN1TwF-oauM0IYXW1d?QKqr#?ntR@D$lMc0`3!0iMU&U8|k^OY>p z(<99cpxU`WGkFTPLD_;2lWmhf1%GPhrKY&Rp)?CKl@Av`U@}iNIfm1(j`Q?kW zY4p!V=_dZQqyI`EdsJP33MeN zS9t;6%3|D8i}6k^#aB~?x4H~(RSDjjG6MD0W3pVx_i;qhHY}uJVrL&|TBKts5* '', - 'MR_CODE_MARQUE' => '', - 'MR_KEY_WEBSERVICE' => '', - 'MR_LANGUAGE' => '', - 'MR_WEIGHT_COEFFICIENT' => '', - 'MR_ORDER_STATE' => 3, - 'id_shop' => 1 - ); - - public $upgrade_detail = array(); - - public function __construct() - { - $this->name = 'mondialrelay'; - $this->tab = 'shipping_logistics'; - $this->version = '2.1.3'; - $this->installed_version = ''; - $this->module_key = '366584e511d311cfaa899fc2d9ec1bd0'; - $this->author = 'PrestaShop'; - - parent::__construct(); - - $this->displayName = $this->l('Mondial Relay'); - $this->description = $this->l('Deliver in Relay points'); - - /** Backward compatibility */ - require(_PS_MODULE_DIR_.'/mondialrelay/backward_compatibility/backward.php'); - - self::initModuleAccess(); - - /* Call everytime to prevent the change of the module by a recent one */ - $this->_updateProcess(); - $this->initAccount(); - - /* Check if it's a mondialrelay ajax query */ - $this->checkAJAX(); - } - - public function install() - { - if (!function_exists('curl_version') || !extension_loaded('soap')) - { - $this->_errors[] = $this->l('Mondial Relay needs SOAP & cURL to be installed on your server.'); - return false; - } - - if (!parent::install()) - return false; - - if (!$this->registerHookByVersion()) - return false; - - if ((!file_exists(MondialRelay::$modulePath.MondialRelay::INSTALL_SQL_FILE)) || - (!$sql = Tools::file_get_contents(MondialRelay::$modulePath.MondialRelay::INSTALL_SQL_FILE))) - return false; - - $sql = str_replace('PREFIX_', _DB_PREFIX_, $sql); - $sql = preg_split("/;\s*[\r\n]+/", $sql); - foreach ($sql as $query) - if (!empty($query)) - Db::getInstance()->execute(trim($query)); - - $result = Db::getInstance()->getRow(' - SELECT id_tab - FROM `'._DB_PREFIX_.'tab` - WHERE class_name="AdminMondialRelay"'); - - if (!$result) - { - $tab = new Tab(); - $languages = Language::getLanguages(false); - foreach ($languages as $language) - $tab->name[$language['id_lang']] = 'Mondial Relay'; - $tab->class_name = 'AdminMondialRelay'; - $tab->module = 'mondialrelay'; - $tab->id_parent = Tab::getIdFromClassName('AdminOrders'); - - if (!$tab->add()) - return false; - - if (is_dir(_PS_MODULE_DIR_.'mondialrelay/')) - @copy(_PS_MODULE_DIR_.'mondialrelay/img/AdminMondialRelay.gif', _PS_IMG_DIR_.'/AdminMondialRelay.gif'); - } - - /* If module isn't installed, set default value */ - if (!Configuration::get('MONDIAL_RELAY')) - { - Configuration::updateValue('MONDIAL_RELAY', $this->version); - Configuration::updateValue('MONDIAL_RELAY_SECURE_KEY', md5( _COOKIE_KEY_.time())); - Configuration::updateValue('MONDIAL_RELAY_MODE', 'widget'); - } - else - { - $query = 'UPDATE `'._DB_PREFIX_.'carrier` c, `'._DB_PREFIX_.'mr_method` m - SET c.`deleted` = 0 - WHERE c.`id_carrier` = m.`id_carrier` - AND m.`is_deleted` = 0'; - - /* Reactive transport if database wasn't remove at the last uninstall */ - Db::getInstance()->execute($query); - } - return true; - } - - /* - ** Return the token depend of the type - */ - public static function getToken($type = 'front') - { - return ($type == 'front') ? MondialRelay::$MRFrontToken : (($type == 'back') ? - MondialRelay::$MRBackToken : null); - } - - /* - ** Register hook depending of the Prestashop version used - */ - private function registerHookByVersion() - { - if (version_compare(_PS_VERSION_, '1.3', '>=') && (!$this->registerHook('extraCarrier') || !$this->registerHook('updateCarrier') || !$this->registerHook('newOrder') || !$this->registerHook('BackOfficeHeader') || !$this->registerHook('header'))) - return false; - if (version_compare(_PS_VERSION_, '1.4', '>=') && (!$this->registerHook('processCarrier') || !$this->registerHook('orderDetailDisplayed'))) - return false; - if (version_compare(_PS_VERSION_, '1.6', '>=') && (!$this->registerHook('displayBackOfficeHeader'))) - return false; - return true; - } - - public function uninstallCommonData() - { - /* Tab uninstall */ - if (($id_tab = Tab::getIdFromClassName('AdminMondialRelay'))) - { - $tab = new Tab($id_tab); - $tab->delete(); - } - - if (!Db::getInstance()->execute(' - UPDATE '._DB_PREFIX_.'carrier c, '._DB_PREFIX_.'mr_method m - SET c.`deleted` = 1 - WHERE c.`id_carrier` = m.`id_carrier`')) - return false; - - return true; - } - - public function uninstall() - { - if (!parent::uninstall()) - return false; - - /* Uninstall data that doesn't need to be keep */ - if (!$this->uninstallCommonData()) - return false; - - if (Tools::getValue('keepDatabase')) - return true; - - Configuration::deleteByName('MR_ACCOUNT_DETAIL'); - - /* Drop databases */ - if (!Db::getInstance()->execute(' - DROP TABLE - '._DB_PREFIX_.'mr_history, - '._DB_PREFIX_.'mr_method, - '._DB_PREFIX_.'mr_selected, - '._DB_PREFIX_.'mr_method_shop')) - { - /* If drop failed, try to turn off the carriers */ - Db::getInstance()->execute(' - UPDATE '._DB_PREFIX_.'carrier c, '._DB_PREFIX_.'mr_method m - SET c.`deleted` = 1 - WHERE c.`id_carrier` = m.`id_carrier`'); - return false; - } - return true; - } - - /** - * Launch upgrade process for 1.3 and 1.4 - */ - public function runUpgrade() - { - /* List of upgraded version existing */ - $files_version = array('1.8.0', '1.8.3', '2.0.6'); - - $upgrade_path = dirname(__FILE__).'/upgrade/'; - - if (version_compare(_PS_VERSION_, '1.5', '<')) - { - foreach ($files_version as $version) - { - $file = $upgrade_path.'install-'.$version.'.php'; - if ($this->installed_version < $version && file_exists($file)) - { - include_once($file); - call_user_func('upgrade_module_'.str_replace('.', '_', $version), $this); - } - } - } - } - - /* - ** UpdateProcess if merchant update the module without a - ** normal installation - */ - private function _updateProcess() - { - if (Module::isInstalled('mondialrelay') && - (($this->installed_version = Configuration::get('MONDIAL_RELAY')) || - $this->installed_version = Configuration::get('MONDIAL_RELAY_1_4')) - && $this->installed_version < $this->version) - $this->runUpgrade(); - } - - /* - ** Get the content to ask for a backup of the database - */ - private function askForBackup($href) - { - return 'return PS_MRObject.uninstall(\''.$href.'\');'; - } - - /* - ** OnClick for input fields under the module list fields action - */ - public function onclickOption($type, $href = false) - { - $content = ''; - - switch ($type) - { - case 'desactive': - break; - case 'reset': - break; - case 'delete': - break; - case 'uninstall': - $content = $this->askForBackup($href); - break; - default: - } - return $content; - } - - /** - * Init the account_shop variable with the account detail for this shop - */ - public function initAccount() - { - /* Get default value */ - $id_order_state = $this->account_shop['MR_ORDER_STATE']; - - if (($account_shop_stored = MondialRelay::getAccountDetail())) - $this->account_shop = $account_shop_stored; - - /* Normally, this can't happen... */ - if (empty($this->account_shop['MR_ORDER_STATE'])) - $this->account_shop['MR_ORDER_STATE'] = $id_order_state; - } - - /* - ** Init the access directory module for URL and file system - ** Allow a compatibility for Presta < 1.4 - */ - public static function initModuleAccess() - { - MondialRelay::$modulePath = _PS_MODULE_DIR_.'mondialrelay/'; - MondialRelay::$MRFrontToken = sha1('mr'._COOKIE_KEY_.'Front'); - MondialRelay::$MRBackToken = sha1('mr'._COOKIE_KEY_.'Back'); - MondialRelay::$moduleURL = __PS_BASE_URI__.'modules/mondialrelay/'; - } - - public function fetchTemplate($path, $name) - { - if (version_compare(_PS_VERSION_, '1.4', '<')) - $this->context->smarty->currentTemplate = $name; - - return $this->context->smarty->fetch(dirname(__FILE__).$path.$name.'.tpl'); - } - - public function hookNewOrder($params) - { - if (!MondialRelay::isMondialRelayCarrier($params['cart']->id_carrier)) - return; - - $order = $params['order']; - $currency = $params['currency']; - $id_lang = (int)$order->id_lang; - $customer = new Customer($order->id_customer); - $carrier = new Carrier($order->id_carrier); - $invoice = new Address((int)($order->id_address_invoice)); - $invoice_state = $invoice->id_state ? new State($invoice->id_state) : false; - if (version_compare(_PS_VERSION_, '1.5', '<')) - $order_date_text = Tools::displayDate($order->date_add, (int)($id_lang)); - else - $order_date_text = Tools::displayDate($order->date_add, null); - - DB::getInstance()->execute(' - UPDATE `'._DB_PREFIX_.'mr_selected` - SET `id_order` = '.(int)$order->id.' - WHERE `id_cart` = '.(int)$params['cart']->id); - - /*============================================ - // GET MR INFOS - //============================================*/ - $sql = 'SELECT * FROM `'._DB_PREFIX_.'mr_selected` WHERE `id_cart` = '.(int)$params['cart']->id.' AND `id_order` = '.(int)$order->id.''; - $mr_point = DB::getInstance()->getRow($sql); - - if (!$mr_point['MR_Selected_Num']) return false; - - /*============================================ - // SEND MAIL - //============================================*/ - $template = 'mr_new_order'; - $subject = $this->l('New order', false, (int)$id_lang).' - '.sprintf('%06d', $order->id); - - $mr_address = ''; - if ($mr_point['MR_Selected_LgAdr2']) - $mr_address .= $mr_point['MR_Selected_LgAdr2'].''; - if ($mr_point['MR_Selected_LgAdr3']) - $mr_address .= $mr_point['MR_Selected_LgAdr3'].''; - if ($mr_point['MR_Selected_LgAdr4']) - $mr_address .= $mr_point['MR_Selected_LgAdr4'].''; - - $templateVars = array( - '{firstname}' => $customer->firstname, - '{lastname}' => $customer->lastname, - '{email}' => $customer->email, - '{delivery_company}' => $mr_point['MR_Selected_LgAdr1'], - '{delivery_address1}' => $mr_address, - '{delivery_city}' => $mr_point['MR_Selected_Ville'], - '{delivery_postal_code}' => $mr_point['MR_Selected_CP'], - '{delivery_country}' => $mr_point['MR_Selected_Pays'], - '{invoice_company}' => $invoice->company, - '{invoice_firstname}' => $invoice->firstname, - '{invoice_lastname}' => $invoice->lastname, - '{invoice_address2}' => $invoice->address2, - '{invoice_address1}' => $invoice->address1, - '{invoice_city}' => $invoice->city, - '{invoice_postal_code}' => $invoice->postcode, - '{invoice_country}' => $invoice->country, - '{invoice_state}' => $invoice->id_state ? $invoice_state->name : '', - '{invoice_phone}' => $invoice->phone, - '{invoice_other}' => $invoice->other, - '{order_name}' => sprintf('%06d', $order->id), - '{shop_name}' => Configuration::get('PS_SHOP_NAME'), - '{date}' => $order_date_text, - '{carrier}' => (($carrier->name == '0') ? Configuration::get('PS_SHOP_NAME') : $carrier->name), - '{payment}' => Tools::substr($order->payment, 0, 32), - '{currency}' => $currency->sign, - ); - - $iso = Language::getIsoById((int)$id_lang); - if (file_exists(dirname(__FILE__).'/mails/'.$iso.'/'.$template.'.txt') && file_exists(dirname(__FILE__).'/mails/'.$iso.'/'.$template.'.html')) - Mail::Send((int)$id_lang, $template, $subject, $templateVars, $customer->email, $customer->firstname.' '.$customer->lastname, Configuration::get('PS_SHOP_EMAIL'), Configuration::get('PS_SHOP_NAME'), null, null, dirname(__FILE__).'/mails/'); - } - - public function hookBackOfficeHeader() - { - if (Tools::getValue('tab') == 'AdminMondialRelay' || Tools::getValue('module_name') == 'mondialrelay' || Tools::strtolower(Tools::getValue('controller')) == 'adminmondialrelay' || Tools::getValue('configure') == 'mondialrelay') - { - $this->context->smarty->assign(array( - 'MR_token' => MondialRelay::$MRBackToken, 'MR_local_path' => MondialRelay::$modulePath, - 'MR_account_set' => MondialRelay::isAccountSet(), 'new_base_dir' => MondialRelay::$moduleURL)); - - return $this->fetchTemplate('/views/templates/admin/', 'bo-header'); - } - } - - public function hookOrderDetailDisplayed($params) - { - if (!Mondialrelay::isMondialRelayCarrier($params['order']->id_carrier)) - return; - - $sql = ' - SELECT s.`MR_Selected_LgAdr1`, s.`MR_Selected_LgAdr2`, s.`MR_Selected_LgAdr3`, s.`MR_Selected_LgAdr4`, - s.`MR_Selected_CP`, s.`MR_Selected_Ville`, s.`MR_Selected_Pays`, s.`MR_Selected_Num`, s.`url_suivi`, s.`exp_number`, m.dlv_mode - FROM `'._DB_PREFIX_.'mr_selected` s - INNER JOIN '._DB_PREFIX_.'mr_method m ON m.id_mr_method = s.id_method - WHERE s.`id_cart` = '.(int)$params['order']->id_cart; - $res = Db::getInstance()->getRow($sql); - - if (!$res) - return; - - $point_relais = $res['MR_Selected_LgAdr1']. - ($res['MR_Selected_LgAdr1'] ? '
' : '').$res['MR_Selected_LgAdr2']. - ($res['MR_Selected_LgAdr2'] ? '
' : '').$res['MR_Selected_LgAdr3']. - ($res['MR_Selected_LgAdr3'] ? '
' : '').$res['MR_Selected_LgAdr4']. - ($res['MR_Selected_LgAdr4'] ? '
' : '').$res['MR_Selected_CP'].' '. - $res['MR_Selected_Ville'].'
'.$res['MR_Selected_Pays']; - - - if (($res['dlv_mode'] == 'LD1') || ($res['dlv_mode'] == 'LDS') || ($res['dlv_mode'] == 'HOM')) - $this->context->smarty->assign( - array( - 'mr_url' => $res['url_suivi'] - )); - else - $this->context->smarty->assign( - array( - 'mr_addr' => $point_relais, - 'mr_url' => $res['url_suivi'] - )); - - return $this->fetchTemplate('/views/templates/front/', 'order_detail'); - } - - /* - ** Update the carrier id to use the new one if changed - */ - public function hookupdateCarrier($params) - { - if ($params['id_carrier'] != $params['carrier']->id) - { - /* Get the old id_mr_method */ - $id_mr_method = Db::getInstance()->getValue(' - SELECT id_mr_method FROM `'._DB_PREFIX_.'mr_method` - WHERE id_carrier='.(int)$params['id_carrier']); - - /* Insert new entry keeping the last one linked to the id_carrier */ - $query = ' - INSERT INTO `'._DB_PREFIX_.'mr_method` - (name, country_list, col_mode, dlv_mode, insurance, id_carrier) - ( - SELECT - "'.pSQL($params['carrier']->name).'", - country_list, - col_mode, - dlv_mode, - insurance, - '.(int)$params['carrier']->id.' - FROM `'._DB_PREFIX_.'mr_method` - WHERE id_carrier ='.(int)$params['id_carrier'].')'; - Db::getInstance()->execute($query); - - /* Do the same process for the multishop table */ - $query = ' - INSERT INTO `'._DB_PREFIX_.'mr_method_shop` - (id_mr_method, id_shop) - ( - SELECT - '.(int)Db::getInstance()->INSERT_ID().', - id_shop - FROM `'._DB_PREFIX_.'mr_method_shop` - WHERE id_mr_method ='.(int)$id_mr_method.')'; - Db::getInstance()->execute($query); - - /* Set the last mr_method to delete */ - Db::getInstance()->execute(' - UPDATE `'._DB_PREFIX_.'mr_method` SET `is_deleted` = 1 - WHERE `id_mr_method` = '.(int)$id_mr_method); - } - } - - /** - * Get a carrier list liable to the module - * - * @return array - */ - public function _getCarriers() - { - /* Query don't use the external_module_name to keep the */ - /* 1.3 compatibility */ - $query = ' - SELECT c.id_carrier, c.range_behavior, m.id_mr_method, - m.dlv_mode, cl.delay - FROM `'._DB_PREFIX_.'mr_method` m - LEFT JOIN `'._DB_PREFIX_.'carrier` c - ON c.`id_carrier` = m.`id_carrier` - LEFT JOIN `'._DB_PREFIX_.'carrier_lang` cl - ON c.`id_carrier` = cl.`id_carrier` - LEFT JOIN `'._DB_PREFIX_.'mr_method_shop` ms - ON m.`id_mr_method` = ms.`id_mr_method` - WHERE c.`deleted` = 0 - AND ms.`id_shop` = '.$this->account_shop['id_shop'].' - AND cl.id_lang = '.$this->context->language->id.' - AND c.`active` = 1 - AND m.`is_deleted` = 0'; - - $carriers = Db::getInstance()->executeS($query); - - if (!is_array($carriers)) - $carriers = array(); - return $carriers; - } - - /** - * Get a specific method entry detail by a defined id_carrier - * - * @static - * @param $id_carrier - * @return array - */ - public static function getMethodByIdCarrier($id_carrier) - { - return Db::getInstance()->getRow(' - SELECT * FROM `'._DB_PREFIX_.'mr_method` m - WHERE m.`id_carrier` = '.(int)$id_carrier); - } - - /* - ** Added to be used properly with OPC - */ - public function hookHeader($params) - { - if (version_compare(_PS_VERSION_, '1.5', '>=')) - $this->context->controller->addJquery(); - - /*Configuration::updateValue('MONDIAL_RELAY_MODE', 'widget');*/ - if (!($file = basename(Tools::getValue('controller')))) - $file = str_replace('.php', '', basename($_SERVER['SCRIPT_NAME'])); - - if (in_array($file, array('order-opc', 'order', 'orderopc'))) - { - $this->context->smarty->assign(array( - 'one_page_checkout' => (Configuration::get('PS_ORDER_PROCESS_TYPE') ? Configuration::get('PS_ORDER_PROCESS_TYPE') : 0), - 'new_base_dir' => MondialRelay::$moduleURL, - 'MR_local_path' => MondialRelay::$modulePath, - 'MRToken' => MondialRelay::$MRFrontToken, - 'MR_MONDIAL_RELAY_MODE' => Configuration::get('MONDIAL_RELAY_MODE'), - ) - ); - - if($this->canAddJSViaController()) - $this->context->controller->addJS('https://maps.google.com/maps/api/js?sensor=false'); - else - $this->context->smarty->assign(array( - 'addJsInTemplate' => true - )); - - if (Configuration::get('MONDIAL_RELAY_MODE') == 'widget') - return $this->fetchTemplate('/views/templates/front/', 'header_widget'); - else - return $this->fetchTemplate('/views/templates/front/', 'header'); - } - return ''; - } - - private function canAddJSViaController() - { - if(version_compare(_PS_VERSION_, '1.6', '>=')) - return true; - - if(Configuration::get('PS_JS_THEME_CACHE')) - return false; - - return true; - } - - public function hookExtraCarrier($params) - { - /* TODO : Makes it work with multi-shipping */ - if (!MondialRelay::isAccountSet()) - return ''; - - $id_carrier = false; - $preSelectedRelay = $this->getRelayPointSelected($this->context->cart->id); - $carriersList = MondialRelay::_getCarriers(); - $address = new Address($this->context->cart->id_address_delivery); - $country = new Country($address->id_country); - $id_zone = Address::getZoneById((int)($address->id)); - - /* Check if the defined carrier are ok */ - foreach ($carriersList as $k => $row) - { - /* For now works only with single shipping (>= 1.5 compatibility) */ - if (method_exists($this->context->cart, 'carrierIsSelected')) - { - if ($this->context->cart->carrierIsSelected($row['id_carrier'], $params['address']->id)) - $id_carrier = $row['id_carrier']; - } - - /* Temporary carrier for some test */ - $carrier = new Carrier((int)($row['id_carrier'])); - if ((($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT) && $carrier->getMaxDeliveryPriceByWeight($id_zone) === false) || (($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_PRICE) && $carrier->getMaxDeliveryPriceByPrice($id_zone) === false)) - unset($carriersList[$k]); - else if ($row['range_behavior']) - { - /* Get id zone */ - $id_zone = (isset($this->context->cart->id_address_delivery) && $this->context->cart->id_address_delivery) ? - Address::getZoneById((int)$this->context->cart->id_address_delivery) : - (int)$this->context->country->id_zone; - - if (($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT && (!Carrier::checkDeliveryPriceByWeight($row['id_carrier'], $this->context->cart->getTotalWeight(), $id_zone))) || - ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_PRICE && - (!Carrier::checkDeliveryPriceByPrice($row['id_carrier'], $this->context->cart->getOrderTotal(true, MondialRelay::BOTH_WITHOUT_SHIPPING), $id_zone, $this->context->cart->id_currency) || - !Carrier::checkDeliveryPriceByPrice($row['id_carrier'], $this->context->cart->getOrderTotal(true, MondialRelay::BOTH_WITHOUT_SHIPPING), $id_zone, $this->context->cart->id_currency)))) - unset($carriersList[$k]); - } - } - - $carrier = null; - if ($id_carrier && ($method = MondialRelay::getMethodByIdCarrier($id_carrier))) - { - $carrier = new Carrier((int)$id_carrier); - /* Add dynamically a new field */ - $carrier->id_mr_method = $method['id_mr_method']; - $carrier->mr_dlv_mode = $method['dlv_mode']; - } - - if (Configuration::get('PS_SSL_ENABLED') || (!empty($_SERVER['HTTPS']) && Tools::strtolower($_SERVER['HTTPS']) != 'off')) - $ssl = 'true'; - else $ssl = 'false'; - - $this->context->smarty->assign(array( - 'address' => $address, - 'account_shop' => $this->account_shop, - 'country' => $country, - 'ssl' => $ssl, - 'MR_Data'=> MRTools::jsonEncode(array( - 'carrier_list' => $carriersList, - 'carrier' => $carrier, - 'PS_VERSION' => _PS_VERSION_, - 'pre_selected_relay' => isset($preSelectedRelay['MR_selected_num']) ? $preSelectedRelay['MR_selected_num'] : -1, - )) - )); - if (Configuration::get('MONDIAL_RELAY_MODE') == 'widget') - return $this->fetchTemplate('/views/templates/front/', 'checkout_process_widget'); - else - return $this->fetchTemplate('/views/templates/front/', 'checkout_process'); - } - - /** - * Return the detailed account - * - * @static - * @return mixed - */ - public static function getAccountDetail() - { - return unserialize((string)Configuration::get('MR_ACCOUNT_DETAIL')); - } - - /** - * Check if the account is set - * - * @static - * @return bool - */ - public static function isAccountSet() - { - $details = MondialRelay::getAccountDetail(); - - if (!$details || !count($details)) - return false; - - foreach ($details as $value) - if (empty($value)) - return false; - - return true; - } - - /** - * Check any submitted form - */ - private function _postValidation() - { - if (Tools::isSubmit('submit_account_detail')) - { - if (Tools::getValue('MR_enseigne_webservice') == '' || !preg_match('#^[0-9A-Z]{2}[0-9A-Z ]{6}$#', Tools::getValue('MR_enseigne_webservice'))) - $this->_postErrors[] = $this->l('Invalid Enseigne'); - if (Tools::getValue('MR_code_marque') == '' || !preg_match('#^[0-9]{2}$#', Tools::getValue('MR_code_marque'))) - $this->_postErrors[] = $this->l('Invalid Mark code'); - if (Tools::getValue('MR_webservice_key') == '' || !preg_match("#^[0-9A-Za-z_\'., /\-]{2,32}$#", Tools::getValue('MR_webservice_key'))) - $this->_postErrors[] = $this->l('Invalid Webservice Key'); - if (Tools::getValue('MR_language') == '' || !preg_match('#^[A-Z]{2}$#', Tools::getValue('MR_language'))) - $this->_postErrors[] = $this->l('Invalid Language'); - if (!Tools::getValue('MR_weight_coefficient') || !Validate::isInt(Tools::getValue('MR_weight_coefficient'))) - $this->_postErrors[] = $this->l('Invalid Weight Coefficient'); - } - - /* Shipping form validation */ - else if (Tools::isSubmit('submitMethod')) - { - if (!preg_match("#^[0-9A-Za-z_\'., /\-]{2,32}$#", Tools::getValue('mr_Name'))) - $this->_postErrors[] = $this->l('Invalid carrier name'); - if (Tools::getValue('mr_ModeCol') != 'CCC') - $this->_postErrors[] = $this->l('Invalid Col mode'); - if (!preg_match('#^REL|24R|ESP|DRI|LDS|LDR|LD1|HOM$#', Tools::getValue('mr_ModeLiv'))) - $this->_postErrors[] = $this->l('Invalid delivery mode'); - if (!Validate::isInt(Tools::getValue('mr_ModeAss')) || Tools::getValue('mr_ModeAss') > 5 || Tools::getValue('mr_ModeAss') < 0) - $this->_postErrors[] = $this->l('Invalid Assurance mode'); - if (!Tools::getValue('mr_Pays_list')) - $this->_postErrors[] = $this->l('You must choose at least one delivery country.'); - } - - /* Order state form validation */ - else if (Tools::isSubmit('submit_order_state')) - { - if (!Validate::isUnsignedInt(Tools::getValue('id_order_state'))) - $this->_postErrors[] = $this->l('Invalid order state'); - } - - - } - - /** - * Update account shop - * - * @return bool - */ - public function updateAccountShop() - { - return Configuration::updateValue('MR_ACCOUNT_DETAIL', serialize($this->account_shop)); - } - - /** - * Post process - * - * @return array - */ - private function _postProcess() - { - $post_action = array( - 'type' =>Tools::safeOutput(Tools::getValue('MR_tab_name')), - 'message_success' => $this->l('Action Succeed'), - 'had_errors' => false - ); - - if (Tools::isSubmit('submitAdvancedSettings')) - Configuration::updateValue('MONDIAL_RELAY_MODE', Tools::getValue('mode', 'widget')); - else if (Tools::isSubmit('submit_account_detail')) - { - $this->account_shop = array( - 'MR_ENSEIGNE_WEBSERVICE' => Tools::safeOutput(Tools::getValue('MR_enseigne_webservice')), - 'MR_CODE_MARQUE' => Tools::safeOutput(Tools::getValue('MR_code_marque')), - 'MR_KEY_WEBSERVICE' =>Tools::safeOutput(Tools::getValue('MR_webservice_key')), - 'MR_LANGUAGE' => Tools::safeOutput(Tools::getValue('MR_language')), - 'MR_ORDER_STATE' => Tools::safeOutput($this->account_shop['MR_ORDER_STATE']), - 'MR_WEIGHT_COEFFICIENT' => Tools::safeOutput(Tools::getValue('MR_weight_coefficient')), - 'id_shop' => $this->context->shop->id - ); - if ($this->updateAccountShop()) - $post_action['message_success'] = $this->l('Account detail has been updated'); - else - $this->_postErrors[] = $this->l('Cannot Update the account shop'); - } - else if (Tools::isSubmit('submit_add_shipping')) - { - if (($this->addShippingMethod())) - $post_action['message_success'] = $this->l('Shipping method has been added'); - } - else if (Tools::isSubmit('submit_order_state')) - { - Configuration::updateValue('MONDIAL_RELAY_ORDER_STATE', Tools::getValue('id_order_state')); - $post_action['message_success'] = $this->l('Order state properly changed'); - } - else if (($id_mr_method = Tools::getValue('delete_mr')) && $this->disableCarrier((int)$id_mr_method)) - $post_action['message_success'] = $this->l('Carrier has been deleted (disabled under the prestashop database)'); - - if (count($this->_postErrors)) - $post_action['had_errors'] = true; - - return $post_action; - } - - public function getContent() - { - $post_action = null; - if (!empty($_POST)) - { - $this->_postValidation(); - if (!count($this->_postErrors)) - $post_action = $this->_postProcess(); - } - $carriers_list = Db::getInstance()->executeS(' - SELECT m.* - FROM `'._DB_PREFIX_.'mr_method` m - LEFT JOIN `'._DB_PREFIX_.'carrier` c - ON (c.`id_carrier` = m.`id_carrier`) - LEFT JOIN `'._DB_PREFIX_.'mr_method_shop` ms - ON ms.`id_mr_method` = m.`id_mr_method` - WHERE c.`deleted` = 0 AND ms.`id_shop` = '.(int)$this->account_shop['id_shop']); - - $controller = version_compare(_PS_VERSION_, '1.5', '<') ? 'AdminContact' : 'AdminStores'; - - /* TODO : Fill an array with admi controller name */ - $this->context->smarty->assign(array( - 'MR_token_admin_performance' => Tools::getAdminToken('AdminPerformance'.(int)(Tab::getIdFromClassName('AdminPerformance')).(int)($this->context->cookie->id_employee)), - 'MR_token_admin_carriers' => (version_compare(_PS_VERSION_, '1.6', '<') ? Tools::getAdminToken('AdminCarriers'.(int)(Tab::getIdFromClassName('AdminCarriers')).(int)$this->context->employee->id) : Tools::getAdminToken('AdminCarrierWizard'.(int)(Tab::getIdFromClassName('AdminCarrierWizard')).(int)$this->context->employee->id)), - 'MR_token_admin_contact' => array( - 'controller_name' => $controller, - 'token' => Tools::getAdminToken($controller.(int)(Tab::getIdFromClassName($controller)).(int)$this->context->employee->id)), - 'MR_token_admin_mondialrelay' => Tools::getAdminToken('AdminMondialRelay'.(int)(Tab::getIdFromClassName('AdminMondialRelay')).(int)$this->context->employee->id), - 'MR_token_admin_module' => Tools::getAdminToken('AdminModules'.(int)(Tab::getIdFromClassName('AdminModules')).(int)$this->context->employee->id), - 'MR_enseigne_webservice' => Tools::getValue('MR_enseigne_webservice') ? Tools::getValue('MR_enseigne_webservice') : $this->account_shop['MR_ENSEIGNE_WEBSERVICE'], - 'MR_code_marque' => Tools::getValue('MR_code_marque') ? Tools::getValue('MR_code_marque') : $this->account_shop['MR_CODE_MARQUE'], - 'MR_webservice_key' => Tools::getValue('MR_webservice_key') ? Tools::getValue('MR_webservice_key') : $this->account_shop['MR_KEY_WEBSERVICE'], - 'MR_available_languages' => Language::getLanguages(), - 'MR_selected_language' => $this->account_shop['MR_LANGUAGE'], - 'MR_weight_coefficient' => Tools::getValue('MR_weight_coefficient') ? Tools::getValue('MR_weight_coefficient') : $this->account_shop['MR_WEIGHT_COEFFICIENT'], - 'MR_PS_WEIGHT_UNIT' => Configuration::get('PS_WEIGHT_UNIT'), - 'MR_order_states_list' => OrderState::getOrderStates($this->context->language->id), - 'MR_MONDIAL_RELAY_ORDER_STATE' => Configuration::get('MONDIAL_RELAY_ORDER_STATE'), - 'MR_CRON_URL' => Tools::getHttpHost(true, true)._MODULE_DIR_.$this->name.'/cron.php?secure_key='.Configuration::get('MONDIAL_RELAY_SECURE_KEY'), - 'MR_name' => Tools::getValue('MR_name') ? Tools::getValue('MR_name') : '', - 'MR_carriers_list' => $carriers_list, - 'MR_error_list' => $this->_postErrors, - 'MR_form_action' => $post_action, - 'MR_PS_ADMIN_IMG_' => _PS_ADMIN_IMG_, - 'MR_tab_selected' => Tools::getValue('MR_tab_name') ? Tools::getValue('MR_tab_name') : (MondialRelay::isAccountSet() ? 'account_form' : 'info_form'), - 'MR_delay' => Tools::getValue('MR_delay') ? Tools::getValue('MR_delay') : '', - 'MR_local_path' => MondialRelay::$modulePath, - 'MR_upgrade_detail' => $this->upgrade_detail, - 'MR_unit_weight_used' => Configuration::get('PS_WEIGHT_UNIT'), - 'MR_account_set' => MondialRelay::isAccountSet(), - 'MR_base_dir' => MondialRelay::$moduleURL, - 'MR_MONDIAL_RELAY_MODE' => Configuration::get('MONDIAL_RELAY_MODE'), - ) - ); - return $this->fetchTemplate('/views/templates/admin/', 'configuration'); - } - - /** - * Add new carrier - * - * @param $name - * @param $delay - * @return bool|int - */ - private function addCarrier($name, $delay) - { - $ret = false; - - if (($carrier = new Carrier())) - { - $delay_lang = array(); - foreach (Language::getLanguages(false) as $lang) - $delay_lang[$lang['id_lang']] = $delay; - $carrier->name = $name; - $carrier->active = 1; - $carrier->range_behavior = 1; - $carrier->need_range = 1; - $carrier->external_module_name = 'mondialrelay'; - $carrier->shipping_method = 1; - $carrier->delay = $delay_lang; - $carrier->is_module = version_compare(_PS_VERSION_, '1.4', '<') ? 0 : 1; - - $ret = $carrier->add(); - } - return $ret ? $carrier->id : false; - } - - public function displayInfoByCart($id_cart) - { - $html = '

'; - $simpleresul = Db::getInstance()->executeS(' - SELECT * FROM '._DB_PREFIX_.'mr_selected - WHERE id_cart='.(int)($id_cart)); - - if (isset($simpleresul[0])) - { - if (trim($simpleresul[0]['exp_number']) != '') - $html .= $this->l('Nb expedition:').$simpleresul[0]['exp_number'].'
'; - if (trim($simpleresul[0]['url_etiquette']) != '') - $html .= ''.$this->l('Label URL').'
'; - if (trim($simpleresul[0]['url_suivi']) != '') - $html .= ''.$this->l('Follow-up URL').'
'; - if (trim($simpleresul[0]['MR_Selected_Num']) != '') - $html .= $this->l('Nb Point Relay :').$simpleresul[0]['MR_Selected_Num'].'
'; - if (trim($simpleresul[0]['MR_Selected_LgAdr1']) != '') - $html .= $simpleresul[0]['MR_Selected_LgAdr1'].'
'; - if (trim($simpleresul[0]['MR_Selected_LgAdr2']) != '') - $html .= $simpleresul[0]['MR_Selected_LgAdr2'].'
'; - if (trim($simpleresul[0]['MR_Selected_LgAdr3']) != '') - $html .= $simpleresul[0]['MR_Selected_LgAdr3'].'
'; - if (trim($simpleresul[0]['MR_Selected_LgAdr4']) != '') - $html .= $simpleresul[0]['MR_Selected_LgAdr4'].'
'; - if (trim($simpleresul[0]['MR_Selected_CP']) != '') - $html .= $simpleresul[0]['MR_Selected_CP'].' '; - if (trim($simpleresul[0]['MR_Selected_Ville']) != '') - $html .= $simpleresul[0]['MR_Selected_Ville'].'
'; - if (trim($simpleresul[0]['MR_Selected_Pays']) != '') - $html .= $simpleresul[0]['MR_Selected_Pays'].'
'; - } - $html .= '

'; - return $html; - } - - /** - * Set necessaries values to the created carrier - * - * @param $id_carrier - * @param $dlv_mode - * @return bool - */ - private function addDefaultCarrierValue($id_carrier, $dlv_mode) - { - $weight_coef = $this->account_shop['MR_WEIGHT_COEFFICIENT']; - - /* Default Range value depending of the delivery mode */ - $range_weight = array( - '24R' => array(0, 30000 / $weight_coef), - 'DRI' => array(30000 / $weight_coef, 130000 / $weight_coef), - 'LD1' => array(0, 60000 / $weight_coef), - 'HOM' => array(0, 60000 / $weight_coef), - 'LDS' => array(30000 / $weight_coef, 130000 / $weight_coef) - ); - - /* Set range weight for a dlv_mode */ - if (!Db::getInstance()->execute( - 'INSERT INTO `'._DB_PREFIX_.'range_weight` - (`id_carrier`, `delimiter1`, `delimiter2`) - VALUES ('.(int)$id_carrier.', '.$range_weight[$dlv_mode][0].', '.$range_weight[$dlv_mode][1].')')) - { - $this->_postErrors[] = $this->l('Range weight can\'t be added'); - return false; - } - - $range_weight_id = Db::getInstance()->Insert_ID(); - - /* Set a range price */ - if (!Db::getInstance()->execute( - 'INSERT INTO `'._DB_PREFIX_.'range_price` - (`id_carrier`, `delimiter1`, `delimiter2`) - VALUES ('.(int)$id_carrier.', 0.000000, 10000.000000)')) - { - $this->_postErrors[] = $this->l('Range price can\'t be added'); - return false; - } - - $range_price_id = Db::getInstance()->Insert_ID(); - - $groups = Group::getGroups(Configuration::get('PS_LANG_DEFAULT')); - foreach ($groups as $group) - if (!Db::getInstance()->execute( - 'INSERT INTO `'._DB_PREFIX_.'carrier_group` - (id_carrier, id_group) - VALUES('.(int)$id_carrier.', '.(int)($group['id_group']).')')) - { - $this->_postErrors[] = $this->l('Default zone can\'t be added'); - return false; - } - - /* Set default zone */ - $zones = Zone::getZones(); - foreach ($zones as $zone) - { - if (!Db::getInstance()->execute( - 'INSERT INTO `'._DB_PREFIX_.'carrier_zone` - (id_carrier, id_zone) - VALUES('.(int)$id_carrier.', '.(int)($zone['id_zone']).')') || - !Db::getInstance()->execute( - 'INSERT INTO `'._DB_PREFIX_.'delivery` - (id_carrier, id_range_price, id_range_weight, id_zone, price) - VALUES('.(int)$id_carrier.', '.(int)($range_price_id).', NULL,'.(int)($zone['id_zone']).', 0.00)') || - !Db::getInstance()->execute( - 'INSERT INTO `'._DB_PREFIX_.'delivery` - (id_carrier, id_range_price, id_range_weight, id_zone, price) - VALUES('.(int)$id_carrier.', NULL, '.(int)($range_weight_id).','.(int)($zone['id_zone']).', 0.00)')) - { - $this->_postErrors[] = $this->l('Carrier zone or delivery data can\'t be added'); - return false; - } - } - return true; - } - - /** - * Add new shipping method - * - * @return bool - */ - private function addShippingMethod() - { - /* Insert new carrier for under Prestashop */ - if (!($id_carrier = $this->addCarrier(Tools::getValue('MR_name'), Tools::getValue('MR_delay')))) - { - $this->_postErrors[] = $this->l('Carrier can\'t be created in PrestaShop'); - return false; - } - - $fields = $_POST; - - unset($fields['submit_add_shipping'], $fields['MR_tab_name'], $fields['tab'], $fields['MR_delay']); - - /* Force col mod to CCC */ - $fields['col_mode'] = 'CCC'; - $fields['id_carrier'] = $id_carrier; - - $query = 'INSERT INTO `'._DB_PREFIX_.'mr_method` (%s) VALUES(%s)'; - - $keys = array(); - $values = array(); - foreach ($fields as $key => $value) - { - $keys[] = '`'.str_replace('MR_', '', $key).'`'; - $values[] = '\''.(is_array($value) ? pSQL(implode(',', $value)) : pSQL($value)).'\''; - } - $query = sprintf($query, implode(',', $keys), implode(',', $values)); - - if (!Db::getInstance()->execute($query) || !Db::getInstance()->execute('INSERT INTO `'._DB_PREFIX_.'mr_method_shop` - (id_mr_method, id_shop) VALUES('.(int)Db::getInstance()->INSERT_ID().', '.(int)$this->account_shop['id_shop'].')')) - { - $this->l('Carrier method can\'t be added for the module'); - Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'carrier` WHERE id_carrier='.(int)$id_carrier); - return false; - } - return $this->addDefaultCarrierValue($id_carrier, $fields['MR_dlv_mode']); - } - - /** - * Disable carrier instead of delete to keep history - * - * @param $id_mr_method - */ - public function disableCarrier($id_mr_method) - { - if (($id_carrier = Db::getInstance()->getValue( - 'SELECT `id_carrier` - FROM `'._DB_PREFIX_.'mr_method` - WHERE `id_mr_method` = '.(int)($id_mr_method))) && - Db::getInstance()->execute( - 'UPDATE `'._DB_PREFIX_.'carrier` c, `'._DB_PREFIX_.'mr_method` m - SET c.`active` = 0, c.`deleted` = 1, m.`is_deleted` = 1 - WHERE - c.`id_carrier` = m.`id_carrier` - AND c.`id_carrier` = '.(int)$id_carrier)) - return true; - - $this->_postErrors = $this->l('Carrier can\'t be deleted yet'); - return false; - } - - /** - * Get the followup url - * - * @param $exp_number - * @return mixed - */ - public function get_followup($exp_number) - { - $query = ' - SELECT url_suivi - FROM '._DB_PREFIX_.'mr_selected - WHERE exp_number='.(int)$exp_number; - - return Db::getInstance()->getValue($query); - } - - /** - * Get the SQL query to fetch order with mr carrier - * - * @static - * @param $id_order_state - * @param $weight_coefficient - * @return string - */ - public static function getBaseOrdersSQLQuery($id_order_state, $weight_coefficient = 0) - { - return 'SELECT o.`id_address_delivery` as id_address_delivery, - o.`id_order` as id_order, - o.`id_customer` as id_customer, - o.`id_cart` as id_cart, - o.`id_lang` as id_lang, - mrs.`id_mr_selected` as id_mr_selected, - CONCAT(c.`firstname`, " ", c.`lastname`) AS `customer`, - o.`total_paid_real` as total, o.`total_shipping` as shipping, - o.`date_add` as date, o.`id_currency` as id_currency, o.`id_lang` as id_lang, - mrs.`MR_poids` as mr_weight, - mrs.`MR_insurance` as mr_insurance, - mr.`name` as mr_Name, mrs.`MR_Selected_Num` as MR_Selected_Num, - mrs.`MR_Selected_Pays` as MR_Selected_Pays, mrs.`exp_number` as exp_number, - mr.`col_mode` as mr_ModeCol, mr.`dlv_mode` as mr_ModeLiv, mr.`insurance` as mr_ModeAss, - ROUND(SUM(odt.`product_weight` * odt.`product_quantity`) * '.(int)$weight_coefficient.') AS "order_weight" - FROM - `'._DB_PREFIX_.'orders` o - LEFT JOIN - `'._DB_PREFIX_.'carrier` ca - ON (ca.`id_carrier` = o.`id_carrier`) - LEFT JOIN - `'._DB_PREFIX_.'mr_selected` mrs - ON (mrs.`id_cart` = o.`id_cart`) - LEFT JOIN - `'._DB_PREFIX_.'mr_method` mr - ON (mr.`id_carrier` = ca.`id_carrier`) - LEFT JOIN - `'._DB_PREFIX_.'customer` c - ON (c.`id_customer` = o.`id_customer`) - LEFT JOIN - `'._DB_PREFIX_.'order_detail` odt - ON odt.`id_order` = o.`id_order` - WHERE ( - SELECT moh.`id_order_state` - FROM `'._DB_PREFIX_.'order_history` moh - WHERE moh.`id_order` = o.`id_order` - ORDER BY moh.`date_add` DESC LIMIT 1) = '.(int)($id_order_state).' - AND o.`id_order` = mrs.`id_order`'; - } - - /** - * Get orders details to create Tickets - * - * @static - * @param array $orderIdList - * @param int $filterEntries - * @param int $weight_coefficient - * @return array - */ - public static function getOrders($orderIdList = array(), $filterEntries = MondialRelay::NO_FILTER, $weight_coefficient = 0) - { - $account_shop = MondialRelay::getAccountDetail(); - $id_order_state = $account_shop['MR_ORDER_STATE']; - $sql = MondialRelay::getBaseOrdersSQLQuery($id_order_state, $weight_coefficient); - - if (count($orderIdList)) - { - $sql .= ' AND o.id_order IN ('; - foreach ($orderIdList as $id_order) - $sql .= (int)$id_order.', '; - $sql = rtrim($sql, ', ').')'; - } - switch ($filterEntries) - { - case MondialRelay::WITHOUT_HOME_DELIVERY: - $sql .= 'AND mr.mr_ModeLiv != "LD1" AND mr.mr_ModeLiv != "LDS" AND mr.mr_ModeLiv != "HOM"'; - break; - } - $sql .= ' - GROUP BY o.`id_order` - ORDER BY o.`date_add` ASC'; - return Db::getInstance()->executeS($sql); - } - - /** - * Get Mondialrelay error code - * - * @param $code - * @return string - */ - public function getErrorCodeDetail($code) - { - include(dirname(__FILE__).'/errorCode.php'); - if (isset($statCode[$code])) - return $statCode[$code]; - return $this->l('This error isn\'t referred : ').$code; - } - - /** - * @param $id_cart - * @return mixed - */ - public function getRelayPointSelected($id_cart) - { - return Db::getInstance()->getRow(' - SELECT s.`MR_selected_num` - FROM `'._DB_PREFIX_.'mr_selected` s - WHERE s.`id_cart` = '.(int)$id_cart); - } - - /** - * @param $id_carrier - * @return mixed - */ - public function isMondialRelayCarrier($id_carrier) - { - return Db::getInstance()->getRow(' - SELECT m.`id_mr_method` - FROM `'._DB_PREFIX_.'mr_method` m - WHERE `id_carrier` = '.(int)$id_carrier); - } - - public function getMethodValueByIdCarier($id_carrier, $key) - { - $content = Db::getInstance()->executeS( - 'SELECT * - FROM `'._DB_PREFIX_.'mr_method` m - WHERE `id_carrier` = '.(int)$id_carrier); - - return isset($content[$key]) ? $content[$key] : ''; - } - - public function checkAJAX() - { - /* Avoid loop inclusion */ - static $is_included = false; - - /* TODO : Find a way to use it on front */ - if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && Tools::strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') - if (Tools::getValue('mrtoken') && !$is_included) - { - $is_included = true; - include(dirname(__FILE__).'/ajax.php'); - exit(0); - } - } + const INSTALL_SQL_FILE = 'sql/mrInstall.sql'; + + private $_postErrors; + + public static $modulePath = ''; + public static $moduleURL = ''; + static public $MRFrontToken = ''; + static public $MRBackToken = ''; + + /* Added for 1.3 compatibility */ + const ONLY_PRODUCTS = 1; + const ONLY_DISCOUNTS = 2; + const BOTH = 3; + const BOTH_WITHOUT_SHIPPING = 4; + const ONLY_SHIPPING = 5; + const ONLY_WRAPPING = 6; + const ONLY_PRODUCTS_WITHOUT_SHIPPING = 7; + + /* SQL FILTER ORDER */ + const NO_FILTER = 0; + const WITHOUT_HOME_DELIVERY = 1; + + const MR_URL = 'http://www.mondialrelay.fr/'; + + /* Contains the details of the current shop used */ + public $account_shop = array( + 'MR_ENSEIGNE_WEBSERVICE' => '', + 'MR_CODE_MARQUE' => '', + 'MR_KEY_WEBSERVICE' => '', + 'MR_LANGUAGE' => '', + 'MR_WEIGHT_COEFFICIENT' => '', + 'MR_ORDER_STATE' => 3, + 'id_shop' => 1 + ); + + public $upgrade_detail = array(); + + public function __construct() + { + $this->name = 'mondialrelay'; + $this->tab = 'shipping_logistics'; + $this->version = '2.1.4'; + $this->installed_version = ''; + $this->module_key = '366584e511d311cfaa899fc2d9ec1bd0'; + $this->author = 'PrestaShop'; + + parent::__construct(); + + $this->displayName = $this->l('Mondial Relay'); + $this->description = $this->l('Deliver in Relay points'); + + /** Backward compatibility */ + require(_PS_MODULE_DIR_.'/mondialrelay/backward_compatibility/backward.php'); + + self::initModuleAccess(); + + /* Call everytime to prevent the change of the module by a recent one */ + $this->_updateProcess(); + $this->initAccount(); + + /* Check if it's a mondialrelay ajax query */ + $this->checkAJAX(); + } + + public function install() + { + if (!function_exists('curl_version') || !extension_loaded('soap')) + { + $this->_errors[] = $this->l('Mondial Relay needs SOAP & cURL to be installed on your server.'); + return false; + } + + if (!parent::install()) + return false; + + if (!$this->registerHookByVersion()) + return false; + + if ((!file_exists(MondialRelay::$modulePath.MondialRelay::INSTALL_SQL_FILE)) || + (!$sql = Tools::file_get_contents(MondialRelay::$modulePath.MondialRelay::INSTALL_SQL_FILE))) + return false; + + $sql = str_replace('PREFIX_', _DB_PREFIX_, $sql); + $sql = preg_split("/;\s*[\r\n]+/", $sql); + foreach ($sql as $query) + if (!empty($query)) + Db::getInstance()->execute(trim($query)); + + $result = Db::getInstance()->getRow(' + SELECT id_tab + FROM `'._DB_PREFIX_.'tab` + WHERE class_name="AdminMondialRelay"'); + + if (!$result) + { + $tab = new Tab(); + $languages = Language::getLanguages(false); + foreach ($languages as $language) + $tab->name[$language['id_lang']] = 'Mondial Relay'; + $tab->class_name = 'AdminMondialRelay'; + $tab->module = 'mondialrelay'; + $tab->id_parent = Tab::getIdFromClassName('AdminOrders'); + + if (!$tab->add()) + return false; + + if (is_dir(_PS_MODULE_DIR_.'mondialrelay/')) + @copy(_PS_MODULE_DIR_.'mondialrelay/img/AdminMondialRelay.gif', _PS_IMG_DIR_.'/AdminMondialRelay.gif'); + } + + /* If module isn't installed, set default value */ + if (!Configuration::get('MONDIAL_RELAY')) + { + Configuration::updateValue('MONDIAL_RELAY', $this->version); + Configuration::updateValue('MONDIAL_RELAY_SECURE_KEY', md5( _COOKIE_KEY_.time())); + Configuration::updateValue('MONDIAL_RELAY_MODE', 'widget'); + } + else + { + $query = 'UPDATE `'._DB_PREFIX_.'carrier` c, `'._DB_PREFIX_.'mr_method` m + SET c.`deleted` = 0 + WHERE c.`id_carrier` = m.`id_carrier` + AND m.`is_deleted` = 0'; + + /* Reactive transport if database wasn't remove at the last uninstall */ + Db::getInstance()->execute($query); + } + return true; + } + + /* + ** Return the token depend of the type + */ + public static function getToken($type = 'front') + { + return ($type == 'front') ? MondialRelay::$MRFrontToken : (($type == 'back') ? + MondialRelay::$MRBackToken : null); + } + + /* + ** Register hook depending of the Prestashop version used + */ + private function registerHookByVersion() + { + if (version_compare(_PS_VERSION_, '1.3', '>=') && (!$this->registerHook('extraCarrier') || !$this->registerHook('updateCarrier') || !$this->registerHook('newOrder') || !$this->registerHook('BackOfficeHeader') || !$this->registerHook('header'))) + return false; + if (version_compare(_PS_VERSION_, '1.4', '>=') && (!$this->registerHook('processCarrier') || !$this->registerHook('orderDetailDisplayed'))) + return false; + if (version_compare(_PS_VERSION_, '1.6', '>=') && (!$this->registerHook('displayBackOfficeHeader'))) + return false; + return true; + } + + public function uninstallCommonData() + { + /* Tab uninstall */ + if (($id_tab = Tab::getIdFromClassName('AdminMondialRelay'))) + { + $tab = new Tab($id_tab); + $tab->delete(); + } + + if (!Db::getInstance()->execute(' + UPDATE '._DB_PREFIX_.'carrier c, '._DB_PREFIX_.'mr_method m + SET c.`deleted` = 1 + WHERE c.`id_carrier` = m.`id_carrier`')) + return false; + + return true; + } + + public function uninstall() + { + if (!parent::uninstall()) + return false; + + /* Uninstall data that doesn't need to be keep */ + if (!$this->uninstallCommonData()) + return false; + + if (Tools::getValue('keepDatabase')) + return true; + + Configuration::deleteByName('MR_ACCOUNT_DETAIL'); + + /* Drop databases */ + if (!Db::getInstance()->execute(' + DROP TABLE + '._DB_PREFIX_.'mr_history, + '._DB_PREFIX_.'mr_method, + '._DB_PREFIX_.'mr_selected, + '._DB_PREFIX_.'mr_method_shop')) + { + /* If drop failed, try to turn off the carriers */ + Db::getInstance()->execute(' + UPDATE '._DB_PREFIX_.'carrier c, '._DB_PREFIX_.'mr_method m + SET c.`deleted` = 1 + WHERE c.`id_carrier` = m.`id_carrier`'); + return false; + } + return true; + } + + /** + * Launch upgrade process for 1.3 and 1.4 + */ + public function runUpgrade() + { + /* List of upgraded version existing */ + $files_version = array('1.8.0', '1.8.3', '2.0.6'); + + $upgrade_path = dirname(__FILE__).'/upgrade/'; + + if (version_compare(_PS_VERSION_, '1.5', '<')) + { + foreach ($files_version as $version) + { + $file = $upgrade_path.'install-'.$version.'.php'; + if ($this->installed_version < $version && file_exists($file)) + { + include_once($file); + call_user_func('upgrade_module_'.str_replace('.', '_', $version), $this); + } + } + } + } + + /* + ** UpdateProcess if merchant update the module without a + ** normal installation + */ + private function _updateProcess() + { + if (Module::isInstalled('mondialrelay') && + (($this->installed_version = Configuration::get('MONDIAL_RELAY')) || + $this->installed_version = Configuration::get('MONDIAL_RELAY_1_4')) + && $this->installed_version < $this->version) + $this->runUpgrade(); + } + + /* + ** Get the content to ask for a backup of the database + */ + private function askForBackup($href) + { + return 'return PS_MRObject.uninstall(\''.$href.'\');'; + } + + /* + ** OnClick for input fields under the module list fields action + */ + public function onclickOption($type, $href = false) + { + $content = ''; + + switch ($type) + { + case 'desactive': + break; + case 'reset': + break; + case 'delete': + break; + case 'uninstall': + $content = $this->askForBackup($href); + break; + default: + } + return $content; + } + + /** + * Init the account_shop variable with the account detail for this shop + */ + public function initAccount() + { + /* Get default value */ + $id_order_state = $this->account_shop['MR_ORDER_STATE']; + + if (($account_shop_stored = MondialRelay::getAccountDetail())) + $this->account_shop = $account_shop_stored; + + /* Normally, this can't happen... */ + if (empty($this->account_shop['MR_ORDER_STATE'])) + $this->account_shop['MR_ORDER_STATE'] = $id_order_state; + } + + /* + ** Init the access directory module for URL and file system + ** Allow a compatibility for Presta < 1.4 + */ + public static function initModuleAccess() + { + MondialRelay::$modulePath = _PS_MODULE_DIR_.'mondialrelay/'; + MondialRelay::$MRFrontToken = sha1('mr'._COOKIE_KEY_.'Front'); + MondialRelay::$MRBackToken = sha1('mr'._COOKIE_KEY_.'Back'); + MondialRelay::$moduleURL = __PS_BASE_URI__.'modules/mondialrelay/'; + } + + public function fetchTemplate($path, $name) + { + if (version_compare(_PS_VERSION_, '1.4', '<')) + $this->context->smarty->currentTemplate = $name; + + return $this->context->smarty->fetch(dirname(__FILE__).$path.$name.'.tpl'); + } + + public function hookNewOrder($params) + { + if (!MondialRelay::isMondialRelayCarrier($params['cart']->id_carrier)) + return; + + $order = $params['order']; + $currency = $params['currency']; + $id_lang = (int)$order->id_lang; + $customer = new Customer($order->id_customer); + $carrier = new Carrier($order->id_carrier); + $invoice = new Address((int)($order->id_address_invoice)); + $invoice_state = $invoice->id_state ? new State($invoice->id_state) : false; + if (version_compare(_PS_VERSION_, '1.5', '<')) + $order_date_text = Tools::displayDate($order->date_add, (int)($id_lang)); + else + $order_date_text = Tools::displayDate($order->date_add, null); + + DB::getInstance()->execute(' + UPDATE `'._DB_PREFIX_.'mr_selected` + SET `id_order` = '.(int)$order->id.' + WHERE `id_cart` = '.(int)$params['cart']->id); + + /*============================================ + // GET MR INFOS + //============================================*/ + $sql = 'SELECT * FROM `'._DB_PREFIX_.'mr_selected` WHERE `id_cart` = '.(int)$params['cart']->id.' AND `id_order` = '.(int)$order->id.''; + $mr_point = DB::getInstance()->getRow($sql); + + if (!$mr_point['MR_Selected_Num']) return false; + + /*============================================ + // SEND MAIL + //============================================*/ + $template = 'mr_new_order'; + $subject = $this->l('New order', false, (int)$id_lang).' - '.sprintf('%06d', $order->id); + + $mr_address = ''; + if ($mr_point['MR_Selected_LgAdr2']) + $mr_address .= $mr_point['MR_Selected_LgAdr2'].''; + if ($mr_point['MR_Selected_LgAdr3']) + $mr_address .= $mr_point['MR_Selected_LgAdr3'].''; + if ($mr_point['MR_Selected_LgAdr4']) + $mr_address .= $mr_point['MR_Selected_LgAdr4'].''; + + $templateVars = array( + '{firstname}' => $customer->firstname, + '{lastname}' => $customer->lastname, + '{email}' => $customer->email, + '{delivery_company}' => $mr_point['MR_Selected_LgAdr1'], + '{delivery_address1}' => $mr_address, + '{delivery_city}' => $mr_point['MR_Selected_Ville'], + '{delivery_postal_code}' => $mr_point['MR_Selected_CP'], + '{delivery_country}' => $mr_point['MR_Selected_Pays'], + '{invoice_company}' => $invoice->company, + '{invoice_firstname}' => $invoice->firstname, + '{invoice_lastname}' => $invoice->lastname, + '{invoice_address2}' => $invoice->address2, + '{invoice_address1}' => $invoice->address1, + '{invoice_city}' => $invoice->city, + '{invoice_postal_code}' => $invoice->postcode, + '{invoice_country}' => $invoice->country, + '{invoice_state}' => $invoice->id_state ? $invoice_state->name : '', + '{invoice_phone}' => $invoice->phone, + '{invoice_other}' => $invoice->other, + '{order_name}' => sprintf('%06d', $order->id), + '{shop_name}' => Configuration::get('PS_SHOP_NAME'), + '{date}' => $order_date_text, + '{carrier}' => (($carrier->name == '0') ? Configuration::get('PS_SHOP_NAME') : $carrier->name), + '{payment}' => Tools::substr($order->payment, 0, 32), + '{currency}' => $currency->sign, + ); + + $iso = Language::getIsoById((int)$id_lang); + if (file_exists(dirname(__FILE__).'/mails/'.$iso.'/'.$template.'.txt') && file_exists(dirname(__FILE__).'/mails/'.$iso.'/'.$template.'.html')) + Mail::Send((int)$id_lang, $template, $subject, $templateVars, $customer->email, $customer->firstname.' '.$customer->lastname, Configuration::get('PS_SHOP_EMAIL'), Configuration::get('PS_SHOP_NAME'), null, null, dirname(__FILE__).'/mails/'); + } + + public function hookBackOfficeHeader() + { + if (Tools::getValue('tab') == 'AdminMondialRelay' || Tools::getValue('module_name') == 'mondialrelay' || Tools::strtolower(Tools::getValue('controller')) == 'adminmondialrelay' || Tools::getValue('configure') == 'mondialrelay') + { + $this->context->smarty->assign(array( + 'MR_token' => MondialRelay::$MRBackToken, 'MR_local_path' => MondialRelay::$modulePath, + 'MR_account_set' => MondialRelay::isAccountSet(), 'new_base_dir' => MondialRelay::$moduleURL)); + + return $this->fetchTemplate('/views/templates/admin/', 'bo-header'); + } + } + + public function hookOrderDetailDisplayed($params) + { + if (!Mondialrelay::isMondialRelayCarrier($params['order']->id_carrier)) + return; + + $sql = ' + SELECT s.`MR_Selected_LgAdr1`, s.`MR_Selected_LgAdr2`, s.`MR_Selected_LgAdr3`, s.`MR_Selected_LgAdr4`, + s.`MR_Selected_CP`, s.`MR_Selected_Ville`, s.`MR_Selected_Pays`, s.`MR_Selected_Num`, s.`url_suivi`, s.`exp_number`, m.dlv_mode + FROM `'._DB_PREFIX_.'mr_selected` s + INNER JOIN '._DB_PREFIX_.'mr_method m ON m.id_mr_method = s.id_method + WHERE s.`id_cart` = '.(int)$params['order']->id_cart; + $res = Db::getInstance()->getRow($sql); + + if (!$res) + return; + + $point_relais = $res['MR_Selected_LgAdr1']. + ($res['MR_Selected_LgAdr1'] ? '
' : '').$res['MR_Selected_LgAdr2']. + ($res['MR_Selected_LgAdr2'] ? '
' : '').$res['MR_Selected_LgAdr3']. + ($res['MR_Selected_LgAdr3'] ? '
' : '').$res['MR_Selected_LgAdr4']. + ($res['MR_Selected_LgAdr4'] ? '
' : '').$res['MR_Selected_CP'].' '. + $res['MR_Selected_Ville'].'
'.$res['MR_Selected_Pays']; + + + if (($res['dlv_mode'] == 'LD1') || ($res['dlv_mode'] == 'LDS') || ($res['dlv_mode'] == 'HOM')) + $this->context->smarty->assign( + array( + 'mr_url' => $res['url_suivi'] + )); + else + $this->context->smarty->assign( + array( + 'mr_addr' => $point_relais, + 'mr_url' => $res['url_suivi'] + )); + + return $this->fetchTemplate('/views/templates/front/', 'order_detail'); + } + + /* + ** Update the carrier id to use the new one if changed + */ + public function hookupdateCarrier($params) + { + if ($params['id_carrier'] != $params['carrier']->id) + { + /* Get the old id_mr_method */ + $id_mr_method = Db::getInstance()->getValue(' + SELECT id_mr_method FROM `'._DB_PREFIX_.'mr_method` + WHERE id_carrier='.(int)$params['id_carrier']); + + /* Insert new entry keeping the last one linked to the id_carrier */ + $query = ' + INSERT INTO `'._DB_PREFIX_.'mr_method` + (name, country_list, col_mode, dlv_mode, insurance, id_carrier) + ( + SELECT + "'.pSQL($params['carrier']->name).'", + country_list, + col_mode, + dlv_mode, + insurance, + '.(int)$params['carrier']->id.' + FROM `'._DB_PREFIX_.'mr_method` + WHERE id_carrier ='.(int)$params['id_carrier'].')'; + Db::getInstance()->execute($query); + + /* Do the same process for the multishop table */ + $query = ' + INSERT INTO `'._DB_PREFIX_.'mr_method_shop` + (id_mr_method, id_shop) + ( + SELECT + '.(int)Db::getInstance()->INSERT_ID().', + id_shop + FROM `'._DB_PREFIX_.'mr_method_shop` + WHERE id_mr_method ='.(int)$id_mr_method.')'; + Db::getInstance()->execute($query); + + /* Set the last mr_method to delete */ + Db::getInstance()->execute(' + UPDATE `'._DB_PREFIX_.'mr_method` SET `is_deleted` = 1 + WHERE `id_mr_method` = '.(int)$id_mr_method); + } + } + + /** + * Get a carrier list liable to the module + * + * @return array + */ + public function _getCarriers() + { + /* Query don't use the external_module_name to keep the */ + /* 1.3 compatibility */ + $query = ' + SELECT c.id_carrier, c.range_behavior, m.id_mr_method, + m.dlv_mode, cl.delay + FROM `'._DB_PREFIX_.'mr_method` m + LEFT JOIN `'._DB_PREFIX_.'carrier` c + ON c.`id_carrier` = m.`id_carrier` + LEFT JOIN `'._DB_PREFIX_.'carrier_lang` cl + ON c.`id_carrier` = cl.`id_carrier` + LEFT JOIN `'._DB_PREFIX_.'mr_method_shop` ms + ON m.`id_mr_method` = ms.`id_mr_method` + WHERE c.`deleted` = 0 + AND ms.`id_shop` = '.$this->account_shop['id_shop'].' + AND cl.id_lang = '.$this->context->language->id.' + AND c.`active` = 1 + AND m.`is_deleted` = 0'; + + $carriers = Db::getInstance()->executeS($query); + + if (!is_array($carriers)) + $carriers = array(); + return $carriers; + } + + /** + * Get a specific method entry detail by a defined id_carrier + * + * @static + * @param $id_carrier + * @return array + */ + public static function getMethodByIdCarrier($id_carrier) + { + return Db::getInstance()->getRow(' + SELECT * FROM `'._DB_PREFIX_.'mr_method` m + WHERE m.`id_carrier` = '.(int)$id_carrier); + } + + /* + ** Added to be used properly with OPC + */ + public function hookHeader($params) + { + if (version_compare(_PS_VERSION_, '1.5', '>=')) + $this->context->controller->addJquery(); + + /*Configuration::updateValue('MONDIAL_RELAY_MODE', 'widget');*/ + if (!($file = basename(Tools::getValue('controller')))) + $file = str_replace('.php', '', basename($_SERVER['SCRIPT_NAME'])); + + if (in_array($file, array('order-opc', 'order', 'orderopc'))) + { + $this->context->smarty->assign(array( + 'one_page_checkout' => (Configuration::get('PS_ORDER_PROCESS_TYPE') ? Configuration::get('PS_ORDER_PROCESS_TYPE') : 0), + 'new_base_dir' => MondialRelay::$moduleURL, + 'MR_local_path' => MondialRelay::$modulePath, + 'MRToken' => MondialRelay::$MRFrontToken, + 'MR_MONDIAL_RELAY_MODE' => Configuration::get('MONDIAL_RELAY_MODE'), + ) + ); + + if($this->canAddJSViaController()) + $this->context->controller->addJS('https://maps.google.com/maps/api/js?sensor=false'); + else + $this->context->smarty->assign(array( + 'addJsInTemplate' => true + )); + + if (Configuration::get('MONDIAL_RELAY_MODE') == 'widget') + return $this->fetchTemplate('/views/templates/front/', 'header_widget'); + else + return $this->fetchTemplate('/views/templates/front/', 'header'); + } + return ''; + } + + private function canAddJSViaController() + { + if(version_compare(_PS_VERSION_, '1.6', '>=')) + return true; + + if(Configuration::get('PS_JS_THEME_CACHE')) + return false; + + return true; + } + + public function hookExtraCarrier($params) + { + /* TODO : Makes it work with multi-shipping */ + if (!MondialRelay::isAccountSet()) + return ''; + + $id_carrier = false; + $preSelectedRelay = $this->getRelayPointSelected($this->context->cart->id); + $carriersList = MondialRelay::_getCarriers(); + $address = new Address($this->context->cart->id_address_delivery); + $country = new Country($address->id_country); + $id_zone = Address::getZoneById((int)($address->id)); + + /* Check if the defined carrier are ok */ + foreach ($carriersList as $k => $row) + { + /* For now works only with single shipping (>= 1.5 compatibility) */ + if (method_exists($this->context->cart, 'carrierIsSelected')) + { + if ($this->context->cart->carrierIsSelected($row['id_carrier'], $params['address']->id)) + $id_carrier = $row['id_carrier']; + } + + /* Temporary carrier for some test */ + $carrier = new Carrier((int)($row['id_carrier'])); + if ((($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT) && $carrier->getMaxDeliveryPriceByWeight($id_zone) === false) || (($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_PRICE) && $carrier->getMaxDeliveryPriceByPrice($id_zone) === false)) + unset($carriersList[$k]); + else if ($row['range_behavior']) + { + /* Get id zone */ + $id_zone = (isset($this->context->cart->id_address_delivery) && $this->context->cart->id_address_delivery) ? + Address::getZoneById((int)$this->context->cart->id_address_delivery) : + (int)$this->context->country->id_zone; + + if (($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_WEIGHT && (!Carrier::checkDeliveryPriceByWeight($row['id_carrier'], $this->context->cart->getTotalWeight(), $id_zone))) || + ($carrier->getShippingMethod() == Carrier::SHIPPING_METHOD_PRICE && + (!Carrier::checkDeliveryPriceByPrice($row['id_carrier'], $this->context->cart->getOrderTotal(true, MondialRelay::BOTH_WITHOUT_SHIPPING), $id_zone, $this->context->cart->id_currency) || + !Carrier::checkDeliveryPriceByPrice($row['id_carrier'], $this->context->cart->getOrderTotal(true, MondialRelay::BOTH_WITHOUT_SHIPPING), $id_zone, $this->context->cart->id_currency)))) + unset($carriersList[$k]); + } + } + + $carrier = null; + if ($id_carrier && ($method = MondialRelay::getMethodByIdCarrier($id_carrier))) + { + $carrier = new Carrier((int)$id_carrier); + /* Add dynamically a new field */ + $carrier->id_mr_method = $method['id_mr_method']; + $carrier->mr_dlv_mode = $method['dlv_mode']; + } + + if (Configuration::get('PS_SSL_ENABLED') || (!empty($_SERVER['HTTPS']) && Tools::strtolower($_SERVER['HTTPS']) != 'off')) + $ssl = 'true'; + else $ssl = 'false'; + + $this->context->smarty->assign(array( + 'address' => $address, + 'account_shop' => $this->account_shop, + 'country' => $country, + 'ssl' => $ssl, + 'MR_Data'=> MRTools::jsonEncode(array( + 'carrier_list' => $carriersList, + 'carrier' => $carrier, + 'PS_VERSION' => _PS_VERSION_, + 'pre_selected_relay' => isset($preSelectedRelay['MR_selected_num']) ? $preSelectedRelay['MR_selected_num'] : -1, + )) + )); + if (Configuration::get('MONDIAL_RELAY_MODE') == 'widget') + return $this->fetchTemplate('/views/templates/front/', 'checkout_process_widget'); + else + return $this->fetchTemplate('/views/templates/front/', 'checkout_process'); + } + + /** + * Return the detailed account + * + * @static + * @return mixed + */ + public static function getAccountDetail() + { + return unserialize((string)Configuration::get('MR_ACCOUNT_DETAIL')); + } + + /** + * Check if the account is set + * + * @static + * @return bool + */ + public static function isAccountSet() + { + $details = MondialRelay::getAccountDetail(); + + if (!$details || !count($details)) + return false; + + foreach ($details as $value) + if (empty($value)) + return false; + + return true; + } + + /** + * Check any submitted form + */ + private function _postValidation() + { + if (Tools::isSubmit('submit_account_detail')) + { + if (Tools::getValue('MR_enseigne_webservice') == '' || !preg_match('#^[0-9A-Z]{2}[0-9A-Z ]{6}$#', Tools::getValue('MR_enseigne_webservice'))) + $this->_postErrors[] = $this->l('Invalid Enseigne'); + if (Tools::getValue('MR_code_marque') == '' || !preg_match('#^[0-9]{2}$#', Tools::getValue('MR_code_marque'))) + $this->_postErrors[] = $this->l('Invalid Mark code'); + if (Tools::getValue('MR_webservice_key') == '' || !preg_match("#^[0-9A-Za-z_\'., /\-]{2,32}$#", Tools::getValue('MR_webservice_key'))) + $this->_postErrors[] = $this->l('Invalid Webservice Key'); + if (Tools::getValue('MR_language') == '' || !preg_match('#^[A-Z]{2}$#', Tools::getValue('MR_language'))) + $this->_postErrors[] = $this->l('Invalid Language'); + if (!Tools::getValue('MR_weight_coefficient') || !Validate::isInt(Tools::getValue('MR_weight_coefficient'))) + $this->_postErrors[] = $this->l('Invalid Weight Coefficient'); + } + + /* Shipping form validation */ + else if (Tools::isSubmit('submitMethod')) + { + if (!preg_match("#^[0-9A-Za-z_\'., /\-]{2,32}$#", Tools::getValue('mr_Name'))) + $this->_postErrors[] = $this->l('Invalid carrier name'); + if (Tools::getValue('mr_ModeCol') != 'CCC') + $this->_postErrors[] = $this->l('Invalid Col mode'); + if (!preg_match('#^REL|24R|ESP|DRI|LDS|LDR|LD1|HOM$#', Tools::getValue('mr_ModeLiv'))) + $this->_postErrors[] = $this->l('Invalid delivery mode'); + if (!Validate::isInt(Tools::getValue('mr_ModeAss')) || Tools::getValue('mr_ModeAss') > 5 || Tools::getValue('mr_ModeAss') < 0) + $this->_postErrors[] = $this->l('Invalid Assurance mode'); + if (!Tools::getValue('mr_Pays_list')) + $this->_postErrors[] = $this->l('You must choose at least one delivery country.'); + } + + /* Order state form validation */ + else if (Tools::isSubmit('submit_order_state')) + { + if (!Validate::isUnsignedInt(Tools::getValue('id_order_state'))) + $this->_postErrors[] = $this->l('Invalid order state'); + } + + + } + + /** + * Update account shop + * + * @return bool + */ + public function updateAccountShop() + { + return Configuration::updateValue('MR_ACCOUNT_DETAIL', serialize($this->account_shop)); + } + + /** + * Post process + * + * @return array + */ + private function _postProcess() + { + $post_action = array( + 'type' =>Tools::safeOutput(Tools::getValue('MR_tab_name')), + 'message_success' => $this->l('Action Succeed'), + 'had_errors' => false + ); + + if (Tools::isSubmit('submitAdvancedSettings')) + Configuration::updateValue('MONDIAL_RELAY_MODE', Tools::getValue('mode', 'widget')); + else if (Tools::isSubmit('submit_account_detail')) + { + $this->account_shop = array( + 'MR_ENSEIGNE_WEBSERVICE' => Tools::safeOutput(Tools::getValue('MR_enseigne_webservice')), + 'MR_CODE_MARQUE' => Tools::safeOutput(Tools::getValue('MR_code_marque')), + 'MR_KEY_WEBSERVICE' =>Tools::safeOutput(Tools::getValue('MR_webservice_key')), + 'MR_LANGUAGE' => Tools::safeOutput(Tools::getValue('MR_language')), + 'MR_ORDER_STATE' => Tools::safeOutput($this->account_shop['MR_ORDER_STATE']), + 'MR_WEIGHT_COEFFICIENT' => Tools::safeOutput(Tools::getValue('MR_weight_coefficient')), + 'id_shop' => $this->context->shop->id + ); + if ($this->updateAccountShop()) + $post_action['message_success'] = $this->l('Account detail has been updated'); + else + $this->_postErrors[] = $this->l('Cannot Update the account shop'); + } + else if (Tools::isSubmit('submit_add_shipping')) + { + if (($this->addShippingMethod())) + $post_action['message_success'] = $this->l('Shipping method has been added'); + } + else if (Tools::isSubmit('submit_order_state')) + { + Configuration::updateValue('MONDIAL_RELAY_ORDER_STATE', Tools::getValue('id_order_state')); + $post_action['message_success'] = $this->l('Order state properly changed'); + } + else if (($id_mr_method = Tools::getValue('delete_mr')) && $this->disableCarrier((int)$id_mr_method)) + $post_action['message_success'] = $this->l('Carrier has been deleted (disabled under the prestashop database)'); + + if (count($this->_postErrors)) + $post_action['had_errors'] = true; + + return $post_action; + } + + public function getContent() + { + $post_action = null; + if (!empty($_POST)) + { + $this->_postValidation(); + if (!count($this->_postErrors)) + $post_action = $this->_postProcess(); + } + $carriers_list = Db::getInstance()->executeS(' + SELECT m.* + FROM `'._DB_PREFIX_.'mr_method` m + LEFT JOIN `'._DB_PREFIX_.'carrier` c + ON (c.`id_carrier` = m.`id_carrier`) + LEFT JOIN `'._DB_PREFIX_.'mr_method_shop` ms + ON ms.`id_mr_method` = m.`id_mr_method` + WHERE c.`deleted` = 0 AND ms.`id_shop` = '.(int)$this->account_shop['id_shop']); + + $controller = version_compare(_PS_VERSION_, '1.5', '<') ? 'AdminContact' : 'AdminStores'; + + /* TODO : Fill an array with admi controller name */ + $this->context->smarty->assign(array( + 'MR_token_admin_performance' => Tools::getAdminToken('AdminPerformance'.(int)(Tab::getIdFromClassName('AdminPerformance')).(int)($this->context->cookie->id_employee)), + 'MR_token_admin_carriers' => (version_compare(_PS_VERSION_, '1.6', '<') ? Tools::getAdminToken('AdminCarriers'.(int)(Tab::getIdFromClassName('AdminCarriers')).(int)$this->context->employee->id) : Tools::getAdminToken('AdminCarrierWizard'.(int)(Tab::getIdFromClassName('AdminCarrierWizard')).(int)$this->context->employee->id)), + 'MR_token_admin_contact' => array( + 'controller_name' => $controller, + 'token' => Tools::getAdminToken($controller.(int)(Tab::getIdFromClassName($controller)).(int)$this->context->employee->id)), + 'MR_token_admin_mondialrelay' => Tools::getAdminToken('AdminMondialRelay'.(int)(Tab::getIdFromClassName('AdminMondialRelay')).(int)$this->context->employee->id), + 'MR_token_admin_module' => Tools::getAdminToken('AdminModules'.(int)(Tab::getIdFromClassName('AdminModules')).(int)$this->context->employee->id), + 'MR_enseigne_webservice' => Tools::getValue('MR_enseigne_webservice') ? Tools::getValue('MR_enseigne_webservice') : $this->account_shop['MR_ENSEIGNE_WEBSERVICE'], + 'MR_code_marque' => Tools::getValue('MR_code_marque') ? Tools::getValue('MR_code_marque') : $this->account_shop['MR_CODE_MARQUE'], + 'MR_webservice_key' => Tools::getValue('MR_webservice_key') ? Tools::getValue('MR_webservice_key') : $this->account_shop['MR_KEY_WEBSERVICE'], + 'MR_available_languages' => Language::getLanguages(), + 'MR_selected_language' => $this->account_shop['MR_LANGUAGE'], + 'MR_weight_coefficient' => Tools::getValue('MR_weight_coefficient') ? Tools::getValue('MR_weight_coefficient') : $this->account_shop['MR_WEIGHT_COEFFICIENT'], + 'MR_PS_WEIGHT_UNIT' => Configuration::get('PS_WEIGHT_UNIT'), + 'MR_order_states_list' => OrderState::getOrderStates($this->context->language->id), + 'MR_MONDIAL_RELAY_ORDER_STATE' => Configuration::get('MONDIAL_RELAY_ORDER_STATE'), + 'MR_CRON_URL' => Tools::getHttpHost(true, true)._MODULE_DIR_.$this->name.'/cron.php?secure_key='.Configuration::get('MONDIAL_RELAY_SECURE_KEY'), + 'MR_name' => Tools::getValue('MR_name') ? Tools::getValue('MR_name') : '', + 'MR_carriers_list' => $carriers_list, + 'MR_error_list' => $this->_postErrors, + 'MR_form_action' => $post_action, + 'MR_PS_ADMIN_IMG_' => _PS_ADMIN_IMG_, + 'MR_tab_selected' => Tools::getValue('MR_tab_name') ? Tools::getValue('MR_tab_name') : (MondialRelay::isAccountSet() ? 'account_form' : 'info_form'), + 'MR_delay' => Tools::getValue('MR_delay') ? Tools::getValue('MR_delay') : '', + 'MR_local_path' => MondialRelay::$modulePath, + 'MR_upgrade_detail' => $this->upgrade_detail, + 'MR_unit_weight_used' => Configuration::get('PS_WEIGHT_UNIT'), + 'MR_account_set' => MondialRelay::isAccountSet(), + 'MR_base_dir' => MondialRelay::$moduleURL, + 'MR_MONDIAL_RELAY_MODE' => Configuration::get('MONDIAL_RELAY_MODE'), + ) + ); + return $this->fetchTemplate('/views/templates/admin/', 'configuration'); + } + + /** + * Add new carrier + * + * @param $name + * @param $delay + * @return bool|int + */ + private function addCarrier($name, $delay) + { + $ret = false; + + if (($carrier = new Carrier())) + { + $delay_lang = array(); + foreach (Language::getLanguages(false) as $lang) + $delay_lang[$lang['id_lang']] = $delay; + $carrier->name = $name; + $carrier->active = 1; + $carrier->range_behavior = 1; + $carrier->need_range = 1; + $carrier->external_module_name = 'mondialrelay'; + $carrier->shipping_method = 1; + $carrier->delay = $delay_lang; + $carrier->is_module = version_compare(_PS_VERSION_, '1.4', '<') ? 0 : 1; + + $ret = $carrier->add(); + } + return $ret ? $carrier->id : false; + } + + public function displayInfoByCart($id_cart) + { + $html = '

'; + $simpleresul = Db::getInstance()->executeS(' + SELECT * FROM '._DB_PREFIX_.'mr_selected + WHERE id_cart='.(int)($id_cart)); + + if (isset($simpleresul[0])) + { + if (trim($simpleresul[0]['exp_number']) != '') + $html .= $this->l('Nb expedition:').$simpleresul[0]['exp_number'].'
'; + if (trim($simpleresul[0]['url_etiquette']) != '') + $html .= ''.$this->l('Label URL').'
'; + if (trim($simpleresul[0]['url_suivi']) != '') + $html .= ''.$this->l('Follow-up URL').'
'; + if (trim($simpleresul[0]['MR_Selected_Num']) != '') + $html .= $this->l('Nb Point Relay :').$simpleresul[0]['MR_Selected_Num'].'
'; + if (trim($simpleresul[0]['MR_Selected_LgAdr1']) != '') + $html .= $simpleresul[0]['MR_Selected_LgAdr1'].'
'; + if (trim($simpleresul[0]['MR_Selected_LgAdr2']) != '') + $html .= $simpleresul[0]['MR_Selected_LgAdr2'].'
'; + if (trim($simpleresul[0]['MR_Selected_LgAdr3']) != '') + $html .= $simpleresul[0]['MR_Selected_LgAdr3'].'
'; + if (trim($simpleresul[0]['MR_Selected_LgAdr4']) != '') + $html .= $simpleresul[0]['MR_Selected_LgAdr4'].'
'; + if (trim($simpleresul[0]['MR_Selected_CP']) != '') + $html .= $simpleresul[0]['MR_Selected_CP'].' '; + if (trim($simpleresul[0]['MR_Selected_Ville']) != '') + $html .= $simpleresul[0]['MR_Selected_Ville'].'
'; + if (trim($simpleresul[0]['MR_Selected_Pays']) != '') + $html .= $simpleresul[0]['MR_Selected_Pays'].'
'; + } + $html .= '

'; + return $html; + } + + /** + * Set necessaries values to the created carrier + * + * @param $id_carrier + * @param $dlv_mode + * @return bool + */ + private function addDefaultCarrierValue($id_carrier, $dlv_mode) + { + $weight_coef = $this->account_shop['MR_WEIGHT_COEFFICIENT']; + + /* Default Range value depending of the delivery mode */ + $range_weight = array( + '24R' => array(0, 30000 / $weight_coef), + 'DRI' => array(30000 / $weight_coef, 130000 / $weight_coef), + 'LD1' => array(0, 60000 / $weight_coef), + 'HOM' => array(0, 60000 / $weight_coef), + 'LDS' => array(30000 / $weight_coef, 130000 / $weight_coef) + ); + + /* Set range weight for a dlv_mode */ + if (!Db::getInstance()->execute( + 'INSERT INTO `'._DB_PREFIX_.'range_weight` + (`id_carrier`, `delimiter1`, `delimiter2`) + VALUES ('.(int)$id_carrier.', '.$range_weight[$dlv_mode][0].', '.$range_weight[$dlv_mode][1].')')) + { + $this->_postErrors[] = $this->l('Range weight can\'t be added'); + return false; + } + + $range_weight_id = Db::getInstance()->Insert_ID(); + + /* Set a range price */ + if (!Db::getInstance()->execute( + 'INSERT INTO `'._DB_PREFIX_.'range_price` + (`id_carrier`, `delimiter1`, `delimiter2`) + VALUES ('.(int)$id_carrier.', 0.000000, 10000.000000)')) + { + $this->_postErrors[] = $this->l('Range price can\'t be added'); + return false; + } + + $range_price_id = Db::getInstance()->Insert_ID(); + + $groups = Group::getGroups(Configuration::get('PS_LANG_DEFAULT')); + foreach ($groups as $group) + if (!Db::getInstance()->execute( + 'INSERT INTO `'._DB_PREFIX_.'carrier_group` + (id_carrier, id_group) + VALUES('.(int)$id_carrier.', '.(int)($group['id_group']).')')) + { + $this->_postErrors[] = $this->l('Default zone can\'t be added'); + return false; + } + + /* Set default zone */ + $zones = Zone::getZones(); + foreach ($zones as $zone) + { + if (!Db::getInstance()->execute( + 'INSERT INTO `'._DB_PREFIX_.'carrier_zone` + (id_carrier, id_zone) + VALUES('.(int)$id_carrier.', '.(int)($zone['id_zone']).')') || + !Db::getInstance()->execute( + 'INSERT INTO `'._DB_PREFIX_.'delivery` + (id_carrier, id_range_price, id_range_weight, id_zone, price) + VALUES('.(int)$id_carrier.', '.(int)($range_price_id).', NULL,'.(int)($zone['id_zone']).', 0.00)') || + !Db::getInstance()->execute( + 'INSERT INTO `'._DB_PREFIX_.'delivery` + (id_carrier, id_range_price, id_range_weight, id_zone, price) + VALUES('.(int)$id_carrier.', NULL, '.(int)($range_weight_id).','.(int)($zone['id_zone']).', 0.00)')) + { + $this->_postErrors[] = $this->l('Carrier zone or delivery data can\'t be added'); + return false; + } + } + return true; + } + + /** + * Add new shipping method + * + * @return bool + */ + private function addShippingMethod() + { + /* Insert new carrier for under Prestashop */ + if (!($id_carrier = $this->addCarrier(Tools::getValue('MR_name'), Tools::getValue('MR_delay')))) + { + $this->_postErrors[] = $this->l('Carrier can\'t be created in PrestaShop'); + return false; + } + + $fields = $_POST; + + unset($fields['submit_add_shipping'], $fields['MR_tab_name'], $fields['tab'], $fields['MR_delay']); + + /* Force col mod to CCC */ + $fields['col_mode'] = 'CCC'; + $fields['id_carrier'] = $id_carrier; + + $query = 'INSERT INTO `'._DB_PREFIX_.'mr_method` (%s) VALUES(%s)'; + + $keys = array(); + $values = array(); + foreach ($fields as $key => $value) + { + $keys[] = '`'.str_replace('MR_', '', $key).'`'; + $values[] = '\''.(is_array($value) ? pSQL(implode(',', $value)) : pSQL($value)).'\''; + } + $query = sprintf($query, implode(',', $keys), implode(',', $values)); + + if (!Db::getInstance()->execute($query) || !Db::getInstance()->execute('INSERT INTO `'._DB_PREFIX_.'mr_method_shop` + (id_mr_method, id_shop) VALUES('.(int)Db::getInstance()->INSERT_ID().', '.(int)$this->account_shop['id_shop'].')')) + { + $this->l('Carrier method can\'t be added for the module'); + Db::getInstance()->execute('DELETE FROM `'._DB_PREFIX_.'carrier` WHERE id_carrier='.(int)$id_carrier); + return false; + } + return $this->addDefaultCarrierValue($id_carrier, $fields['MR_dlv_mode']); + } + + /** + * Disable carrier instead of delete to keep history + * + * @param $id_mr_method + */ + public function disableCarrier($id_mr_method) + { + if (($id_carrier = Db::getInstance()->getValue( + 'SELECT `id_carrier` + FROM `'._DB_PREFIX_.'mr_method` + WHERE `id_mr_method` = '.(int)($id_mr_method))) && + Db::getInstance()->execute( + 'UPDATE `'._DB_PREFIX_.'carrier` c, `'._DB_PREFIX_.'mr_method` m + SET c.`active` = 0, c.`deleted` = 1, m.`is_deleted` = 1 + WHERE + c.`id_carrier` = m.`id_carrier` + AND c.`id_carrier` = '.(int)$id_carrier)) + return true; + + $this->_postErrors = $this->l('Carrier can\'t be deleted yet'); + return false; + } + + /** + * Get the followup url + * + * @param $exp_number + * @return mixed + */ + public function get_followup($exp_number) + { + $query = ' + SELECT url_suivi + FROM '._DB_PREFIX_.'mr_selected + WHERE exp_number='.(int)$exp_number; + + return Db::getInstance()->getValue($query); + } + + /** + * Get the SQL query to fetch order with mr carrier + * + * @static + * @param $id_order_state + * @param $weight_coefficient + * @return string + */ + public static function getBaseOrdersSQLQuery($id_order_state, $weight_coefficient = 0) + { + return 'SELECT o.`id_address_delivery` as id_address_delivery, + o.`id_order` as id_order, + o.`id_customer` as id_customer, + o.`id_cart` as id_cart, + o.`id_lang` as id_lang, + mrs.`id_mr_selected` as id_mr_selected, + CONCAT(c.`firstname`, " ", c.`lastname`) AS `customer`, + o.`total_paid_real` as total, o.`total_shipping` as shipping, + o.`date_add` as date, o.`id_currency` as id_currency, o.`id_lang` as id_lang, + mrs.`MR_poids` as mr_weight, + mrs.`MR_insurance` as mr_insurance, + mr.`name` as mr_Name, mrs.`MR_Selected_Num` as MR_Selected_Num, + mrs.`MR_Selected_Pays` as MR_Selected_Pays, mrs.`exp_number` as exp_number, + mr.`col_mode` as mr_ModeCol, mr.`dlv_mode` as mr_ModeLiv, mr.`insurance` as mr_ModeAss, + ROUND(SUM(odt.`product_weight` * odt.`product_quantity`) * '.(int)$weight_coefficient.') AS "order_weight" + FROM + `'._DB_PREFIX_.'orders` o + LEFT JOIN + `'._DB_PREFIX_.'carrier` ca + ON (ca.`id_carrier` = o.`id_carrier`) + LEFT JOIN + `'._DB_PREFIX_.'mr_selected` mrs + ON (mrs.`id_cart` = o.`id_cart`) + LEFT JOIN + `'._DB_PREFIX_.'mr_method` mr + ON (mr.`id_carrier` = ca.`id_carrier`) + LEFT JOIN + `'._DB_PREFIX_.'customer` c + ON (c.`id_customer` = o.`id_customer`) + LEFT JOIN + `'._DB_PREFIX_.'order_detail` odt + ON odt.`id_order` = o.`id_order` + WHERE ( + SELECT moh.`id_order_state` + FROM `'._DB_PREFIX_.'order_history` moh + WHERE moh.`id_order` = o.`id_order` + ORDER BY moh.`date_add` DESC LIMIT 1) = '.(int)($id_order_state).' + AND o.`id_order` = mrs.`id_order`'; + } + + /** + * Get orders details to create Tickets + * + * @static + * @param array $orderIdList + * @param int $filterEntries + * @param int $weight_coefficient + * @return array + */ + public static function getOrders($orderIdList = array(), $filterEntries = MondialRelay::NO_FILTER, $weight_coefficient = 0) + { + $account_shop = MondialRelay::getAccountDetail(); + $id_order_state = $account_shop['MR_ORDER_STATE']; + $sql = MondialRelay::getBaseOrdersSQLQuery($id_order_state, $weight_coefficient); + + if (count($orderIdList)) + { + $sql .= ' AND o.id_order IN ('; + foreach ($orderIdList as $id_order) + $sql .= (int)$id_order.', '; + $sql = rtrim($sql, ', ').')'; + } + switch ($filterEntries) + { + case MondialRelay::WITHOUT_HOME_DELIVERY: + $sql .= 'AND mr.mr_ModeLiv != "LD1" AND mr.mr_ModeLiv != "LDS" AND mr.mr_ModeLiv != "HOM"'; + break; + } + $sql .= ' + GROUP BY o.`id_order` + ORDER BY o.`date_add` ASC'; + return Db::getInstance()->executeS($sql); + } + + /** + * Get Mondialrelay error code + * + * @param $code + * @return string + */ + public function getErrorCodeDetail($code) + { + include(dirname(__FILE__).'/errorCode.php'); + if (isset($statCode[$code])) + return $statCode[$code]; + return $this->l('This error isn\'t referred : ').$code; + } + + /** + * @param $id_cart + * @return mixed + */ + public function getRelayPointSelected($id_cart) + { + return Db::getInstance()->getRow(' + SELECT s.`MR_selected_num` + FROM `'._DB_PREFIX_.'mr_selected` s + WHERE s.`id_cart` = '.(int)$id_cart); + } + + /** + * @param $id_carrier + * @return mixed + */ + public function isMondialRelayCarrier($id_carrier) + { + return Db::getInstance()->getRow(' + SELECT m.`id_mr_method` + FROM `'._DB_PREFIX_.'mr_method` m + WHERE `id_carrier` = '.(int)$id_carrier); + } + + public function getMethodValueByIdCarier($id_carrier, $key) + { + $content = Db::getInstance()->executeS( + 'SELECT * + FROM `'._DB_PREFIX_.'mr_method` m + WHERE `id_carrier` = '.(int)$id_carrier); + + return isset($content[$key]) ? $content[$key] : ''; + } + + public function checkAJAX() + { + /* Avoid loop inclusion */ + static $is_included = false; + + /* TODO : Find a way to use it on front */ + if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && Tools::strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') + if (Tools::getValue('mrtoken') && !$is_included) + { + $is_included = true; + include(dirname(__FILE__).'/ajax.php'); + exit(0); + } + } } diff --git a/nl.php b/nl.php old mode 100644 new mode 100755 diff --git a/sql/index.php b/sql/index.php old mode 100644 new mode 100755 index fc4110f..087b026 --- a/sql/index.php +++ b/sql/index.php @@ -27,10 +27,10 @@ header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT"); - + header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); - + header("Location: ../"); exit; \ No newline at end of file diff --git a/sql/mrInstall.sql b/sql/mrInstall.sql old mode 100644 new mode 100755 diff --git a/upgrade/index.php b/upgrade/index.php old mode 100644 new mode 100755 index fc4110f..087b026 --- a/upgrade/index.php +++ b/upgrade/index.php @@ -27,10 +27,10 @@ header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT"); - + header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); - + header("Location: ../"); exit; \ No newline at end of file diff --git a/upgrade/install-1.8.0.php b/upgrade/install-1.8.0.php old mode 100644 new mode 100755 index 7d99093..3d16016 --- a/upgrade/install-1.8.0.php +++ b/upgrade/install-1.8.0.php @@ -28,103 +28,103 @@ /* File Example for upgrade */ if (!defined('_PS_VERSION_')) - exit; + exit; /* object module ($this) available */ function upgrade_module_1_8_0($object) { - $upgrade_version = '1.8.0'; - - $object->upgrade_detail[$upgrade_version] = array(); - - /* Add new table to handle multi-shop for a carrier */ - $query = ' - CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'mr_method_shop` ( - `id_mr_method_shop` int(10) unsigned NOT NULL auto_increment, - `id_mr_method` int(10) unsigned NOT NULL, - `id_shop` int(10) unsigned NOT NULL, - PRIMARY KEY (`id_mr_method_shop`) - ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;'; - - if (!Db::getInstance()->execute($query)) - $object->upgrade_detail[$upgrade_version][] = $object->l('Can\'t create method shop table'); - - /* Refacto name */ - $query = ' - ALTER TABLE `'._DB_PREFIX_.'mr_method` CHANGE `id_mr_method` `id_mr_method` INT( 10 ) UNSIGNED NOT NULL AUTO_INCREMENT , - CHANGE `mr_Name` `name` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL , - CHANGE `mr_Pays_list` `country_list` VARCHAR( 1000 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL , - CHANGE `mr_ModeCol` `col_mode` VARCHAR( 3 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL , - CHANGE `mr_ModeLiv` `dlv_mode` VARCHAR( 3 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL , - CHANGE `mr_ModeAss` `insurance` VARCHAR( 3 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT \'0\', - CHANGE `id_carrier` `id_carrier` INT( 10 ) NOT NULL'; - - if (!Db::getInstance()->execute($query)) - $object->upgrade_detail[$upgrade_version][] = $object->l('Can\'t change name of the method table'); - - $query = 'RENAME TABLE `'._DB_PREFIX_.'mr_historique` TO `'._DB_PREFIX_.'mr_history`'; - - if (!Db::getInstance()->execute($query)) - $object->upgrade_detail[$upgrade_version][] = $object->l('Can\'t rename the history table'); - - $object->account_shop['MR_ENSEIGNE_WEBSERVICE'] = Configuration::get('MR_ENSEIGNE_WEBSERVICE'); - $object->account_shop['MR_CODE_MARQUE'] = Configuration::get('MR_CODE_MARQUE'); - $object->account_shop['MR_KEY_WEBSERVICE'] = Configuration::get('MR_KEY_WEBSERVICE'); - $object->account_shop['MR_LANGUAGE'] = Configuration::get('MR_LANGUAGE'); - $object->account_shop['MR_WEIGHT_COEFFICIENT'] = Configuration::get('MR_WEIGHT_COEF'); - $object->account_shop['MR_ORDER_STATE'] = Configuration::get('MONDIAL_RELAY_ORDER_STATE'); - $object->updateAccountShop(); - - Configuration::deleteByName('MONDIAL_RELAY_INSTALL_UPDATE'); - Configuration::deleteByName('MONDIAL_RELAY_ORDER_STATE'); - Configuration::deleteByName('MR_ENSEIGNE_WEBSERVICE'); - Configuration::deleteByName('MR_CODE_MARQUE'); - Configuration::deleteByName('MR_KEY_WEBSERVICE'); - Configuration::deleteByName('MR_WEIGHT_COEF'); - Configuration::deleteByName('MR_LANGUAGE'); - Configuration::deleteByName('MONDIAL_RELAY_1_4'); - Configuration::deleteByName('MONDIAL_RELAY_INSTALL_UPDATE_1'); - - Configuration::updateValue('MONDIAL_RELAY', $upgrade_version); - - $methods = Db::getInstance()->executeS('SELECT * FROM `'._DB_PREFIX_.'mr_method`'); - if (count($methods)) - { - $query = ' - INSERT INTO `'._DB_PREFIX_.'mr_method_shop` - (id_mr_method, id_shop) VALUES '; - - foreach ($methods as $method) - $query .= '('.(int)$method['id_mr_method'].', '.(int)$object->account_shop['id_shop'].'),'; - $query = trim($query, ','); - if (!Db::getInstance()->execute($query)) - $object->upgrade_detail[$upgrade_version][] = $object->l('Can\'t update table mr_method_shop'); - - } - - if (!empty($object->installed_version)) - { - if ($object->installed_version < '1.4') - Db::getInstance()->execute(' - UPDATE `'._DB_PREFIX_.'carrier` - SET - `shipping_external` = 0, - `need_range` = 1, - `external_module_name` = "mondialrelay", - `shipping_method` = 1 - WHERE `id_carrier` - IN (SELECT `id_carrier` - FROM `'._DB_PREFIX_.'mr_method`)'); - } - - /* Try to register the new hook since 1.7 */ - if (!$object->isRegisteredInHook('newOrder')) - $object->registerHook('newOrder'); - if (!$object->isRegisteredInHook('BackOfficeHeader')) - $object->registerHook('BackOfficeHeader'); - - if (!$object->isRegisteredInHook('header')) - $object->registerHook('header'); - - return (bool)count($object->upgrade_detail[$upgrade_version]); + $upgrade_version = '1.8.0'; + + $object->upgrade_detail[$upgrade_version] = array(); + + /* Add new table to handle multi-shop for a carrier */ + $query = ' + CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'mr_method_shop` ( + `id_mr_method_shop` int(10) unsigned NOT NULL auto_increment, + `id_mr_method` int(10) unsigned NOT NULL, + `id_shop` int(10) unsigned NOT NULL, + PRIMARY KEY (`id_mr_method_shop`) + ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;'; + + if (!Db::getInstance()->execute($query)) + $object->upgrade_detail[$upgrade_version][] = $object->l('Can\'t create method shop table'); + + /* Refacto name */ + $query = ' + ALTER TABLE `'._DB_PREFIX_.'mr_method` CHANGE `id_mr_method` `id_mr_method` INT( 10 ) UNSIGNED NOT NULL AUTO_INCREMENT , + CHANGE `mr_Name` `name` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL , + CHANGE `mr_Pays_list` `country_list` VARCHAR( 1000 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL , + CHANGE `mr_ModeCol` `col_mode` VARCHAR( 3 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL , + CHANGE `mr_ModeLiv` `dlv_mode` VARCHAR( 3 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL , + CHANGE `mr_ModeAss` `insurance` VARCHAR( 3 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT \'0\', + CHANGE `id_carrier` `id_carrier` INT( 10 ) NOT NULL'; + + if (!Db::getInstance()->execute($query)) + $object->upgrade_detail[$upgrade_version][] = $object->l('Can\'t change name of the method table'); + + $query = 'RENAME TABLE `'._DB_PREFIX_.'mr_historique` TO `'._DB_PREFIX_.'mr_history`'; + + if (!Db::getInstance()->execute($query)) + $object->upgrade_detail[$upgrade_version][] = $object->l('Can\'t rename the history table'); + + $object->account_shop['MR_ENSEIGNE_WEBSERVICE'] = Configuration::get('MR_ENSEIGNE_WEBSERVICE'); + $object->account_shop['MR_CODE_MARQUE'] = Configuration::get('MR_CODE_MARQUE'); + $object->account_shop['MR_KEY_WEBSERVICE'] = Configuration::get('MR_KEY_WEBSERVICE'); + $object->account_shop['MR_LANGUAGE'] = Configuration::get('MR_LANGUAGE'); + $object->account_shop['MR_WEIGHT_COEFFICIENT'] = Configuration::get('MR_WEIGHT_COEF'); + $object->account_shop['MR_ORDER_STATE'] = Configuration::get('MONDIAL_RELAY_ORDER_STATE'); + $object->updateAccountShop(); + + Configuration::deleteByName('MONDIAL_RELAY_INSTALL_UPDATE'); + Configuration::deleteByName('MONDIAL_RELAY_ORDER_STATE'); + Configuration::deleteByName('MR_ENSEIGNE_WEBSERVICE'); + Configuration::deleteByName('MR_CODE_MARQUE'); + Configuration::deleteByName('MR_KEY_WEBSERVICE'); + Configuration::deleteByName('MR_WEIGHT_COEF'); + Configuration::deleteByName('MR_LANGUAGE'); + Configuration::deleteByName('MONDIAL_RELAY_1_4'); + Configuration::deleteByName('MONDIAL_RELAY_INSTALL_UPDATE_1'); + + Configuration::updateValue('MONDIAL_RELAY', $upgrade_version); + + $methods = Db::getInstance()->executeS('SELECT * FROM `'._DB_PREFIX_.'mr_method`'); + if (count($methods)) + { + $query = ' + INSERT INTO `'._DB_PREFIX_.'mr_method_shop` + (id_mr_method, id_shop) VALUES '; + + foreach ($methods as $method) + $query .= '('.(int)$method['id_mr_method'].', '.(int)$object->account_shop['id_shop'].'),'; + $query = trim($query, ','); + if (!Db::getInstance()->execute($query)) + $object->upgrade_detail[$upgrade_version][] = $object->l('Can\'t update table mr_method_shop'); + + } + + if (!empty($object->installed_version)) + { + if ($object->installed_version < '1.4') + Db::getInstance()->execute(' + UPDATE `'._DB_PREFIX_.'carrier` + SET + `shipping_external` = 0, + `need_range` = 1, + `external_module_name` = "mondialrelay", + `shipping_method` = 1 + WHERE `id_carrier` + IN (SELECT `id_carrier` + FROM `'._DB_PREFIX_.'mr_method`)'); + } + + /* Try to register the new hook since 1.7 */ + if (!$object->isRegisteredInHook('newOrder')) + $object->registerHook('newOrder'); + if (!$object->isRegisteredInHook('BackOfficeHeader')) + $object->registerHook('BackOfficeHeader'); + + if (!$object->isRegisteredInHook('header')) + $object->registerHook('header'); + + return (bool)count($object->upgrade_detail[$upgrade_version]); } \ No newline at end of file diff --git a/upgrade/install-1.8.3.php b/upgrade/install-1.8.3.php old mode 100644 new mode 100755 index d416e1c..6d500a6 --- a/upgrade/install-1.8.3.php +++ b/upgrade/install-1.8.3.php @@ -26,20 +26,20 @@ */ if (!defined('_PS_VERSION_')) - exit; + exit; /** * object module available */ function upgrade_module_1_8_3($object) { - $upgrade_version = '1.8.3'; + $upgrade_version = '1.8.3'; - $object->upgrade_detail[$upgrade_version] = array(); + $object->upgrade_detail[$upgrade_version] = array(); - if (!Db::getInstance()->execute('ALTER TABLE `'._DB_PREFIX_.'mr_method` ADD `is_deleted` INT NOT NULL')) - $object->upgrade_detail[$upgrade_version][] = $object->l('Can\'t add new field in methodtable'); + if (!Db::getInstance()->execute('ALTER TABLE `'._DB_PREFIX_.'mr_method` ADD `is_deleted` INT NOT NULL')) + $object->upgrade_detail[$upgrade_version][] = $object->l('Can\'t add new field in methodtable'); - Configuration::updateValue('MONDIAL_RELAY', $upgrade_version); - return (bool)count($object->upgrade_detail[$upgrade_version]); + Configuration::updateValue('MONDIAL_RELAY', $upgrade_version); + return (bool)count($object->upgrade_detail[$upgrade_version]); } \ No newline at end of file diff --git a/upgrade/install-2.0.6.php b/upgrade/install-2.0.6.php old mode 100644 new mode 100755 index ff4f9fd..cb4050a --- a/upgrade/install-2.0.6.php +++ b/upgrade/install-2.0.6.php @@ -26,23 +26,23 @@ */ if (!defined('_PS_VERSION_')) - exit; + exit; /** * object module available */ function upgrade_module_2_0_6($object) { - $upgrade_version = '2.0.6'; + $upgrade_version = '2.0.6'; - $object->upgrade_detail[$upgrade_version] = array(); + $object->upgrade_detail[$upgrade_version] = array(); - try { - if (!Db::getInstance()->execute('ALTER TABLE `'._DB_PREFIX_.'mr_selected` ADD `MR_insurance` INT( 11 ) NOT NULL AFTER `MR_poids`')) - $object->upgrade_detail[$upgrade_version][] = $object->l('Can\'t add new field in methodtable'); - } - catch (Exception $e) { } - - Configuration::updateValue('MONDIAL_RELAY', $upgrade_version); - return (bool)count($object->upgrade_detail[$upgrade_version]); + try { + if (!Db::getInstance()->execute('ALTER TABLE `'._DB_PREFIX_.'mr_selected` ADD `MR_insurance` INT( 11 ) NOT NULL AFTER `MR_poids`')) + $object->upgrade_detail[$upgrade_version][] = $object->l('Can\'t add new field in methodtable'); + } + catch (Exception $e) { } + + Configuration::updateValue('MONDIAL_RELAY', $upgrade_version); + return (bool)count($object->upgrade_detail[$upgrade_version]); } \ No newline at end of file diff --git a/views/index.php b/views/index.php old mode 100644 new mode 100755 index 0bfbc8e..fa0395b --- a/views/index.php +++ b/views/index.php @@ -27,10 +27,10 @@ header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT"); - + header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); - + header("Location: ../"); exit; \ No newline at end of file diff --git a/views/templates/admin/bo-header.tpl b/views/templates/admin/bo-header.tpl old mode 100644 new mode 100755 diff --git a/views/templates/admin/configuration.tpl b/views/templates/admin/configuration.tpl old mode 100644 new mode 100755 diff --git a/views/templates/admin/generate_tickets.tpl b/views/templates/admin/generate_tickets.tpl old mode 100644 new mode 100755 diff --git a/views/templates/admin/history.tpl b/views/templates/admin/history.tpl old mode 100644 new mode 100755 diff --git a/views/templates/admin/index.php b/views/templates/admin/index.php old mode 100644 new mode 100755 index 4deda52..9cf60e3 --- a/views/templates/admin/index.php +++ b/views/templates/admin/index.php @@ -27,10 +27,10 @@ header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT"); - + header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); - + header("Location: ../"); exit; \ No newline at end of file diff --git a/views/templates/admin/post_action.tpl b/views/templates/admin/post_action.tpl old mode 100644 new mode 100755 diff --git a/views/templates/admin/settings.tpl b/views/templates/admin/settings.tpl old mode 100644 new mode 100755 diff --git a/views/templates/front/checkout_process.tpl b/views/templates/front/checkout_process.tpl old mode 100644 new mode 100755 index e221b9e..29a308a --- a/views/templates/front/checkout_process.tpl +++ b/views/templates/front/checkout_process.tpl @@ -24,6 +24,10 @@ * International Registered Trademark & Property of PrestaShop SA *} + + {*if $MR_Data.PS_VERSION >= '1.5' && !$MR_Data.carrier} {l s='Mondial relay can\'t fetch any replay point due to prestashop error' mod='mondialrelay'} -{/if*} \ No newline at end of file +{/if*} diff --git a/views/templates/front/checkout_process_widget.tpl b/views/templates/front/checkout_process_widget.tpl old mode 100644 new mode 100755 index 7eaee98..a9edcf3 --- a/views/templates/front/checkout_process_widget.tpl +++ b/views/templates/front/checkout_process_widget.tpl @@ -23,12 +23,17 @@ * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0) * International Registered Trademark & Property of PrestaShop SA *} + + + diff --git a/views/templates/front/header_widget.tpl b/views/templates/front/header_widget.tpl old mode 100644 new mode 100755 index 040c1bd..95f8ecc --- a/views/templates/front/header_widget.tpl +++ b/views/templates/front/header_widget.tpl @@ -29,6 +29,7 @@ {/if} + @@ -48,4 +49,4 @@ PS_MRTranslationList['errorSelection'] = "{l s='Please choose a relay point' mod='mondialrelay' js=1}"; PS_MRTranslationList['openingRelay'] = "{l s='Opening hours' mod='mondialrelay' js=1}"; PS_MRTranslationList['moreDetails'] = "{l s='More details' mod='mondialrelay' js=1}"; - \ No newline at end of file + diff --git a/views/templates/front/index.php b/views/templates/front/index.php old mode 100644 new mode 100755 index 7752dc5..21075f4 --- a/views/templates/front/index.php +++ b/views/templates/front/index.php @@ -26,10 +26,10 @@ header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT"); - + header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); - + header("Location: ../"); exit; \ No newline at end of file diff --git a/views/templates/front/jquery-overload.tpl b/views/templates/front/jquery-overload.tpl old mode 100644 new mode 100755 diff --git a/views/templates/front/order_detail.tpl b/views/templates/front/order_detail.tpl old mode 100644 new mode 100755 diff --git a/views/templates/index.php b/views/templates/index.php old mode 100644 new mode 100755 index fc4110f..087b026 --- a/views/templates/index.php +++ b/views/templates/index.php @@ -27,10 +27,10 @@ header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT"); - + header("Cache-Control: no-store, no-cache, must-revalidate"); header("Cache-Control: post-check=0, pre-check=0", false); header("Pragma: no-cache"); - + header("Location: ../"); exit; \ No newline at end of file From a51f20bfb221f169ea0301f3bcc01de9cea16801 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thoma=20Bigue=CC=80res?= Date: Mon, 11 Jan 2016 15:47:58 +0100 Subject: [PATCH 2/6] Patch empty Carrier name, and Carrier delay --- mondialrelay.php | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/mondialrelay.php b/mondialrelay.php index 1693964..07fce71 100755 --- a/mondialrelay.php +++ b/mondialrelay.php @@ -884,6 +884,13 @@ private function addCarrier($name, $delay) { $ret = false; + if(empty($name)){ + return false; + } + if(empty($delay)){ + return false; + } + if (($carrier = new Carrier())) { $delay_lang = array(); From d062b2594971ee7bbb54f00636861a4755d2d1c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thoma=20Bigue=CC=80res?= Date: Fri, 15 Jan 2016 16:31:58 +0100 Subject: [PATCH 3/6] [*] MO - mondial relay : english config.xml --- config.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config.xml b/config.xml index 4519432..8ecf352 100755 --- a/config.xml +++ b/config.xml @@ -3,7 +3,7 @@ mondialrelay - + 1 From 422ede5775ae4f2b3eccfdfacb1554c89f3ec8c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phane=20Dessaint?= Date: Thu, 4 Feb 2016 09:57:56 +0100 Subject: [PATCH 4/6] Change display alert message for prestashop 1.5 / 1.6 with fancybox Add Control to OnePageCheckout / 5 steps checkout --- js/common.js | 96 ++++++-- js/mondialrelay.js | 3 +- js/mondialrelay_widget.js | 478 +++++++++++++++++++------------------- mondialrelay.php | 6 +- 4 files changed, 316 insertions(+), 267 deletions(-) diff --git a/js/common.js b/js/common.js index ec4d163..21dd778 100755 --- a/js/common.js +++ b/js/common.js @@ -24,41 +24,99 @@ */ function checkMrSelection() { - + if (PS_MRData.PS_VERSION < '1.5') { var selected_carrier_id = $('input[name=id_carrier]:checked').val(); } else { var selected_carrier_id = parseInt($('.delivery_option_radio:checked').val()); } - /* - console.log(PS_MRData.PS_VERSION); - console.log(selected_carrier_id); - console.log(PS_MRSelectedRelayPoint['carrier_id']); - console.log(PS_MRSelectedRelayPoint['relayPointNum']); - */ + var MR_carrier_selected = (selected_carrier_id==PS_MRSelectedRelayPoint['carrier_id']); // is a mondial relay carrier ? var MR_relay_selected = (PS_MRSelectedRelayPoint['relayPointNum']>0); // a relay has been selected ? - if (!MR_carrier_selected) { + if (!MR_carrier_selected) return true; - } else if (MR_relay_selected) { + + if (MR_relay_selected) { return true; } else { - alert(PS_MRTranslationList['errorSelection']); + if (!!$.prototype.fancybox && !(PS_MRData.PS_VERSION < '1.5')) + $.fancybox.open([ + { + type: 'inline', + autoScale: true, + minHeight: 30, + content: '

' + PS_MRTranslationList['errorSelection'] + '

' + }], + { + padding: 0 + }); + else + alert(PS_MRTranslationList['errorSelection']); + return false; } } -$(document).ready(function() { +function isOnePageCheckout(){ + + if($('.payment_module a').length && typeof(PS_MRData) != 'undefined'){ + return true; + } + return false; +} - $('#form button[name="processCarrier"], #form input[name="processCarrier"]').click(function(event) { - return checkMrSelection(); - }); +function setProtectRelaySelected(){ + if(isOnePageCheckout()){ + $('.payment_module a').each(function(){ + if(typeof($(this).attr('onclick'))!='undefined'){ + $(this).data('onclick', $(this).attr('onclick')); + $(this).attr('onclick', ''); + } + }); + + //OPC Validation - Warn user to select a relay point + $('.payment_module').click(function(event) { + if(!checkMrSelection()){ + event.stopPropagation(); + return false; + } + else{ + var lien= $('a', $(this)); + if( lien.is("[onclick]") && lien.attr('onclick') == '' ){ + lien.attr('onclick', lien.data('onclick')); + lien.trigger('click'); + } + } + }); - //OPC Validation - Warn user to select a relay point - $(document).on('click', '.payment_module', function() { - return checkMrSelection(); - }); + $('form').submit(function(event) { -}); + if(checkMrSelection()){ + $(this).off('submit').submit(); + + } + event.stopPropagation(); + return false; + }); + + } + + $('#form button[name="processCarrier"], #form input[name="processCarrier"]').click(function(event) { + if(!checkMrSelection()){ + event.stopPropagation(); + return false; + } + }); + +} + +(function($) { + + $(function(){ + + //setProtectRelaySelected(); + + }); +})(jQuery); diff --git a/js/mondialrelay.js b/js/mondialrelay.js index eaf40d4..fa312fc 100755 --- a/js/mondialrelay.js +++ b/js/mondialrelay.js @@ -1176,7 +1176,6 @@ var PS_MRObject = (function($, undefined) { // Hide MR input if one of them is not selected if($(e).val() == carrier_selected) { - console.log(carrier_selected); if(MR_carrier != false) { PS_MRCarrierMethodList[MR_idcarrier] = MR_carrier.id_mr_method; PS_MRSelectedRelayPoint['carrier_id'] = MR_idcarrier; @@ -1197,6 +1196,7 @@ var PS_MRObject = (function($, undefined) { } }); } + } } @@ -1307,6 +1307,7 @@ var PS_MRObject = (function($, undefined) { return { initFront : function() { checkToDisplayRelayList(); + setProtectRelaySelected(); }, uninstall : function(url) { diff --git a/js/mondialrelay_widget.js b/js/mondialrelay_widget.js index d7ad3b5..755d763 100755 --- a/js/mondialrelay_widget.js +++ b/js/mondialrelay_widget.js @@ -1,245 +1,235 @@ /* -* 2007-2015 PrestaShop -* -* NOTICE OF LICENSE -* -* This source file is subject to the Academic Free License (AFL 3.0) -* that is bundled with this package in the file LICENSE.txt. -* It is also available through the world-wide-web at this URL: -* http://opensource.org/licenses/afl-3.0.php -* If you did not receive a copy of the license and are unable to -* obtain it through the world-wide-web, please send an email -* to license@prestashop.com so we can send you a copy immediately. -* -* DISCLAIMER -* -* Do not edit or add to this file if you wish to upgrade PrestaShop to newer -* versions in the future. If you wish to customize PrestaShop for your -* needs please refer to http://www.prestashop.com for more information. -* -* @author PrestaShop SA -* @copyright 2007-2015 PrestaShop SA -* @version Release: $Revision: 16986 $ -* @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0) -* International Registered Trademark & Property of PrestaShop SA -*/ - function getNumeric(val) { - var reg=new RegExp("[0-9]+","g"); - var res = reg.exec(val); - if(isNaN(res)) - return 0; - else - return res; - } - - function checkToDisplayRelayList() - { - if (typeof PS_MRData != 'undefined') - { - //============================================================ - // auto display fancybox if radio already check - //============================================================ - PS_MRSelectedRelayPoint['relayPointNum'] = PS_MRData.pre_selected_relay; - // PS_VERSION < '1.5' - if (PS_MRData.PS_VERSION < '1.5') - { - // Bind id_carrierX to an ajax call - $.each(PS_MRData.carrier_list, function(i, carrier) { - PS_MRCarrierMethodList[carrier.id_carrier] = carrier.id_mr_method; - if ($('#id_carrier' + carrier.id_carrier).attr('checked')) { - PS_MRSelectedRelayPoint['carrier_id'] = carrier.id_carrier; - PS_MRDisplayWidget(carrier.id_carrier); - } - }); - - } - else if (PS_MRData.PS_VERSION >= '1.5' - && typeof PS_MRData.carrier != 'undefined' - ) - { // 1.5 way - var carrier_selected = $('input[class=delivery_option_radio]:checked').val(); - $.each(PS_MRData.carrier_list, function(i, carrier) { - PS_MRCarrierMethodList[carrier.id_carrier] = carrier.id_mr_method; - if (carrier.id_carrier+',' == carrier_selected || carrier.id_carrier == carrier_selected) { - overrideUpdateExtraCarrier(carrier_selected, id_address); - PS_MRSelectedRelayPoint['carrier_id'] = carrier.id_carrier; - PS_MRDisplayWidget(carrier.id_carrier); - } - }); - } - //============================================================ - // Handle input click of the other input to hide the previous relay point list displayed - $('input[name=id_carrier], input.delivery_option_radio').click(function(e){ - displayPickupPlace(0); - }); - } - //return false; - } - - function isMRCarrier(id_carrier){ - var carrier_list = PS_MRData.carrier_list; - for(i in carrier_list){ - var MR_carrier = carrier_list[i]; - if(MR_carrier.id_carrier == id_carrier) { - return MR_carrier; - } - } - return false; - } - - function hideRelaySelectedBox(_this){ - // Hide MR input if one of them is not selected - if (PS_MRCarrierMethodList[_this.val()] == undefined){ - // 1.5 way - var id = getNumeric(_this.val()); - if(PS_MRCarrierMethodList[id] == undefined) { - displayPickupPlace(0); - PS_MRSelectedRelayPoint['carrier_id'] = 0; - PS_MRDisplayWidget(0); - PS_MRSelectedRelayPoint['relayPointNum'] = 0; - } - else { - PS_MRSelectedRelayPoint['carrier_id'] = id; - PS_MRDisplayWidget(id); - } - } - else { - PS_MRSelectedRelayPoint['carrier_id'] = _this.val(); - PS_MRDisplayWidget(_this.val()); - } - return false; - } - - function PS_MRDisplayWidget(carrier_id) { - var dlv_mode = ''; - $.each(PS_MRData.carrier_list, function(i, carrier) { - if (carrier.id_carrier == carrier_id) - dlv_mode = carrier.dlv_mode; - PS_MRSelectedRelayPoint['relayPointNum'] = -1; - PS_MRAddSelectedCarrierInDB(carrier_id); - } - ); - if(carrier_id) { - if(dlv_mode!='LD1' && dlv_mode!='LDS' && dlv_mode!='HOM') { - loadMR_Map("#Zone_Widget", dlv_mode); - $("#link_zone_widget").click(); - if(PS_MRSelectedRelayPoint['relayPointNum'] == -1) - PS_MRSelectedRelayPoint['relayPointNum'] = 0; - } - else - displayPickupPlace(0); - } - return false; - } - - - function overrideUpdateExtraCarrier(id_delivery_option, id_address) - { - if(PS_MRData.PS_VERSION < '1.5') - return false; - - var url = ""; - var method = 'updateExtraCarrier'; - var params = ''; - if(typeof(orderOpcUrl) !== 'undefined') { - method = 'updateCarrierAndGetPayments'; - params += '&recyclable='+(($('#recyclable:checked').val() != undefined)? 1:0); - params += '&gift='+(($('#gift:checked').val() != undefined)? 1:0); - params += '&gift_message='+$('#gift_message').val(); - params += '&delivery_option['+id_address+']='+id_delivery_option; - url = orderOpcUrl; - } - else - url = orderUrl; - - $.ajax({ - type: 'POST', - headers: { "cache-control": "no-cache" }, - url: url + '?rand=' + new Date().getTime(), - async: false, - cache: false, - dataType : "json", - data: 'ajax=true' - +'&method='+method - +params - +'&id_address='+id_address - +'&id_delivery_option='+id_delivery_option - +'&token='+static_token - +'&allow_refresh=1', - success: function(jsonData) - { - //$('#HOOK_EXTRACARRIER_'+id_address).html(jsonData['content']); - return false; - } - }); - return false; - } - - function displayPickupPlace(info) { - var id = "relay_point_selected_box"; - - if(!info) { - $('#'+id).hide(); - $('#'+id).remove(); - return false; - } - - if (PS_MRData.PS_VERSION < '1.5') - { - var block_carrier = $('#carrierTable'); - } - else { - var block_carrier = $('.delivery_options_address'); - } - if($('#'+id).length !== 0) { - $('#'+id).html('

'+relay_point_selected_box_label+'

'+info); - $('#'+id).show(); - } - else { - $('

'+relay_point_selected_box_label+'

'+info+'
').insertAfter(block_carrier); - } - return false; - } - - function PS_MRAddSelectedCarrierInDB(id_carrier) - { - // Make the request - $.ajax({ - type: 'POST', - url: _PS_MR_MODULE_DIR_ + 'ajax.php', - data: {'method' : 'addSelectedCarrierToDB', - 'id_carrier' : id_carrier, - 'id_mr_method' : PS_MRCarrierMethodList[id_carrier], - 'mrtoken' : mrtoken}, - success: function(json) - { - return false; - } - }); - return false; - } - - $(document).ready(function() - { - - // If MR carrier selected, check MR relay point is selected too - $('input[name=processCarrier], button[name=processCarrier]').click(function(){ - var carrier_selected = $('input[class=delivery_option_radio]:checked').val(); - if (PS_MRSelectedRelayPoint['carrier_id']+',' == carrier_selected || PS_MRSelectedRelayPoint['carrier_id'] == carrier_selected) - { - var _return = !(PS_MRSelectedRelayPoint['carrier_id'] && !PS_MRSelectedRelayPoint['relayPointNum']); - if (!_return) - alert(PS_MRTranslationList['errorSelection']); - return _return; - } - }); - - if (typeof PS_MRData != 'undefined') - { - if (PS_MRData.PS_VERSION < '1.5') { - $('input[name="id_carrier"]').click(function(){ - checkToDisplayRelayList(); - }); - } - } - }); + * 2007-2015 PrestaShop + * + * NOTICE OF LICENSE + * + * This source file is subject to the Academic Free License (AFL 3.0) + * that is bundled with this package in the file LICENSE.txt. + * It is also available through the world-wide-web at this URL: + * http://opensource.org/licenses/afl-3.0.php + * If you did not receive a copy of the license and are unable to + * obtain it through the world-wide-web, please send an email + * to license@prestashop.com so we can send you a copy immediately. + * + * DISCLAIMER + * + * Do not edit or add to this file if you wish to upgrade PrestaShop to newer + * versions in the future. If you wish to customize PrestaShop for your + * needs please refer to http://www.prestashop.com for more information. + * + * @author PrestaShop SA + * @copyright 2007-2015 PrestaShop SA + * @version Release: $Revision: 16986 $ + * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0) + * International Registered Trademark & Property of PrestaShop SA + */ +function getNumeric(val) { + var reg = new RegExp("[0-9]+", "g"); + var res = reg.exec(val); + if (isNaN(res)) + return 0; + else + return res; +} + +function checkToDisplayRelayList() +{ + if (typeof PS_MRData != 'undefined') + { + //============================================================ + // auto display fancybox if radio already check + //============================================================ + PS_MRSelectedRelayPoint['relayPointNum'] = PS_MRData.pre_selected_relay; + // PS_VERSION < '1.5' + if (PS_MRData.PS_VERSION < '1.5') + { + // Bind id_carrierX to an ajax call + $.each(PS_MRData.carrier_list, function (i, carrier) { + PS_MRCarrierMethodList[carrier.id_carrier] = carrier.id_mr_method; + if ($('#id_carrier' + carrier.id_carrier).attr('checked')) { + PS_MRSelectedRelayPoint['carrier_id'] = carrier.id_carrier; + PS_MRDisplayWidget(carrier.id_carrier); + setProtectRelaySelected(); + } + }); + + } + else if (PS_MRData.PS_VERSION >= '1.5' + && typeof PS_MRData.carrier != 'undefined' + ) + { // 1.5 way + var carrier_selected = $('input[class=delivery_option_radio]:checked').val(); + $.each(PS_MRData.carrier_list, function (i, carrier) { + PS_MRCarrierMethodList[carrier.id_carrier] = carrier.id_mr_method; + if (carrier.id_carrier + ',' == carrier_selected || carrier.id_carrier == carrier_selected) { + overrideUpdateExtraCarrier(carrier_selected, id_address); + PS_MRSelectedRelayPoint['carrier_id'] = carrier.id_carrier; + PS_MRDisplayWidget(carrier.id_carrier); + } + }); + } + //============================================================ + // Handle input click of the other input to hide the previous relay point list displayed + $('input[name=id_carrier], input.delivery_option_radio').click(function (e) { + displayPickupPlace(0); + }); + } + //return false; +} + +function isMRCarrier(id_carrier) { + var carrier_list = PS_MRData.carrier_list; + for (i in carrier_list) { + var MR_carrier = carrier_list[i]; + if (MR_carrier.id_carrier == id_carrier) { + return MR_carrier; + } + } + return false; +} + +function hideRelaySelectedBox(_this) { + // Hide MR input if one of them is not selected + if (PS_MRCarrierMethodList[_this.val()] == undefined) { + // 1.5 way + var id = getNumeric(_this.val()); + if (PS_MRCarrierMethodList[id] == undefined) { + displayPickupPlace(0); + PS_MRSelectedRelayPoint['carrier_id'] = 0; + PS_MRDisplayWidget(0); + PS_MRSelectedRelayPoint['relayPointNum'] = 0; + } + else { + PS_MRSelectedRelayPoint['carrier_id'] = id; + PS_MRDisplayWidget(id); + } + } + else { + PS_MRSelectedRelayPoint['carrier_id'] = _this.val(); + PS_MRDisplayWidget(_this.val()); + } + return false; +} + +function PS_MRDisplayWidget(carrier_id) { + var dlv_mode = ''; + $.each(PS_MRData.carrier_list, function (i, carrier) { + if (carrier.id_carrier == carrier_id) + dlv_mode = carrier.dlv_mode; + PS_MRSelectedRelayPoint['relayPointNum'] = -1; + PS_MRAddSelectedCarrierInDB(carrier_id); + } + ); + if (carrier_id) { + if (dlv_mode != 'LD1' && dlv_mode != 'LDS' && dlv_mode != 'HOM') { + loadMR_Map("#Zone_Widget", dlv_mode); + $("#link_zone_widget").click(); + if (PS_MRSelectedRelayPoint['relayPointNum'] == -1) + PS_MRSelectedRelayPoint['relayPointNum'] = 0; + } + else + displayPickupPlace(0); + } + return false; +} + + +function overrideUpdateExtraCarrier(id_delivery_option, id_address) +{ + if (PS_MRData.PS_VERSION < '1.5') + return false; + + var url = ""; + var method = 'updateExtraCarrier'; + var params = ''; + if (typeof (orderOpcUrl) !== 'undefined') { + method = 'updateCarrierAndGetPayments'; + params += '&recyclable=' + (($('#recyclable:checked').val() != undefined) ? 1 : 0); + params += '&gift=' + (($('#gift:checked').val() != undefined) ? 1 : 0); + params += '&gift_message=' + $('#gift_message').val(); + params += '&delivery_option[' + id_address + ']=' + id_delivery_option; + url = orderOpcUrl; + } + else + url = orderUrl; + + $.ajax({ + type: 'POST', + headers: {"cache-control": "no-cache"}, + url: url + '?rand=' + new Date().getTime(), + async: false, + cache: false, + dataType: "json", + data: 'ajax=true' + + '&method=' + method + + params + + '&id_address=' + id_address + + '&id_delivery_option=' + id_delivery_option + + '&token=' + static_token + + '&allow_refresh=1', + success: function (jsonData) + { + //$('#HOOK_EXTRACARRIER_'+id_address).html(jsonData['content']); + setProtectRelaySelected(); + return false; + } + }); + return false; +} + +function displayPickupPlace(info) { + var id = "relay_point_selected_box"; + + if (!info) { + $('#' + id).hide(); + $('#' + id).remove(); + return false; + } + + if (PS_MRData.PS_VERSION < '1.5') + { + var block_carrier = $('#carrierTable'); + } + else { + var block_carrier = $('.delivery_options_address'); + } + if ($('#' + id).length !== 0) { + $('#' + id).html('

' + relay_point_selected_box_label + '

' + info); + $('#' + id).show(); + } + else { + $('

' + relay_point_selected_box_label + '

' + info + '
').insertAfter(block_carrier); + } + return false; +} + +function PS_MRAddSelectedCarrierInDB(id_carrier) +{ + // Make the request + $.ajax({ + type: 'POST', + url: _PS_MR_MODULE_DIR_ + 'ajax.php', + data: {'method': 'addSelectedCarrierToDB', + 'id_carrier': id_carrier, + 'id_mr_method': PS_MRCarrierMethodList[id_carrier], + 'mrtoken': mrtoken}, + success: function (json) + { + return false; + } + }); + return false; +} + +$(document).ready(function () +{ + + if (typeof PS_MRData != 'undefined') + { + if (PS_MRData.PS_VERSION < '1.5') { + $('input[name="id_carrier"]').click(function () { + checkToDisplayRelayList(); + }); + } + } +}); diff --git a/mondialrelay.php b/mondialrelay.php index 07fce71..4d45220 100755 --- a/mondialrelay.php +++ b/mondialrelay.php @@ -72,7 +72,7 @@ public function __construct() { $this->name = 'mondialrelay'; $this->tab = 'shipping_logistics'; - $this->version = '2.1.4'; + $this->version = '2.1.5'; $this->installed_version = ''; $this->module_key = '366584e511d311cfaa899fc2d9ec1bd0'; $this->author = 'PrestaShop'; @@ -599,8 +599,8 @@ public function hookHeader($params) private function canAddJSViaController() { - if(version_compare(_PS_VERSION_, '1.6', '>=')) - return true; + if(version_compare(_PS_VERSION_, '1.5', '<')) + return false; if(Configuration::get('PS_JS_THEME_CACHE')) return false; From bfc934889f90be62eedc025263f216b39ea33a01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phane=20Dessaint?= Date: Thu, 11 Feb 2016 17:40:04 +0100 Subject: [PATCH 5/6] correction du bug avec les CGV --- js/common.js | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/js/common.js b/js/common.js index 21dd778..cd6b447 100755 --- a/js/common.js +++ b/js/common.js @@ -114,8 +114,16 @@ function setProtectRelaySelected(){ (function($) { $(function(){ - - //setProtectRelaySelected(); + $('#cgv').click(function(){ + if($(this).attr('checked')){ + $("body").bind("ajaxComplete", function(e, xhr, settings){ + setProtectRelaySelected(); + + }); + + } + }); + }); })(jQuery); From 61dd394370eb9cc25fed195d0c6cfd97fbd4f5e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phane=20Dessaint?= Date: Wed, 16 Mar 2016 10:44:05 +0100 Subject: [PATCH 6/6] Fixed bugs in the OPC if the user is offline. Fixed various bugs. Adding the update to correct the database. --- ajax.php | 3 +- js/mondialrelay.js | 17 +++++----- mondialrelay.php | 10 +++--- sql/mrInstall.sql | 2 +- upgrade/install-2.1.7.php | 31 +++++++++++++++++++ views/templates/front/checkout_process.tpl | 5 ++- .../front/checkout_process_widget.tpl | 6 ++-- views/templates/front/header.tpl | 2 +- 8 files changed, 56 insertions(+), 20 deletions(-) create mode 100644 upgrade/install-2.1.7.php diff --git a/ajax.php b/ajax.php index fba0f0d..2eaccc3 100755 --- a/ajax.php +++ b/ajax.php @@ -34,7 +34,8 @@ /* * Clean displayed content for Admin ajax query */ -@ob_clean(); +if ( ob_get_level() && ob_get_length() > 0) + @ob_clean(); /* * Front Ajax query, need the front cookie and MR class diff --git a/js/mondialrelay.js b/js/mondialrelay.js index fa312fc..b876275 100755 --- a/js/mondialrelay.js +++ b/js/mondialrelay.js @@ -1281,7 +1281,7 @@ var PS_MRObject = (function($, undefined) { $('#MR_config_menu').children('ul').css('margin-left', width + 'px'); } - +/* // If MR carrier selected, check MR relay point is selected too $('input[name=processCarrier], button[name=processCarrier]').click(function(){ var _return = !(PS_MRSelectedRelayPoint['carrier_id'] && !PS_MRSelectedRelayPoint['relayPointNum']); @@ -1290,15 +1290,14 @@ var PS_MRObject = (function($, undefined) { return _return; }); - - if (typeof PS_MRData != 'undefined') +*/ + // En OPC, si l'utilisateur est déconnecter, PS_MRData n'existe pas au début + $('input[name="id_carrier"]').live('click', function(){ + if (typeof PS_MRData != 'undefined' && PS_MRData.PS_VERSION < '1.5') { - if (PS_MRData.PS_VERSION < '1.5') { - $('input[name="id_carrier"]').click(function(){ - checkToDisplayRelayList(); - }); - } + checkToDisplayRelayList(); } + }); // Handle input click of the other input to hide the previous relay point list displayed }); @@ -1307,7 +1306,7 @@ var PS_MRObject = (function($, undefined) { return { initFront : function() { checkToDisplayRelayList(); - setProtectRelaySelected(); + setProtectRelaySelected(); }, uninstall : function(url) { diff --git a/mondialrelay.php b/mondialrelay.php index 4d45220..dc7552a 100755 --- a/mondialrelay.php +++ b/mondialrelay.php @@ -72,7 +72,7 @@ public function __construct() { $this->name = 'mondialrelay'; $this->tab = 'shipping_logistics'; - $this->version = '2.1.5'; + $this->version = '2.1.7'; $this->installed_version = ''; $this->module_key = '366584e511d311cfaa899fc2d9ec1bd0'; $this->author = 'PrestaShop'; @@ -481,7 +481,7 @@ public function hookupdateCarrier($params) /* Insert new entry keeping the last one linked to the id_carrier */ $query = ' INSERT INTO `'._DB_PREFIX_.'mr_method` - (name, country_list, col_mode, dlv_mode, insurance, id_carrier) + (name, country_list, col_mode, dlv_mode, insurance, id_carrier, is_deleted) ( SELECT "'.pSQL($params['carrier']->name).'", @@ -489,7 +489,8 @@ public function hookupdateCarrier($params) col_mode, dlv_mode, insurance, - '.(int)$params['carrier']->id.' + '.(int)$params['carrier']->id.', + 0 FROM `'._DB_PREFIX_.'mr_method` WHERE id_carrier ='.(int)$params['id_carrier'].')'; Db::getInstance()->execute($query); @@ -1046,7 +1047,8 @@ private function addShippingMethod() /* Force col mod to CCC */ $fields['col_mode'] = 'CCC'; $fields['id_carrier'] = $id_carrier; - + $fields['is_deleted'] = 0; + $query = 'INSERT INTO `'._DB_PREFIX_.'mr_method` (%s) VALUES(%s)'; $keys = array(); diff --git a/sql/mrInstall.sql b/sql/mrInstall.sql index 0d3cb5b..b63ebe0 100755 --- a/sql/mrInstall.sql +++ b/sql/mrInstall.sql @@ -6,7 +6,7 @@ CREATE TABLE IF NOT EXISTS `PREFIX_mr_method` ( `dlv_mode` varchar(3) NOT NULL, `insurance` varchar(3) NOT NULL DEFAULT '0', `id_carrier` int(10) NOT NULL, - `is_deleted` int(10) NOT NULL, + `is_deleted` int(10) NOT NULL DEFAULT '0', PRIMARY KEY (`id_mr_method`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1; diff --git a/upgrade/install-2.1.7.php b/upgrade/install-2.1.7.php new file mode 100644 index 0000000..99e7099 --- /dev/null +++ b/upgrade/install-2.1.7.php @@ -0,0 +1,31 @@ +upgrade_detail[$upgrade_version] = array(); + + try { + // return false si erreur + if (!Db::getInstance()->execute('ALTER TABLE `'._DB_PREFIX_.'mr_method` ALTER `is_deleted` SET DEFAULT "0"')) + $object->upgrade_detail[$upgrade_version][] = $object->l('Can\'t add new field in methodtable'); + + return Configuration::updateValue('MONDIAL_RELAY', $upgrade_version); + } + catch (Exception $e) { + return false; + } +} \ No newline at end of file diff --git a/views/templates/front/checkout_process.tpl b/views/templates/front/checkout_process.tpl index 29a308a..384c326 100755 --- a/views/templates/front/checkout_process.tpl +++ b/views/templates/front/checkout_process.tpl @@ -34,7 +34,10 @@ {assign var=MR_Data value=$MR_Data|json_decode:1} // literal for smarty v2 compatibility $(document).ready(function() {literal}{{/literal} - PS_MRObject.initFront(); + // settimeout utiliser pour la connection de l'utilisateur en opc + setTimeout(function(){ + PS_MRObject.initFront(); + },1000); {literal}}{/literal}); {*if $MR_Data.PS_VERSION >= '1.5' && !$MR_Data.carrier} diff --git a/views/templates/front/checkout_process_widget.tpl b/views/templates/front/checkout_process_widget.tpl index a9edcf3..ef98f71 100755 --- a/views/templates/front/checkout_process_widget.tpl +++ b/views/templates/front/checkout_process_widget.tpl @@ -135,8 +135,8 @@ $(document).ready(function () { //loadMR_Map("#Zone_Widget", "24R"); - - //setTimeout(function(){ + // settimeout utiliser pour la connection de l'utilisateur en opc + setTimeout(function(){ $("#link_zone_widget").fancybox( { width : 705, @@ -158,7 +158,7 @@ } }); checkToDisplayRelayList(); - //},1500); + },1000); }); diff --git a/views/templates/front/header.tpl b/views/templates/front/header.tpl index a019eaf..5dab3af 100755 --- a/views/templates/front/header.tpl +++ b/views/templates/front/header.tpl @@ -37,7 +37,7 @@ PS_MRTranslationList['Select'] = "{l s='Select' mod='mondialrelay'}"; PS_MRTranslationList['Selected'] = "{l s='Selected' mod='mondialrelay'}"; - PS_MRTranslationList['errorSelection'] = "{l s='Please choose a relay point' mod='mondialrelay'}"; + PS_MRTranslationList['errorSelection'] = "{l s='Please choose a relay point' mod='mondialrelay' js=1}"; PS_MRTranslationList['openingRelay'] = "{l s='Opening hours' mod='mondialrelay'}"; PS_MRTranslationList['moreDetails'] = "{l s='More details' mod='mondialrelay'}";