├── .gitignore ├── LICENSE.md ├── Readme.md ├── binshopsrest.php ├── classes ├── APIRoutes.php ├── RESTMainMenu.php ├── RESTProductLazyArray.php ├── RESTTrait.php └── index.php ├── config.xml ├── controllers ├── AbstractAuthRESTController.php ├── AbstractCartRESTController.php ├── AbstractPaymentRESTController.php ├── AbstractProductListingRESTController.php ├── AbstractRESTController.php ├── front │ ├── Readme.md │ ├── accountedit.php │ ├── accountinfo.php │ ├── address.php │ ├── addressform.php │ ├── alladdresses.php │ ├── bootstrap.php │ ├── carriers.php │ ├── cart.php │ ├── categoryproducts.php │ ├── emailsubscription.php │ ├── featuredproducts.php │ ├── hello.php │ ├── index.php │ ├── lightbootstrap.php │ ├── listcomments.php │ ├── login.php │ ├── logout.php │ ├── orderhistory.php │ ├── paymentoptions.php │ ├── postcomment.php │ ├── productdetail.php │ ├── productsearch.php │ ├── ps_cashondelivery.php │ ├── ps_checkpayment.php │ ├── ps_wirepayment.php │ ├── register.php │ ├── resetpasswordbyemail.php │ ├── resetpasswordcheck.php │ ├── resetpasswordemail.php │ ├── resetpasswordenter.php │ ├── setaddresscheckout.php │ ├── setcarriercheckout.php │ └── wishlist.php └── index.php ├── doc └── PrestaShop REST API.postman_collection.json ├── index.php ├── logo.png ├── mails ├── en │ ├── index.php │ ├── password_query_mobile.html │ └── password_query_mobile.txt └── index.php ├── override └── classes │ └── controller │ └── FrontController.php ├── sql ├── index.php ├── install.php └── uninstall.php ├── translations └── index.php ├── upgrade ├── index.php └── upgrade-2.5.0.php └── views ├── css ├── back.css ├── front.css └── index.php ├── img └── index.php ├── index.php ├── js ├── back.js ├── front.js └── index.php └── templates ├── admin ├── configure.tpl └── index.php └── index.php /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/* 2 | *.iml -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Academic Free License ("AFL") v. 3.0 2 | 3 | This Academic Free License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following licensing notice adjacent to the copyright notice for the Original Work: 4 | 5 | Licensed under the Academic Free License version 3.0 6 | 7 | 1) Grant of Copyright License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, for the duration of the copyright, to do the following: 8 | 9 | a) to reproduce the Original Work in copies, either alone or as part of a collective work; 10 | 11 | b) to translate, adapt, alter, transform, modify, or arrange the Original Work, thereby creating derivative works ("Derivative Works") based upon the Original Work; 12 | 13 | c) to distribute or communicate copies of the Original Work and Derivative Works to the public, under any license of your choice that does not contradict the terms and conditions, including Licensor's reserved rights and remedies, in this Academic Free License; 14 | 15 | d) to perform the Original Work publicly; and 16 | 17 | e) to display the Original Work publicly. 18 | 19 | 2) Grant of Patent License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, for the duration of the patents, to make, use, sell, offer for sale, have made, and import the Original Work and Derivative Works. 20 | 21 | 3) Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work. 22 | 23 | 4) Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior permission of the Licensor. Except as expressly stated herein, nothing in this License grants any license to Licensor's trademarks, copyrights, patents, trade secrets or any other intellectual property. No patent license is granted to make, use, sell, offer for sale, have made, or import embodiments of any patent claims other than the licensed claims defined in Section 2. No license is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under terms different from this License any Original Work that Licensor otherwise would have a right to license. 24 | 25 | 5) External Deployment. The term "External Deployment" means the use, distribution, or communication of the Original Work or Derivative Works in any way such that the Original Work or Derivative Works may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Work or a Derivative Work as a distribution under section 1(c). 26 | 27 | 6) Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent, or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work. 28 | 29 | 7) Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately preceding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of non-infringement, merchantability or fitness for a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to the Original Work is granted by this License except under this disclaimer. 30 | 31 | 8) Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to anyone for any indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to the extent applicable law prohibits such limitation. 32 | 33 | 9) Acceptance and Termination. If, at any time, You expressly assented to this License, that assent indicates your clear and irrevocable acceptance of this License and all of its terms and conditions. If You distribute or communicate copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. This License conditions your rights to undertake the activities listed in Section 1, including your right to create Derivative Works based upon the Original Work, and doing so without honoring these terms and conditions is prohibited by copyright law and international treaty. Nothing in this License is intended to affect copyright exceptions and limitations (including "fair use" or "fair dealing"). This License shall terminate immediately and You may no longer exercise any of the rights granted to You by this License upon your failure to honor the conditions in Section 1(c). 34 | 35 | 10) Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware. 36 | 37 | 11) Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of copyright or patent law in the appropriate jurisdiction. This section shall survive the termination of this License. 38 | 39 | 12) Attorneys' Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License. 40 | 41 | 13) Miscellaneous. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. 42 | 43 | 14) Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. 44 | 45 | 15) Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You. 46 | 47 | 16) Modification of This License. This License is Copyright © 2005 Lawrence Rosen. Permission is granted to copy, distribute, or communicate this License without modification. Nothing in this License permits You to modify this License as applied to the Original Work or to Derivative Works. However, You may modify the text of this License and copy, distribute or communicate your modified version (the "Modified License") and apply it to other original works of authorship subject to the following conditions: (i) You may not indicate in any way that your Modified License is the "Academic Free License" or "AFL" and you may not use those names in the name of your Modified License; (ii) You must replace the notice specified in the first paragraph above with the notice "Licensed under " or with a notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your original works are open source software unless your Modified License has been approved by Open Source Initiative (OSI) and You comply with its license review and certification process. 48 | -------------------------------------------------------------------------------- /Readme.md: -------------------------------------------------------------------------------- 1 |
2 | 3 |
4 | 5 | # PrestaShop REST API Module 6 | Easily expose REST API endpoints for your Prestashop website. No configuration needed, just install and use it. 7 | 8 | ## [Official Supported Version v5](https://addons.prestashop.com/en/website-performance/52062-rest-api-pro-version-with-fast-api-caching.html) 9 | Compatible with PrestaShop 8.x, Annotation-based API routing support, and many admin APIs and full front APIs. 10 | 11 | Latest release v5.4.0 (Jan, 2025) 12 | 13 | ## [Free Version v2.5](https://www.binshops.com/prestashop-api) 14 | For demo and testing, not recommended for production. 15 | 16 | ## The products that use this REST API 17 | 18 | 19 | 22 | 28 | 29 |
20 | PrestaShop PWAPrestaShop PWA 21 | 23 | 24 | PrestaShop Mobile Application 25 | PrestaShop Mobile App 26 | 27 |
30 | 31 | # [Headless Commerce](https://www.binshops.com/blog/why-headless-commerce) 32 | This module helps you to build Headless applications based on PrestaShop platform. You can read [this article](https://www.binshops.com/blog/why-headless-commerce) to know about Headless PrestaShop and Headless Commerce, why we need it and why it matters. 33 | 34 | ### Demo Link 35 | https://rest.binshops.com/rest/bootstrap 36 | 37 | ### Your API Endpoint 38 | After installation access your API endpoints at: http://yourdomain.tld/rest. 39 | 40 | ### Why we need this API module? Is not Webservice API enough? 41 | You can get more info about this module: https://www.binshops.com/prestashop-api 42 | 43 | ### Documentation 44 | You can access full documentation for REST endpoints on Postman publisher: 45 | https://documenter.getpostman.com/view/1491681/TzkyP1UC 46 | 47 | ### How to write your API? 48 | Annotation-based API routing added in v5. 49 | ```php 50 | /** 51 | * @Route("/rest/get-products", name=”products”) 52 | */ 53 | public function getProducts() 54 | { 55 | // ... 56 | } 57 | ``` 58 | 59 | ### Required Modules 60 | These native modules, which are already included in PrestaShop out of the box, are required to work with some endpoints. 61 | 62 | - ps_mainmenu (Native Ps Menu module) 63 | - ps_featuredproducts (Native Ps Featured Products module) 64 | - ps_facetedsearch (Native Ps Faceted Search module) 65 | - productcomments (Native Ps Product Comments module) 66 | - ps_banner (Native Ps Banner module) 67 | - ps_imageslider (Native Ps Image slider module) 68 | - ps_wirepayment (Native Ps Bankwire module) 69 | - ps_checkpayment (Native Ps Pay by Check module) 70 | - blockwishlist (Native Ps Wishlist module) 71 | 72 | If you need custom APIs or you want to have APIs for a third-party module, you can send your request for custom API implementation on Binshops website - [Request Form](https://www.binshops.com/prestashop-api#request-custom-api) 73 | -------------------------------------------------------------------------------- /binshopsrest.php: -------------------------------------------------------------------------------- 1 | name = 'binshopsrest'; 25 | $this->tab = 'others'; 26 | $this->version = '2.5.5'; 27 | $this->author = 'Binshops'; 28 | $this->need_instance = 0; 29 | 30 | /** 31 | * Set $this->bootstrap to true if your module is compliant with bootstrap (PrestaShop 1.6) 32 | */ 33 | $this->bootstrap = true; 34 | 35 | parent::__construct(); 36 | 37 | $this->displayName = $this->l('PrestaShop REST API'); 38 | $this->description = $this->l('This module exposes REST API endpoints for your Prestashop website.'); 39 | 40 | $this->confirmUninstall = $this->l('Are you sure you want to uninstall my module?'); 41 | 42 | $this->ps_versions_compliancy = array('min' => '1.7.7', 'max' => _PS_VERSION_); 43 | $this->module_key = 'b3c3c0c41d0223b9ff10c87b8acb65f5'; 44 | } 45 | 46 | public function isUsingNewTranslationSystem() 47 | { 48 | return true; 49 | } 50 | 51 | /** 52 | * Don't forget to create update methods if needed: 53 | * http://doc.prestashop.com/display/PS16/Enabling+the+Auto-Update 54 | */ 55 | public function install() 56 | { 57 | Configuration::updateValue('BINSHOPSREST_LIVE_MODE', false); 58 | 59 | include(dirname(__FILE__) . '/sql/install.php'); 60 | 61 | return parent::install() && 62 | $this->registerHook('header') && 63 | $this->registerHook('backOfficeHeader') && 64 | $this->registerHook('moduleRoutes') && 65 | $this->registerHook('actionDispatcherBefore'); 66 | } 67 | 68 | public function uninstall() 69 | { 70 | Configuration::deleteByName('BINSHOPSREST_LIVE_MODE'); 71 | 72 | include(dirname(__FILE__) . '/sql/uninstall.php'); 73 | 74 | return parent::uninstall(); 75 | } 76 | 77 | /** 78 | * Load the configuration form 79 | */ 80 | public function getContent() 81 | { 82 | /** 83 | * If values have been submitted in the form, process. 84 | */ 85 | if (((bool)Tools::isSubmit('submitBinshopsrestModule')) == true) { 86 | $this->postProcess(); 87 | } 88 | 89 | $this->context->smarty->assign('module_dir', $this->_path); 90 | 91 | $output = $this->context->smarty->fetch($this->local_path . 'views/templates/admin/configure.tpl'); 92 | 93 | return $output; 94 | } 95 | 96 | /** 97 | * Create the form that will be displayed in the configuration of your module. 98 | */ 99 | protected function renderForm() 100 | { 101 | $helper = new HelperForm(); 102 | 103 | $helper->show_toolbar = false; 104 | $helper->table = $this->table; 105 | $helper->module = $this; 106 | $helper->default_form_language = $this->context->language->id; 107 | $helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG', 0); 108 | 109 | $helper->identifier = $this->identifier; 110 | $helper->submit_action = 'submitBinshopsrestModule'; 111 | $helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false) 112 | . '&configure=' . $this->name . '&tab_module=' . $this->tab . '&module_name=' . $this->name; 113 | $helper->token = Tools::getAdminTokenLite('AdminModules'); 114 | 115 | $helper->tpl_vars = array( 116 | 'fields_value' => $this->getConfigFormValues(), /* Add values for your inputs */ 117 | 'languages' => $this->context->controller->getLanguages(), 118 | 'id_language' => $this->context->language->id, 119 | ); 120 | 121 | return $helper->generateForm(array($this->getConfigForm())); 122 | } 123 | 124 | /** 125 | * Create the structure of your form. 126 | */ 127 | protected function getConfigForm() 128 | { 129 | return array( 130 | 'form' => array( 131 | 'legend' => array( 132 | 'title' => $this->l('Settings'), 133 | 'icon' => 'icon-cogs', 134 | ), 135 | 'input' => array( 136 | array( 137 | 'type' => 'switch', 138 | 'label' => $this->l('Live mode'), 139 | 'name' => 'BINSHOPSREST_LIVE_MODE', 140 | 'is_bool' => true, 141 | 'desc' => $this->l('Use this module in live mode'), 142 | 'values' => array( 143 | array( 144 | 'id' => 'active_on', 145 | 'value' => true, 146 | 'label' => $this->l('Enabled') 147 | ), 148 | array( 149 | 'id' => 'active_off', 150 | 'value' => false, 151 | 'label' => $this->l('Disabled') 152 | ) 153 | ), 154 | ), 155 | array( 156 | 'col' => 3, 157 | 'type' => 'text', 158 | 'prefix' => '', 159 | 'desc' => $this->l('Enter a valid email address'), 160 | 'name' => 'BINSHOPSREST_ACCOUNT_EMAIL', 161 | 'label' => $this->l('Email'), 162 | ), 163 | array( 164 | 'type' => 'password', 165 | 'name' => 'BINSHOPSREST_ACCOUNT_PASSWORD', 166 | 'label' => $this->l('Password'), 167 | ), 168 | ), 169 | 'submit' => array( 170 | 'title' => $this->l('Save'), 171 | ), 172 | ), 173 | ); 174 | } 175 | 176 | /** 177 | * Set values for the inputs. 178 | */ 179 | protected function getConfigFormValues() 180 | { 181 | return array( 182 | 'BINSHOPSREST_LIVE_MODE' => Configuration::get('BINSHOPSREST_LIVE_MODE', true), 183 | 'BINSHOPSREST_ACCOUNT_EMAIL' => Configuration::get('BINSHOPSREST_ACCOUNT_EMAIL', 'contact@prestashop.com'), 184 | 'BINSHOPSREST_ACCOUNT_PASSWORD' => Configuration::get('BINSHOPSREST_ACCOUNT_PASSWORD', null), 185 | ); 186 | } 187 | 188 | /** 189 | * Save form data. 190 | */ 191 | protected function postProcess() 192 | { 193 | $form_values = $this->getConfigFormValues(); 194 | 195 | foreach (array_keys($form_values) as $key) { 196 | Configuration::updateValue($key, Tools::getValue($key)); 197 | } 198 | } 199 | 200 | /** 201 | * Add the CSS & JavaScript files you want to be loaded in the BO. 202 | */ 203 | public function hookBackOfficeHeader() 204 | { 205 | if (Tools::getValue('module_name') == $this->name) { 206 | $this->context->controller->addJS($this->_path . 'views/js/back.js'); 207 | $this->context->controller->addCSS($this->_path . 'views/css/back.css'); 208 | } 209 | } 210 | 211 | /** 212 | * Add the CSS & JavaScript files you want to be added on the FO. 213 | */ 214 | public function hookHeader() 215 | { 216 | $this->context->controller->addJS($this->_path . '/views/js/front.js'); 217 | $this->context->controller->addCSS($this->_path . '/views/css/front.css'); 218 | } 219 | 220 | public function hookactionDispatcherBefore($controller) 221 | { 222 | if ($controller['controller_type'] === 1 && preg_match("#/rest/#", $_SERVER['REQUEST_URI'], $k)){ 223 | preg_match('`rest/(.*)`', $_SERVER['REQUEST_URI'], $m); 224 | $s = explode('/', $m[0]); 225 | $_GET['fc'] = 'module'; 226 | $_GET['module'] = $s[1]; 227 | $_GET['controller'] = $s[2]; 228 | $controller_name = $s[2]; 229 | 230 | $module_name = Validate::isModuleName(Tools::getValue('module')) ? Tools::getValue('module') : ''; 231 | 232 | $module = Module::getInstanceByName($module_name); 233 | $controller_class = 'PageNotFoundController'; 234 | 235 | if (Validate::isLoadedObject($module) && $module->active) { 236 | $controllers = Dispatcher::getControllers(_PS_MODULE_DIR_ . "$module_name/controllers/front/"); 237 | if (isset($controllers[strtolower($controller_name)])) { 238 | include_once _PS_MODULE_DIR_ . "$module_name/controllers/front/{$controller_name}.php"; 239 | if (file_exists( 240 | _PS_OVERRIDE_DIR_ . "modules/$module_name/controllers/front/{$controller_name}.php" 241 | )) { 242 | include_once _PS_OVERRIDE_DIR_ . "modules/$module_name/controllers/front/{$controller_name}.php"; 243 | $controller_class = $module_name . $controller_name . 'ModuleFrontControllerOverride'; 244 | } else { 245 | $controller_class = $module_name . $controller_name . 'ModuleFrontController'; 246 | } 247 | } 248 | } 249 | 250 | if (!isset($controller) || !$module){ 251 | header('Content-Type: ' . "application/json"); 252 | 253 | echo json_encode([ 254 | 'success' => true, 255 | 'message' => 'This endpoint is not defined.', 256 | 'code' => 410 257 | ]); 258 | die; 259 | } 260 | 261 | $controller = Controller::getController($controller_class); 262 | 263 | $controller->restRun(); 264 | } 265 | } 266 | 267 | public function hookModuleRoutes() 268 | { 269 | return APIRoutes::getRoutes(); 270 | } 271 | } 272 | -------------------------------------------------------------------------------- /classes/APIRoutes.php: -------------------------------------------------------------------------------- 1 | [ 9 | 'rule' => 'rest/bootstrap', 10 | 'keywords' => [], 11 | 'controller' => 'bootstrap', 12 | 'params' => [ 13 | 'fc' => 'module', 14 | 'module' => 'binshopsrest' 15 | ] 16 | ], 17 | 'module-binshopsrest-lightbootstrap' => [ 18 | 'rule' => 'rest/lightbootstrap', 19 | 'keywords' => [], 20 | 'controller' => 'lightbootstrap', 21 | 'params' => [ 22 | 'fc' => 'module', 23 | 'module' => 'binshopsrest' 24 | ] 25 | ], 26 | 'module-binshopsrest-login' => [ 27 | 'rule' => 'rest/login', 28 | 'keywords' => [], 29 | 'controller' => 'login', 30 | 'params' => [ 31 | 'fc' => 'module', 32 | 'module' => 'binshopsrest' 33 | ] 34 | ], 35 | 'module-binshopsrest-register' => [ 36 | 'rule' => 'rest/register', 37 | 'keywords' => [], 38 | 'controller' => 'register', 39 | 'params' => [ 40 | 'fc' => 'module', 41 | 'module' => 'binshopsrest' 42 | ] 43 | ], 44 | 'module-binshopsrest-logout' => [ 45 | 'rule' => 'rest/logout', 46 | 'keywords' => [], 47 | 'controller' => 'logout', 48 | 'params' => [ 49 | 'fc' => 'module', 50 | 'module' => 'binshopsrest' 51 | ] 52 | ], 53 | 'module-binshopsrest-accountinfo' => [ 54 | 'rule' => 'rest/accountInfo', 55 | 'keywords' => [], 56 | 'controller' => 'accountinfo', 57 | 'params' => [ 58 | 'fc' => 'module', 59 | 'module' => 'binshopsrest' 60 | ] 61 | ], 62 | 'module-binshopsrest-accountedit' => [ 63 | 'rule' => 'rest/accountedit', 64 | 'keywords' => [], 65 | 'controller' => 'accountedit', 66 | 'params' => [ 67 | 'fc' => 'module', 68 | 'module' => 'binshopsrest' 69 | ] 70 | ], 71 | 'module-binshopsrest-productdetail' => [ 72 | 'rule' => 'rest/productdetail', 73 | 'keywords' => [], 74 | 'controller' => 'productdetail', 75 | 'params' => [ 76 | 'fc' => 'module', 77 | 'module' => 'binshopsrest' 78 | ] 79 | ], 80 | 'module-binshopsrest-orderhistory' => [ 81 | 'rule' => 'rest/orderhistory', 82 | 'keywords' => [], 83 | 'controller' => 'orderhistory', 84 | 'params' => [ 85 | 'fc' => 'module', 86 | 'module' => 'binshopsrest' 87 | ] 88 | ], 89 | 'module-binshopsrest-cart' => [ 90 | 'rule' => 'rest/cart', 91 | 'keywords' => [], 92 | 'controller' => 'cart', 93 | 'params' => [ 94 | 'fc' => 'module', 95 | 'module' => 'binshopsrest' 96 | ] 97 | ], 98 | 'module-binshopsrest-categoryproducts' => [ 99 | 'rule' => 'rest/categoryProducts', 100 | 'keywords' => [], 101 | 'controller' => 'categoryproducts', 102 | 'params' => [ 103 | 'fc' => 'module', 104 | 'module' => 'binshopsrest' 105 | ] 106 | ], 107 | 'module-binshopsrest-productsearch' => [ 108 | 'rule' => 'rest/productSearch', 109 | 'keywords' => [], 110 | 'controller' => 'productsearch', 111 | 'params' => [ 112 | 'fc' => 'module', 113 | 'module' => 'binshopsrest' 114 | ] 115 | ], 116 | 'module-binshopsrest-featuredproducts' => [ 117 | 'rule' => 'rest/featuredproducts', 118 | 'keywords' => [], 119 | 'controller' => 'featuredproducts', 120 | 'params' => [ 121 | 'fc' => 'module', 122 | 'module' => 'binshopsrest' 123 | ] 124 | ], 125 | 'module-binshopsrest-address' => [ 126 | 'rule' => 'rest/address', 127 | 'keywords' => [], 128 | 'controller' => 'address', 129 | 'params' => [ 130 | 'fc' => 'module', 131 | 'module' => 'binshopsrest' 132 | ] 133 | ], 134 | 'module-binshopsrest-alladdresses' => [ 135 | 'rule' => 'rest/alladdresses', 136 | 'keywords' => [], 137 | 'controller' => 'alladdresses', 138 | 'params' => [ 139 | 'fc' => 'module', 140 | 'module' => 'binshopsrest' 141 | ] 142 | ], 143 | 'module-binshopsrest-addressform' => [ 144 | 'rule' => 'rest/addressform', 145 | 'keywords' => [], 146 | 'controller' => 'addressform', 147 | 'params' => [ 148 | 'fc' => 'module', 149 | 'module' => 'binshopsrest' 150 | ] 151 | ], 152 | 'module-binshopsrest-carriers' => [ 153 | 'rule' => 'rest/carriers', 154 | 'keywords' => [], 155 | 'controller' => 'carriers', 156 | 'params' => [ 157 | 'fc' => 'module', 158 | 'module' => 'binshopsrest' 159 | ] 160 | ], 161 | 'module-binshopsrest-setaddresscheckout' => [ 162 | 'rule' => 'rest/setaddresscheckout', 163 | 'keywords' => [], 164 | 'controller' => 'setaddresscheckout', 165 | 'params' => [ 166 | 'fc' => 'module', 167 | 'module' => 'binshopsrest' 168 | ] 169 | ], 170 | 'module-binshopsrest-setcarriercheckout' => [ 171 | 'rule' => 'rest/setcarriercheckout', 172 | 'keywords' => [], 173 | 'controller' => 'setcarriercheckout', 174 | 'params' => [ 175 | 'fc' => 'module', 176 | 'module' => 'binshopsrest' 177 | ] 178 | ], 179 | 'module-binshopsrest-paymentoptions' => [ 180 | 'rule' => 'rest/paymentoptions', 181 | 'keywords' => [], 182 | 'controller' => 'paymentoptions', 183 | 'params' => [ 184 | 'fc' => 'module', 185 | 'module' => 'binshopsrest' 186 | ] 187 | ], 188 | 'module-binshopsrest-resetpasswordemail' => [ 189 | 'rule' => 'rest/resetpasswordemail', 190 | 'keywords' => [], 191 | 'controller' => 'resetpasswordemail', 192 | 'params' => [ 193 | 'fc' => 'module', 194 | 'module' => 'binshopsrest' 195 | ] 196 | ], 197 | 'module-binshopsrest-resetpasswordcheck' => [ 198 | 'rule' => 'rest/resetpasswordcheck', 199 | 'keywords' => [], 200 | 'controller' => 'resetpasswordcheck', 201 | 'params' => [ 202 | 'fc' => 'module', 203 | 'module' => 'binshopsrest' 204 | ] 205 | ], 206 | 'module-binshopsrest-resetpasswordenter' => [ 207 | 'rule' => 'rest/resetpasswordenter', 208 | 'keywords' => [], 209 | 'controller' => 'resetpasswordenter', 210 | 'params' => [ 211 | 'fc' => 'module', 212 | 'module' => 'binshopsrest' 213 | ] 214 | ], 215 | 'module-binshopsrest-resetpasswordbyemail' => [ 216 | 'rule' => 'rest/resetpasswordbyemail', 217 | 'keywords' => [], 218 | 'controller' => 'resetpasswordbyemail', 219 | 'params' => [ 220 | 'fc' => 'module', 221 | 'module' => 'binshopsrest' 222 | ] 223 | ], 224 | 'module-binshopsrest-listcomments' => [ 225 | 'rule' => 'rest/listcomments', 226 | 'keywords' => [], 227 | 'controller' => 'listcomments', 228 | 'params' => [ 229 | 'fc' => 'module', 230 | 'module' => 'binshopsrest' 231 | ] 232 | ], 233 | 'module-binshopsrest-postcomment' => [ 234 | 'rule' => 'rest/postcomment', 235 | 'keywords' => [], 236 | 'controller' => 'postcomment', 237 | 'params' => [ 238 | 'fc' => 'module', 239 | 'module' => 'binshopsrest' 240 | ] 241 | ], 242 | 'module-binshopsrest-hello' => [ 243 | 'rule' => 'rest', 244 | 'keywords' => [], 245 | 'controller' => 'hello', 246 | 'params' => [ 247 | 'fc' => 'module', 248 | 'module' => 'binshopsrest' 249 | ] 250 | ], 251 | 'module-binshopsrest-hello-s' => [ 252 | 'rule' => 'rest/', 253 | 'keywords' => [], 254 | 'controller' => 'hello', 255 | 'params' => [ 256 | 'fc' => 'module', 257 | 'module' => 'binshopsrest' 258 | ] 259 | ], 260 | 'module-binshopsrest-ps_checkpayment' => [ 261 | 'rule' => 'rest/ps_checkpayment', 262 | 'keywords' => [], 263 | 'controller' => 'ps_checkpayment', 264 | 'params' => [ 265 | 'fc' => 'module', 266 | 'module' => 'binshopsrest' 267 | ] 268 | ], 269 | 'module-binshopsrest-ps_wirepayment' => [ 270 | 'rule' => 'rest/ps_wirepayment', 271 | 'keywords' => [], 272 | 'controller' => 'ps_wirepayment', 273 | 'params' => [ 274 | 'fc' => 'module', 275 | 'module' => 'binshopsrest' 276 | ] 277 | ], 278 | 'module-binshopsrest-ps_cashondelivery' => [ 279 | 'rule' => 'rest/ps_cashondelivery', 280 | 'keywords' => [], 281 | 'controller' => 'ps_cashondelivery', 282 | 'params' => [ 283 | 'fc' => 'module', 284 | 'module' => 'binshopsrest' 285 | ] 286 | ], 287 | 'module-binshopsrest-wishlist' => [ 288 | 'rule' => 'rest/wishlist', 289 | 'keywords' => [], 290 | 'controller' => 'wishlist', 291 | 'params' => [ 292 | 'fc' => 'module', 293 | 'module' => 'binshopsrest' 294 | ] 295 | ], 296 | 'module-binshopsrest-emailsubscription' => [ 297 | 'rule' => 'rest/emailsubscription', 298 | 'keywords' => [], 299 | 'controller' => 'emailsubscription', 300 | 'params' => [ 301 | 'fc' => 'module', 302 | 'module' => 'binshopsrest' 303 | ] 304 | ], 305 | ]; 306 | } 307 | } 308 | -------------------------------------------------------------------------------- /classes/RESTProductLazyArray.php: -------------------------------------------------------------------------------- 1 | settings = $settings; 60 | $this->product = $product; 61 | $this->language = $language; 62 | $this->priceFormatter = $priceFormatter; 63 | $this->imageRetriever = $imageRetriever; 64 | $this->translator = $translator; 65 | 66 | $this->fillImages( 67 | $product, 68 | $language 69 | ); 70 | 71 | $this->addPriceInformation( 72 | $settings, 73 | $product 74 | ); 75 | 76 | $this->addQuantityInformation( 77 | $settings, 78 | $product, 79 | $language 80 | ); 81 | } 82 | 83 | protected function addPriceInformation( 84 | ProductPresentationSettings $settings, 85 | array $product 86 | ) { 87 | $this->product['has_discount'] = false; 88 | $this->product['discount_type'] = null; 89 | $this->product['discount_percentage'] = null; 90 | $this->product['discount_percentage_absolute'] = null; 91 | $this->product['discount_amount'] = null; 92 | $this->product['discount_amount_to_display'] = null; 93 | 94 | if ($settings->include_taxes) { 95 | $price = $regular_price = $product['price']; 96 | } else { 97 | $price = $regular_price = $product['price_tax_exc']; 98 | } 99 | 100 | if ($product['specific_prices']) { 101 | $this->product['has_discount'] = (0 != $product['reduction']); 102 | $this->product['discount_type'] = $product['specific_prices']['reduction_type']; 103 | 104 | $absoluteReduction = new Number($product['specific_prices']['reduction']); 105 | $absoluteReduction = $absoluteReduction->times(new Number('100')); 106 | $negativeReduction = $absoluteReduction->toNegative(); 107 | $presAbsoluteReduction = $absoluteReduction->round(2, Rounding::ROUND_HALF_UP); 108 | $presNegativeReduction = $negativeReduction->round(2, Rounding::ROUND_HALF_UP); 109 | 110 | // TODO: add percent sign according to locale preferences 111 | $this->product['discount_percentage'] = Tools::displayNumber($presNegativeReduction) . '%'; 112 | $this->product['discount_percentage_absolute'] = Tools::displayNumber($presAbsoluteReduction) . '%'; 113 | if ($settings->include_taxes) { 114 | $regular_price = $product['price_without_reduction']; 115 | $this->product['discount_amount'] = $this->priceFormatter->format( 116 | $product['reduction'] 117 | ); 118 | } else { 119 | $regular_price = $product['price_without_reduction_without_tax']; 120 | $this->product['discount_amount'] = $this->priceFormatter->format( 121 | $product['reduction_without_tax'] 122 | ); 123 | } 124 | $this->product['discount_amount_to_display'] = '-' . $this->product['discount_amount']; 125 | } 126 | 127 | $this->product['price_amount'] = $price; 128 | $this->product['price'] = $this->priceFormatter->format($price); 129 | $this->product['regular_price_amount'] = $regular_price; 130 | $this->product['regular_price'] = $this->priceFormatter->format($regular_price); 131 | 132 | if ($product['reduction'] < $product['price_without_reduction']) { 133 | $this->product['discount_to_display'] = $this->product['discount_amount']; 134 | } else { 135 | $this->product['discount_to_display'] = $this->product['regular_price']; 136 | } 137 | 138 | if (isset($product['unit_price']) && $product['unit_price']) { 139 | $this->product['unit_price'] = $this->priceFormatter->format($product['unit_price']); 140 | $this->product['unit_price_full'] = $this->priceFormatter->format($product['unit_price']) 141 | . ' ' . $product['unity']; 142 | } else { 143 | $this->product['unit_price'] = $this->product['unit_price_full'] = ''; 144 | } 145 | } 146 | 147 | private function fillImages( 148 | array $product, 149 | Language $language 150 | ) { 151 | // Get all product images, including potential cover 152 | $productImages = $this->imageRetriever->getAllProductImages( 153 | $product, 154 | $language 155 | ); 156 | 157 | // Get filtered product images matching the specified id_product_attribute 158 | if (Tools::getValue('with_all_images')) { 159 | $this->product['images'] = $this->filterImagesForCombination($productImages, $product['id_product_attribute']); 160 | 161 | // Get default image for selected combination (used for product page, cart details, ...) 162 | $this->product['default_image'] = reset($this->product['images']); 163 | foreach ($this->product['images'] as $image) { 164 | // If one of the image is a cover it is used as such 165 | if (isset($image['cover']) && null !== $image['cover']) { 166 | $this->product['default_image'] = $image; 167 | 168 | break; 169 | } 170 | } 171 | }else{ 172 | $images = $this->filterImagesForCombination($productImages, $product['id_product_attribute']); 173 | 174 | // Get default image for selected combination (used for product page, cart details, ...) 175 | $tmp = reset($images); 176 | $this->product['default_image'] = $tmp['bySize'][Tools::getValue('image_size', "home_default")]; 177 | foreach ($images as $image) { 178 | // If one of the image is a cover it is used as such 179 | if (isset($image['cover']) && null !== $image['cover']) { 180 | $this->product['default_image'] = $image['bySize'][Tools::getValue('image_size', "home_default")]; 181 | 182 | break; 183 | } 184 | } 185 | } 186 | 187 | // Get generic product image, used for product listing 188 | if (isset($product['cover_image_id'])) { 189 | // First try to find cover in product images 190 | foreach ($productImages as $productImage) { 191 | if ($productImage['id_image'] == $product['cover_image_id']) { 192 | if (Tools::getValue('with_all_images')) { 193 | $this->product['cover'] = $productImage; 194 | }else{ 195 | $this->product['cover'] = $productImage['bySize'][Tools::getValue('image_size', "home_default")]; 196 | } 197 | break; 198 | } 199 | } 200 | 201 | // If the cover is not associated to the product images it is fetched manually 202 | if (!isset($this->product['cover'])) { 203 | $coverImage = $this->imageRetriever->getImage(new Product($product['id_product'], false, $language->getId()), $product['cover_image_id']); 204 | $this->product['cover'] = array_merge($coverImage, [ 205 | 'legend' => $coverImage['legend'], 206 | ]); 207 | } 208 | } 209 | 210 | // If no cover fallback on default image 211 | if (!isset($this->product['cover'])) { 212 | $this->product['cover'] = $this->product['default_image']; 213 | } 214 | } 215 | 216 | /** 217 | * @param ProductPresentationSettings $settings 218 | * @param array $product 219 | * @param Language $language 220 | */ 221 | public function addQuantityInformation( 222 | ProductPresentationSettings $settings, 223 | array $product, 224 | Language $language 225 | ) { 226 | $show_price = $this->shouldShowPrice($settings, $product); 227 | $show_availability = $show_price && $settings->stock_management_enabled; 228 | $this->product['show_availability'] = $show_availability; 229 | $product['quantity_wanted'] = $this->getQuantityWanted(); 230 | 231 | if (isset($product['available_date']) && '0000-00-00' == $product['available_date']) { 232 | $product['available_date'] = null; 233 | } 234 | 235 | if ($show_availability) { 236 | if ($product['quantity'] - $product['quantity_wanted'] >= 0) { 237 | $this->product['availability_date'] = $product['available_date']; 238 | 239 | if ($product['quantity'] < $settings->lastRemainingItems) { 240 | $this->applyLastItemsInStockDisplayRule(); 241 | } else { 242 | $this->product['availability_message'] = $product['available_now'] ? $product['available_now'] 243 | : Configuration::get('PS_LABEL_IN_STOCK_PRODUCTS', $language->id); 244 | $this->product['availability'] = 'available'; 245 | } 246 | } elseif ($product['allow_oosp']) { 247 | $this->product['availability_message'] = $product['available_later'] ? $product['available_later'] 248 | : Configuration::get('PS_LABEL_OOS_PRODUCTS_BOA', $language->id); 249 | $this->product['availability_date'] = $product['available_date']; 250 | $this->product['availability'] = 'available'; 251 | } elseif ($product['quantity_wanted'] > 0 && $product['quantity'] > 0) { 252 | $this->product['availability_message'] = $this->translator->trans( 253 | 'There are not enough products in stock', 254 | [], 255 | 'Shop.Notifications.Error' 256 | ); 257 | $this->product['availability'] = 'unavailable'; 258 | $this->product['availability_date'] = null; 259 | } elseif (!empty($product['quantity_all_versions']) && $product['quantity_all_versions'] > 0) { 260 | $this->product['availability_message'] = $this->translator->trans( 261 | 'Product available with different options', 262 | [], 263 | 'Shop.Theme.Catalog' 264 | ); 265 | $this->product['availability_date'] = $product['available_date']; 266 | $this->product['availability'] = 'unavailable'; 267 | } else { 268 | $this->product['availability_message'] = 269 | Configuration::get('PS_LABEL_OOS_PRODUCTS_BOD', $language->id); 270 | $this->product['availability_date'] = $product['available_date']; 271 | $this->product['availability'] = 'unavailable'; 272 | } 273 | } else { 274 | $this->product['availability_message'] = null; 275 | $this->product['availability_date'] = null; 276 | $this->product['availability'] = null; 277 | } 278 | } 279 | 280 | /** 281 | * @param array $images 282 | * @param int $productAttributeId 283 | * 284 | * @return array 285 | */ 286 | private function filterImagesForCombination(array $images, int $productAttributeId) 287 | { 288 | $filteredImages = []; 289 | 290 | foreach ($images as $image) { 291 | if (in_array($productAttributeId, $image['associatedVariants'])) { 292 | $filteredImages[] = $image; 293 | } 294 | } 295 | 296 | return (0 === count($filteredImages)) ? $images : $filteredImages; 297 | } 298 | 299 | /** 300 | * Prices should be shown for products with active "Show price" option 301 | * and customer groups with active "Show price" option. 302 | * 303 | * @param ProductPresentationSettings $settings 304 | * @param array $product 305 | * 306 | * @return bool 307 | */ 308 | private function shouldShowPrice( 309 | ProductPresentationSettings $settings, 310 | array $product 311 | ) { 312 | return $settings->shouldShowPrice() && (bool)$product['show_price']; 313 | } 314 | 315 | /** 316 | * @return int Quantity of product requested by the customer 317 | */ 318 | private function getQuantityWanted() 319 | { 320 | return (int)Tools::getValue('quantity_wanted', 1); 321 | } 322 | 323 | /** 324 | * Override availability message. 325 | */ 326 | protected function applyLastItemsInStockDisplayRule() 327 | { 328 | $this->product['availability_message'] = $this->translator->trans( 329 | 'Last items in stock', 330 | [], 331 | 'Shop.Theme.Catalog' 332 | ); 333 | $this->product['availability'] = 'last_remaining_items'; 334 | } 335 | 336 | /** 337 | * @return array 338 | */ 339 | public function getProduct(): array 340 | { 341 | return $this->product; 342 | } 343 | } 344 | -------------------------------------------------------------------------------- /classes/RESTTrait.php: -------------------------------------------------------------------------------- 1 | true, 16 | 'code' => 210, 17 | 'psdata' => null, 18 | 'message' => 'empty' 19 | ]; 20 | 21 | switch ($_SERVER['REQUEST_METHOD']) { 22 | case 'GET': 23 | $response = $this->processGetRequest(); 24 | break; 25 | case 'POST': 26 | $response = $this->processPostRequest(); 27 | break; 28 | case 'PATCH': 29 | case 'PUT': 30 | $response = $this->processPutRequest(); 31 | break; 32 | case 'DELETE': 33 | $response = $this->processDeleteRequest(); 34 | break; 35 | default: 36 | // throw some error or whatever 37 | } 38 | 39 | $this->ajaxRender(json_encode($response)); 40 | die; 41 | } 42 | 43 | protected function processGetRequest(){ 44 | return [ 45 | 'success' => true, 46 | 'code' => 310, 47 | 'psdata' => null, 48 | 'message' => $this->trans('GET not supported on this path', [], 'Modules.Binshopsrest.Admin'), 49 | ]; 50 | } 51 | 52 | protected function processPostRequest(){ 53 | return [ 54 | 'success' => true, 55 | 'code' => 310, 56 | 'psdata' => null, 57 | 'message' => $this->trans('POST not supported on this path', [], 'Modules.Binshopsrest.Admin'), 58 | ]; 59 | } 60 | 61 | protected function processPutRequest(){ 62 | return [ 63 | 'success' => true, 64 | 'code' => 310, 65 | 'psdata' => null, 66 | 'message' => $this->trans('PUT not supported on this path', [], 'Modules.Binshopsrest.Admin'), 67 | ]; 68 | } 69 | 70 | protected function processDeleteRequest(){ 71 | return [ 72 | 'success' => true, 73 | 'code' => 310, 74 | 'psdata' => null, 75 | 'message' => $this->trans('DELETE not supported on this path', [], 'Modules.Binshopsrest.Admin'), 76 | ]; 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /classes/index.php: -------------------------------------------------------------------------------- 1 | 2 | 3 | binshopsrest 4 | 5 | 6 | 7 | 8 | 9 | 10 | 1 11 | 0 12 | 13 | 14 | -------------------------------------------------------------------------------- /controllers/AbstractAuthRESTController.php: -------------------------------------------------------------------------------- 1 | context->customer->isLogged() && $this->php_self != 'authentication' && $this->php_self != 'password') { 26 | $this->ajaxRender(json_encode([ 27 | 'code' => 410, 28 | 'success' => false, 29 | 'message' => $this->trans('User Not Authenticated', [], 'Modules.Binshopsrest.Admin') 30 | ])); 31 | die; 32 | } 33 | 34 | parent::init(); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /controllers/AbstractCartRESTController.php: -------------------------------------------------------------------------------- 1 | true, 21 | 'code' => 210, 22 | 'psdata' => null, 23 | 'message' => 'empty' 24 | ]; 25 | 26 | switch ($_SERVER['REQUEST_METHOD']) { 27 | case 'GET': 28 | $response = $this->processGetRequest(); 29 | break; 30 | case 'POST': 31 | $response = $this->processPostRequest(); 32 | break; 33 | case 'PATCH': 34 | case 'PUT': 35 | $response = $this->processPutRequest(); 36 | break; 37 | case 'DELETE': 38 | $response = $this->processDeleteRequest(); 39 | break; 40 | default: 41 | // throw some error or whatever 42 | } 43 | 44 | $this->ajaxRender(json_encode($response)); 45 | die; 46 | } 47 | 48 | protected function checkCartProductsMinimalQuantities() 49 | { 50 | $productList = $this->context->cart->getProducts(); 51 | 52 | foreach ($productList as $product) { 53 | if ($product['minimal_quantity'] > $product['cart_quantity']) { 54 | // display minimal quantity warning error message 55 | $this->errors[] = $this->trans( 56 | 'The minimum purchase order quantity for the product %product% is %quantity%.', 57 | [ 58 | '%product%' => $product['name'], 59 | '%quantity%' => $product['minimal_quantity'], 60 | ], 61 | 'Shop.Notifications.Error' 62 | ); 63 | } 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /controllers/AbstractPaymentRESTController.php: -------------------------------------------------------------------------------- 1 | context->customer->isLogged() && $this->php_self != 'authentication' && $this->php_self != 'password') { 30 | $this->ajaxRender(json_encode([ 31 | 'code' => 410, 32 | 'success' => false, 33 | 'message' => $this->trans('User Not Authenticated', [], 'Modules.Binshopsrest.Admin') 34 | ])); 35 | die; 36 | } 37 | 38 | parent::init(); 39 | switch ($_SERVER['REQUEST_METHOD']) { 40 | case 'GET': 41 | $this->processGetRequest(); 42 | break; 43 | case 'POST': 44 | $this->processPostRequest(); 45 | break; 46 | case 'PATCH': 47 | case 'PUT': 48 | $this->processPutRequest(); 49 | break; 50 | case 'DELETE': 51 | $this->processDeleteRequest(); 52 | break; 53 | default: 54 | // throw some error or whatever 55 | } 56 | } 57 | 58 | protected final function processGetRequest(){ 59 | $cart = $this->context->cart; 60 | 61 | if ($cart->id_customer == 0 || $cart->id_address_delivery == 0 || $cart->id_address_invoice == 0 || !$this->module->active) { 62 | Tools::redirect('index.php?controller=order&step=1'); 63 | 64 | $this->ajaxRender(json_encode([ 65 | 'success' => false, 66 | 'code' => 301, 67 | 'message' => $this->trans('Payment processing failed', [], 'Modules.Binshopsrest.Payment') 68 | ])); 69 | die; 70 | } 71 | 72 | if (Validate::isLoadedObject($this->context->cart) && $this->context->cart->OrderExists() == false){ 73 | $this->processRESTPayment(); 74 | }else{ 75 | $this->ajaxRender(json_encode([ 76 | 'success' => false, 77 | 'code' => 302, 78 | 'message' => $this->trans('Cart cannot be loaded or an order has already been placed using this cart', [], 'Admin.Payment.Notification') 79 | ])); 80 | die; 81 | } 82 | 83 | $order_presenter = new OrderPresenter(); 84 | 85 | $order = new Order(Order::getIdByCartId((int) ($cart->id))); 86 | $presentedOrder = $order_presenter->present($order); 87 | 88 | $this->ajaxRender(json_encode([ 89 | 'success' => true, 90 | 'code' => 200, 91 | 'message' => 'successful payment', 92 | 'psdata' => [ 93 | 'order' => $presentedOrder 94 | ] 95 | ])); 96 | die; 97 | } 98 | 99 | protected final function processPostRequest() 100 | { 101 | $this->ajaxRender(json_encode([ 102 | 'success' => true, 103 | 'message' => 'POST not supported on this path' 104 | ])); 105 | die; 106 | } 107 | 108 | protected final function processPutRequest() 109 | { 110 | $this->ajaxRender(json_encode([ 111 | 'success' => true, 112 | 'message' => 'put not supported on this path' 113 | ])); 114 | die; 115 | } 116 | 117 | protected final function processDeleteRequest() 118 | { 119 | $this->ajaxRender(json_encode([ 120 | 'success' => true, 121 | 'message' => 'delete not supported on this path' 122 | ])); 123 | die; 124 | } 125 | 126 | abstract protected function processRESTPayment(); 127 | } 128 | -------------------------------------------------------------------------------- /controllers/AbstractProductListingRESTController.php: -------------------------------------------------------------------------------- 1 | true, 42 | 'code' => 210, 43 | 'psdata' => null, 44 | 'message' => 'empty' 45 | ]; 46 | 47 | switch ($_SERVER['REQUEST_METHOD']) { 48 | case 'GET': 49 | $response = $this->processGetRequest(); 50 | break; 51 | case 'POST': 52 | $response = $this->processPostRequest(); 53 | break; 54 | case 'PATCH': 55 | case 'PUT': 56 | $response = $this->processPutRequest(); 57 | break; 58 | case 'DELETE': 59 | $response = $this->processDeleteRequest(); 60 | break; 61 | default: 62 | // throw some error or whatever 63 | } 64 | 65 | $this->ajaxRender(json_encode($response)); 66 | die; 67 | } 68 | 69 | protected function getImage($object, $id_image) 70 | { 71 | $retriever = new ImageRetriever( 72 | $this->context->link 73 | ); 74 | 75 | return $retriever->getImage($object, $id_image); 76 | } 77 | 78 | protected function getProductSearchVariables() 79 | { 80 | /* 81 | * To render the page we need to find something (a ProductSearchProviderInterface) 82 | * that knows how to query products. 83 | */ 84 | 85 | // the search provider will need a context (language, shop...) to do its job 86 | $context = $this->getProductSearchContext(); 87 | 88 | // the controller generates the query... 89 | if (Tools::getValue('s')) { 90 | $query = $this->getProductSearchQuery(); 91 | } else { 92 | $query = new ProductSearchQuery(); 93 | $query 94 | ->setIdCategory(Tools::getValue('id_category')) 95 | ->setSortOrder(new SortOrder('product', Tools::getProductsOrder('by'), Tools::getProductsOrder('way'))); 96 | } 97 | 98 | // ...modules decide if they can handle it (first one that can is used) 99 | $provider = $this->getProductSearchProviderFromModules($query); 100 | 101 | // if no module wants to do the query, then the core feature is used 102 | if (null === $provider) { 103 | $provider = $this->getDefaultProductSearchProvider(); 104 | } 105 | 106 | $resultsPerPage = (int)Tools::getValue('resultsPerPage'); 107 | if ($resultsPerPage <= 0) { 108 | $resultsPerPage = Configuration::get('PS_PRODUCTS_PER_PAGE'); 109 | } 110 | 111 | // we need to set a few parameters from back-end preferences 112 | $query 113 | ->setResultsPerPage($resultsPerPage) 114 | ->setPage(max((int)Tools::getValue('page'), 1)); 115 | 116 | // set the sort order if provided in the URL 117 | if (($encodedSortOrder = Tools::getValue('order'))) { 118 | $query->setSortOrder(SortOrder::newFromString( 119 | $encodedSortOrder 120 | )); 121 | } 122 | 123 | // get the parameters containing the encoded facets from the URL 124 | $encodedFacets = Tools::getValue('q'); 125 | 126 | /* 127 | * The controller is agnostic of facets. 128 | * It's up to the search module to use /define them. 129 | * 130 | * Facets are encoded in the "q" URL parameter, which is passed 131 | * to the search provider through the query's "$encodedFacets" property. 132 | */ 133 | 134 | $query->setEncodedFacets($encodedFacets); 135 | 136 | // We're ready to run the actual query! 137 | 138 | /** @var ProductSearchResult $result */ 139 | $result = $provider->runQuery( 140 | $context, 141 | $query 142 | ); 143 | 144 | if (Configuration::get('PS_CATALOG_MODE') && !Configuration::get('PS_CATALOG_MODE_WITH_PRICES')) { 145 | $this->disablePriceControls($result); 146 | } 147 | 148 | // sort order is useful for template, 149 | // add it if undefined - it should be the same one 150 | // as for the query anyway 151 | if (!$result->getCurrentSortOrder()) { 152 | $result->setCurrentSortOrder($query->getSortOrder()); 153 | } 154 | 155 | // prepare the products 156 | $products = $result->getProducts(); 157 | 158 | // render the facets 159 | $facets = $this->getFacets( 160 | $result 161 | ); 162 | 163 | $pagination = $this->getTemplateVarPagination( 164 | $query, 165 | $result 166 | ); 167 | 168 | // prepare the sort orders 169 | // note that, again, the product controller is sort-orders 170 | // agnostic 171 | // a module can easily add specific sort orders that it needs 172 | // to support (e.g. sort by "energy efficiency") 173 | $sort_orders = $this->getTemplateVarSortOrders( 174 | $result->getAvailableSortOrders(), 175 | $query->getSortOrder()->toString() 176 | ); 177 | 178 | $sort_selected = false; 179 | if (!empty($sort_orders)) { 180 | foreach ($sort_orders as $order) { 181 | if (isset($order['current']) && true === $order['current']) { 182 | $sort_selected = $order['label']; 183 | 184 | break; 185 | } 186 | } 187 | } 188 | 189 | $searchVariables = array( 190 | 'result' => $result, 191 | 'label' => $this->getListingLabel(), 192 | 'products' => $products, 193 | 'sort_orders' => $sort_orders, 194 | 'sort_selected' => $sort_selected, 195 | 'pagination' => $pagination, 196 | 'facets' => $facets, 197 | 'js_enabled' => $this->ajax, 198 | 'current_url' => $this->updateQueryString(array( 199 | 'q' => $result->getEncodedFacets(), 200 | )), 201 | ); 202 | 203 | Hook::exec('filterProductSearch', array('searchVariables' => &$searchVariables)); 204 | Hook::exec('actionProductSearchAfter', $searchVariables); 205 | 206 | return $searchVariables; 207 | } 208 | 209 | private function getProductSearchProviderFromModules($query) 210 | { 211 | $providers = Hook::exec( 212 | 'productSearchProvider', 213 | ['query' => $query], 214 | null, 215 | true 216 | ); 217 | 218 | if (!is_array($providers)) { 219 | $providers = []; 220 | } 221 | 222 | foreach ($providers as $provider) { 223 | if ($provider instanceof ProductSearchProviderInterface) { 224 | return $provider; 225 | } 226 | } 227 | } 228 | 229 | protected function getFacets(ProductSearchResult $result) 230 | { 231 | $facetCollection = $result->getFacetCollection(); 232 | // not all search providers generate menus 233 | if (empty($facetCollection)) { 234 | return ''; 235 | } 236 | 237 | $facetsVar = array_map( 238 | [$this, 'prepareFacetForTemplate'], 239 | $facetCollection->getFacets() 240 | ); 241 | 242 | $activeFilters = []; 243 | foreach ($facetsVar as $facet) { 244 | foreach ($facet['filters'] as $filter) { 245 | if ($filter['active']) { 246 | $activeFilters[] = $filter; 247 | } 248 | } 249 | } 250 | 251 | return [ 252 | 'filters' => $facetCollection, 253 | 'activeFilters' => $activeFilters 254 | ]; 255 | } 256 | } 257 | -------------------------------------------------------------------------------- /controllers/AbstractRESTController.php: -------------------------------------------------------------------------------- 1 | true, 35 | 'code' => 210, 36 | 'psdata' => null, 37 | 'message' => 'empty' 38 | ]; 39 | 40 | switch ($_SERVER['REQUEST_METHOD']) { 41 | case 'GET': 42 | $response = $this->processGetRequest(); 43 | break; 44 | case 'POST': 45 | $response = $this->processPostRequest(); 46 | break; 47 | case 'PATCH': 48 | case 'PUT': 49 | $response = $this->processPutRequest(); 50 | break; 51 | case 'DELETE': 52 | $response = $this->processDeleteRequest(); 53 | break; 54 | default: 55 | // throw some error or whatever 56 | } 57 | 58 | $this->ajaxRender(json_encode($response)); 59 | die; 60 | } 61 | 62 | public function formatPrice($price) 63 | { 64 | return Tools::displayPrice( 65 | $price, 66 | $this->context->currency, 67 | false, 68 | $this->context 69 | ); 70 | } 71 | 72 | public function getImageType($type = 'large') 73 | { 74 | if ($type == 'large') { 75 | return $this->img1 . $this->img3; 76 | } elseif ($type == 'medium') { 77 | return $this->img2 . $this->img3; 78 | } else { 79 | return $this->img1 . $this->img3; 80 | } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /controllers/front/Readme.md: -------------------------------------------------------------------------------- 1 | All of the REST controllers are prestashop Front Controllers. -------------------------------------------------------------------------------- /controllers/front/accountedit.php: -------------------------------------------------------------------------------- 1 | context->customer->id) { 32 | $this->ajaxRender(json_encode([ 33 | 'success' => false, 34 | 'code' => 310, 35 | 'psdata' => null, 36 | 'message' => $this->trans('The email is already used, please choose another one or sign in', [], 'Modules.Binshopsrest.Account') 37 | ])); 38 | die; 39 | } 40 | 41 | $birthday = Tools::getValue('birthday'); 42 | if (!empty($birthday) && 43 | Validate::isBirthDate($birthday, $this->context->language->date_format_lite) 44 | ) { 45 | $dateBuilt = DateTime::createFromFormat( 46 | $this->context->language->date_format_lite, 47 | $birthday 48 | ); 49 | $birthday = $dateBuilt->format('Y-m-d'); 50 | } 51 | 52 | if (empty($email)) { 53 | $success = false; 54 | $message = "An email address required"; 55 | $messageCode = 301; 56 | } elseif (!Validate::isEmail($email)) { 57 | $success = false; 58 | $message = "Invalid email address"; 59 | $messageCode = 302; 60 | } elseif (empty($password)) { 61 | $success = false; 62 | $message = 'Password is not provided'; 63 | $messageCode = 303; 64 | } elseif (!Validate::isPasswd($password)) { 65 | $success = false; 66 | $message = "Invalid Password"; 67 | $messageCode = 304; 68 | } elseif (empty($firstName)) { 69 | $success = false; 70 | $message = "First name required"; 71 | $messageCode = 305; 72 | } elseif (empty($lastName)) { 73 | $success = false; 74 | $message = "Last name required"; 75 | $messageCode = 306; 76 | } elseif (empty($gender)) { 77 | $success = false; 78 | $message = "gender required"; 79 | $messageCode = 307; 80 | } elseif (!Validate::isCustomerName($firstName)){ 81 | $success = false; 82 | $message = "firstname bad format"; 83 | $messageCode = 311; 84 | } elseif (!Validate::isCustomerName($lastName)){ 85 | $success = false; 86 | $message = "lastname bad format"; 87 | $messageCode = 312; 88 | } else { 89 | $guestAllowedCheckout = Configuration::get('PS_GUEST_CHECKOUT_ENABLED'); 90 | $cp = new CustomerPersister( 91 | $this->context, 92 | $this->get('hashing'), 93 | $this->getTranslator(), 94 | $guestAllowedCheckout 95 | ); 96 | try { 97 | $customer = new Customer($this->context->customer->id); 98 | $customer->firstname = $firstName; 99 | $customer->lastname = $lastName; 100 | $customer->email = $email; 101 | $customer->id_gender = $gender; 102 | $customer->id_shop = (int)$this->context->shop->id; 103 | $customer->newsletter = $newsletter; 104 | 105 | if (!empty($birthday)){ 106 | $customer->birthday = $birthday; 107 | } 108 | 109 | $clearTextPassword = Tools::getValue('password'); 110 | $newPassword = Tools::getValue('new_password'); 111 | 112 | $status = $cp->save( 113 | $customer, 114 | $clearTextPassword, 115 | $newPassword, 116 | true 117 | ); 118 | 119 | if ($status) { 120 | $messageCode = 200; 121 | $message = 'User updated successfully'; 122 | $psdata = array( 123 | 'registered' => $status, 124 | 'message' => $this->trans('User updated successfully', [], 'Modules.Binshopsrest.Account'), 125 | 'customer_id' => $customer->id, 126 | 'session_data' => (int)$this->context->cart->id 127 | ); 128 | } else { 129 | $success = false; 130 | $messageCode = 350; 131 | $message = 'could not update customer'; 132 | $psdata = array( 133 | 'registered' => $status, 134 | 'message' => $this->trans('Password Incorrect', [], 'Modules.Binshopsrest.Account'), 135 | 'customer_id' => $customer->id, 136 | 'session_data' => (int)$this->context->cart->id 137 | ); 138 | } 139 | } catch (Exception $exception) { 140 | $messageCode = 300; 141 | $message = $exception->getMessage(); 142 | $success = false; 143 | } 144 | } 145 | 146 | $this->ajaxRender(json_encode([ 147 | 'success' => $success, 148 | 'code' => $messageCode, 149 | 'psdata' => $psdata, 150 | 'message' => $message 151 | ])); 152 | die; 153 | } 154 | } 155 | -------------------------------------------------------------------------------- /controllers/front/accountinfo.php: -------------------------------------------------------------------------------- 1 | context->customer; 19 | unset($user->secure_key); 20 | unset($user->passwd); 21 | unset($user->last_passwd_gen); 22 | unset($user->reset_password_token); 23 | unset($user->reset_password_validity); 24 | 25 | $this->ajaxRender(json_encode([ 26 | 'code' => 200, 27 | 'success' => true, 28 | 'psdata' => $user 29 | ])); 30 | die; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /controllers/front/address.php: -------------------------------------------------------------------------------- 1 | context->language->id 24 | ); 25 | 26 | $this->ajaxRender(json_encode([ 27 | 'success' => true, 28 | 'code' => 200, 29 | 'psdata' => $address 30 | ])); 31 | die; 32 | } 33 | 34 | protected function processPostRequest() 35 | { 36 | $_POST = json_decode(Tools::file_get_contents('php://input'), true); 37 | $validate_obj = $this->validatePost(); 38 | 39 | if (!$validate_obj['valid']) { 40 | $this->ajaxRender(json_encode([ 41 | 'success' => false, 42 | 'code' => 301, 43 | 'psdata' => $validate_obj['errors'] 44 | ])); 45 | die; 46 | } 47 | 48 | $availableCountries = Country::getCountries($this->context->language->id, true); 49 | $formatter = new CustomerAddressFormatter( 50 | $this->context->country, 51 | $this->getTranslator(), 52 | $availableCountries 53 | ); 54 | 55 | $country = $formatter->getCountry(); 56 | if ($country->need_zip_code){ 57 | if (!$country->checkZipCode(Tools::getValue('postcode'))) { 58 | $this->ajaxRender(json_encode([ 59 | 'success' => false, 60 | 'code' => 303, 61 | 'psdata' => [], 62 | 'message' => $this->translator->trans( 63 | 'Invalid postcode - should look like "%zipcode%"', 64 | ['%zipcode%' => $country->zip_code_format], 65 | 'Shop.Forms.Errors' 66 | ) 67 | ])); 68 | die; 69 | } 70 | } 71 | 72 | if (Tools::getValue('id_address')) { 73 | $msg = $this->trans('Successfully updated address', [], 'Modules.Binshopsrest.Shop'); 74 | } else { 75 | $msg = $this->trans('Successfully added address', [], 'Modules.Binshopsrest.Shop'); 76 | } 77 | 78 | $address = new Address( 79 | Tools::getValue('id_address'), 80 | $this->context->language->id 81 | ); 82 | 83 | if (!Tools::getValue('id_state')) { 84 | $address->id_state = 0; 85 | } 86 | 87 | $deliveryOptionsFinder = new DeliveryOptionsFinder( 88 | $this->context, 89 | $this->getTranslator(), 90 | $this->objectPresenter, 91 | new PriceFormatter() 92 | ); 93 | $session = new CheckoutSession( 94 | $this->context, 95 | $deliveryOptionsFinder 96 | ); 97 | 98 | if (!Tools::getValue('firstname')){ 99 | $address->firstname = $session->getCustomer()->firstname; 100 | }else{ 101 | $address->firstname = Tools::getValue('firstname'); 102 | } 103 | 104 | if (!Tools::getValue('lastname')){ 105 | $address->lastname = $session->getCustomer()->lastname; 106 | }else{ 107 | $address->lastname = Tools::getValue('lastname'); 108 | } 109 | 110 | $address->alias = Tools::getValue('alias'); 111 | $address->id_country = Tools::getValue('id_country'); 112 | $address->country = Tools::getValue('country'); 113 | $address->id_state = Tools::getValue('id_state'); 114 | $address->postcode = Tools::getValue('postcode'); 115 | $address->city = Tools::getValue('city'); 116 | $address->address1 = Tools::getValue('address1'); 117 | $address->address2 = Tools::getValue('address2'); 118 | $address->company = Tools::getValue('company'); 119 | $address->other = Tools::getValue('other'); 120 | $address->phone = Tools::getValue('phone'); 121 | $address->phone_mobile = Tools::getValue('phone_mobile'); 122 | $address->vat_number = Tools::getValue('vat_number'); 123 | $address->dni = Tools::getValue('dni'); 124 | 125 | Hook::exec('actionSubmitCustomerAddressForm', ['address' => &$address]); 126 | 127 | $persister = new CustomerAddressPersister( 128 | $this->context->customer, 129 | $this->context->cart, 130 | Tools::getToken(true, $this->context) 131 | ); 132 | 133 | $saved = $persister->save( 134 | $address, 135 | Tools::getToken(true, $this->context) 136 | ); 137 | 138 | if (!$saved) { 139 | $this->ajaxRender(json_encode([ 140 | 'success' => false, 141 | 'code' => 302, 142 | 'psdata' => "internal-server-error" 143 | ])); 144 | die; 145 | } 146 | 147 | $this->ajaxRender(json_encode([ 148 | 'success' => true, 149 | 'code' => 200, 150 | 'psdata' => $address, 151 | 'message' => $msg 152 | ])); 153 | die; 154 | } 155 | 156 | protected function processDeleteRequest() 157 | { 158 | $_POST = json_decode(Tools::file_get_contents('php://input'), true); 159 | Tools::getValue('id_address'); 160 | 161 | $address = new Address( 162 | Tools::getValue('id_address'), 163 | $this->context->language->id 164 | ); 165 | 166 | if ($address->id_customer != $this->context->customer->id) { 167 | $this->ajaxRender(json_encode([ 168 | 'success' => true, 169 | 'code' => 301, 170 | 'message' => $this->trans("Address is not available", [], 'Modules.Binshopsrest.Address') 171 | ])); 172 | die; 173 | } 174 | 175 | if ($address->id) { 176 | if (!$address->deleted){ 177 | $address->deleted = true; 178 | 179 | $persister = new CustomerAddressPersister( 180 | $this->context->customer, 181 | $this->context->cart, 182 | Tools::getToken(true, $this->context) 183 | ); 184 | 185 | $saved = $persister->save( 186 | $address, 187 | Tools::getToken(true, $this->context) 188 | ); 189 | }else{ 190 | $this->ajaxRender(json_encode([ 191 | 'success' => true, 192 | 'code' => 202, 193 | 'message' => $this->trans("Address was already deleted", [], 'Modules.Binshopsrest.Address') 194 | ])); 195 | die; 196 | } 197 | } else { 198 | $this->ajaxRender(json_encode([ 199 | 'success' => true, 200 | 'code' => 301, 201 | 'message' => $this->trans("Address is not available", [], 'Modules.Binshopsrest.Address') 202 | ])); 203 | die; 204 | } 205 | 206 | $this->ajaxRender(json_encode([ 207 | 'success' => true, 208 | 'code' => 200, 209 | 'psdata' => $saved, 210 | 'message' => $this->trans("Address successfully deleted", [], 'Modules.Binshopsrest.Address') 211 | ])); 212 | die; 213 | } 214 | 215 | public function validatePost() 216 | { 217 | $psdata = array(); 218 | $psdata['valid'] = true; 219 | $psdata['errors'] = array(); 220 | 221 | if (!Tools::getValue('alias')) { 222 | $psdata['valid'] = false; 223 | $psdata['errors'][] = "alias-required"; 224 | } 225 | if (!Tools::getValue('postcode')) { 226 | $psdata['valid'] = false; 227 | $psdata['errors'][] = "postcode-required"; 228 | } 229 | if (!Tools::getValue('address1')) { 230 | $psdata['valid'] = false; 231 | $psdata['errors'][] = "address1-required"; 232 | } 233 | if (!Tools::getValue('id_country')) { 234 | $psdata['valid'] = false; 235 | $psdata['errors'][] = "id_country-required"; 236 | } 237 | if (!Tools::getValue('country')) { 238 | $psdata['valid'] = false; 239 | $psdata['errors'][] = "country-required"; 240 | } 241 | if (!Tools::getValue('city')) { 242 | $psdata['valid'] = false; 243 | $psdata['errors'][] = "city-required"; 244 | } 245 | if (Address::dniRequired(Tools::getValue('id_country')) && !Tools::getValue('dni')) { 246 | $psdata['valid'] = false; 247 | $psdata['errors'][] = "dni-required"; 248 | } 249 | 250 | return $psdata; 251 | } 252 | } 253 | -------------------------------------------------------------------------------- /controllers/front/addressform.php: -------------------------------------------------------------------------------- 1 | context->language->id, true, true); 20 | } else { 21 | $availableCountries = Country::getCountries($this->context->language->id, true); 22 | } 23 | 24 | $psdata = array(); 25 | $psdata['countries'] = $availableCountries; 26 | 27 | $this->ajaxRender(json_encode([ 28 | 'success' => true, 29 | 'code' => 200, 30 | 'psdata' => $psdata 31 | ])); 32 | die; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /controllers/front/alladdresses.php: -------------------------------------------------------------------------------- 1 | context->customer; 19 | $psdata = $customer->getSimpleAddresses( 20 | $this->context->language->id, 21 | true // no cache 22 | ); 23 | 24 | $this->ajaxRender(json_encode([ 25 | 'success' => true, 26 | 'code' => 200, 27 | 'psdata' => $psdata 28 | ])); 29 | die; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /controllers/front/bootstrap.php: -------------------------------------------------------------------------------- 1 | banner = Module::getInstanceByName('ps_banner'); 35 | $imagesSlider = Module::getInstanceByName('ps_imageslider'); 36 | 37 | $restMenu = new RESTMainMenu(); 38 | $menuItems = $restMenu->renderMenu($this->context, $mainMenu); 39 | $featuredProductsList = $this->getFeaturedProducts(); 40 | $slidesList = $imagesSlider->getWidgetVariables(null, []); 41 | 42 | if (Tools::getValue('menu_with_images', false)){ 43 | foreach ($menuItems as $key => $item) { 44 | $retriever = new \PrestaShop\PrestaShop\Adapter\Image\ImageRetriever( 45 | $this->context->link 46 | ); 47 | $category = new Category( 48 | Tools::substr($item['page_identifier'], -1), 49 | $this->context->language->id 50 | ); 51 | if (Tools::getValue('menu_with_images', 'all') === "single"){ 52 | $menuItems[$key]['image']['src'] =$this->context->link->getCatImageLink( 53 | urlencode($item['slug']), 54 | ($category->id_image), 55 | 'small_default' 56 | ); 57 | }else{ 58 | $menuItems[$key]['images'] = $retriever->getImage( 59 | $category, 60 | $category->id_image 61 | ); 62 | } 63 | } 64 | } 65 | 66 | $id_shop = (int) $this->context->shop->id; 67 | 68 | $psdata = array(); 69 | $psdata['menuItems'] = $menuItems; 70 | $psdata['featuredProductsList'] = $featuredProductsList['products']; 71 | $psdata['numberOfFeaturedProd'] = 10; 72 | $psdata['banner'] = $this->getBanner(); 73 | $psdata['slides'] = $slidesList['homeslider']['slides']; 74 | $psdata['currencies'] = $this->getCurrencies(); 75 | $psdata['languages'] = $this->getLanguages(); 76 | $psdata['logo_url'] = Tools::getHttpHost(true) . _PS_IMG_ .Configuration::get('PS_LOGO', null, null, $id_shop); 77 | 78 | $psdata['contact_info'] = $this->getContactInfo(); 79 | 80 | $this->ajaxRender(json_encode([ 81 | 'success' => true, 82 | 'code' => $messageCode, 83 | 'psdata' => $psdata 84 | ])); 85 | die; 86 | } 87 | 88 | protected function getLanguages(){ 89 | $languages = Language::getLanguages(true, $this->context->shop->id); 90 | 91 | foreach ($languages as &$lang) { 92 | $lang['name_simple'] = $this->getNameSimple($lang['name']); 93 | } 94 | 95 | return array( 96 | 'languages' => $languages, 97 | 'current_language' => array( 98 | 'id_lang' => $this->context->language->id, 99 | 'name' => $this->context->language->name, 100 | 'name_simple' => $this->getNameSimple($this->context->language->name), 101 | 'iso_code' => $this->context->language->iso_code 102 | ) 103 | ); 104 | } 105 | 106 | private function getNameSimple($name) 107 | { 108 | return preg_replace('/\s\(.*\)$/', '', $name); 109 | } 110 | 111 | protected function getCurrencies(){ 112 | $current_currency = null; 113 | $serializer = new ObjectPresenter(); 114 | $currencies = array_map( 115 | function ($currency) use ($serializer, &$current_currency) { 116 | $currencyArray = $serializer->present($currency); 117 | 118 | // serializer doesn't see 'sign' because it is not a regular 119 | // ObjectModel field. 120 | $currencyArray['sign'] = $currency->sign; 121 | 122 | $url = $this->context->link->getLanguageLink($this->context->language->id); 123 | 124 | $parsedUrl = parse_url($url); 125 | $urlParams = []; 126 | if (isset($parsedUrl['query'])) { 127 | parse_str($parsedUrl['query'], $urlParams); 128 | } 129 | $newParams = array_merge( 130 | $urlParams, 131 | [ 132 | 'SubmitCurrency' => 1, 133 | 'id_currency' => $currency->id, 134 | ] 135 | ); 136 | $newUrl = sprintf('%s://%s%s%s?%s', 137 | $parsedUrl['scheme'], 138 | $parsedUrl['host'], 139 | isset($parsedUrl['port']) ? ':' . $parsedUrl['port'] : '', 140 | $parsedUrl['path'], 141 | http_build_query($newParams) 142 | ); 143 | 144 | $currencyArray['url'] = $newUrl; 145 | 146 | if ($currency->id === $this->context->currency->id) { 147 | $currencyArray['current'] = true; 148 | $current_currency = $currencyArray; 149 | } else { 150 | $currencyArray['current'] = false; 151 | } 152 | 153 | return $currencyArray; 154 | }, 155 | Currency::getCurrencies(true, true) 156 | ); 157 | 158 | return [ 159 | 'currencies' => $currencies, 160 | 'current_currency' => $current_currency, 161 | ]; 162 | } 163 | 164 | protected function getBanner() 165 | { 166 | $imgname = Configuration::get('BANNER_IMG', $this->context->language->id); 167 | $image_url = ""; 168 | 169 | if ($imgname && file_exists(_PS_MODULE_DIR_ . $this->banner->name . DIRECTORY_SEPARATOR . 'img' . DIRECTORY_SEPARATOR . $imgname)) { 170 | $image_url = $this->context->link->protocol_content . Tools::getMediaServer($imgname) . __PS_BASE_URI__ . 'modules/' . $this->banner->name . '/' . 'img/' . $imgname; 171 | } 172 | 173 | $banner_link = Configuration::get('BANNER_LINK', $this->context->language->id); 174 | if (!$banner_link) { 175 | $banner_link = $this->context->link->getPageLink('index'); 176 | } 177 | 178 | return array( 179 | 'image_url' => $image_url, 180 | 'banner_link' => $this->updateUrl($banner_link), 181 | 'banner_desc' => Configuration::get('BANNER_DESC', $this->context->language->id) 182 | ); 183 | } 184 | 185 | private function updateUrl($link) 186 | { 187 | if (Tools::substr($link, 0, 7) !== "http://" && Tools::substr($link, 0, 8) !== "https://") { 188 | $link = "http://" . $link; 189 | } 190 | 191 | return $link; 192 | } 193 | 194 | public function getFeaturedProducts(){ 195 | $category = new Category((int) Configuration::get('HOME_FEATURED_CAT')); 196 | 197 | $searchProvider = new CategoryProductSearchProvider( 198 | $this->context->getTranslator(), 199 | $category 200 | ); 201 | 202 | $context = new ProductSearchContext($this->context); 203 | 204 | $query = new ProductSearchQuery(); 205 | $nProducts = Configuration::get('HOME_FEATURED_NBR'); 206 | if ($nProducts < 0) { 207 | $nProducts = 12; 208 | } 209 | 210 | $query 211 | ->setResultsPerPage($nProducts) 212 | ->setPage(1) 213 | ; 214 | 215 | if (Configuration::get('HOME_FEATURED_RANDOMIZE')) { 216 | $query->setSortOrder(SortOrder::random()); 217 | } else { 218 | $query->setSortOrder(new SortOrder('product', 'position', 'asc')); 219 | } 220 | 221 | $result = $searchProvider->runQuery( 222 | $context, 223 | $query 224 | ); 225 | 226 | $products_for_template = []; 227 | $settings = $this->getProductPresentationSettings(); 228 | $retriever = new \PrestaShop\PrestaShop\Adapter\Image\ImageRetriever( 229 | $this->context->link 230 | ); 231 | 232 | foreach ($result->getProducts() as $rawProduct) { 233 | $populated_product = (new ProductAssembler($this->context)) 234 | ->assembleProduct($rawProduct); 235 | $lazy_product = new RESTProductLazyArray( 236 | $settings, 237 | $populated_product, 238 | $this->context->language, 239 | new \PrestaShop\PrestaShop\Adapter\Product\PriceFormatter(), 240 | $retriever, 241 | $this->context->getTranslator() 242 | ); 243 | 244 | $products_for_template[] = $lazy_product->getProduct(); 245 | } 246 | 247 | return array( 248 | 'products' => $products_for_template, 249 | 'allProductsLink' => Context::getContext()->link->getCategoryLink($this->getConfigFieldsValues()['HOME_FEATURED_CAT']), 250 | ); 251 | } 252 | 253 | public function getConfigFieldsValues() 254 | { 255 | return array( 256 | 'HOME_FEATURED_NBR' => Tools::getValue('HOME_FEATURED_NBR', (int) Configuration::get('HOME_FEATURED_NBR')), 257 | 'HOME_FEATURED_CAT' => Tools::getValue('HOME_FEATURED_CAT', (int) Configuration::get('HOME_FEATURED_CAT')), 258 | 'HOME_FEATURED_RANDOMIZE' => Tools::getValue('HOME_FEATURED_RANDOMIZE', (bool) Configuration::get('HOME_FEATURED_RANDOMIZE')), 259 | ); 260 | } 261 | 262 | private function getFactory() 263 | { 264 | return new ProductPresenterFactory($this->context, new TaxConfiguration()); 265 | } 266 | 267 | protected function getProductPresentationSettings() 268 | { 269 | return $this->getFactory()->getPresentationSettings(); 270 | } 271 | 272 | public function getContactInfo(){ 273 | $address = $this->context->shop->getAddress(); 274 | 275 | $contact_infos = [ 276 | 'company' => Configuration::get('PS_SHOP_NAME'), 277 | 'address' => [ 278 | 'formatted' => AddressFormat::generateAddress($address, [], '
'), 279 | 'address1' => $address->address1, 280 | 'address2' => $address->address2, 281 | 'postcode' => $address->postcode, 282 | 'city' => $address->city, 283 | 'state' => (!empty($address->id_state) ? (new State($address->id_state))->name[$this->context->language->id] : null), 284 | 'country' => (new Country($address->id_country))->name[$this->context->language->id], 285 | ], 286 | 'phone' => Configuration::get('PS_SHOP_PHONE'), 287 | 'fax' => Configuration::get('PS_SHOP_FAX'), 288 | 'email' => Configuration::get('PS_SHOP_EMAIL'), 289 | 'details' => Configuration::get('PS_SHOP_DETAILS'), 290 | ]; 291 | 292 | return $contact_infos; 293 | } 294 | } 295 | -------------------------------------------------------------------------------- /controllers/front/carriers.php: -------------------------------------------------------------------------------- 1 | context, 22 | $this->getTranslator(), 23 | $this->objectPresenter, 24 | new PriceFormatter() 25 | ); 26 | $session = new CheckoutSession( 27 | $this->context, 28 | $deliveryOptionsFinder 29 | ); 30 | $carriers = $session->getDeliveryOptions(); 31 | 32 | foreach ($carriers as &$carrier) { 33 | unset($carrier['product_list']); 34 | unset($carrier['package_list']); 35 | } 36 | 37 | $this->ajaxRender(json_encode([ 38 | 'success' => true, 39 | 'code' => 200, 40 | 'psdata' => $carriers 41 | ])); 42 | die; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /controllers/front/cart.php: -------------------------------------------------------------------------------- 1 | updateCart(); 24 | 25 | if (Configuration::isCatalogMode() && Tools::getValue('action') === 'show') { 26 | $this->ajaxRender(json_encode([ 27 | 'code' => 200, 28 | 'success' => true, 29 | 'message' => $this->trans('Just show - catalog mode is enabled and the action is show', [], 'Modules.Binshopsrest.Cart'), 30 | ])); 31 | die; 32 | } 33 | 34 | if (!Tools::getValue('ajax')) { 35 | $this->checkCartProductsMinimalQuantities(); 36 | } 37 | $presenter = new CartPresenter(); 38 | $presented_cart = $presenter->present($this->context->cart, $shouldSeparateGifts = true); 39 | 40 | $products = $this->context->cart->getProducts(true); 41 | $link = Context::getContext()->link; 42 | 43 | foreach ($products as $key => $product) { 44 | $products[$key]['image_url'] = $link->getImageLink($product['link_rewrite'], $product['id_image'], Tools::getValue('image_size', ImageType::getFormattedName('small'))); 45 | 46 | $products[$key]['attributes_array'] = $presented_cart['products'][$key]['attributes']; 47 | 48 | $products[$key]['formatted_price'] = $presented_cart['products'][$key]['price']; 49 | $products[$key]['formatted_total'] = $presented_cart['products'][$key]['total']; 50 | $products[$key]['formatted_price_amount'] = $presented_cart['products'][$key]['price_amount']; 51 | $products[$key]['formatted_price_tax_exc'] = $presented_cart['products'][$key]['price_tax_exc']; 52 | $products[$key]['formatted_regular_price'] = $presented_cart['products'][$key]['regular_price']; 53 | $products[$key]['formatted_discount_to_display'] = $presented_cart['products'][$key]['discount_to_display']; 54 | $products[$key]['formatted_discount_amount_to_display'] = $presented_cart['products'][$key]['discount_amount_to_display']; 55 | $products[$key]['formatted_discount_type'] = $presented_cart['products'][$key]['discount_type']; 56 | $products[$key]['formatted_discount_percentage'] = $presented_cart['products'][$key]['discount_percentage']; 57 | } 58 | 59 | $presented_cart['products'] = $products; 60 | 61 | /* Check if the products in the cart are available */ 62 | $isAvailable = $this->areProductsAvailable(); 63 | if (true !== $isAvailable) { 64 | $this->errors[] = $isAvailable; 65 | } 66 | 67 | $presented_cart['errors'] = $this->errors; 68 | 69 | $this->ajaxRender(json_encode([ 70 | 'code' => 200, 71 | 'success' => true, 72 | 'message' => $this->trans('cart operation successfully done', [], 'Modules.Binshopsrest.Cart'), 73 | 'psdata' => $presented_cart 74 | ])); 75 | die; 76 | } 77 | 78 | protected function updateCart() 79 | { 80 | // Update the cart ONLY if $this->cookies are available, in order to avoid ghost carts created by bots 81 | if ($this->context->cookie->exists() 82 | && !$this->errors) 83 | { 84 | if (Tools::getIsset('add') || Tools::getIsset('update')) { 85 | $this->processChangeProductInCart(); 86 | } elseif (Tools::getIsset('delete')) { 87 | $this->processDeleteProductInCart(); 88 | } elseif (CartRule::isFeatureActive()) { 89 | if (Tools::getIsset('addDiscount')) { 90 | if (!($code = trim(Tools::getValue('discount_name')))) { 91 | $this->errors[] = $this->trans( 92 | 'You must enter a voucher code.', 93 | [], 94 | 'Shop.Notifications.Error' 95 | ); 96 | } elseif (!Validate::isCleanHtml($code)) { 97 | $this->errors[] = $this->trans( 98 | 'The voucher code is invalid.', 99 | [], 100 | 'Shop.Notifications.Error' 101 | ); 102 | } else { 103 | if (($cartRule = new CartRule(CartRule::getIdByCode($code))) 104 | && Validate::isLoadedObject($cartRule) 105 | ) { 106 | if ($error = $cartRule->checkValidity($this->context, false, true)) { 107 | $this->errors[] = $error; 108 | } else { 109 | $this->context->cart->addCartRule($cartRule->id); 110 | } 111 | } else { 112 | $this->errors[] = $this->trans( 113 | 'This voucher does not exist.', 114 | [], 115 | 'Shop.Notifications.Error' 116 | ); 117 | } 118 | } 119 | } elseif (($id_cart_rule = (int) Tools::getValue('deleteDiscount')) 120 | && Validate::isUnsignedId($id_cart_rule) 121 | ) { 122 | $this->context->cart->removeCartRule($id_cart_rule); 123 | CartRule::autoAddToCart($this->context); 124 | } 125 | } 126 | } elseif (!$this->isTokenValid() && Tools::getValue('action') !== 'show' && !Tools::getValue('ajax')) { 127 | $this->ajaxRender(json_encode([ 128 | 'code' => 301, 129 | 'success' => false, 130 | 'message' => $this->trans('Cookie is not set', [], 'Modules.Binshopsrest.Cart'), 131 | ])); 132 | die; 133 | } 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /controllers/front/categoryproducts.php: -------------------------------------------------------------------------------- 1 | executeS($sql); 35 | 36 | if (empty($result)){ 37 | $this->ajaxRender(json_encode([ 38 | 'code' => 302, 39 | 'success' => false, 40 | 'message' => $this->trans('There is not a category with this slug', [], 'Modules.Binshopsrest.Category') 41 | ])); 42 | die; 43 | }else{ 44 | $this->id_category = $result[0]['id_category']; 45 | $id_category = $result[0]['id_category']; 46 | $_POST['id_category'] = $id_category; 47 | } 48 | }else{ 49 | $this->ajaxRender(json_encode([ 50 | 'code' => 301, 51 | 'success' => false, 52 | 'message' => $this->trans('Id category or slug not specified', [], 'Modules.Binshopsrest.Category') 53 | ])); 54 | die; 55 | } 56 | 57 | $this->category = new Category( 58 | $id_category, 59 | $this->context->language->id 60 | ); 61 | 62 | $variables = $this->getProductSearchVariables(); 63 | $productList = $variables['products']; 64 | $retriever = new \PrestaShop\PrestaShop\Adapter\Image\ImageRetriever( 65 | $this->context->link 66 | ); 67 | 68 | $settings = $this->getProductPresentationSettings(); 69 | 70 | foreach ($productList as $key => $product) { 71 | $populated_product = (new ProductAssembler($this->context)) 72 | ->assembleProduct($product); 73 | 74 | $lazy_product = new RESTProductLazyArray( 75 | $settings, 76 | $populated_product, 77 | $this->context->language, 78 | new \PrestaShop\PrestaShop\Adapter\Product\PriceFormatter(), 79 | $retriever, 80 | $this->context->getTranslator() 81 | ); 82 | 83 | $productList[$key] = $lazy_product->getProduct(); 84 | } 85 | 86 | $facets = array(); 87 | if (array_key_exists('filters',$variables['facets'])){ 88 | foreach ($variables['facets']['filters']->getFacets() as $facet) { 89 | array_push($facets, $facet->toArray()); 90 | } 91 | } 92 | 93 | $psdata = [ 94 | 'name' => $this->category->name, 95 | 'description' => $this->category->description, 96 | 'meta_title' => $this->category->meta_title, 97 | 'meta_description' => $this->category->meta_description, 98 | 'meta_keywords' => $this->category->meta_keywords, 99 | 'active' => $this->category->active, 100 | 'images' => $this->getImage( 101 | $this->category, 102 | $this->category->id_image 103 | ), 104 | 'label' => $variables['label'], 105 | 'products' => $productList, 106 | 'sort_orders' => $variables['sort_orders'], 107 | 'sort_selected' => $variables['sort_selected'], 108 | 'pagination' => $variables['pagination'], 109 | 'facets' => $facets 110 | ]; 111 | 112 | if (Tools::getValue('with_category_tree')){ 113 | $this->context->cookie->last_visited_category = $id_category; 114 | $categoryTreeModule = Module::getInstanceByName('ps_categorytree'); 115 | $categoryTreeVariables = $categoryTreeModule->getWidgetVariables(); 116 | $psdata['categories'] = $categoryTreeVariables['categories']; 117 | } 118 | 119 | $this->ajaxRender(json_encode([ 120 | 'code' => 200, 121 | 'success' => true, 122 | 'psdata' => $psdata 123 | ])); 124 | die; 125 | } 126 | 127 | public function getListingLabel() 128 | { 129 | if (!Validate::isLoadedObject($this->category)) { 130 | $this->category = new Category( 131 | (int)Tools::getValue('id_category'), 132 | $this->context->language->id 133 | ); 134 | } 135 | 136 | return $this->trans( 137 | 'Category: %category_name%', 138 | array('%category_name%' => $this->category->name), 139 | 'Shop.Theme.Catalog' 140 | ); 141 | } 142 | 143 | /** 144 | * Gets the product search query for the controller. 145 | * That is, the minimum contract with which search modules 146 | * must comply. 147 | * 148 | * @return \PrestaShop\PrestaShop\Core\Product\Search\ProductSearchQuery 149 | */ 150 | protected function getProductSearchQuery() 151 | { 152 | $query = new ProductSearchQuery(); 153 | $query 154 | ->setIdCategory($this->category->id) 155 | ->setSortOrder(new SortOrder('product', Tools::getProductsOrder('by'), Tools::getProductsOrder('way'))); 156 | 157 | return $query; 158 | } 159 | 160 | /** 161 | * We cannot assume that modules will handle the query, 162 | * so we need a default implementation for the search provider. 163 | * 164 | * @return \PrestaShop\PrestaShop\Core\Product\Search\ProductSearchProviderInterface 165 | */ 166 | protected function getDefaultProductSearchProvider() 167 | { 168 | return new CategoryProductSearchProvider( 169 | $this->getTranslator(), 170 | $this->category 171 | ); 172 | } 173 | } 174 | -------------------------------------------------------------------------------- /controllers/front/emailsubscription.php: -------------------------------------------------------------------------------- 1 | context->language->id); 20 | 21 | $this->ajaxRender(json_encode([ 22 | 'success' => true, 23 | 'code' => 200, 24 | 'psdata' => $conditions, 25 | 'message' => $this->trans('Success', [], 'Modules.Binshopsrest.Subscription') 26 | ])); 27 | die; 28 | } 29 | 30 | protected function processPostRequest() 31 | { 32 | $ps_emailsubscription = Module::getInstanceByName('ps_emailsubscription'); 33 | $email = Tools::getValue('email', ''); 34 | 35 | if ($ps_emailsubscription->isNewsletterRegistered($email) === 1 || $ps_emailsubscription->isNewsletterRegistered($email) === 2){ 36 | $this->ajaxRender(json_encode([ 37 | 'success' => false, 38 | 'code' => 301, 39 | 'message' => $this->trans('This email is already registered', [], 'Modules.Binshopsrest.Subscription') 40 | ])); 41 | die; 42 | } 43 | 44 | if ($this->registerGuest($email)) { 45 | $this->ajaxRender(json_encode([ 46 | 'success' => true, 47 | 'code' => 200, 48 | 'message' => $this->trans('Success', [], 'Modules.Binshopsrest.Subscription') 49 | ])); 50 | die; 51 | 52 | } elseif ($ps_emailsubscription->valid) { 53 | $this->ajaxRender(json_encode([ 54 | 'success' => false, 55 | 'code' => 300, 56 | 'message' => $this->trans('Failure', [], 'Modules.Binshopsrest.Subscription') 57 | ])); 58 | die; 59 | } 60 | } 61 | 62 | protected function registerGuest($email, $active = true) 63 | { 64 | $sql = 'INSERT INTO ' . _DB_PREFIX_ . 'emailsubscription (id_shop, id_shop_group, email, newsletter_date_add, ip_registration_newsletter, http_referer, active, id_lang) 65 | VALUES 66 | (' . $this->context->shop->id . ', 67 | ' . $this->context->shop->id_shop_group . ', 68 | \'' . pSQL($email) . '\', 69 | NOW(), 70 | \'' . pSQL(Tools::getRemoteAddr()) . '\', 71 | ( 72 | SELECT c.http_referer 73 | FROM ' . _DB_PREFIX_ . 'connections c 74 | WHERE c.id_guest = ' . (int) $this->context->customer->id . ' 75 | ORDER BY c.date_add DESC LIMIT 1 76 | ), 77 | ' . (int) $active . ', 78 | ' . $this->context->language->id . ' 79 | )'; 80 | 81 | return Db::getInstance()->execute($sql); 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /controllers/front/featuredproducts.php: -------------------------------------------------------------------------------- 1 | getFeaturedProducts(); 29 | 30 | $this->ajaxRender(json_encode([ 31 | 'code' => 200, 32 | 'success' => true, 33 | 'psdata' => $featuredProductsList['products'] 34 | ])); 35 | die; 36 | } 37 | 38 | public function getFeaturedProducts(){ 39 | $category = new Category((int) Configuration::get('HOME_FEATURED_CAT')); 40 | 41 | $searchProvider = new CategoryProductSearchProvider( 42 | $this->context->getTranslator(), 43 | $category 44 | ); 45 | 46 | $context = new ProductSearchContext($this->context); 47 | 48 | $query = new ProductSearchQuery(); 49 | $nProducts = Configuration::get('HOME_FEATURED_NBR'); 50 | if ($nProducts < 0) { 51 | $nProducts = 12; 52 | } 53 | 54 | $query 55 | ->setResultsPerPage($nProducts) 56 | ->setPage(1) 57 | ; 58 | 59 | if (Configuration::get('HOME_FEATURED_RANDOMIZE')) { 60 | $query->setSortOrder(SortOrder::random()); 61 | } else { 62 | $query->setSortOrder(new SortOrder('product', 'position', 'asc')); 63 | } 64 | 65 | $result = $searchProvider->runQuery( 66 | $context, 67 | $query 68 | ); 69 | 70 | $products_for_template = []; 71 | $settings = $this->getProductPresentationSettings(); 72 | $retriever = new \PrestaShop\PrestaShop\Adapter\Image\ImageRetriever( 73 | $this->context->link 74 | ); 75 | 76 | foreach ($result->getProducts() as $rawProduct) { 77 | $populated_product = (new ProductAssembler($this->context)) 78 | ->assembleProduct($rawProduct); 79 | $lazy_product = new RESTProductLazyArray( 80 | $settings, 81 | $populated_product, 82 | $this->context->language, 83 | new \PrestaShop\PrestaShop\Adapter\Product\PriceFormatter(), 84 | $retriever, 85 | $this->context->getTranslator() 86 | ); 87 | 88 | $products_for_template[] = $lazy_product->getProduct(); 89 | } 90 | 91 | return array( 92 | 'products' => $products_for_template, 93 | 'allProductsLink' => Context::getContext()->link->getCategoryLink($this->getConfigFieldsValues()['HOME_FEATURED_CAT']), 94 | ); 95 | } 96 | 97 | public function getConfigFieldsValues() 98 | { 99 | return array( 100 | 'HOME_FEATURED_NBR' => Tools::getValue('HOME_FEATURED_NBR', (int) Configuration::get('HOME_FEATURED_NBR')), 101 | 'HOME_FEATURED_CAT' => Tools::getValue('HOME_FEATURED_CAT', (int) Configuration::get('HOME_FEATURED_CAT')), 102 | 'HOME_FEATURED_RANDOMIZE' => Tools::getValue('HOME_FEATURED_RANDOMIZE', (bool) Configuration::get('HOME_FEATURED_RANDOMIZE')), 103 | ); 104 | } 105 | 106 | private function getFactory() 107 | { 108 | return new ProductPresenterFactory($this->context, new TaxConfiguration()); 109 | } 110 | 111 | protected function getProductPresentationSettings() 112 | { 113 | return $this->getFactory()->getPresentationSettings(); 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /controllers/front/hello.php: -------------------------------------------------------------------------------- 1 | ajaxRender(json_encode([ 28 | 'code' => 200, 29 | 'success' => true, 30 | 'message' => 'PrestaShop REST API', 31 | 'psdata' => [ 32 | 'postman_link' => 'https://documenter.getpostman.com/view/1491681/TzkyP1UC', 33 | 'endpoints' => $endpoints 34 | ] 35 | ])); 36 | die; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /controllers/front/index.php: -------------------------------------------------------------------------------- 1 | renderMenu($this->context, $mainMenu); 34 | 35 | if (Tools::getValue('menu_with_images', false)){ 36 | foreach ($menuItems as $key => $item) { 37 | $retriever = new \PrestaShop\PrestaShop\Adapter\Image\ImageRetriever( 38 | $this->context->link 39 | ); 40 | $category = new Category( 41 | Tools::substr($item['page_identifier'], -1), 42 | $this->context->language->id 43 | ); 44 | if (Tools::getValue('menu_with_images', 'all') === "single"){ 45 | $menuItems[$key]['image']['src'] =$this->context->link->getImageLink( 46 | urlencode($item['slug']), 47 | ($category->id . '-' . $category->id_image), 48 | $this->getImageType('large') 49 | ); 50 | }else{ 51 | $menuItems[$key]['images'] = $retriever->getImage( 52 | $category, 53 | $category->id_image 54 | ); 55 | } 56 | } 57 | } 58 | 59 | $id_shop = (int) $this->context->shop->id; 60 | 61 | $psdata = array(); 62 | $psdata['menuItems'] = $menuItems; 63 | $psdata['currencies'] = $this->getCurrencies(); 64 | $psdata['languages'] = $this->getLanguages(); 65 | $psdata['logo_url'] = Tools::getHttpHost(true) . _PS_IMG_ .Configuration::get('PS_LOGO', null, null, $id_shop); 66 | 67 | $this->ajaxRender(json_encode([ 68 | 'success' => true, 69 | 'code' => $messageCode, 70 | 'psdata' => $psdata 71 | ])); 72 | die; 73 | } 74 | 75 | protected function getCurrencies(){ 76 | $current_currency = null; 77 | $serializer = new ObjectPresenter(); 78 | $currencies = array_map( 79 | function ($currency) use ($serializer, &$current_currency) { 80 | $currencyArray = $serializer->present($currency); 81 | 82 | // serializer doesn't see 'sign' because it is not a regular 83 | // ObjectModel field. 84 | $currencyArray['sign'] = $currency->sign; 85 | 86 | $url = $this->context->link->getLanguageLink($this->context->language->id); 87 | 88 | $parsedUrl = parse_url($url); 89 | $urlParams = []; 90 | if (isset($parsedUrl['query'])) { 91 | parse_str($parsedUrl['query'], $urlParams); 92 | } 93 | $newParams = array_merge( 94 | $urlParams, 95 | [ 96 | 'SubmitCurrency' => 1, 97 | 'id_currency' => $currency->id, 98 | ] 99 | ); 100 | $newUrl = sprintf('%s://%s%s%s?%s', 101 | $parsedUrl['scheme'], 102 | $parsedUrl['host'], 103 | isset($parsedUrl['port']) ? ':' . $parsedUrl['port'] : '', 104 | $parsedUrl['path'], 105 | http_build_query($newParams) 106 | ); 107 | 108 | $currencyArray['url'] = $newUrl; 109 | 110 | if ($currency->id === $this->context->currency->id) { 111 | $currencyArray['current'] = true; 112 | $current_currency = $currencyArray; 113 | } else { 114 | $currencyArray['current'] = false; 115 | } 116 | 117 | return $currencyArray; 118 | }, 119 | Currency::getCurrencies(true, true) 120 | ); 121 | 122 | return [ 123 | 'currencies' => $currencies, 124 | 'current_currency' => $current_currency, 125 | ]; 126 | } 127 | 128 | protected function getLanguages(){ 129 | $languages = Language::getLanguages(true, $this->context->shop->id); 130 | 131 | foreach ($languages as &$lang) { 132 | $lang['name_simple'] = $this->getNameSimple($lang['name']); 133 | } 134 | 135 | return array( 136 | 'languages' => $languages, 137 | 'current_language' => array( 138 | 'id_lang' => $this->context->language->id, 139 | 'name' => $this->context->language->name, 140 | 'name_simple' => $this->getNameSimple($this->context->language->name), 141 | 'iso_code' => $this->context->language->iso_code 142 | ) 143 | ); 144 | } 145 | 146 | private function getNameSimple($name) 147 | { 148 | return preg_replace('/\s\(.*\)$/', '', $name); 149 | } 150 | } 151 | -------------------------------------------------------------------------------- /controllers/front/listcomments.php: -------------------------------------------------------------------------------- 1 | context->controller->getContainer()->get('product_comment_repository'); 21 | 22 | $productComments = $productCommentRepository->paginate( 23 | $idProduct, 24 | $page, 25 | (int) Configuration::get('PRODUCT_COMMENTS_COMMENTS_PER_PAGE'), 26 | (bool) Configuration::get('PRODUCT_COMMENTS_MODERATE') 27 | ); 28 | $productCommentsNb = $productCommentRepository->getCommentsNumber( 29 | $idProduct, 30 | (bool) Configuration::get('PRODUCT_COMMENTS_MODERATE') 31 | ); 32 | 33 | $responseArray = [ 34 | 'comments_nb' => $productCommentsNb, 35 | 'comments_per_page' => Configuration::get('PRODUCT_COMMENTS_COMMENTS_PER_PAGE'), 36 | 'comments' => [], 37 | ]; 38 | 39 | foreach ($productComments as $productComment) { 40 | $dateAdd = new \DateTime($productComment['date_add'], new \DateTimeZone('UTC')); 41 | $dateAdd->setTimezone(new \DateTimeZone(date_default_timezone_get())); 42 | $dateFormatter = new \IntlDateFormatter( 43 | $this->context->language->locale, 44 | \IntlDateFormatter::SHORT, 45 | \IntlDateFormatter::SHORT 46 | ); 47 | $productComment['customer_name'] = htmlentities($productComment['customer_name']); 48 | $productComment['title'] = htmlentities($productComment['title']); 49 | $productComment['content'] = htmlentities($productComment['content']); 50 | $productComment['date_add'] = $dateFormatter->format($dateAdd); 51 | 52 | if ($isLastNameAnynomus) { 53 | $productComment['lastname'] = substr($productComment['lastname'], 0, 1) . '.'; 54 | } 55 | 56 | $usefulness = $productCommentRepository->getProductCommentUsefulness($productComment['id_product_comment']); 57 | $productComment = array_merge($productComment, $usefulness); 58 | if (empty($productComment['customer_name']) && !isset($productComment['firstname']) && !isset($productComment['lastname'])) { 59 | $productComment['customer_name'] = $this->trans('Deleted account', [], 'Modules.Productcomments.Shop'); 60 | } 61 | 62 | $responseArray['comments'][] = $productComment; 63 | } 64 | 65 | $this->ajaxRender(json_encode([ 66 | 'success' => true, 67 | 'code' => 200, 68 | 'psdata' => $responseArray 69 | ])); 70 | die; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /controllers/front/login.php: -------------------------------------------------------------------------------- 1 | context->cart->id_currency = $this->context->currency->id; 27 | $this->context->cart = new Cart($cart_id); 28 | $this->context->cookie->id_cart = (int)$this->context->cart->id; 29 | $this->context->cookie->write(); 30 | } 31 | 32 | if (empty($email)) { 33 | $psdata = $this->trans("An email address required", [], 'Modules.Binshopsrest.Auth'); 34 | $messageCode = 301; 35 | } elseif (!Validate::isEmail($email)) { 36 | $psdata = $this->trans("Invalid email address", [], 'Modules.Binshopsrest.Auth'); 37 | $messageCode = 302; 38 | } elseif (empty($password)) { 39 | $psdata = $this->trans('Password is not provided', [], 'Modules.Binshopsrest.Auth'); 40 | $messageCode = 303; 41 | } elseif (!Validate::isPasswd($password)) { 42 | $psdata = $this->trans("Invalid Password", [], 'Modules.Binshopsrest.Auth'); 43 | $messageCode = 304; 44 | } else { 45 | Hook::exec('actionAuthenticationBefore'); 46 | $customer = new Customer(); 47 | $authentication = $customer->getByEmail( 48 | $email, 49 | $password 50 | ); 51 | 52 | if (isset($authentication->active) && !$authentication->active) { 53 | $psdata = $this->trans('Your account isn\'t available at this time.', [], 'Modules.Binshopsrest.Auth'); 54 | $messageCode = 305; 55 | } elseif (!$authentication || !$customer->id || $customer->is_guest) { 56 | $psdata = $this->trans("Authentication failed", [], 'Modules.Binshopsrest.Auth'); 57 | $messageCode = 306; 58 | } else { 59 | $this->context->updateCustomer($customer); 60 | 61 | Hook::exec('actionAuthentication', ['customer' => $this->context->customer]); 62 | 63 | $messageCode = 200; 64 | $user = $this->context->customer; 65 | unset($user->secure_key); 66 | unset($user->passwd); 67 | unset($user->last_passwd_gen); 68 | unset($user->reset_password_token); 69 | unset($user->reset_password_validity); 70 | 71 | $psdata = array( 72 | 'status' => 'success', 73 | 'message' => $this->trans('User login successfully', [], 'Modules.Binshopsrest.Auth'), 74 | 'customer_id' => $customer->id, 75 | 'session_data' => (int)$this->context->cart->id, 76 | 'cart_count' => Cart::getNbProducts($this->context->cookie->id_cart), 77 | 'user' => $user 78 | ); 79 | 80 | // Login information have changed, so we check if the cart rules still apply 81 | CartRule::autoRemoveFromCart($this->context); 82 | CartRule::autoAddToCart($this->context); 83 | } 84 | } 85 | 86 | $this->ajaxRender(json_encode([ 87 | 'success' => true, 88 | 'code' => $messageCode, 89 | 'psdata' => $psdata 90 | ])); 91 | die; 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /controllers/front/logout.php: -------------------------------------------------------------------------------- 1 | context->customer->mylogout(); 19 | 20 | $this->ajaxRender(json_encode([ 21 | 'code' => 200, 22 | 'success' => true, 23 | 'message' => $this->trans('Customer logged out successfully', [], 'Modules.Binshopsrest.Auth') 24 | ])); 25 | die; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /controllers/front/orderhistory.php: -------------------------------------------------------------------------------- 1 | ajaxRender(json_encode([ 27 | 'success' => false, 28 | 'code' => 404, 29 | 'message' => $this->trans('order not found', [], 'Modules.Binshopsrest.Order') 30 | ])); 31 | die; 32 | } 33 | 34 | //there is a duplication of code but a prevention of new object creation too 35 | $order = new Order($id_order, $this->context->language->id); 36 | if (Validate::isLoadedObject($order) && $order->id_customer == $this->context->customer->id){ 37 | $order_to_display = (new OrderPresenter())->present($order); 38 | 39 | if (Tools::isEmpty($id_order) or !Validate::isLoadedObject($order)) { 40 | 41 | $this->ajaxRender(json_encode([ 42 | 'success' => true, 43 | 'code' => 404, 44 | 'message' => $this->trans('order not found', [], 'Modules.Binshopsrest.Order') 45 | ])); 46 | die; 47 | } else { 48 | 49 | $this->ajaxRender(json_encode([ 50 | 'success' => true, 51 | 'code' => 200, 52 | 'psdata' => $order_to_display 53 | ])); 54 | die; 55 | } 56 | }else{ 57 | $this->ajaxRender(json_encode([ 58 | 'success' => false, 59 | 'code' => 404, 60 | 'message' => $this->trans('order not found', [], 'Modules.Binshopsrest.Order') 61 | ])); 62 | die; 63 | } 64 | } 65 | 66 | //process all orders 67 | $customer_orders = Order::getCustomerOrders($this->context->customer->id); 68 | 69 | $this->ajaxRender(json_encode([ 70 | 'success' => true, 71 | 'code' => 200, 72 | 'psdata' => $customer_orders 73 | ])); 74 | die; 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /controllers/front/paymentoptions.php: -------------------------------------------------------------------------------- 1 | context, 22 | $this->getTranslator(), 23 | $this->objectPresenter, 24 | new PriceFormatter() 25 | ); 26 | 27 | $session = new CheckoutSession( 28 | $this->context, 29 | $deliveryOptionsFinder 30 | ); 31 | 32 | $paymentOptionsFinder = new PaymentOptionsFinder(); 33 | $isFree = 0 == (float)$session->getCart()->getOrderTotal(true, Cart::BOTH); 34 | $paymentOptions = $paymentOptionsFinder->present($isFree); 35 | 36 | $this->ajaxRender(json_encode([ 37 | 'success' => true, 38 | 'code' => 200, 39 | 'psdata' => $paymentOptions 40 | ])); 41 | die; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /controllers/front/postcomment.php: -------------------------------------------------------------------------------- 1 | context->cookie->id_customer && !Configuration::get('PRODUCT_COMMENTS_ALLOW_GUESTS')) { 25 | 26 | $this->ajaxRender(json_encode([ 27 | 'success' => false, 28 | 'code' => 205, 29 | 'psdata' => 'user should login to leave a comment' 30 | ])); 31 | die; 32 | } 33 | 34 | $id_product = (int) Tools::getValue('id_product'); 35 | $comment_title = Tools::getValue('comment_title'); 36 | $comment_content = Tools::getValue('comment_content'); 37 | $customer_name = Tools::getValue('customer_name'); 38 | $criterions = Tools::getValue('criterion'); 39 | 40 | /** @var ProductCommentRepository $productCommentRepository */ 41 | $productCommentRepository = $this->context->controller->getContainer()->get('product_comment_repository'); 42 | $isPostAllowed = $productCommentRepository->isPostAllowed( 43 | $id_product, 44 | (int) $this->context->cookie->id_customer, 45 | (int) $this->context->cookie->id_guest 46 | ); 47 | if (!$isPostAllowed) { 48 | $this->ajaxRender( 49 | json_encode( 50 | [ 51 | 'success' => false, 52 | 'error' => $this->trans('You are not allowed to post a review at the moment, please try again later.', [], 'Modules.Productcomments.Shop'), 53 | ] 54 | ) 55 | ); 56 | 57 | return false; 58 | } 59 | 60 | /** @var EntityManagerInterface $entityManager */ 61 | $entityManager = $this->container->get('doctrine.orm.entity_manager'); 62 | 63 | //Create product comment 64 | $productComment = new ProductComment(); 65 | $productComment 66 | ->setProductId($id_product) 67 | ->setTitle($comment_title) 68 | ->setContent($comment_content) 69 | ->setCustomerName($customer_name) 70 | ->setCustomerId($this->context->cookie->id_customer) 71 | ->setGuestId($this->context->cookie->id_guest) 72 | ->setDateAdd(new \DateTime('now', new \DateTimeZone('UTC'))) 73 | ; 74 | $entityManager->persist($productComment); 75 | $this->addCommentGrades($productComment, $criterions); 76 | 77 | //Validate comment 78 | $errors = $this->validateComment($productComment); 79 | if (!empty($errors)) { 80 | $this->ajaxRender( 81 | json_encode( 82 | [ 83 | 'success' => false, 84 | 'errors' => $errors, 85 | ] 86 | ) 87 | ); 88 | 89 | return false; 90 | } 91 | 92 | $entityManager->flush(); 93 | 94 | $this->ajaxRender(json_encode([ 95 | 'success' => true, 96 | 'code' => 200, 97 | 'psdata' => $productComment->toArray() 98 | ])); 99 | die; 100 | } 101 | 102 | /** 103 | * @param ProductComment $productComment 104 | * @param array $criterions 105 | * 106 | * @throws Exception 107 | */ 108 | private function addCommentGrades(ProductComment $productComment, array $criterions) 109 | { 110 | /** @var EntityManagerInterface $entityManager */ 111 | $entityManager = $this->container->get('doctrine.orm.entity_manager'); 112 | $criterionRepository = $entityManager->getRepository(ProductCommentCriterion::class); 113 | $averageGrade = 0; 114 | 115 | foreach ($criterions as $criterionId => $grade) { 116 | $criterion = $criterionRepository->findOneBy(['id' => $criterionId]); 117 | $criterionGrade = new ProductCommentGrade( 118 | $productComment, 119 | $criterion, 120 | $grade 121 | ); 122 | 123 | $entityManager->persist($criterionGrade); 124 | $averageGrade += $grade; 125 | } 126 | 127 | $averageGrade /= count($criterions); 128 | $productComment->setGrade($averageGrade); 129 | } 130 | 131 | /** 132 | * Manual validation for now, this would be nice to use Symfony validator with the annotation 133 | * 134 | * @param ProductComment $productComment 135 | * 136 | * @return array 137 | */ 138 | private function validateComment(ProductComment $productComment) 139 | { 140 | $errors = []; 141 | if (empty($productComment->getTitle())) { 142 | $errors[] = $this->trans('Title cannot be empty', [], 'Modules.Productcomments.Shop'); 143 | } elseif (strlen($productComment->getTitle()) > ProductComment::TITLE_MAX_LENGTH) { 144 | $errors[] = $this->trans('Title cannot be more than %s characters', [ProductComment::TITLE_MAX_LENGTH], 'Modules.Productcomments.Shop'); 145 | } 146 | 147 | if (!$productComment->getCustomerId()) { 148 | if (empty($productComment->getCustomerName())) { 149 | $errors[] = $this->trans('Customer name cannot be empty', [], 'Modules.Productcomments.Shop'); 150 | } elseif (strlen($productComment->getCustomerName()) > ProductComment::CUSTOMER_NAME_MAX_LENGTH) { 151 | $errors[] = $this->trans('Customer name cannot be more than %s characters', [ProductComment::CUSTOMER_NAME_MAX_LENGTH], 'Modules.Productcomments.Shop'); 152 | } 153 | } 154 | 155 | return $errors; 156 | } 157 | } 158 | -------------------------------------------------------------------------------- /controllers/front/productsearch.php: -------------------------------------------------------------------------------- 1 | search_string = Tools::getValue('s'); 33 | if (!$this->search_string && !Tools::getValue('q')) { 34 | $this->ajaxRender(json_encode([ 35 | 'code' => 301, 36 | 'success' => false, 37 | 'message' => $this->trans('query string is not specified', [], 'Modules.Binshopsrest.Search') 38 | ])); 39 | die; 40 | } 41 | 42 | $this->search_tag = Tools::getValue('tag'); 43 | 44 | $variables = $this->getProductSearchVariables(); 45 | $productList = $variables['products']; 46 | $retriever = new \PrestaShop\PrestaShop\Adapter\Image\ImageRetriever( 47 | $this->context->link 48 | ); 49 | 50 | $settings = $this->getProductPresentationSettings(); 51 | 52 | foreach ($productList as $key => $product) { 53 | $populated_product = (new ProductAssembler($this->context)) 54 | ->assembleProduct($product); 55 | 56 | $lazy_product = new RESTProductLazyArray( 57 | $settings, 58 | $populated_product, 59 | $this->context->language, 60 | new \PrestaShop\PrestaShop\Adapter\Product\PriceFormatter(), 61 | $retriever, 62 | $this->context->getTranslator() 63 | ); 64 | 65 | $productList[$key] = $lazy_product->getProduct(); 66 | } 67 | 68 | $facets = array(); 69 | if ($variables['facets']) { 70 | foreach ($variables['facets']['filters']->getFacets() as $facet) { 71 | array_push($facets, $facet->toArray()); 72 | } 73 | } 74 | 75 | $psdata = [ 76 | 'label' => $variables['label'], 77 | 'products' => $productList, 78 | 'sort_orders' => $variables['sort_orders'], 79 | 'sort_selected' => $variables['sort_selected'], 80 | 'pagination' => $variables['pagination'], 81 | 'facets' => $facets, 82 | 'active_filter' => isset($variables['facets']['activeFilters'])?$variables['facets']['activeFilters']:[] 83 | ]; 84 | 85 | $this->ajaxRender(json_encode([ 86 | 'code' => 200, 87 | 'success' => true, 88 | 'psdata' => $psdata 89 | ])); 90 | die; 91 | } 92 | 93 | public function getListingLabel() 94 | { 95 | return $this->getTranslator()->trans('Search results', array(), 'Shop.Theme.Catalog'); 96 | } 97 | 98 | /** 99 | * Gets the product search query for the controller. 100 | * That is, the minimum contract with which search modules 101 | * must comply. 102 | * 103 | * @return \PrestaShop\PrestaShop\Core\Product\Search\ProductSearchQuery 104 | */ 105 | protected function getProductSearchQuery() 106 | { 107 | $query = new ProductSearchQuery(); 108 | $query 109 | ->setSortOrder(new SortOrder('product', 'position', 'desc')) 110 | ->setSearchString($this->search_string) 111 | ->setSearchTag($this->search_tag); 112 | 113 | return $query; 114 | } 115 | 116 | /** 117 | * We cannot assume that modules will handle the query, 118 | * so we need a default implementation for the search provider. 119 | * 120 | * @return \PrestaShop\PrestaShop\Core\Product\Search\ProductSearchProviderInterface 121 | */ 122 | protected function getDefaultProductSearchProvider() 123 | { 124 | return new SearchProductSearchProvider( 125 | $this->getTranslator() 126 | ); 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /controllers/front/ps_cashondelivery.php: -------------------------------------------------------------------------------- 1 | context->cart; 17 | 18 | // Check that this payment option is still available in case the customer changed his address just before the end of the checkout process 19 | $authorized = false; 20 | foreach (Module::getPaymentModules() as $module) { 21 | if ($module['name'] == 'ps_cashondelivery') { 22 | $authorized = true; 23 | break; 24 | } 25 | } 26 | 27 | if (!$authorized) { 28 | $this->ajaxRender(json_encode([ 29 | 'success' => false, 30 | 'code' => 302, 31 | 'message' => $this->trans('This payment method is not available', [], 'Modules.Binshopsrest.Payment') 32 | ])); 33 | die; 34 | } 35 | 36 | $customer = new Customer($cart->id_customer); 37 | 38 | if (!Validate::isLoadedObject($customer)) { 39 | $this->ajaxRender(json_encode([ 40 | 'success' => false, 41 | 'code' => 301, 42 | 'message' => $this->trans('payment processing failed', [], 'Modules.Binshopsrest.Payment') 43 | ])); 44 | die; 45 | } 46 | 47 | $currency = $this->context->currency; 48 | $total = (float) $cart->getOrderTotal(true, Cart::BOTH); 49 | 50 | $mailVars = [ 51 | '{check_name}' => Configuration::get('CHEQUE_NAME'), 52 | '{check_address}' => Configuration::get('CHEQUE_ADDRESS'), 53 | '{check_address_html}' => str_replace("\n", '
', Configuration::get('CHEQUE_ADDRESS')), ]; 54 | 55 | $ps_cashondelivery = Module::getInstanceByName('ps_cashondelivery'); 56 | 57 | $ps_cashondelivery->validateOrder( 58 | (int) $cart->id, 59 | (int) Configuration::getGlobalValue(Ps_Cashondelivery::CONFIG_OS_CASH_ON_DELIVERY), 60 | $total, 61 | $ps_cashondelivery->displayName, 62 | null, 63 | $mailVars, 64 | (int) $currency->id, 65 | false, 66 | $customer->secure_key 67 | ); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /controllers/front/ps_checkpayment.php: -------------------------------------------------------------------------------- 1 | context->cart; 17 | 18 | // Check that this payment option is still available in case the customer changed his address just before the end of the checkout process 19 | $authorized = false; 20 | foreach (Module::getPaymentModules() as $module) { 21 | if ($module['name'] == 'ps_checkpayment') { 22 | $authorized = true; 23 | break; 24 | } 25 | } 26 | 27 | if (!$authorized) { 28 | $this->ajaxRender(json_encode([ 29 | 'success' => false, 30 | 'code' => 302, 31 | 'message' => $this->trans('This payment method is not available', [], 'Modules.Binshopsrest.Payment') 32 | ])); 33 | die; 34 | } 35 | 36 | $customer = new Customer($cart->id_customer); 37 | 38 | if (!Validate::isLoadedObject($customer)) { 39 | $this->ajaxRender(json_encode([ 40 | 'success' => false, 41 | 'code' => 301, 42 | 'message' => $this->trans('payment processing failed', [], 'Modules.Binshopsrest.Payment') 43 | ])); 44 | die; 45 | } 46 | 47 | $currency = $this->context->currency; 48 | $total = (float) $cart->getOrderTotal(true, Cart::BOTH); 49 | 50 | $mailVars = [ 51 | '{check_name}' => Configuration::get('CHEQUE_NAME'), 52 | '{check_address}' => Configuration::get('CHEQUE_ADDRESS'), 53 | '{check_address_html}' => str_replace("\n", '
', Configuration::get('CHEQUE_ADDRESS')), ]; 54 | 55 | $ps_checkpayment = Module::getInstanceByName('ps_checkpayment'); 56 | 57 | $ps_checkpayment->validateOrder( 58 | (int) $cart->id, 59 | (int) Configuration::get('PS_OS_CHEQUE'), 60 | $total, 61 | $ps_checkpayment->displayName, 62 | null, 63 | $mailVars, 64 | (int) $currency->id, 65 | false, 66 | $customer->secure_key 67 | ); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /controllers/front/ps_wirepayment.php: -------------------------------------------------------------------------------- 1 | context->cart; 16 | 17 | // Check that this payment option is still available in case the customer changed his address just before the end of the checkout process 18 | $authorized = false; 19 | foreach (Module::getPaymentModules() as $module) 20 | if ($module['name'] == 'ps_wirepayment') 21 | { 22 | $authorized = true; 23 | break; 24 | } 25 | if (!$authorized){ 26 | $this->ajaxRender(json_encode([ 27 | 'success' => false, 28 | 'code' => 303, 29 | 'message' => $this->trans('This payment method is not available.', [], 'Modules.Binshopsrest.Payment') 30 | ])); 31 | die; 32 | } 33 | 34 | $customer = new Customer($cart->id_customer); 35 | if (!Validate::isLoadedObject($customer)){ 36 | $this->ajaxRender(json_encode([ 37 | 'success' => false, 38 | 'code' => 301, 39 | 'message' => $this->trans('payment processing failed', [], 'Modules.Binshopsrest.Payment') 40 | ])); 41 | die; 42 | } 43 | 44 | $currency = $this->context->currency; 45 | $total = (float)$cart->getOrderTotal(true, Cart::BOTH); 46 | $mailVars = array( 47 | '{bankwire_owner}' => Configuration::get('BANK_WIRE_OWNER'), 48 | '{bankwire_details}' => nl2br(Configuration::get('BANK_WIRE_DETAILS')), 49 | '{bankwire_address}' => nl2br(Configuration::get('BANK_WIRE_ADDRESS')) 50 | ); 51 | 52 | $ps_wirepayment = Module::getInstanceByName('ps_wirepayment'); 53 | 54 | $ps_wirepayment->validateOrder($cart->id, Configuration::get('PS_OS_BANKWIRE'), $total, $this->module->displayName, NULL, $mailVars, (int)$currency->id, false, $customer->secure_key); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /controllers/front/register.php: -------------------------------------------------------------------------------- 1 | trans("An email address required", [], 'Modules.Binshopsrest.Auth'); 30 | $messageCode = 301; 31 | } elseif (!Validate::isEmail($email)) { 32 | $psdata = $this->trans("Invalid email address", [], 'Modules.Binshopsrest.Auth'); 33 | $messageCode = 302; 34 | } elseif (!empty($password) && !Validate::isPasswd($password)) { 35 | $psdata = $this->trans("Invalid Password", [], 'Modules.Binshopsrest.Auth'); 36 | $messageCode = 304; 37 | } elseif (empty($firstName)) { 38 | $psdata = $this->trans("First name required", [], 'Modules.Binshopsrest.Auth'); 39 | $messageCode = 305; 40 | } elseif (empty($lastName)) { 41 | $psdata = $this->trans("Last name required", [], 'Modules.Binshopsrest.Auth'); 42 | $messageCode = 306; 43 | } elseif (Customer::customerExists($email, false, true)) { 44 | $psdata = $this->trans("User already exists - checked by email", [], 'Modules.Binshopsrest.Auth'); 45 | $messageCode = 308; 46 | } else { 47 | $guestAllowedCheckout = Configuration::get('PS_GUEST_CHECKOUT_ENABLED'); 48 | $cp = new CustomerPersister( 49 | $this->context, 50 | $this->get('hashing'), 51 | $this->getTranslator(), 52 | $guestAllowedCheckout 53 | ); 54 | try { 55 | $customer = new Customer(); 56 | $customer->firstname = $firstName; 57 | $customer->lastname = $lastName; 58 | $customer->email = $email; 59 | $customer->id_gender = $gender; 60 | $customer->id_shop = (int)$this->context->shop->id; 61 | $customer->newsletter = $newsletter; 62 | 63 | $status = $cp->save($customer, $password); 64 | 65 | $messageCode = 200; 66 | $psdata = array( 67 | 'registered' => $status, 68 | 'message' => $this->trans('User registered successfully', [], 'Modules.Binshopsrest.Auth'), 69 | 'customer_id' => $customer->id, 70 | 'session_data' => (int)$this->context->cart->id 71 | ); 72 | } catch (Exception $exception) { 73 | $messageCode = 300; 74 | $psdata = $exception->getMessage(); 75 | $success = false; 76 | } 77 | } 78 | 79 | $this->ajaxRender(json_encode([ 80 | 'success' => $success, 81 | 'code' => $messageCode, 82 | 'psdata' => $psdata 83 | ])); 84 | die; 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /controllers/front/resetpasswordbyemail.php: -------------------------------------------------------------------------------- 1 | psdata = $this->trans("pass reset mail successfully sent", [], 'Modules.Binshopsrest.Auth'); 22 | 23 | $this->sendRenewPasswordLink(); 24 | 25 | $this->ajaxRender(json_encode([ 26 | 'success' => false, 27 | 'code' => 200, 28 | 'psdata' => $this->psdata 29 | ])); 30 | die; 31 | } 32 | 33 | protected function sendRenewPasswordLink() 34 | { 35 | if (!($email = (trim(Tools::getValue('email')))) || !Validate::isEmail($email)) { 36 | $this->psdata = $this->trans('Invalid email address.', [], 'Shop.Notifications.Error'); 37 | } else { 38 | $customer = new Customer(); 39 | $customer->getByEmail($email); 40 | if (null === $customer->email) { 41 | $customer->email = Tools::getValue('email'); 42 | } 43 | 44 | if (!Validate::isLoadedObject($customer)) { 45 | } elseif (!$customer->active) { 46 | $this->psdata = $this->trans('You cannot regenerate the password for this account.', [], 'Shop.Notifications.Error'); 47 | } elseif ((strtotime($customer->last_passwd_gen . '+' . ($minTime = (int)Configuration::get('PS_PASSWD_TIME_FRONT')) . ' minutes') - time()) > 0) { 48 | $this->psdata = $this->trans('You can regenerate your password only every %d minute(s)', [(int)$minTime], 'Shop.Notifications.Error'); 49 | } else { 50 | if (!$customer->hasRecentResetPasswordToken()) { 51 | $customer->stampResetPasswordToken(); 52 | $customer->update(); 53 | } 54 | 55 | $mailParams = [ 56 | '{email}' => $customer->email, 57 | '{lastname}' => $customer->lastname, 58 | '{firstname}' => $customer->firstname, 59 | '{url}' => $this->context->link->getPageLink('password', true, null, 'token=' . $customer->secure_key . '&id_customer=' . (int)$customer->id . '&reset_token=' . $customer->reset_password_token), 60 | ]; 61 | 62 | if (Mail::Send( 63 | $this->context->language->id, 64 | 'password_query', 65 | $this->trans( 66 | 'Password query confirmation', 67 | [], 68 | 'Emails.Subject' 69 | ), 70 | $mailParams, 71 | $customer->email, 72 | $customer->firstname . ' ' . $customer->lastname 73 | ) 74 | ) { 75 | } else { 76 | $this->psdata = $this->trans('An error occurred while sending the email.', [], 'Shop.Notifications.Error'); 77 | } 78 | } 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /controllers/front/resetpasswordcheck.php: -------------------------------------------------------------------------------- 1 | errors[] = $this->trans('Invalid email address.', [], 'Shop.Notifications.Error'); 22 | } else { 23 | $customer = new Customer(); 24 | $customer->getByEmail($email); 25 | } 26 | 27 | $sql = 'SELECT * FROM `' . _DB_PREFIX_ . 'binshopsrest_reset_pass_tokens` 28 | WHERE id_customer =' . $customer->id; 29 | $result = Db::getInstance()->executeS($sql); 30 | 31 | if (empty($result)) { 32 | $this->ajaxRender(json_encode([ 33 | 'success' => true, 34 | 'code' => 200, 35 | 'psdata' => $this->trans("this state is not expected", [], 'Modules.Binshopsrest.Auth') 36 | ])); 37 | die; 38 | } elseif (strtotime(end($result)['reset_password_validity']) < time()) { 39 | $this->ajaxRender(json_encode([ 40 | 'success' => true, 41 | 'code' => 200, 42 | 'psdata' => $this->trans("expired", [], 'Modules.Binshopsrest.Auth') 43 | ])); 44 | die; 45 | } 46 | 47 | $theCode = end($result)['reset_password_token']; 48 | 49 | if (Tools::getValue('pass-code') === $theCode) { 50 | $this->ajaxRender(json_encode([ 51 | 'success' => true, 52 | 'code' => 200, 53 | 'psdata' => $this->trans("success", [], 'Modules.Binshopsrest.Auth') 54 | ])); 55 | die; 56 | } else { 57 | $this->ajaxRender(json_encode([ 58 | 'success' => false, 59 | 'code' => 301, 60 | 'psdata' => $this->trans("code not matched", [], 'Modules.Binshopsrest.Auth') 61 | ])); 62 | die; 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /controllers/front/resetpasswordemail.php: -------------------------------------------------------------------------------- 1 | sendRenewPasswordLink(); 21 | 22 | $this->ajaxRender(json_encode([ 23 | 'success' => $this->trans("Successfully send rest-code", [], 'Modules.Binshopsrest.Auth'), 24 | 'code' => 200 25 | ])); 26 | die; 27 | } 28 | 29 | protected function sendRenewPasswordLink() 30 | { 31 | if (!($email = Tools::getValue('email')) || !Validate::isEmail($email)) { 32 | $this->errors[] = $this->trans('Invalid email address.', [], 'Shop.Notifications.Error'); 33 | } else { 34 | $customer = new Customer(); 35 | $customer->getByEmail($email); 36 | if (null === $customer->email) { 37 | $customer->email = Tools::getValue('email'); 38 | } 39 | 40 | if (!Validate::isLoadedObject($customer)) { 41 | $this->success[] = $this->trans( 42 | 'If this email address has been registered in our shop, you will receive a link to reset your password at %email%.', 43 | ['%email%' => $customer->email], 44 | 'Shop.Notifications.Success' 45 | ); 46 | $this->setTemplate('customer/password-infos'); 47 | } elseif (!$customer->active) { 48 | $this->errors[] = $this->trans('You cannot regenerate the password for this account.', [], 'Shop.Notifications.Error'); 49 | } elseif ((strtotime($customer->last_passwd_gen . '+' . ($minTime = (int)Configuration::get('PS_PASSWD_TIME_FRONT')) . ' minutes') - time()) > 0) { 50 | $this->errors[] = $this->trans('You can regenerate your password only every %d minute(s)', [(int)$minTime], 'Shop.Notifications.Error'); 51 | } else { 52 | $gen_code = $this->hasRecentResetPasswordToken($customer); 53 | if (empty($gen_code)) { 54 | $gen_code = $this->stampResetPasswordToken($customer); 55 | } 56 | 57 | $mailParams = [ 58 | '{email}' => $customer->email, 59 | '{lastname}' => $customer->lastname, 60 | '{firstname}' => $customer->firstname, 61 | '{gen_code}' => $gen_code, 62 | ]; 63 | 64 | if (Mail::Send( 65 | $this->context->language->id, 66 | 'password_query_mobile', 67 | $this->trans( 68 | 'Password query confirmation', 69 | [], 70 | 'Emails.Subject' 71 | ), 72 | $mailParams, 73 | $customer->email, 74 | $customer->firstname . ' ' . $customer->lastname 75 | ) 76 | ) { 77 | $this->success[] = $this->trans('If this email address has been registered in our shop, you will receive a link to reset your password at %email%.', ['%email%' => $customer->email], 'Shop.Notifications.Success'); 78 | $this->setTemplate('customer/password-infos'); 79 | } else { 80 | $this->errors[] = $this->trans('An error occurred while sending the email.', [], 'Shop.Notifications.Error'); 81 | } 82 | } 83 | } 84 | } 85 | 86 | public function stampResetPasswordToken($customer) 87 | { 88 | $digits = 5; 89 | $rand = rand(pow(10, $digits - 1), pow(10, $digits) - 1); 90 | $validity = (int)Configuration::get('PS_PASSWD_RESET_VALIDITY') ?: 1440; 91 | $reset_password_validity = date('Y-m-d H:i:s', strtotime('+' . $validity . ' minutes')); 92 | 93 | $db = Db::getInstance(); 94 | $sql = 'INSERT INTO `' . _DB_PREFIX_ . 'binshopsrest_reset_pass_tokens` (`reset_password_token`, `reset_password_validity`,`id_customer`) 95 | VALUES (\'' . $rand . '\',\'' . $reset_password_validity . '\',' . $customer->id . ')'; 96 | $db->execute($sql); 97 | return $rand; 98 | } 99 | 100 | public function hasRecentResetPasswordToken($customer) 101 | { 102 | $sql = 'SELECT * FROM `' . _DB_PREFIX_ . 'binshopsrest_reset_pass_tokens` 103 | WHERE id_customer =' . $customer->id; 104 | $result = Db::getInstance()->executeS($sql); 105 | 106 | if (empty($result)) { 107 | return false; 108 | } elseif (strtotime(end($result)['reset_password_validity']) < time()) { 109 | return false; 110 | } 111 | 112 | return end($result)['reset_password_token']; 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /controllers/front/resetpasswordenter.php: -------------------------------------------------------------------------------- 1 | changePassword(); 23 | 24 | $this->ajaxRender(json_encode([ 25 | 'success' => false, 26 | 'code' => 200, 27 | 'psdata' => "password reset successfully" 28 | ])); 29 | die; 30 | } 31 | 32 | protected function changePassword() 33 | { 34 | if (!($email = Tools::getValue('email')) || !Validate::isEmail($email)) { 35 | $this->errors[] = $this->trans('Invalid email address.', [], 'Shop.Notifications.Error'); 36 | } else { 37 | $customer = new Customer(); 38 | $customer->getByEmail($email); 39 | } 40 | 41 | $sql = 'SELECT * FROM `' . _DB_PREFIX_ . 'binshopsrest_reset_pass_tokens` 42 | WHERE id_customer =' . $customer->id; 43 | $result = Db::getInstance()->executeS($sql); 44 | 45 | if (empty($result)) { 46 | $this->ajaxRender(json_encode([ 47 | 'success' => true, 48 | 'code' => 200, 49 | 'psdata' => $this->trans("this state is not expected", [], 'Modules.Binshopsrest.Auth') 50 | ])); 51 | die; 52 | } elseif (strtotime(end($result)['reset_password_validity']) < time()) { 53 | $this->ajaxRender(json_encode([ 54 | 'success' => true, 55 | 'code' => 200, 56 | 'psdata' => $this->trans("expired", [], 'Modules.Binshopsrest.Auth') 57 | ])); 58 | die; 59 | } 60 | 61 | $theCode = end($result)['reset_password_token']; 62 | 63 | if (Tools::getValue('pass-code') === $theCode) { 64 | if (!$passwd = Tools::getValue('passwd')) { 65 | $this->psdata = $this->trans('The password is missing: please enter your new password.', [], 'Shop.Notifications.Error'); 66 | } 67 | 68 | if (!$confirmation = Tools::getValue('confirmation')) { 69 | $this->psdata = $this->trans('The confirmation is empty: please fill in the password confirmation as well', [], 'Shop.Notifications.Error'); 70 | } 71 | 72 | if ($passwd && $confirmation) { 73 | if ($passwd !== $confirmation) { 74 | $this->psdata = $this->trans('The password and its confirmation do not match.', [], 'Shop.Notifications.Error'); 75 | } 76 | 77 | if (!Validate::isPasswd($passwd)) { 78 | $this->psdata = $this->trans('The password is not in a valid format.', [], 'Shop.Notifications.Error'); 79 | } 80 | } 81 | $customer->passwd = $this->get('hashing')->hash($password = Tools::getValue('passwd'), _COOKIE_KEY_); 82 | $customer->last_passwd_gen = date('Y-m-d H:i:s', time()); 83 | 84 | if ($customer->update()) { 85 | Hook::exec('actionPasswordRenew', ['customer' => $customer, 'password' => $password]); 86 | $customer->removeResetPasswordToken(); 87 | $customer->update(); 88 | 89 | $mail_params = [ 90 | '{email}' => $customer->email, 91 | '{lastname}' => $customer->lastname, 92 | '{firstname}' => $customer->firstname, 93 | ]; 94 | 95 | if (Mail::Send( 96 | $this->context->language->id, 97 | 'password', 98 | $this->trans( 99 | 'Your new password', 100 | [], 101 | 'Emails.Subject' 102 | ), 103 | $mail_params, 104 | $customer->email, 105 | $customer->firstname . ' ' . $customer->lastname 106 | ) 107 | ) { 108 | $this->context->smarty->assign([ 109 | 'customer_email' => $customer->email, 110 | ]); 111 | $this->success[] = $this->trans('Your password has been successfully reset and a confirmation has been sent to your email address: %s', [$customer->email], 'Shop.Notifications.Success'); 112 | $this->context->updateCustomer($customer); 113 | $this->redirectWithNotifications('index.php?controller=my-account'); 114 | } else { 115 | $this->errors[] = $this->trans('An error occurred while sending the email.', [], 'Shop.Notifications.Error'); 116 | } 117 | } else { 118 | $this->errors[] = $this->trans('An error occurred with your account, which prevents us from updating the new password. Please report this issue using the contact form.', [], 'Shop.Notifications.Error'); 119 | } 120 | } else { 121 | $this->ajaxRender(json_encode([ 122 | 'success' => false, 123 | 'code' => 301, 124 | 'psdata' => $this->trans("code not matched", [], 'Modules.Binshopsrest.Auth') 125 | ])); 126 | die; 127 | } 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /controllers/front/setaddresscheckout.php: -------------------------------------------------------------------------------- 1 | context, 24 | $this->getTranslator(), 25 | $this->objectPresenter, 26 | new PriceFormatter() 27 | ); 28 | $session = new CheckoutSession( 29 | $this->context, 30 | $deliveryOptionsFinder 31 | ); 32 | 33 | $session->setIdAddressDelivery(Tools::getValue('id_address')); 34 | $session->setIdAddressInvoice(Tools::getValue('id_address')); 35 | } else { 36 | $this->ajaxRender(json_encode([ 37 | 'success' => true, 38 | 'code' => 301, 39 | 'psdata' => $this->trans("id_address-required", [], 'Modules.Binshopsrest.Checkout') 40 | ])); 41 | die; 42 | } 43 | 44 | $this->ajaxRender(json_encode([ 45 | 'success' => true, 46 | 'code' => 200, 47 | 'psdata' => $this->trans("id address has been successfully set", [], 'Modules.Binshopsrest.Checkout') 48 | ])); 49 | die; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /controllers/front/setcarriercheckout.php: -------------------------------------------------------------------------------- 1 | context, 24 | $this->getTranslator(), 25 | $this->objectPresenter, 26 | new PriceFormatter() 27 | ); 28 | $session = new CheckoutSession( 29 | $this->context, 30 | $deliveryOptionsFinder 31 | ); 32 | 33 | $delivery_option = array(); 34 | //[7] = [',7'] 35 | $delivery_option[Tools::getValue('id_address')] = Tools::getValue('id_carrier'); 36 | 37 | //set carrier option 38 | $session->setDeliveryOption($delivery_option); 39 | $session->getSelectedDeliveryOption(); 40 | } else { 41 | $this->ajaxRender(json_encode([ 42 | 'success' => true, 43 | 'code' => 301, 44 | 'psdata' => $this->trans("id_carrier-required", [], 'Modules.Binshopsrest.Checkout') 45 | ])); 46 | die; 47 | } 48 | 49 | $this->ajaxRender(json_encode([ 50 | 'success' => true, 51 | 'code' => 200, 52 | 'psdata' => $this->trans("id carrier has been successfully set", [], 'Modules.Binshopsrest.Checkout') 53 | ])); 54 | die; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /controllers/front/wishlist.php: -------------------------------------------------------------------------------- 1 | context->customer->id)){ 31 | $this->ajaxRender(json_encode([ 32 | 'success' => true, 33 | 'code' => 300, 34 | 'message' => $this->trans('You must be logged in to use wishlist', [], 'Modules.Binshopsrest.Wishlist') 35 | ])); 36 | die; 37 | } 38 | 39 | switch (Tools::getValue('action')){ 40 | case 'list': 41 | $this->listWishlists(); 42 | break; 43 | case 'addProductToWishlist': 44 | $this->addToWishlist(); 45 | break; 46 | case 'viewWishlist': 47 | $this->viewWishlist(); 48 | break; 49 | case 'deleteProductFromWishList': 50 | $this->deleteProductFromWishList(); 51 | break; 52 | case 'createWishlist': 53 | $this->createWishlist(); 54 | break; 55 | case 'deleteWishlist': 56 | $this->deleteWishlist(); 57 | break; 58 | case 'renameWishlist': 59 | $this->renameWishlist(); 60 | break; 61 | } 62 | } 63 | 64 | /** 65 | * Action Methods 66 | * ********************************************************************** 67 | */ 68 | 69 | private function listWishlists(){ 70 | $infos = WishList::getAllWishListsByIdCustomer($this->context->customer->id); 71 | if (empty($infos)) { 72 | $wishlist = new WishList(); 73 | $wishlist->id_shop = $this->context->shop->id; 74 | $wishlist->id_shop_group = $this->context->shop->id_shop_group; 75 | $wishlist->id_customer = $this->context->customer->id; 76 | $wishlist->name = Configuration::get('blockwishlist_WishlistDefaultTitle', $this->context->language->id); 77 | $wishlist->default = 1; 78 | $wishlist->add(); 79 | 80 | $infos = WishList::getAllWishListsByIdCustomer($this->context->customer->id); 81 | } 82 | 83 | if (false === empty($infos)) { 84 | $this->ajaxRender(json_encode([ 85 | 'success' => true, 86 | 'code' => 200, 87 | 'psdata' => $infos, 88 | 'message' => $this->trans('success', [], 'Modules.Binshopsrest.Wishlist') 89 | ])); 90 | die; 91 | } 92 | } 93 | 94 | private function addToWishlist(){ 95 | $id_product = Tools::getValue('id_product'); 96 | $product = new Product($id_product); 97 | if (!Validate::isLoadedObject($product)) { 98 | $this->ajaxRender(json_encode([ 99 | 'success' => false, 100 | 'code' => 310, 101 | 'message' => $this->trans('There was an error adding the product', [], 'Modules.Blockwishlist.Shop') 102 | ])); 103 | die; 104 | } 105 | 106 | $idWishList = Tools::getValue('idWishList'); 107 | 108 | $id_product_attribute = Tools::getValue('id_product_attribute'); 109 | if (!$id_product_attribute){ 110 | $id_product_attribute = $product->getDefaultIdProductAttribute(); 111 | } 112 | 113 | $quantity = Tools::getValue('quantity'); 114 | if (0 === $quantity) { 115 | $quantity = $product->minimal_quantity; 116 | } 117 | 118 | if (false === $this->assertProductAttributeExists($id_product, $id_product_attribute) && $id_product_attribute !== 0) { 119 | 120 | $this->ajaxRender(json_encode([ 121 | 'success' => false, 122 | 'code' => 320, 123 | 'message' => $this->trans('There was an error while adding the product attributes', [], 'Modules.Blockwishlist.Shop') 124 | ])); 125 | die; 126 | } 127 | 128 | if (!$idWishList){ 129 | $infos = WishList::getAllWishListsByIdCustomer($this->context->customer->id); 130 | if (empty($infos)) { 131 | $wishlist = new WishList(); 132 | $wishlist->id_shop = $this->context->shop->id; 133 | $wishlist->id_shop_group = $this->context->shop->id_shop_group; 134 | $wishlist->id_customer = $this->context->customer->id; 135 | $wishlist->name = Configuration::get('blockwishlist_WishlistDefaultTitle', $this->context->language->id); 136 | $wishlist->default = 1; 137 | $wishlist->token = $this->generateWishListToken(); 138 | 139 | $wishlist->add(); 140 | 141 | $infos = WishList::getAllWishListsByIdCustomer($this->context->customer->id); 142 | } 143 | $wishlist = $infos[0]; 144 | $idWishList = $wishlist['id_wishlist']; 145 | $wishlist = new WishList($wishlist['id_wishlist']); 146 | }else{ 147 | $wishlist = new WishList($idWishList); 148 | } 149 | 150 | // Exit if not owner of the wishlist 151 | $this->assertWriteAccess($wishlist); 152 | 153 | $productIsAdded = $wishlist->addProduct( 154 | $idWishList, 155 | $this->context->customer->id, 156 | $id_product, 157 | $id_product_attribute, 158 | $quantity 159 | ); 160 | 161 | $newStat = new Statistics(); 162 | $newStat->id_product = $id_product; 163 | $newStat->id_product_attribute = $id_product_attribute; 164 | $newStat->id_shop = $this->context->shop->id; 165 | $newStat->save(); 166 | 167 | if (false === $productIsAdded) { 168 | $this->ajaxRender(json_encode([ 169 | 'success' => false, 170 | 'code' => 330, 171 | 'message' => $this->trans('There was an error adding the product', [], 'Modules.Blockwishlist.Shop') 172 | ])); 173 | die; 174 | } 175 | 176 | Hook::exec('actionWishlistAddProduct', [ 177 | 'idWishlist' => $idWishList, 178 | 'customerId' => $this->context->customer->id, 179 | 'idProduct' => $id_product, 180 | 'idProductAttribute' => $id_product_attribute, 181 | ]); 182 | 183 | $wishlistData = $this->getWishlistData($idWishList); 184 | 185 | $this->ajaxRender(json_encode([ 186 | 'success' => true, 187 | 'code' => 200, 188 | 'message' => $this->trans('Product added', [], 'Modules.Blockwishlist.Shop'), 189 | 'psdata' =>[ 190 | 'wishlistName' => $this->wishlist->name, 191 | 'label' => $wishlistData['label'], 192 | 'products' => $wishlistData['products'] 193 | ] 194 | ])); 195 | die; 196 | } 197 | 198 | private function viewWishlist(){ 199 | $idWishList = Tools::getValue('id_wishlist'); 200 | $wishlistData = $this->getWishlistData($idWishList); 201 | 202 | $psdata = [ 203 | 'wishlistName' => $this->wishlist->name, 204 | 'label' => $wishlistData['label'], 205 | 'products' => $wishlistData['products'] 206 | ]; 207 | 208 | $this->ajaxRender(json_encode([ 209 | 'code' => 200, 210 | 'success' => true, 211 | 'psdata' => $psdata, 212 | 'message' => $this->trans('success', [], 'Modules.Binshopsrest.Wishlist') 213 | ])); 214 | die; 215 | } 216 | 217 | private function deleteProductFromWishList(){ 218 | $id_product = Tools::getValue('id_product'); 219 | $idWishList = Tools::getValue('idWishList'); 220 | $id_product_attribute = Tools::getValue('id_product_attribute'); 221 | $product = new Product($id_product); 222 | 223 | if (!$id_product){ 224 | $this->ajaxRender(json_encode([ 225 | 'success' => false, 226 | 'code' => 310, 227 | 'message' => $this->trans('Id product is not set', [], 'Modules.Blockwishlist.Shop') 228 | ])); 229 | die; 230 | } 231 | 232 | if (!$id_product_attribute){ 233 | $id_product_attribute = $product->getDefaultIdProductAttribute(); 234 | } 235 | 236 | if (!$idWishList){ 237 | $infos = WishList::getAllWishListsByIdCustomer($this->context->customer->id); 238 | if (empty($infos)) { 239 | $wishlist = new WishList(); 240 | $wishlist->id_shop = $this->context->shop->id; 241 | $wishlist->id_shop_group = $this->context->shop->id_shop_group; 242 | $wishlist->id_customer = $this->context->customer->id; 243 | $wishlist->name = Configuration::get('blockwishlist_WishlistDefaultTitle', $this->context->language->id); 244 | $wishlist->default = 1; 245 | $wishlist->add(); 246 | 247 | $infos = WishList::getAllWishListsByIdCustomer($this->context->customer->id); 248 | } 249 | $wishlist = $infos[0]; 250 | $idWishList = $wishlist['id_wishlist']; 251 | $wishlist = new WishList($wishlist['id_wishlist']); 252 | }else{ 253 | $wishlist = new WishList($idWishList); 254 | } 255 | 256 | $this->assertWriteAccess($wishlist); 257 | 258 | $isDeleted = WishList::removeProduct( 259 | $idWishList, 260 | $this->context->customer->id, 261 | $id_product, 262 | $id_product_attribute 263 | ); 264 | 265 | $wishlistData = $this->getWishlistData($idWishList); 266 | 267 | if ($isDeleted) { 268 | $this->ajaxRender(json_encode([ 269 | 'success' => true, 270 | 'code' => 200, 271 | 'message' => $this->trans('Product successfully removed', [], 'Modules.Blockwishlist.Shop'), 272 | 'psdata' =>[ 273 | 'wishlistName' => $wishlist->name, 274 | 'label' => $wishlistData['label'], 275 | 'products' => $wishlistData['products'] 276 | ] 277 | ])); 278 | die; 279 | } 280 | } 281 | 282 | private function createWishlist(){ 283 | $wishlistName = Tools::getValue('name'); 284 | 285 | if (!$wishlistName){ 286 | $this->ajaxRender(json_encode([ 287 | 'success' => false, 288 | 'code' => 310, 289 | 'message' => $this->trans('Wishlist name required', [], 'Modules.Blockwishlist.Shop') 290 | ])); 291 | die; 292 | } 293 | 294 | $wishlist = new WishList(); 295 | $wishlist->name = $wishlistName; 296 | $wishlist->id_shop_group = $this->context->shop->id_shop_group; 297 | $wishlist->id_customer = $this->context->customer->id; 298 | $wishlist->id_shop = $this->context->shop->id; 299 | $wishlist->token = $this->generateWishListToken(); 300 | 301 | if ($wishlist->save()) { 302 | $this->ajaxRender(json_encode([ 303 | 'success' => true, 304 | 'code' => 200, 305 | 'psdata' => [ 306 | 'name' => $wishlist->name, 307 | 'id_wishlist' => $wishlist->id, 308 | ], 309 | 'message' => $this->trans('The list has been properly created', [], 'Modules.Blockwishlist.Shop') 310 | ])); 311 | die; 312 | } 313 | } 314 | 315 | private function deleteWishlist(){ 316 | if (!Tools::getValue('idWishList')){ 317 | $this->ajaxRender(json_encode([ 318 | 'success' => false, 319 | 'code' => 310, 320 | 'message' => $this->trans('Wishlist id required', [], 'Modules.Blockwishlist.Shop') 321 | ])); 322 | die; 323 | } 324 | $wishlist = new WishList(Tools::getValue('idWishList')); 325 | 326 | $this->assertWriteAccess($wishlist); 327 | 328 | if (true === (bool) $wishlist->delete()) { 329 | $this->ajaxRender(json_encode([ 330 | 'success' => true, 331 | 'code' => 200, 332 | 'message' => $this->trans('List has been removed', [], 'Modules.Blockwishlist.Shop') 333 | ])); 334 | die; 335 | } 336 | } 337 | 338 | private function renameWishlist(){ 339 | $wishlistName = Tools::getValue('name'); 340 | $idWishList = Tools::getValue('idWishList'); 341 | 342 | if (!$idWishList){ 343 | $this->ajaxRender(json_encode([ 344 | 'success' => false, 345 | 'code' => 310, 346 | 'message' => $this->trans('Wishlist id required', [], 'Modules.Blockwishlist.Shop') 347 | ])); 348 | die; 349 | }elseif(!$wishlistName){ 350 | $this->ajaxRender(json_encode([ 351 | 'success' => false, 352 | 'code' => 320, 353 | 'message' => $this->trans('Wishlist name required', [], 'Modules.Blockwishlist.Shop') 354 | ])); 355 | die; 356 | } 357 | 358 | $wishlist = new WishList($idWishList); 359 | // Exit if not owner of the wishlist 360 | $this->assertWriteAccess($wishlist); 361 | 362 | $wishlist->name = $wishlistName; 363 | 364 | if ($wishlist->save()) { 365 | $this->ajaxRender(json_encode([ 366 | 'success' => false, 367 | 'code' => 200, 368 | 'message' => $this->trans('List has been renamed', [], 'Modules.Blockwishlist.Shop') 369 | ])); 370 | die; 371 | } 372 | } 373 | 374 | /** 375 | * Helper methods 376 | * ********************************************************************** 377 | */ 378 | 379 | private function getWishlistData($idWishlist){ 380 | if (!$idWishlist){ 381 | $infos = WishList::getAllWishListsByIdCustomer($this->context->customer->id); 382 | if (empty($infos)) { 383 | $wishlist = new WishList(); 384 | $wishlist->id_shop = $this->context->shop->id; 385 | $wishlist->id_shop_group = $this->context->shop->id_shop_group; 386 | $wishlist->id_customer = $this->context->customer->id; 387 | $wishlist->name = Configuration::get('blockwishlist_WishlistDefaultTitle', $this->context->language->id); 388 | $wishlist->default = 1; 389 | $wishlist->add(); 390 | 391 | $infos = WishList::getAllWishListsByIdCustomer($this->context->customer->id); 392 | } 393 | $wishlist = $infos[0]; 394 | $this->wishlist = new WishList($wishlist['id_wishlist']); 395 | }else{ 396 | $this->wishlist = new WishList($idWishlist); 397 | } 398 | 399 | $this->assertReadAccess($this->wishlist); 400 | 401 | $variables = $this->getProductSearchVariables(); 402 | $productList = $variables['products']; 403 | $retriever = new \PrestaShop\PrestaShop\Adapter\Image\ImageRetriever( 404 | $this->context->link 405 | ); 406 | 407 | $settings = $this->getProductPresentationSettings(); 408 | 409 | foreach ($productList as $key => $product) { 410 | $populated_product = (new ProductAssembler($this->context)) 411 | ->assembleProduct($product); 412 | 413 | $lazy_product = new RESTProductLazyArray( 414 | $settings, 415 | $populated_product, 416 | $this->context->language, 417 | new \PrestaShop\PrestaShop\Adapter\Product\PriceFormatter(), 418 | $retriever, 419 | $this->context->getTranslator() 420 | ); 421 | 422 | $productList[$key] = $lazy_product->getProduct(); 423 | } 424 | 425 | return [ 426 | 'products' => $productList, 427 | 'label' => $variables['label'] 428 | ]; 429 | } 430 | 431 | private function generateWishListToken() 432 | { 433 | return strtoupper(substr(sha1(uniqid((string) rand(), true) . _COOKIE_KEY_ . $this->context->customer->id), 0, 16)); 434 | } 435 | 436 | private function assertProductAttributeExists($id_product, $id_product_attribute) 437 | { 438 | return Db::getInstance()->getValue( 439 | 'SELECT pas.`id_product_attribute` ' . 440 | 'FROM `' . _DB_PREFIX_ . 'product_attribute` pa ' . 441 | 'INNER JOIN `' . _DB_PREFIX_ . 'product_attribute_shop` pas ON (pas.id_product_attribute = pa.id_product_attribute) ' . 442 | 'WHERE pas.id_shop =' . (int) $this->context->shop->id . ' AND pa.`id_product` = ' . (int) $id_product . ' ' . 443 | 'AND pas.id_product_attribute = ' . (int) $id_product_attribute 444 | ); 445 | } 446 | 447 | private function assertWriteAccess(WishList $wishlist) 448 | { 449 | if ((new CustomerAccess($this->context->customer))->hasWriteAccessToWishlist($wishlist)) { 450 | return; 451 | } 452 | 453 | $this->ajaxRender(json_encode([ 454 | 'success' => false, 455 | 'code' => 340, 456 | 'message' => $this->trans('You\'re not allowed to manage this list.', [], 'Modules.Blockwishlist.Shop') 457 | ])); 458 | die; 459 | } 460 | 461 | public function assertReadAccess(WishList $wishlist) 462 | { 463 | $this->assertWriteAccess($wishlist); 464 | } 465 | 466 | public function getListingLabel() 467 | { 468 | return $this->getTranslator()->trans('Your Wishlist', array(), 'Shop.Theme.Catalog'); 469 | } 470 | 471 | protected function getProductSearchQuery() 472 | { 473 | $query = new ProductSearchQuery(); 474 | $query->setSortOrder( 475 | new SortOrder( 476 | 'product', 477 | Tools::getProductsOrder('by'), 478 | Tools::getProductsOrder('way') 479 | ) 480 | ); 481 | 482 | return $query; 483 | } 484 | 485 | protected function getDefaultProductSearchProvider() 486 | { 487 | return new WishListProductSearchProvider( 488 | Db::getInstance(), 489 | $this->wishlist, 490 | new SortOrderFactory($this->getTranslator()), 491 | $this->getTranslator() 492 | ); 493 | } 494 | } 495 | -------------------------------------------------------------------------------- /controllers/index.php: -------------------------------------------------------------------------------- 1 | true, 16 | 'code' => 210, 17 | 'psdata' => null, 18 | 'message' => 'empty' 19 | ]; 20 | 21 | switch ($_SERVER['REQUEST_METHOD']) { 22 | case 'GET': 23 | $response = $this->processGetRequest(); 24 | break; 25 | case 'POST': 26 | $response = $this->processPostRequest(); 27 | break; 28 | case 'PATCH': 29 | case 'PUT': 30 | $response = $this->processPutRequest(); 31 | break; 32 | case 'DELETE': 33 | $response = $this->processDeleteRequest(); 34 | break; 35 | default: 36 | // throw some error or whatever 37 | } 38 | 39 | $this->ajaxRender(json_encode($response)); 40 | die; 41 | } 42 | 43 | protected function processGetRequest(){ 44 | return [ 45 | 'success' => true, 46 | 'code' => 310, 47 | 'psdata' => null, 48 | 'message' => $this->trans('GET not supported on this path', [], 'Modules.Binshopsrest.Admin'), 49 | ]; 50 | } 51 | 52 | protected function processPostRequest(){ 53 | return [ 54 | 'success' => true, 55 | 'code' => 310, 56 | 'psdata' => null, 57 | 'message' => $this->trans('POST not supported on this path', [], 'Modules.Binshopsrest.Admin'), 58 | ]; 59 | } 60 | 61 | protected function processPutRequest(){ 62 | return [ 63 | 'success' => true, 64 | 'code' => 310, 65 | 'psdata' => null, 66 | 'message' => $this->trans('PUT not supported on this path', [], 'Modules.Binshopsrest.Admin'), 67 | ]; 68 | } 69 | 70 | protected function processDeleteRequest(){ 71 | return [ 72 | 'success' => true, 73 | 'code' => 310, 74 | 'psdata' => null, 75 | 'message' => $this->trans('DELETE not supported on this path', [], 'Modules.Binshopsrest.Admin'), 76 | ]; 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /sql/index.php: -------------------------------------------------------------------------------- 1 | execute($query) == false) { 25 | return false; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /sql/uninstall.php: -------------------------------------------------------------------------------- 1 | execute($query) == false) { 21 | return false; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /translations/index.php: -------------------------------------------------------------------------------- 1 | registerHook('actionDispatcherBefore'); 19 | return true; 20 | } 21 | -------------------------------------------------------------------------------- /views/css/back.css: -------------------------------------------------------------------------------- 1 | /** 2 | * BINSHOPS 3 | * 4 | * @author BINSHOPS 5 | * @copyright BINSHOPS 6 | * 7 | */ 8 | -------------------------------------------------------------------------------- /views/css/front.css: -------------------------------------------------------------------------------- 1 | /** 2 | * BINSHOPS 3 | * 4 | * @author BINSHOPS 5 | * @copyright BINSHOPS 6 | * 7 | */ 8 | -------------------------------------------------------------------------------- /views/css/index.php: -------------------------------------------------------------------------------- 1 | 10 |

{l s='PrestaShop REST API Free version' mod='binshopsrest'}

11 |

12 | {l s='Your endpoints are ready!' mod='binshopsrest'}
13 | {l s='There is no configuration required for this module out of the box. Your endpoint: https://example.com/rest/{endpoint}' mod='binshopsrest'} 14 |

15 | 16 |

{l s='Official Supported Version' mod='binshopsrest'}

17 |

18 | Get the latest supported version and documentation including the amazing features from Official PrestaShop Addons. Let's take a look at the list of benefits. 19 |

20 |

21 | New! Annotation-based API routing added and structural changes made in version 5. 22 |

23 | 24 | 25 |
26 |

{l s='Endpoints' mod='binshopsrest'}

27 |

28 | » {l s='List of endpoints' mod='binshopsrest'} : 29 |

90 | 91 | More endpoints on Pro version 92 |

93 |
94 | -------------------------------------------------------------------------------- /views/templates/admin/index.php: -------------------------------------------------------------------------------- 1 |