PageRenderTime 38ms CodeModel.GetById 8ms RepoModel.GetById 1ms app.codeStats 0ms

/controllers/front/AddressController.php

https://bitbucket.org/enurkov/prestashop
PHP | 366 lines | 257 code | 34 blank | 75 comment | 92 complexity | 05c212bf2fde770b6a8f6d448f187a7a MD5 | raw file
  1. <?php
  2. /*
  3. * 2007-2012 PrestaShop
  4. *
  5. * NOTICE OF LICENSE
  6. *
  7. * This source file is subject to the Open Software License (OSL 3.0)
  8. * that is bundled with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://opensource.org/licenses/osl-3.0.php
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@prestashop.com so we can send you a copy immediately.
  14. *
  15. * DISCLAIMER
  16. *
  17. * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
  18. * versions in the future. If you wish to customize PrestaShop for your
  19. * needs please refer to http://www.prestashop.com for more information.
  20. *
  21. * @author PrestaShop SA <contact@prestashop.com>
  22. * @copyright 2007-2012 PrestaShop SA
  23. * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
  24. * International Registered Trademark & Property of PrestaShop SA
  25. */
  26. class AddressControllerCore extends FrontController
  27. {
  28. public $auth = true;
  29. public $guestAllowed = true;
  30. public $php_self = 'address';
  31. public $authRedirection = 'addresses';
  32. public $ssl = true;
  33. /**
  34. * @var Address Current address
  35. */
  36. protected $_address;
  37. /**
  38. * Set default medias for this controller
  39. */
  40. public function setMedia()
  41. {
  42. parent::setMedia();
  43. $this->addJS(_THEME_JS_DIR_.'tools/statesManagement.js');
  44. }
  45. /**
  46. * Initialize address controller
  47. * @see FrontController::init()
  48. */
  49. public function init()
  50. {
  51. parent::init();
  52. // Get address ID
  53. $id_address = 0;
  54. if ($this->ajax && Tools::isSubmit('type'))
  55. {
  56. if (Tools::getValue('type') == 'delivery' && isset($this->context->cart->id_address_delivery))
  57. $id_address = (int)$this->context->cart->id_address_delivery;
  58. else if (Tools::getValue('type') == 'invoice' && isset($this->context->cart->id_address_invoice)
  59. && $this->context->cart->id_address_invoice != $this->context->cart->id_address_delivery)
  60. $id_address = (int)$this->context->cart->id_address_invoice;
  61. }
  62. else
  63. $id_address = (int)Tools::getValue('id_address', 0);
  64. // Initialize address
  65. if ($id_address)
  66. {
  67. $this->_address = new Address($id_address);
  68. if (Validate::isLoadedObject($this->_address) && Customer::customerHasAddress($this->context->customer->id, $id_address))
  69. {
  70. if (Tools::isSubmit('delete'))
  71. {
  72. if ($this->_address->delete())
  73. {
  74. if ($this->context->cart->id_address_invoice == $this->_address->id)
  75. unset($this->context->cart->id_address_invoice);
  76. if ($this->context->cart->id_address_delivery == $this->_address->id)
  77. {
  78. unset($this->context->cart->id_address_delivery);
  79. $this->context->cart->updateAddressId($this->_address->id, (int)Address::getFirstCustomerAddressId(Context::getContext()->customer->id));
  80. }
  81. Tools::redirect('index.php?controller=addresses');
  82. }
  83. $this->errors[] = Tools::displayError('This address cannot be deleted.');
  84. }
  85. }
  86. elseif ($this->ajax)
  87. exit;
  88. else
  89. Tools::redirect('index.php?controller=addresses');
  90. }
  91. }
  92. /**
  93. * Start forms process
  94. * @see FrontController::postProcess()
  95. */
  96. public function postProcess()
  97. {
  98. if (Tools::isSubmit('submitAddress'))
  99. $this->processSubmitAddress();
  100. else if (!Validate::isLoadedObject($this->_address) && Validate::isLoadedObject($this->context->customer))
  101. {
  102. $_POST['firstname'] = $this->context->customer->firstname;
  103. $_POST['lastname'] = $this->context->customer->lastname;
  104. $_POST['company'] = $this->context->customer->company;
  105. }
  106. }
  107. /**
  108. * Process changes on an address
  109. */
  110. protected function processSubmitAddress()
  111. {
  112. $address = new Address();
  113. $this->errors = $address->validateController();
  114. $address->id_customer = (int)$this->context->customer->id;
  115. // Check page token
  116. if ($this->context->customer->isLogged() && !$this->isTokenValid())
  117. $this->errors[] = Tools::displayError('Invalid token');
  118. // Check phone
  119. if (Configuration::get('PS_ONE_PHONE_AT_LEAST') && !Tools::getValue('phone') && !Tools::getValue('phone_mobile'))
  120. $this->errors[] = Tools::displayError('You must register at least one phone number');
  121. if ($address->id_country)
  122. {
  123. // Check country
  124. if (!($country = new Country($address->id_country)) || !Validate::isLoadedObject($country))
  125. throw new PrestaShopException('Country cannot be loaded with address->id_country');
  126. if ((int)$country->contains_states && !(int)$address->id_state)
  127. $this->errors[] = Tools::displayError('This country requires a state selection.');
  128. // US customer: normalize the address
  129. if ($address->id_country == Country::getByIso('US'))
  130. {
  131. include_once(_PS_TAASC_PATH_.'AddressStandardizationSolution.php');
  132. $normalize = new AddressStandardizationSolution;
  133. $address->address1 = $normalize->AddressLineStandardization($address->address1);
  134. $address->address2 = $normalize->AddressLineStandardization($address->address2);
  135. }
  136. // Check country zip code
  137. $zip_code_format = $country->zip_code_format;
  138. if ($country->need_zip_code)
  139. {
  140. if (($postcode = Tools::getValue('postcode')) && $zip_code_format)
  141. {
  142. if (!$country->checkZipCode($postcode))
  143. $this->errors[] = sprintf(
  144. Tools::displayError('Zip/Postal code is invalid. Must be typed as follows: %s'),
  145. str_replace('C', $country->iso_code, str_replace('N', '0', str_replace('L', 'A', $country->zip_code_format)))
  146. );
  147. }
  148. else if ($zip_code_format)
  149. $this->errors[] = Tools::displayError('Zip/Postal code is required.');
  150. else if ($postcode && !preg_match('/^[0-9a-zA-Z -]{4,9}$/ui', $postcode))
  151. $this->errors[] = sprintf(
  152. Tools::displayError('Zip/Postal code is invalid. Must be typed as follows: %s'),
  153. str_replace('C', $country->iso_code, str_replace('N', '0', str_replace('L', 'A', $country->zip_code_format)))
  154. );
  155. }
  156. // Check country DNI
  157. if ($country->isNeedDni() && (!Tools::getValue('dni') || !Validate::isDniLite(Tools::getValue('dni'))))
  158. $this->errors[] = Tools::displayError('Identification number is incorrect or has already been used.');
  159. else if (!$country->isNeedDni())
  160. $address->dni = null;
  161. }
  162. // Check if the alias exists
  163. if (!$this->context->customer->is_guest && !empty($_POST['alias'])
  164. && (int)$this->context->customer->id > 0
  165. && Db::getInstance()->getValue('
  166. SELECT count(*)
  167. FROM '._DB_PREFIX_.'address
  168. WHERE `alias` = \''.pSql($_POST['alias']).'\'
  169. AND id_address != '.(int)Tools::getValue('id_address').'
  170. AND id_customer = '.(int)$this->context->customer->id.'
  171. AND deleted = 0') > 0)
  172. $this->errors[] = sprintf(Tools::displayError('The alias "%s" is already used, please chose another one.'), Tools::safeOutput($_POST['alias']));
  173. // Check the requires fields which are settings in the BO
  174. $this->errors = array_merge($this->errors, $address->validateFieldsRequiredDatabase());
  175. // Don't continue this process if we have errors !
  176. if ($this->errors && !$this->ajax)
  177. return;
  178. // If we edit this address, delete old address and create a new one
  179. if (Validate::isLoadedObject($this->_address))
  180. {
  181. if (Validate::isLoadedObject($country) && !$country->contains_states)
  182. $address->id_state = 0;
  183. $address_old = $this->_address;
  184. if (Customer::customerHasAddress($this->context->customer->id, (int)$address_old->id))
  185. {
  186. if ($address_old->isUsed())
  187. $address_old->delete();
  188. else
  189. {
  190. $address->id = (int)($address_old->id);
  191. $address->date_add = $address_old->date_add;
  192. }
  193. }
  194. }
  195. // Save address
  196. if ($result = $address->save())
  197. {
  198. // Update id address of the current cart if necessary
  199. if (isset($address_old) && $address_old->isUsed())
  200. $this->context->cart->updateAddressId($address_old->id, $address->id);
  201. else // Update cart address
  202. $this->context->cart->autosetProductAddress();
  203. if ($this->ajax)
  204. {
  205. $return = array(
  206. 'hasError' => (bool)$this->errors,
  207. 'errors' => $this->errors,
  208. 'id_address_delivery' => $this->context->cart->id_address_delivery,
  209. 'id_address_invoice' => $this->context->cart->id_address_invoice
  210. );
  211. die(Tools::jsonEncode($return));
  212. }
  213. // Redirect to old page or current page
  214. if ($back = Tools::getValue('back'))
  215. {
  216. $mod = Tools::getValue('mod');
  217. Tools::redirect('index.php?controller='.$back.($mod ? '&back='.$mod : ''));
  218. }
  219. else
  220. Tools::redirect('index.php?controller=addresses');
  221. }
  222. $this->errors[] = Tools::displayError('An error occurred while updating your address.');
  223. }
  224. /**
  225. * Assign template vars related to page content
  226. * @see FrontController::initContent()
  227. */
  228. public function initContent()
  229. {
  230. parent::initContent();
  231. $this->assignCountries();
  232. $this->assignVatNumber();
  233. $this->assignAddressFormat();
  234. // Assign common vars
  235. $this->context->smarty->assign(array(
  236. 'one_phone_at_least' => (int)Configuration::get('PS_ONE_PHONE_AT_LEAST'),
  237. 'ajaxurl' => _MODULE_DIR_,
  238. 'errors' => $this->errors,
  239. 'token' => Tools::getToken(false),
  240. 'select_address' => (int)Tools::getValue('select_address'),
  241. 'address' => $this->_address,
  242. 'id_address' => (Validate::isLoadedObject($this->_address)) ? $this->_address->id : 0,
  243. ));
  244. if ($back = Tools::getValue('back'))
  245. $this->context->smarty->assign('back', Tools::safeOutput($back));
  246. if ($mod = Tools::getValue('mod'))
  247. $this->context->smarty->assign('mod', Tools::safeOutput($mod));
  248. if (isset($this->context->cookie->account_created))
  249. {
  250. $this->context->smarty->assign('account_created', 1);
  251. unset($this->context->cookie->account_created);
  252. }
  253. $this->setTemplate(_PS_THEME_DIR_.'address.tpl');
  254. }
  255. /**
  256. * Assign template vars related to countries display
  257. */
  258. protected function assignCountries()
  259. {
  260. // Get selected country
  261. if (Tools::isSubmit('id_country') && !is_null(Tools::getValue('id_country')) && is_numeric(Tools::getValue('id_country')))
  262. $selected_country = (int)Tools::getValue('id_country');
  263. else if (isset($this->_address) && isset($this->_address->id_country) && !empty($this->_address->id_country) && is_numeric($this->_address->id_country))
  264. $selected_country = (int)$this->_address->id_country;
  265. else if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))
  266. {
  267. $array = preg_split('/,|-/', $_SERVER['HTTP_ACCEPT_LANGUAGE']);
  268. if (!Validate::isLanguageIsoCode($array[0]) || !($selected_country = Country::getByIso($array[0])))
  269. $selected_country = (int)Configuration::get('PS_COUNTRY_DEFAULT');
  270. }
  271. else
  272. $selected_country = (int)Configuration::get('PS_COUNTRY_DEFAULT');
  273. // Generate countries list
  274. if (Configuration::get('PS_RESTRICT_DELIVERED_COUNTRIES'))
  275. $countries = Carrier::getDeliveredCountries($this->context->language->id, true, true);
  276. else
  277. $countries = Country::getCountries($this->context->language->id, true);
  278. // @todo use helper
  279. $list = '';
  280. foreach ($countries as $country)
  281. {
  282. $selected = ($country['id_country'] == $selected_country) ? 'selected="selected"' : '';
  283. $list .= '<option value="'.(int)$country['id_country'].'" '.$selected.'>'.htmlentities($country['name'], ENT_COMPAT, 'UTF-8').'</option>';
  284. }
  285. // Assign vars
  286. $this->context->smarty->assign(array(
  287. 'countries_list' => $list,
  288. 'countries' => $countries,
  289. ));
  290. }
  291. /**
  292. * Assign template vars related to address format
  293. */
  294. protected function assignAddressFormat()
  295. {
  296. $id_country = is_null($this->_address)? 0 : (int)$this->_address->id_country;
  297. $dlv_adr_fields = AddressFormat::getOrderedAddressFields($id_country, true, true);
  298. $this->context->smarty->assign('ordered_adr_fields', $dlv_adr_fields);
  299. }
  300. /**
  301. * Assign template vars related to vat number
  302. * @todo move this in vatnumber module !
  303. */
  304. protected function assignVatNumber()
  305. {
  306. $vat_number_exists = file_exists(_PS_MODULE_DIR_.'vatnumber/vatnumber.php');
  307. $vat_number_management = Configuration::get('VATNUMBER_MANAGEMENT');
  308. if ($vat_number_management && $vat_number_exists)
  309. include_once(_PS_MODULE_DIR_.'vatnumber/vatnumber.php');
  310. if ($vat_number_management && $vat_number_exists && VatNumber::isApplicable(Configuration::get('PS_COUNTRY_DEFAULT')))
  311. $vat_display = 2;
  312. else if ($vat_number_management)
  313. $vat_display = 1;
  314. else
  315. $vat_display = 0;
  316. $this->context->smarty->assign(array(
  317. 'vatnumber_ajax_call' => file_exists(_PS_MODULE_DIR_.'vatnumber/ajax.php'),
  318. 'vat_display' => $vat_display,
  319. ));
  320. }
  321. public function displayAjax()
  322. {
  323. if (count($this->errors))
  324. {
  325. $return = array(
  326. 'hasError' => !empty($this->errors),
  327. 'errors' => $this->errors
  328. );
  329. die(Tools::jsonEncode($return));
  330. }
  331. }
  332. }