PageRenderTime 42ms CodeModel.GetById 8ms RepoModel.GetById 0ms app.codeStats 0ms

/app/code/core/Mage/Customer/controllers/AccountController.php

https://bitbucket.org/andrewjleavitt/magestudy
PHP | 680 lines | 472 code | 75 blank | 133 comment | 84 complexity | cf6d206fead2f61f6d01427929585f83 MD5 | raw file
Possible License(s): CC-BY-SA-3.0, LGPL-2.1, GPL-2.0, WTFPL
  1. <?php
  2. /**
  3. * Magento
  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@magentocommerce.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 Magento to newer
  18. * versions in the future. If you wish to customize Magento for your
  19. * needs please refer to http://www.magentocommerce.com for more information.
  20. *
  21. * @category Mage
  22. * @package Mage_Customer
  23. * @copyright Copyright (c) 2010 Magento Inc. (http://www.magentocommerce.com)
  24. * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
  25. */
  26. /**
  27. * Customer account controller
  28. *
  29. * @category Mage
  30. * @package Mage_Customer
  31. * @author Magento Core Team <core@magentocommerce.com>
  32. */
  33. class Mage_Customer_AccountController extends Mage_Core_Controller_Front_Action
  34. {
  35. /**
  36. * Action list where need check enabled cookie
  37. *
  38. * @var array
  39. */
  40. protected $_cookieCheckActions = array('loginPost', 'createpost');
  41. /**
  42. * Retrieve customer session model object
  43. *
  44. * @return Mage_Customer_Model_Session
  45. */
  46. protected function _getSession()
  47. {
  48. return Mage::getSingleton('customer/session');
  49. }
  50. /**
  51. * Action predispatch
  52. *
  53. * Check customer authentication for some actions
  54. */
  55. public function preDispatch()
  56. {
  57. // a brute-force protection here would be nice
  58. parent::preDispatch();
  59. if (!$this->getRequest()->isDispatched()) {
  60. return;
  61. }
  62. $action = $this->getRequest()->getActionName();
  63. $pattern = '/^(create|login|logoutSuccess|forgotpassword|forgotpasswordpost|confirm|confirmation)/i';
  64. if (!preg_match($pattern, $action)) {
  65. if (!$this->_getSession()->authenticate($this)) {
  66. $this->setFlag('', 'no-dispatch', true);
  67. }
  68. } else {
  69. $this->_getSession()->setNoReferer(true);
  70. }
  71. }
  72. /**
  73. * Action postdispatch
  74. *
  75. * Remove No-referer flag from customer session after each action
  76. */
  77. public function postDispatch()
  78. {
  79. parent::postDispatch();
  80. $this->_getSession()->unsNoReferer(false);
  81. }
  82. /**
  83. * Default customer account page
  84. */
  85. public function indexAction()
  86. {
  87. $this->loadLayout();
  88. $this->_initLayoutMessages('customer/session');
  89. $this->_initLayoutMessages('catalog/session');
  90. $this->getLayout()->getBlock('content')->append(
  91. $this->getLayout()->createBlock('customer/account_dashboard')
  92. );
  93. $this->getLayout()->getBlock('head')->setTitle($this->__('My Account'));
  94. $this->renderLayout();
  95. }
  96. /**
  97. * Customer login form page
  98. */
  99. public function loginAction()
  100. {
  101. if ($this->_getSession()->isLoggedIn()) {
  102. $this->_redirect('*/*/');
  103. return;
  104. }
  105. $this->getResponse()->setHeader('Login-Required', 'true');
  106. $this->loadLayout();
  107. $this->_initLayoutMessages('customer/session');
  108. $this->_initLayoutMessages('catalog/session');
  109. $this->renderLayout();
  110. }
  111. /**
  112. * Login post action
  113. */
  114. public function loginPostAction()
  115. {
  116. if ($this->_getSession()->isLoggedIn()) {
  117. $this->_redirect('*/*/');
  118. return;
  119. }
  120. $session = $this->_getSession();
  121. if ($this->getRequest()->isPost()) {
  122. $login = $this->getRequest()->getPost('login');
  123. if (!empty($login['username']) && !empty($login['password'])) {
  124. try {
  125. $session->login($login['username'], $login['password']);
  126. if ($session->getCustomer()->getIsJustConfirmed()) {
  127. $this->_welcomeCustomer($session->getCustomer(), true);
  128. }
  129. } catch (Mage_Core_Exception $e) {
  130. switch ($e->getCode()) {
  131. case Mage_Customer_Model_Customer::EXCEPTION_EMAIL_NOT_CONFIRMED:
  132. $value = Mage::helper('customer')->getEmailConfirmationUrl($login['username']);
  133. $message = Mage::helper('customer')->__('This account is not confirmed. <a href="%s">Click here</a> to resend confirmation email.', $value);
  134. break;
  135. case Mage_Customer_Model_Customer::EXCEPTION_INVALID_EMAIL_OR_PASSWORD:
  136. $message = $e->getMessage();
  137. break;
  138. default:
  139. $message = $e->getMessage();
  140. }
  141. $session->addError($message);
  142. $session->setUsername($login['username']);
  143. } catch (Exception $e) {
  144. // Mage::logException($e); // PA DSS violation: this exception log can disclose customer password
  145. }
  146. } else {
  147. $session->addError($this->__('Login and password are required.'));
  148. }
  149. }
  150. $this->_loginPostRedirect();
  151. }
  152. /**
  153. * Define target URL and redirect customer after logging in
  154. */
  155. protected function _loginPostRedirect()
  156. {
  157. $session = $this->_getSession();
  158. if (!$session->getBeforeAuthUrl() || $session->getBeforeAuthUrl() == Mage::getBaseUrl()) {
  159. // Set default URL to redirect customer to
  160. $session->setBeforeAuthUrl(Mage::helper('customer')->getAccountUrl());
  161. // Redirect customer to the last page visited after logging in
  162. if ($session->isLoggedIn()) {
  163. if (!Mage::getStoreConfigFlag('customer/startup/redirect_dashboard')) {
  164. $referer = $this->getRequest()->getParam(Mage_Customer_Helper_Data::REFERER_QUERY_PARAM_NAME);
  165. if ($referer) {
  166. $referer = Mage::helper('core')->urlDecode($referer);
  167. if ($this->_isUrlInternal($referer)) {
  168. $session->setBeforeAuthUrl($referer);
  169. }
  170. }
  171. } else if ($session->getAfterAuthUrl()) {
  172. $session->setBeforeAuthUrl($session->getAfterAuthUrl(true));
  173. }
  174. } else {
  175. $session->setBeforeAuthUrl(Mage::helper('customer')->getLoginUrl());
  176. }
  177. } else if ($session->getBeforeAuthUrl() == Mage::helper('customer')->getLogoutUrl()) {
  178. $session->setBeforeAuthUrl(Mage::helper('customer')->getDashboardUrl());
  179. } else {
  180. if (!$session->getAfterAuthUrl()) {
  181. $session->setAfterAuthUrl($session->getBeforeAuthUrl());
  182. }
  183. if ($session->isLoggedIn()) {
  184. $session->setBeforeAuthUrl($session->getAfterAuthUrl(true));
  185. }
  186. }
  187. $this->_redirectUrl($session->getBeforeAuthUrl(true));
  188. }
  189. /**
  190. * Customer logout action
  191. */
  192. public function logoutAction()
  193. {
  194. $this->_getSession()->logout()
  195. ->setBeforeAuthUrl(Mage::getUrl());
  196. $this->_redirect('*/*/logoutSuccess');
  197. }
  198. /**
  199. * Logout success page
  200. */
  201. public function logoutSuccessAction()
  202. {
  203. $this->loadLayout();
  204. $this->renderLayout();
  205. }
  206. /**
  207. * Customer register form page
  208. */
  209. public function createAction()
  210. {
  211. if ($this->_getSession()->isLoggedIn()) {
  212. $this->_redirect('*/*');
  213. return;
  214. }
  215. $this->loadLayout();
  216. $this->_initLayoutMessages('customer/session');
  217. $this->renderLayout();
  218. }
  219. /**
  220. * Create customer account action
  221. */
  222. public function createPostAction()
  223. {
  224. $session = $this->_getSession();
  225. if ($session->isLoggedIn()) {
  226. $this->_redirect('*/*/');
  227. return;
  228. }
  229. $session->setEscapeMessages(true); // prevent XSS injection in user input
  230. if ($this->getRequest()->isPost()) {
  231. $errors = array();
  232. if (!$customer = Mage::registry('current_customer')) {
  233. $customer = Mage::getModel('customer/customer')->setId(null);
  234. }
  235. /* @var $customerForm Mage_Customer_Model_Form */
  236. $customerForm = Mage::getModel('customer/form');
  237. $customerForm->setFormCode('customer_account_create')
  238. ->setEntity($customer);
  239. $customerData = $customerForm->extractData($this->getRequest());
  240. if ($this->getRequest()->getParam('is_subscribed', false)) {
  241. $customer->setIsSubscribed(1);
  242. }
  243. /**
  244. * Initialize customer group id
  245. */
  246. $customer->getGroupId();
  247. if ($this->getRequest()->getPost('create_address')) {
  248. /* @var $address Mage_Customer_Model_Address */
  249. $address = Mage::getModel('customer/address');
  250. /* @var $addressForm Mage_Customer_Model_Form */
  251. $addressForm = Mage::getModel('customer/form');
  252. $addressForm->setFormCode('customer_register_address')
  253. ->setEntity($address);
  254. $addressData = $addressForm->extractData($this->getRequest(), 'address', false);
  255. $addressErrors = $addressForm->validateData($addressData);
  256. if ($addressErrors === true) {
  257. $address->setId(null)
  258. ->setIsDefaultBilling($this->getRequest()->getParam('default_billing', false))
  259. ->setIsDefaultShipping($this->getRequest()->getParam('default_shipping', false));
  260. $addressForm->compactData($addressData);
  261. $customer->addAddress($address);
  262. $addressErrors = $address->validate();
  263. if (is_array($addressErrors)) {
  264. $errors = array_merge($errors, $addressErrors);
  265. }
  266. } else {
  267. $errors = array_merge($errors, $addressErrors);
  268. }
  269. }
  270. try {
  271. $customerErrors = $customerForm->validateData($customerData);
  272. if ($customerErrors !== true) {
  273. $errors = array_merge($customerErrors, $errors);
  274. } else {
  275. $customerForm->compactData($customerData);
  276. $customer->setPassword($this->getRequest()->getPost('password'));
  277. $customer->setConfirmation($this->getRequest()->getPost('confirmation'));
  278. $customerErrors = $customer->validate();
  279. if (is_array($customerErrors)) {
  280. $errors = array_merge($customerErrors, $errors);
  281. }
  282. }
  283. $validationResult = count($errors) == 0;
  284. if (true === $validationResult) {
  285. $customer->save();
  286. if ($customer->isConfirmationRequired()) {
  287. $customer->sendNewAccountEmail('confirmation', $session->getBeforeAuthUrl());
  288. $session->addSuccess($this->__('Account confirmation is required. Please, check your email for the confirmation link. To resend the confirmation email please <a href="%s">click here</a>.', Mage::helper('customer')->getEmailConfirmationUrl($customer->getEmail())));
  289. $this->_redirectSuccess(Mage::getUrl('*/*/index', array('_secure'=>true)));
  290. return;
  291. } else {
  292. $session->setCustomerAsLoggedIn($customer);
  293. $url = $this->_welcomeCustomer($customer);
  294. $this->_redirectSuccess($url);
  295. return;
  296. }
  297. } else {
  298. $session->setCustomerFormData($this->getRequest()->getPost());
  299. if (is_array($errors)) {
  300. foreach ($errors as $errorMessage) {
  301. $session->addError($errorMessage);
  302. }
  303. } else {
  304. $session->addError($this->__('Invalid customer data'));
  305. }
  306. }
  307. } catch (Mage_Core_Exception $e) {
  308. $session->setCustomerFormData($this->getRequest()->getPost());
  309. if ($e->getCode() === Mage_Customer_Model_Customer::EXCEPTION_EMAIL_EXISTS) {
  310. $url = Mage::getUrl('customer/account/forgotpassword');
  311. $message = $this->__('There is already an account with this email address. If you are sure that it is your email address, <a href="%s">click here</a> to get your password and access your account.', $url);
  312. $session->setEscapeMessages(false);
  313. } else {
  314. $message = $e->getMessage();
  315. }
  316. $session->addError($message);
  317. } catch (Exception $e) {
  318. $session->setCustomerFormData($this->getRequest()->getPost())
  319. ->addException($e, $this->__('Cannot save the customer.'));
  320. }
  321. }
  322. $this->_redirectError(Mage::getUrl('*/*/create', array('_secure' => true)));
  323. }
  324. /**
  325. * Add welcome message and send new account email.
  326. * Returns success URL
  327. *
  328. * @param Mage_Customer_Model_Customer $customer
  329. * @param bool $isJustConfirmed
  330. * @return string
  331. */
  332. protected function _welcomeCustomer(Mage_Customer_Model_Customer $customer, $isJustConfirmed = false)
  333. {
  334. $this->_getSession()->addSuccess(
  335. $this->__('Thank you for registering with %s.', Mage::app()->getStore()->getFrontendName())
  336. );
  337. $customer->sendNewAccountEmail($isJustConfirmed ? 'confirmed' : 'registered');
  338. $successUrl = Mage::getUrl('*/*/index', array('_secure'=>true));
  339. if ($this->_getSession()->getBeforeAuthUrl()) {
  340. $successUrl = $this->_getSession()->getBeforeAuthUrl(true);
  341. }
  342. return $successUrl;
  343. }
  344. /**
  345. * Confirm customer account by id and confirmation key
  346. */
  347. public function confirmAction()
  348. {
  349. if ($this->_getSession()->isLoggedIn()) {
  350. $this->_redirect('*/*/');
  351. return;
  352. }
  353. try {
  354. $id = $this->getRequest()->getParam('id', false);
  355. $key = $this->getRequest()->getParam('key', false);
  356. $backUrl = $this->getRequest()->getParam('back_url', false);
  357. if (empty($id) || empty($key)) {
  358. throw new Exception($this->__('Bad request.'));
  359. }
  360. // load customer by id (try/catch in case if it throws exceptions)
  361. try {
  362. $customer = Mage::getModel('customer/customer')->load($id);
  363. if ((!$customer) || (!$customer->getId())) {
  364. throw new Exception('Failed to load customer by id.');
  365. }
  366. }
  367. catch (Exception $e) {
  368. throw new Exception($this->__('Wrong customer account specified.'));
  369. }
  370. // check if it is inactive
  371. if ($customer->getConfirmation()) {
  372. if ($customer->getConfirmation() !== $key) {
  373. throw new Exception($this->__('Wrong confirmation key.'));
  374. }
  375. // activate customer
  376. try {
  377. $customer->setConfirmation(null);
  378. $customer->save();
  379. }
  380. catch (Exception $e) {
  381. throw new Exception($this->__('Failed to confirm customer account.'));
  382. }
  383. // log in and send greeting email, then die happy
  384. $this->_getSession()->setCustomerAsLoggedIn($customer);
  385. $successUrl = $this->_welcomeCustomer($customer, true);
  386. $this->_redirectSuccess($backUrl ? $backUrl : $successUrl);
  387. return;
  388. }
  389. // die happy
  390. $this->_redirectSuccess(Mage::getUrl('*/*/index', array('_secure'=>true)));
  391. return;
  392. }
  393. catch (Exception $e) {
  394. // die unhappy
  395. $this->_getSession()->addError($e->getMessage());
  396. $this->_redirectError(Mage::getUrl('*/*/index', array('_secure'=>true)));
  397. return;
  398. }
  399. }
  400. /**
  401. * Send confirmation link to specified email
  402. */
  403. public function confirmationAction()
  404. {
  405. $customer = Mage::getModel('customer/customer');
  406. if ($this->_getSession()->isLoggedIn()) {
  407. $this->_redirect('*/*/');
  408. return;
  409. }
  410. // try to confirm by email
  411. $email = $this->getRequest()->getPost('email');
  412. if ($email) {
  413. try {
  414. $customer->setWebsiteId(Mage::app()->getStore()->getWebsiteId())->loadByEmail($email);
  415. if (!$customer->getId()) {
  416. throw new Exception('');
  417. }
  418. if ($customer->getConfirmation()) {
  419. $customer->sendNewAccountEmail('confirmation');
  420. $this->_getSession()->addSuccess($this->__('Please, check your email for confirmation key.'));
  421. } else {
  422. $this->_getSession()->addSuccess($this->__('This email does not require confirmation.'));
  423. }
  424. $this->_getSession()->setUsername($email);
  425. $this->_redirectSuccess(Mage::getUrl('*/*/index', array('_secure' => true)));
  426. } catch (Exception $e) {
  427. $this->_getSession()->addException($e, $this->__('Wrong email.'));
  428. $this->_redirectError(Mage::getUrl('*/*/*', array('email' => $email, '_secure' => true)));
  429. }
  430. return;
  431. }
  432. // output form
  433. $this->loadLayout();
  434. $this->getLayout()->getBlock('accountConfirmation')
  435. ->setEmail($this->getRequest()->getParam('email', $email));
  436. $this->_initLayoutMessages('customer/session');
  437. $this->renderLayout();
  438. }
  439. /**
  440. * Forgot customer password page
  441. */
  442. public function forgotPasswordAction()
  443. {
  444. $this->loadLayout();
  445. $this->getLayout()->getBlock('forgotPassword')->setEmailValue(
  446. $this->_getSession()->getForgottenEmail()
  447. );
  448. $this->_getSession()->unsForgottenEmail();
  449. $this->_initLayoutMessages('customer/session');
  450. $this->renderLayout();
  451. }
  452. /**
  453. * Forgot customer password action
  454. */
  455. public function forgotPasswordPostAction()
  456. {
  457. $email = $this->getRequest()->getPost('email');
  458. if ($email) {
  459. if (!Zend_Validate::is($email, 'EmailAddress')) {
  460. $this->_getSession()->setForgottenEmail($email);
  461. $this->_getSession()->addError($this->__('Invalid email address.'));
  462. $this->getResponse()->setRedirect(Mage::getUrl('*/*/forgotpassword'));
  463. return;
  464. }
  465. $customer = Mage::getModel('customer/customer')
  466. ->setWebsiteId(Mage::app()->getStore()->getWebsiteId())
  467. ->loadByEmail($email);
  468. if ($customer->getId()) {
  469. try {
  470. $newPassword = $customer->generatePassword();
  471. $customer->changePassword($newPassword, false);
  472. $customer->sendPasswordReminderEmail();
  473. $this->_getSession()->addSuccess($this->__('A new password has been sent.'));
  474. $this->getResponse()->setRedirect(Mage::getUrl('*/*'));
  475. return;
  476. }
  477. catch (Exception $e){
  478. $this->_getSession()->addError($e->getMessage());
  479. }
  480. } else {
  481. $this->_getSession()->addError($this->__('This email address was not found in our records.'));
  482. $this->_getSession()->setForgottenEmail($email);
  483. }
  484. } else {
  485. $this->_getSession()->addError($this->__('Please enter your email.'));
  486. $this->getResponse()->setRedirect(Mage::getUrl('*/*/forgotpassword'));
  487. return;
  488. }
  489. $this->getResponse()->setRedirect(Mage::getUrl('*/*/forgotpassword'));
  490. }
  491. /**
  492. * Forgot customer account information page
  493. */
  494. public function editAction()
  495. {
  496. $this->loadLayout();
  497. $this->_initLayoutMessages('customer/session');
  498. $this->_initLayoutMessages('catalog/session');
  499. $block = $this->getLayout()->getBlock('customer_edit');
  500. if ($block) {
  501. $block->setRefererUrl($this->_getRefererUrl());
  502. }
  503. $data = $this->_getSession()->getCustomerFormData(true);
  504. $customer = $this->_getSession()->getCustomer();
  505. if (!empty($data)) {
  506. $customer->addData($data);
  507. }
  508. if ($this->getRequest()->getParam('changepass')==1){
  509. $customer->setChangePassword(1);
  510. }
  511. $this->getLayout()->getBlock('head')->setTitle($this->__('Account Information'));
  512. $this->renderLayout();
  513. }
  514. /**
  515. * Change customer password action
  516. */
  517. public function editPostAction()
  518. {
  519. if (!$this->_validateFormKey()) {
  520. return $this->_redirect('*/*/edit');
  521. }
  522. if ($this->getRequest()->isPost()) {
  523. /** @var $customer Mage_Customer_Model_Customer */
  524. $customer = $this->_getSession()->getCustomer();
  525. /** @var $customerForm Mage_Customer_Model_Form */
  526. $customerForm = Mage::getModel('customer/form');
  527. $customerForm->setFormCode('customer_account_edit')
  528. ->setEntity($customer);
  529. $customerData = $customerForm->extractData($this->getRequest());
  530. $errors = array();
  531. $customerErrors = $customerForm->validateData($customerData);
  532. if ($customerErrors !== true) {
  533. $errors = array_merge($customerErrors, $errors);
  534. } else {
  535. $customerForm->compactData($customerData);
  536. $errors = array();
  537. // If password change was requested then add it to common validation scheme
  538. if ($this->getRequest()->getParam('change_password')) {
  539. $currPass = $this->getRequest()->getPost('current_password');
  540. $newPass = $this->getRequest()->getPost('password');
  541. $confPass = $this->getRequest()->getPost('confirmation');
  542. $oldPass = $this->_getSession()->getCustomer()->getPasswordHash();
  543. if (Mage::helper('core/string')->strpos($oldPass, ':')) {
  544. list($_salt, $salt) = explode(':', $oldPass);
  545. } else {
  546. $salt = false;
  547. }
  548. if ($customer->hashPassword($currPass, $salt) == $oldPass) {
  549. if (strlen($newPass)) {
  550. /**
  551. * Set entered password and its confirmation - they
  552. * will be validated later to match each other and be of right length
  553. */
  554. $customer->setPassword($newPass);
  555. $customer->setConfirmation($confPass);
  556. } else {
  557. $errors[] = $this->__('New password field cannot be empty.');
  558. }
  559. } else {
  560. $errors[] = $this->__('Invalid current password');
  561. }
  562. }
  563. // Validate account and compose list of errors if any
  564. $customerErrors = $customer->validate();
  565. if (is_array($customerErrors)) {
  566. $errors = array_merge($errors, $customerErrors);
  567. }
  568. }
  569. if (!empty($errors)) {
  570. $this->_getSession()->setCustomerFormData($this->getRequest()->getPost());
  571. foreach ($errors as $message) {
  572. $this->_getSession()->addError($message);
  573. }
  574. $this->_redirect('*/*/edit');
  575. return $this;
  576. }
  577. try {
  578. $customer->setConfirmation(null);
  579. $customer->save();
  580. $this->_getSession()->setCustomer($customer)
  581. ->addSuccess($this->__('The account information has been saved.'));
  582. $this->_redirect('customer/account');
  583. return;
  584. } catch (Mage_Core_Exception $e) {
  585. $this->_getSession()->setCustomerFormData($this->getRequest()->getPost())
  586. ->addError($e->getMessage());
  587. } catch (Exception $e) {
  588. $this->_getSession()->setCustomerFormData($this->getRequest()->getPost())
  589. ->addException($e, $this->__('Cannot save the customer.'));
  590. }
  591. }
  592. $this->_redirect('*/*/edit');
  593. }
  594. /**
  595. * Filtering posted data. Converting localized data if needed
  596. *
  597. * @param array
  598. * @return array
  599. */
  600. protected function _filterPostData($data)
  601. {
  602. $data = $this->_filterDates($data, array('dob'));
  603. return $data;
  604. }
  605. }