PageRenderTime 47ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 1ms

/app/code/core/Mage/Customer/Model/Customer.php

https://bitbucket.org/andrewjleavitt/magestudy
PHP | 1151 lines | 687 code | 119 blank | 345 comment | 118 complexity | 17ee90614a36fa794c65711f1181ee37 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 model
  28. *
  29. * @author Magento Core Team <core@magentocommerce.com>
  30. */
  31. class Mage_Customer_Model_Customer extends Mage_Core_Model_Abstract
  32. {
  33. const XML_PATH_REGISTER_EMAIL_TEMPLATE = 'customer/create_account/email_template';
  34. const XML_PATH_REGISTER_EMAIL_IDENTITY = 'customer/create_account/email_identity';
  35. const XML_PATH_FORGOT_EMAIL_TEMPLATE = 'customer/password/forgot_email_template';
  36. const XML_PATH_FORGOT_EMAIL_IDENTITY = 'customer/password/forgot_email_identity';
  37. const XML_PATH_DEFAULT_EMAIL_DOMAIN = 'customer/create_account/email_domain';
  38. const XML_PATH_IS_CONFIRM = 'customer/create_account/confirm';
  39. const XML_PATH_CONFIRM_EMAIL_TEMPLATE = 'customer/create_account/email_confirmation_template';
  40. const XML_PATH_CONFIRMED_EMAIL_TEMPLATE = 'customer/create_account/email_confirmed_template';
  41. const XML_PATH_GENERATE_HUMAN_FRIENDLY_ID = 'customer/create_account/generate_human_friendly_id';
  42. const EXCEPTION_EMAIL_NOT_CONFIRMED = 1;
  43. const EXCEPTION_INVALID_EMAIL_OR_PASSWORD = 2;
  44. const EXCEPTION_EMAIL_EXISTS = 3;
  45. const SUBSCRIBED_YES = 'yes';
  46. const SUBSCRIBED_NO = 'no';
  47. protected $_eventPrefix = 'customer';
  48. protected $_eventObject = 'customer';
  49. protected $_errors = array();
  50. protected $_attributes;
  51. /**
  52. * Customer addresses array
  53. *
  54. * @var array
  55. * @deprecated after 1.4.0.0-rc1
  56. */
  57. protected $_addresses = null;
  58. /**
  59. * Customer addresses collection
  60. *
  61. * @var Mage_Customer_Model_Entity_Address_Collection
  62. */
  63. protected $_addressesCollection;
  64. /**
  65. * Is model deleteable
  66. *
  67. * @var boolean
  68. */
  69. protected $_isDeleteable = true;
  70. /**
  71. * Is model readonly
  72. *
  73. * @var boolean
  74. */
  75. protected $_isReadonly = false;
  76. private static $_isConfirmationRequired;
  77. function _construct()
  78. {
  79. $this->_init('customer/customer');
  80. }
  81. /**
  82. * Retrieve customer sharing configuration model
  83. *
  84. * @return Mage_Customer_Model_Config_Share
  85. */
  86. public function getSharingConfig()
  87. {
  88. return Mage::getSingleton('customer/config_share');
  89. }
  90. /**
  91. * Authenticate customer
  92. *
  93. * @param string $login
  94. * @param string $password
  95. * @return true
  96. * @throws Exception
  97. */
  98. public function authenticate($login, $password)
  99. {
  100. $this->loadByEmail($login);
  101. if ($this->getConfirmation() && $this->isConfirmationRequired()) {
  102. throw Mage::exception('Mage_Core', Mage::helper('customer')->__('This account is not confirmed.'),
  103. self::EXCEPTION_EMAIL_NOT_CONFIRMED
  104. );
  105. }
  106. if (!$this->validatePassword($password)) {
  107. throw Mage::exception('Mage_Core', Mage::helper('customer')->__('Invalid login or password.'),
  108. self::EXCEPTION_INVALID_EMAIL_OR_PASSWORD
  109. );
  110. }
  111. Mage::dispatchEvent('customer_customer_authenticated', array(
  112. 'model' => $this,
  113. 'password' => $password,
  114. ));
  115. return true;
  116. }
  117. /**
  118. * Load customer by email
  119. *
  120. * @param string $customerEmail
  121. * @return Mage_Customer_Model_Customer
  122. */
  123. public function loadByEmail($customerEmail)
  124. {
  125. $this->_getResource()->loadByEmail($this, $customerEmail);
  126. return $this;
  127. }
  128. /**
  129. * Processing object before save data
  130. *
  131. * @return Mage_Core_Model_Abstract
  132. */
  133. protected function _beforeSave()
  134. {
  135. parent::_beforeSave();
  136. $storeId = $this->getStoreId();
  137. if (is_null($storeId)) {
  138. $this->setStoreId(Mage::app()->getStore()->getId());
  139. }
  140. $this->getGroupId();
  141. return $this;
  142. }
  143. /**
  144. * Change customer password
  145. *
  146. * @param string $newPassword
  147. * @return this
  148. */
  149. public function changePassword($newPassword)
  150. {
  151. $this->_getResource()->changePassword($this, $newPassword);
  152. return $this;
  153. }
  154. /**
  155. * Get full customer name
  156. *
  157. * @return string
  158. */
  159. public function getName()
  160. {
  161. $name = '';
  162. $config = Mage::getSingleton('eav/config');
  163. if ($config->getAttribute('customer', 'prefix')->getIsVisible() && $this->getPrefix()) {
  164. $name .= $this->getPrefix() . ' ';
  165. }
  166. $name .= $this->getFirstname();
  167. if ($config->getAttribute('customer', 'middlename')->getIsVisible() && $this->getMiddlename()) {
  168. $name .= ' ' . $this->getMiddlename();
  169. }
  170. $name .= ' ' . $this->getLastname();
  171. if ($config->getAttribute('customer', 'suffix')->getIsVisible() && $this->getSuffix()) {
  172. $name .= ' ' . $this->getSuffix();
  173. }
  174. return $name;
  175. }
  176. /**
  177. * Add address to address collection
  178. *
  179. * @param Mage_Customer_Model_Address $address
  180. * @return Mage_Customer_Model_Customer
  181. */
  182. public function addAddress(Mage_Customer_Model_Address $address)
  183. {
  184. $this->getAddressesCollection()->addItem($address);
  185. $this->getAddresses();
  186. $this->_addresses[] = $address;
  187. return $this;
  188. }
  189. /**
  190. * Retrieve customer address by address id
  191. *
  192. * @param int $addressId
  193. * @return Mage_Customer_Model_Address
  194. */
  195. public function getAddressById($addressId)
  196. {
  197. return Mage::getModel('customer/address')
  198. ->load($addressId);
  199. }
  200. /**
  201. * Getting customer address object from collection by identifier
  202. *
  203. * @param int $addressId
  204. * @return Mage_Customer_Model_Address
  205. */
  206. public function getAddressItemById($addressId)
  207. {
  208. return $this->getAddressesCollection()->getItemById($addressId);
  209. }
  210. /**
  211. * Retrieve not loaded address collection
  212. *
  213. * @return Mage_Customer_Model_Entity_Address_Collection
  214. */
  215. public function getAddressCollection()
  216. {
  217. return Mage::getResourceModel('customer/address_collection');
  218. }
  219. /**
  220. * Customer addresses collection
  221. *
  222. * @return Mage_Customer_Model_Entity_Address_Collection
  223. */
  224. public function getAddressesCollection()
  225. {
  226. if (is_null($this->_addressesCollection)) {
  227. $this->_addressesCollection = $this->getAddressCollection()
  228. ->setCustomerFilter($this)
  229. ->addAttributeToSelect('*');
  230. foreach ($this->_addressesCollection as $address) {
  231. $address->setCustomer($this);
  232. }
  233. }
  234. return $this->_addressesCollection;
  235. }
  236. /**
  237. * Retrieve customer address array
  238. *
  239. * @return array
  240. */
  241. public function getAddresses()
  242. {
  243. $this->_addresses = $this->getAddressesCollection()->getItems();
  244. return $this->_addresses;
  245. }
  246. /**
  247. * Retrieve all customer attributes
  248. *
  249. * @return array
  250. */
  251. public function getAttributes()
  252. {
  253. if (null === $this->_attributes) {
  254. $this->_attributes = $this->_getResource()
  255. ->loadAllAttributes($this)
  256. ->getSortedAttributes();
  257. }
  258. return $this->_attributes;
  259. }
  260. /**
  261. * Get customer attribute model object
  262. *
  263. * @param string $attributeCode
  264. * @return Mage_Customer_Model_Entity_Attribute || null
  265. */
  266. public function getAttribute($attributeCode)
  267. {
  268. $this->getAttributes();
  269. if (isset($this->_attributes[$attributeCode])) {
  270. return $this->_attributes[$attributeCode];
  271. }
  272. return null;
  273. }
  274. /**
  275. * Set plain and hashed password
  276. *
  277. * @param string $password
  278. * @return Mage_Customer_Model_Customer
  279. */
  280. public function setPassword($password)
  281. {
  282. $this->setData('password', $password);
  283. $this->setPasswordHash($this->hashPassword($password));
  284. return $this;
  285. }
  286. /**
  287. * Hash customer password
  288. *
  289. * @param string $password
  290. * @return string
  291. */
  292. public function hashPassword($password, $salt=null)
  293. {
  294. return Mage::helper('core')->getHash($password, !is_null($salt) ? $salt : 2);
  295. }
  296. /**
  297. * Retrieve random password
  298. *
  299. * @param int $length
  300. * @return string
  301. */
  302. public function generatePassword($length=6)
  303. {
  304. return Mage::helper('core')->getRandomString($length);
  305. }
  306. /**
  307. * Validate password with salted hash
  308. *
  309. * @param string $password
  310. * @return boolean
  311. */
  312. public function validatePassword($password)
  313. {
  314. if (!($hash = $this->getPasswordHash())) {
  315. return false;
  316. }
  317. return Mage::helper('core')->validateHash($password, $hash);
  318. }
  319. /**
  320. * Encrypt password
  321. *
  322. * @param string $password
  323. * @return string
  324. */
  325. public function encryptPassword($password)
  326. {
  327. return Mage::helper('core')->encrypt($password);
  328. }
  329. /**
  330. * Decrypt password
  331. *
  332. * @param string $password
  333. * @return string
  334. */
  335. public function decryptPassword($password)
  336. {
  337. return Mage::helper('core')->decrypt($password);
  338. }
  339. /**
  340. * Retrieve default address by type(attribute)
  341. *
  342. * @param string $attributeCode address type attribute code
  343. * @return Mage_Customer_Model_Address
  344. */
  345. public function getPrimaryAddress($attributeCode)
  346. {
  347. $primaryAddress = $this->getAddressesCollection()->getItemById($this->getData($attributeCode));
  348. return $primaryAddress ? $primaryAddress : false;
  349. }
  350. /**
  351. * Get customer default billing address
  352. *
  353. * @return Mage_Customer_Model_Address
  354. */
  355. public function getPrimaryBillingAddress()
  356. {
  357. return $this->getPrimaryAddress('default_billing');
  358. }
  359. /**
  360. * Get customer default billing address
  361. *
  362. * @return Mage_Customer_Model_Address
  363. */
  364. public function getDefaultBillingAddress()
  365. {
  366. return $this->getPrimaryBillingAddress();
  367. }
  368. /**
  369. * Get default customer shipping address
  370. *
  371. * @return Mage_Customer_Model_Address
  372. */
  373. public function getPrimaryShippingAddress()
  374. {
  375. return $this->getPrimaryAddress('default_shipping');
  376. }
  377. /**
  378. * Get default customer shipping address
  379. *
  380. * @return Mage_Customer_Model_Address
  381. */
  382. public function getDefaultShippingAddress()
  383. {
  384. return $this->getPrimaryShippingAddress();
  385. }
  386. /**
  387. * Retrieve ids of default addresses
  388. *
  389. * @return unknown
  390. */
  391. public function getPrimaryAddressIds()
  392. {
  393. $ids = array();
  394. if ($this->getDefaultBilling()) {
  395. $ids[] = $this->getDefaultBilling();
  396. }
  397. if ($this->getDefaultShipping()) {
  398. $ids[] = $this->getDefaultShipping();
  399. }
  400. return $ids;
  401. }
  402. /**
  403. * Retrieve all customer default addresses
  404. *
  405. * @return array
  406. */
  407. public function getPrimaryAddresses()
  408. {
  409. $addresses = array();
  410. $primaryBilling = $this->getPrimaryBillingAddress();
  411. if ($primaryBilling) {
  412. $addresses[] = $primaryBilling;
  413. $primaryBilling->setIsPrimaryBilling(true);
  414. }
  415. $primaryShipping = $this->getPrimaryShippingAddress();
  416. if ($primaryShipping) {
  417. if ($primaryBilling->getId() == $primaryShipping->getId()) {
  418. $primaryBilling->setIsPrimaryShipping(true);
  419. }
  420. else {
  421. $primaryShipping->setIsPrimaryShipping(true);
  422. $addresses[] = $primaryShipping;
  423. }
  424. }
  425. return $addresses;
  426. }
  427. /**
  428. * Retrieve not default addresses
  429. *
  430. * @return array
  431. */
  432. public function getAdditionalAddresses()
  433. {
  434. $addresses = array();
  435. $primatyIds = $this->getPrimaryAddressIds();
  436. foreach ($this->getAddressesCollection() as $address) {
  437. if (!in_array($address->getId(), $primatyIds)) {
  438. $addresses[] = $address;
  439. }
  440. }
  441. return $addresses;
  442. }
  443. public function isAddressPrimary(Mage_Customer_Model_Address $address)
  444. {
  445. if (!$address->getId()) {
  446. return false;
  447. }
  448. return ($address->getId() == $this->getDefaultBilling()) || ($address->getId() == $this->getDefaultShipping());
  449. }
  450. /**
  451. * Send email with new account specific information
  452. *
  453. * @return Mage_Customer_Model_Customer
  454. */
  455. public function sendNewAccountEmail($type = 'registered', $backUrl = '', $storeId = '0')
  456. {
  457. $types = array(
  458. 'registered' => self::XML_PATH_REGISTER_EMAIL_TEMPLATE, // welcome email, when confirmation is disabled
  459. 'confirmed' => self::XML_PATH_CONFIRMED_EMAIL_TEMPLATE, // welcome email, when confirmation is enabled
  460. 'confirmation' => self::XML_PATH_CONFIRM_EMAIL_TEMPLATE, // email with confirmation link
  461. );
  462. if (!isset($types[$type])) {
  463. throw new Exception(Mage::helper('customer')->__('Wrong transactional account email type.'));
  464. }
  465. $translate = Mage::getSingleton('core/translate');
  466. /* @var $translate Mage_Core_Model_Translate */
  467. $translate->setTranslateInline(false);
  468. if (!$storeId) {
  469. $storeId = $this->_getWebsiteStoreId($this->getSendemailStoreId());
  470. }
  471. Mage::getModel('core/email_template')
  472. ->setDesignConfig(array('area'=>'frontend', 'store'=>$storeId))
  473. ->sendTransactional(
  474. Mage::getStoreConfig($types[$type], $storeId),
  475. Mage::getStoreConfig(self::XML_PATH_REGISTER_EMAIL_IDENTITY, $storeId),
  476. $this->getEmail(),
  477. $this->getName(),
  478. array('customer' => $this, 'back_url' => $backUrl));
  479. $translate->setTranslateInline(true);
  480. return $this;
  481. }
  482. /**
  483. * Check if accounts confirmation is required in config
  484. *
  485. * @return bool
  486. */
  487. public function isConfirmationRequired()
  488. {
  489. if ($this->canSkipConfirmation()) {
  490. return false;
  491. }
  492. if (null === self::$_isConfirmationRequired) {
  493. $storeId = $this->getStoreId() ? $this->getStoreId() : null;
  494. self::$_isConfirmationRequired = 1 == Mage::getStoreConfig(self::XML_PATH_IS_CONFIRM, $storeId);
  495. }
  496. return self::$_isConfirmationRequired;
  497. }
  498. public function getRandomConfirmationKey()
  499. {
  500. return md5(uniqid());
  501. }
  502. /**
  503. * Send email with new customer password
  504. *
  505. * @return Mage_Customer_Model_Customer
  506. */
  507. public function sendPasswordReminderEmail()
  508. {
  509. $translate = Mage::getSingleton('core/translate');
  510. /* @var $translate Mage_Core_Model_Translate */
  511. $translate->setTranslateInline(false);
  512. $storeId = $this->getStoreId();
  513. if (!$storeId) {
  514. $storeId = $this->_getWebsiteStoreId();
  515. }
  516. Mage::getModel('core/email_template')
  517. ->setDesignConfig(array('area'=>'frontend', 'store'=>$storeId))
  518. ->sendTransactional(
  519. Mage::getStoreConfig(self::XML_PATH_FORGOT_EMAIL_TEMPLATE, $storeId),
  520. Mage::getStoreConfig(self::XML_PATH_FORGOT_EMAIL_IDENTITY, $storeId),
  521. $this->getEmail(),
  522. $this->getName(),
  523. array('customer'=>$this)
  524. );
  525. $translate->setTranslateInline(true);
  526. return $this;
  527. }
  528. /**
  529. * Retrieve customer group identifier
  530. *
  531. * @return int
  532. */
  533. public function getGroupId()
  534. {
  535. if (!$this->hasData('group_id')) {
  536. $storeId = $this->getStoreId() ? $this->getStoreId() : Mage::app()->getStore()->getId();
  537. $this->setData('group_id', Mage::getStoreConfig(Mage_Customer_Model_Group::XML_PATH_DEFAULT_ID, $storeId));
  538. }
  539. return $this->getData('group_id');
  540. }
  541. /**
  542. * Retrieve customer tax class identifier
  543. *
  544. * @return int
  545. */
  546. public function getTaxClassId()
  547. {
  548. if (!$this->getData('tax_class_id')) {
  549. $this->setTaxClassId(Mage::getModel('customer/group')->getTaxClassId($this->getGroupId()));
  550. }
  551. return $this->getData('tax_class_id');
  552. }
  553. /**
  554. * Check store availability for customer
  555. *
  556. * @param mixed $store
  557. * @return bool
  558. */
  559. public function isInStore($store)
  560. {
  561. if ($store instanceof Mage_Core_Model_Store) {
  562. $storeId = $store->getId();
  563. }
  564. else {
  565. $storeId = $store;
  566. }
  567. $availableStores = $this->getSharedStoreIds();
  568. return in_array($storeId, $availableStores);
  569. }
  570. /**
  571. * Retrieve store where customer was created
  572. *
  573. * @return Mage_Core_Model_Store
  574. */
  575. public function getStore()
  576. {
  577. return Mage::app()->getStore($this->getStoreId());
  578. }
  579. /**
  580. * Retrieve shared store ids
  581. *
  582. * @return array
  583. */
  584. public function getSharedStoreIds()
  585. {
  586. $ids = $this->_getData('shared_store_ids');
  587. if (is_null($ids)) {
  588. $ids = array();
  589. if ((bool)$this->getSharingConfig()->isWebsiteScope()) {
  590. $ids = Mage::app()->getWebsite($this->getWebsiteId())->getStoreIds();
  591. }
  592. else {
  593. foreach (Mage::app()->getStores() as $store) {
  594. $ids[] = $store->getId();
  595. }
  596. }
  597. $this->setData('shared_store_ids', $ids);
  598. }
  599. return $ids;
  600. }
  601. /**
  602. * Retrive shared website ids
  603. *
  604. * @return array
  605. */
  606. public function getSharedWebsiteIds()
  607. {
  608. $ids = $this->_getData('shared_website_ids');
  609. if (is_null($ids)) {
  610. $ids = array();
  611. if ((bool)$this->getSharingConfig()->isWebsiteScope()) {
  612. $ids[] = $this->getWebsiteId();
  613. }
  614. else {
  615. foreach (Mage::app()->getWebsites() as $website) {
  616. $ids[] = $website->getId();
  617. }
  618. }
  619. $this->setData('shared_website_ids', $ids);
  620. }
  621. return $ids;
  622. }
  623. /**
  624. * Enter description here...
  625. *
  626. * @param Mage_Core_Model_Store $store
  627. * @return Mage_Customer_Model_Customer
  628. */
  629. public function setStore(Mage_Core_Model_Store $store)
  630. {
  631. $this->setStoreId($store->getId());
  632. $this->setWebsiteId($store->getWebsite()->getId());
  633. return $this;
  634. }
  635. /**
  636. * Validate customer attribute values.
  637. * For existing customer password + confirmation will be validated only when password is set (i.e. its change is requested)
  638. *
  639. * @return bool
  640. */
  641. public function validate()
  642. {
  643. $errors = array();
  644. $customerHelper = Mage::helper('customer');
  645. if (!Zend_Validate::is( trim($this->getFirstname()) , 'NotEmpty')) {
  646. $errors[] = $customerHelper->__('The first name cannot be empty.');
  647. }
  648. if (!Zend_Validate::is( trim($this->getLastname()) , 'NotEmpty')) {
  649. $errors[] = $customerHelper->__('The last name cannot be empty.');
  650. }
  651. if (!Zend_Validate::is($this->getEmail(), 'EmailAddress')) {
  652. $errors[] = $customerHelper->__('Invalid email address "%s".', $this->getEmail());
  653. }
  654. $password = $this->getPassword();
  655. if (!$this->getId() && !Zend_Validate::is($password , 'NotEmpty')) {
  656. $errors[] = $customerHelper->__('The password cannot be empty.');
  657. }
  658. if (strlen($password) && !Zend_Validate::is($password, 'StringLength', array(6))) {
  659. $errors[] = $customerHelper->__('The minimum password length is %s', 6);
  660. }
  661. $confirmation = $this->getConfirmation();
  662. if ($password != $confirmation) {
  663. $errors[] = $customerHelper->__('Please make sure your passwords match.');
  664. }
  665. $entityType = Mage::getSingleton('eav/config')->getEntityType('customer');
  666. $attribute = Mage::getModel('customer/attribute')->loadByCode($entityType, 'dob');
  667. if ($attribute->getIsRequired() && '' == trim($this->getDob())) {
  668. $errors[] = $customerHelper->__('The Date of Birth is required.');
  669. }
  670. $attribute = Mage::getModel('customer/attribute')->loadByCode($entityType, 'taxvat');
  671. if ($attribute->getIsRequired() && '' == trim($this->getTaxvat())) {
  672. $errors[] = $customerHelper->__('The TAX/VAT number is required.');
  673. }
  674. $attribute = Mage::getModel('customer/attribute')->loadByCode($entityType, 'gender');
  675. if ($attribute->getIsRequired() && '' == trim($this->getGender())) {
  676. $errors[] = $customerHelper->__('Gender is required.');
  677. }
  678. if (empty($errors)) {
  679. return true;
  680. }
  681. return $errors;
  682. }
  683. /**
  684. * Importing customer data from text array
  685. *
  686. * @param array $row
  687. * @return uMage_Customer_Model_Customer
  688. */
  689. public function importFromTextArray(array $row)
  690. {
  691. $this->resetErrors();
  692. $hlp = Mage::helper('customer');
  693. $line = $row['i'];
  694. $row = $row['row'];
  695. $regions = Mage::getResourceModel('directory/region_collection');
  696. // $config = Mage::getSingleton('eav/config')->getEntityType('customer');
  697. $website = Mage::getModel('core/website')->load($row['website_code'], 'code');
  698. if (!$website->getId()) {
  699. $this->addError($hlp->__('Invalid website, skipping the record, line: %s.', $line));
  700. } else {
  701. $row['website_id'] = $website->getWebsiteId();
  702. $this->setWebsiteId($row['website_id']);
  703. }
  704. // Validate Email
  705. if (empty($row['email'])) {
  706. $this->addError($hlp->__('Missing email, skipping the record, line: %s.', $line));
  707. } else {
  708. $this->loadByEmail($row['email']);
  709. }
  710. if (empty($row['entity_id'])) {
  711. if ($this->getData('entity_id')) {
  712. $this->addError($hlp->__('The customer email (%s) already exists, skipping the record, line: %s.', $row['email'], $line));
  713. }
  714. } else {
  715. if ($row['entity_id'] != $this->getData('entity_id')) {
  716. $this->addError($hlp->__('The customer ID and email did not match, skipping the record, line: %s.', $line));
  717. } else {
  718. $this->unsetData();
  719. $this->load($row['entity_id']);
  720. if (isset($row['store_view'])) {
  721. $storeId = Mage::app()->getStore($row['store_view'])->getId();
  722. if ($storeId) $this->setStoreId($storeId);
  723. }
  724. }
  725. }
  726. if (empty($row['website_code'])) {
  727. $this->addError($hlp->__('Missing website, skipping the record, line: %s.', $line));
  728. }
  729. if (empty($row['group'])) {
  730. $row['group'] = 'General';
  731. }
  732. if (empty($row['firstname'])) {
  733. $this->addError($hlp->__('Missing first name, skipping the record, line: %s.', $line));
  734. }
  735. if (empty($row['lastname'])) {
  736. $this->addError($hlp->__('Missing last name, skipping the record, line: %s.', $line));
  737. }
  738. if (!empty($row['password_new'])) {
  739. $this->setPassword($row['password_new']);
  740. unset($row['password_new']);
  741. if (!empty($row['password_hash'])) unset($row['password_hash']);
  742. }
  743. if ($errors = $this->getErrors()) {
  744. $this->unsetData();
  745. $this->printError(join("<br />",$errors));
  746. return;
  747. }
  748. // $entity = $this->getResource();
  749. foreach ($row as $field=>$value) {
  750. // $attribute = $entity->getAttribute($field);
  751. // if (!$attribute) {
  752. // echo $field;
  753. // continue;
  754. // }
  755. // if ($attribute->usesSource()) {
  756. // $source = $attribute->getSource();
  757. // $optionId = $config->getSourceOptionId($source, $value);
  758. // if (is_null($optionId)) {
  759. // $this->printError($hlp->__("Invalid attribute option specified for attribute attribute %s (%s).", $field, $value), $line);
  760. // }
  761. // $value = $optionId;
  762. // }
  763. $this->setData($field, $value);
  764. }
  765. if (!$this->validateAddress($row, 'billing')) {
  766. $this->printError($hlp->__('Invalid billing address for (%s).', $row['email']), $line);
  767. } else {
  768. // Handling billing address
  769. $billingAddress = $this->getPrimaryBillingAddress();
  770. if (!$billingAddress instanceof Mage_Customer_Model_Address) {
  771. $billingAddress = Mage::getModel('customer/address');
  772. }
  773. $regions->addRegionNameFilter($row['billing_region'])->load();
  774. if ($regions) foreach($regions as $region) {
  775. $regionId = $region->getId();
  776. }
  777. $billingAddress->setFirstname($row['firstname']);
  778. $billingAddress->setLastname($row['lastname']);
  779. $billingAddress->setCity($row['billing_city']);
  780. $billingAddress->setRegion($row['billing_region']);
  781. if (isset($regionId)) $billingAddress->setRegionId($regionId);
  782. $billingAddress->setCountryId($row['billing_country']);
  783. $billingAddress->setPostcode($row['billing_postcode']);
  784. if (isset($row['billing_street2'])) {
  785. $billingAddress->setStreet(array($row['billing_street1'],$row['billing_street2']));
  786. } else {
  787. $billingAddress->setStreet(array($row['billing_street1']));
  788. }
  789. if (isset($row['billing_telephone'])) {
  790. $billingAddress->setTelephone($row['billing_telephone']);
  791. }
  792. if (!$billingAddress->getId()) {
  793. $billingAddress->setIsDefaultBilling(true);
  794. if ($this->getDefaultBilling()) {
  795. $this->setData('default_billing', '');
  796. }
  797. $this->addAddress($billingAddress);
  798. } // End handling billing address
  799. }
  800. if (!$this->validateAddress($row, 'shipping')) {
  801. $this->printError($hlp->__('Invalid shipping address for (%s).', $row['email']), $line);
  802. } else {
  803. // Handling shipping address
  804. $shippingAddress = $this->getPrimaryShippingAddress();
  805. if (!$shippingAddress instanceof Mage_Customer_Model_Address) {
  806. $shippingAddress = Mage::getModel('customer/address');
  807. }
  808. $regions->addRegionNameFilter($row['shipping_region'])->load();
  809. if ($regions) foreach($regions as $region) {
  810. $regionId = $region->getId();
  811. }
  812. $shippingAddress->setFirstname($row['firstname']);
  813. $shippingAddress->setLastname($row['lastname']);
  814. $shippingAddress->setCity($row['shipping_city']);
  815. $shippingAddress->setRegion($row['shipping_region']);
  816. if (isset($regionId)) $shippingAddress->setRegionId($regionId);
  817. $shippingAddress->setCountryId($row['shipping_country']);
  818. $shippingAddress->setPostcode($row['shipping_postcode']);
  819. if (isset($row['shipping_street2'])) {
  820. $shippingAddress->setStreet(array($row['shipping_street1'], $row['shipping_street2']));
  821. } else {
  822. $shippingAddress->setStreet(array($row['shipping_street1']));
  823. }
  824. if (!empty($row['shipping_telephone'])) {
  825. $shippingAddress->setTelephone($row['shipping_telephone']);
  826. }
  827. if (!$shippingAddress->getId()) {
  828. $shippingAddress->setIsDefaultShipping(true);
  829. $this->addAddress($shippingAddress);
  830. }
  831. // End handling shipping address
  832. }
  833. if (!empty($row['is_subscribed'])) {
  834. $this->setIsSubscribed(strtolower($row['is_subscribed'])==self::SUBSCRIBED_YES ? 1 : 0);
  835. }
  836. unset($row);
  837. return $this;
  838. }
  839. function unsetSubscription()
  840. {
  841. if (isset($this->_isSubscribed)) {
  842. unset($this->_isSubscribed);
  843. }
  844. }
  845. function cleanAllAddresses() {
  846. $this->_addressesCollection = null;
  847. $this->_addresses = null;
  848. }
  849. function addError($error)
  850. {
  851. $this->_errors[] = $error;
  852. }
  853. function getErrors()
  854. {
  855. return $this->_errors;
  856. }
  857. function resetErrors()
  858. {
  859. $this->_errors = array();
  860. }
  861. function printError($error, $line = null)
  862. {
  863. if ($error == null) return false;
  864. $img = 'error_msg_icon.gif';
  865. $liStyle = 'background-color:#FDD; ';
  866. echo '<li style="'.$liStyle.'">';
  867. echo '<img src="'.Mage::getDesign()->getSkinUrl('images/'.$img).'" class="v-middle"/>';
  868. echo $error;
  869. if ($line) {
  870. echo '<small>, Line: <b>'.$line.'</b></small>';
  871. }
  872. echo "</li>";
  873. }
  874. function validateAddress(array $data, $type = 'billing')
  875. {
  876. $fields = array('city',
  877. 'country', 'postcode',
  878. 'telephone', 'street1');
  879. $usca = array('US', 'CA');
  880. $prefix = $type ? $type.'_':'';
  881. if ($data) {
  882. foreach($fields as $field) {
  883. if (!isset($data[$prefix.$field])) {
  884. return false;
  885. }
  886. if ($field == 'country'
  887. && in_array(strtolower($data[$prefix.$field]), array('US', 'CA'))) {
  888. if (!isset($data[$prefix.'region'])) {
  889. return false;
  890. }
  891. $region = Mage::getModel('directory/region')
  892. ->loadByName($data[$prefix.'region']);
  893. if (!$region->getId()) {
  894. return false;
  895. }
  896. unset($region);
  897. }
  898. }
  899. unset($data);
  900. return true;
  901. }
  902. return false;
  903. }
  904. protected function _beforeDelete()
  905. {
  906. $this->_protectFromNonAdmin();
  907. return parent::_beforeDelete();
  908. }
  909. /**
  910. * Get customer created at date timestamp
  911. *
  912. * @return int
  913. */
  914. public function getCreatedAtTimestamp()
  915. {
  916. if ($date = $this->getCreatedAt()) {
  917. return $this->_getResource()->mktime($date);
  918. }
  919. return null;
  920. }
  921. /**
  922. * Reset all model data
  923. *
  924. * @return Mage_Customer_Model_Customer
  925. */
  926. public function reset()
  927. {
  928. $this->setData(array());
  929. $this->setOrigData();
  930. $this->_attributes = null;
  931. return $this;
  932. }
  933. /**
  934. * Checks model is deleteable
  935. *
  936. * @return boolean
  937. */
  938. public function isDeleteable()
  939. {
  940. return $this->_isDeleteable;
  941. }
  942. /**
  943. * Set is deleteable flag
  944. *
  945. * @param boolean $value
  946. * @return Mage_Customer_Model_Customer
  947. */
  948. public function setIsDeleteable($value)
  949. {
  950. $this->_isDeleteable = (boolean) $value;
  951. return $this;
  952. }
  953. /**
  954. * Checks model is readonly
  955. *
  956. * @return boolean
  957. */
  958. public function isReadonly()
  959. {
  960. return $this->_isReadonly;
  961. }
  962. /**
  963. * Set is readonly flag
  964. *
  965. * @param boolean $value
  966. * @return Mage_Customer_Model_Customer
  967. */
  968. public function setIsReadonly($value)
  969. {
  970. $this->_isReadonly = (boolean) $value;
  971. return $this;
  972. }
  973. /**
  974. * Check whether confirmation may be skipped when registering using certain email address
  975. *
  976. * @return bool
  977. */
  978. public function canSkipConfirmation()
  979. {
  980. return $this->getId() && $this->hasSkipConfirmationIfEmail()
  981. && strtolower($this->getSkipConfirmationIfEmail()) === strtolower($this->getEmail());
  982. }
  983. public function __clone()
  984. {
  985. $newAddressCollection = $this->getPrimaryAddresses();
  986. $newAddressCollection = array_merge($newAddressCollection, $this->getAdditionalAddresses());
  987. $this->setId(null);
  988. $this->cleanAllAddresses();
  989. foreach ($newAddressCollection as $address) {
  990. $this->addAddress(clone $address);
  991. }
  992. }
  993. /**
  994. * Return Entity Type instance
  995. *
  996. * @return Mage_Eav_Model_Entity_Type
  997. */
  998. public function getEntityType()
  999. {
  1000. return $this->_getResource()->getEntityType();
  1001. }
  1002. /**
  1003. * Return Entity Type ID
  1004. *
  1005. * @return int
  1006. */
  1007. public function getEntityTypeId()
  1008. {
  1009. $entityTypeId = $this->getData('entity_type_id');
  1010. if (!$entityTypeId) {
  1011. $entityTypeId = $this->getEntityType()->getId();
  1012. $this->setData('entity_type_id', $entityTypeId);
  1013. }
  1014. return $entityTypeId;
  1015. }
  1016. /**
  1017. * Get either first store ID from a set website or the provided as default
  1018. *
  1019. * @param int|string|null $storeId
  1020. *
  1021. * @return int
  1022. */
  1023. protected function _getWebsiteStoreId($defaultStoreId = null)
  1024. {
  1025. if ($this->getWebsiteId() != 0 && empty($defaultStoreId)) {
  1026. $storeIds = Mage::app()->getWebsite($this->getWebsiteId())->getStoreIds();
  1027. reset($storeIds);
  1028. $defaultStoreId = current($storeIds);
  1029. }
  1030. return $defaultStoreId;
  1031. }
  1032. }