Advertisement
Guest User

test

a guest
Nov 7th, 2016
809
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 262.38 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4. * @package Core.Client
  5. * @author michal
  6. * @access public
  7. */
  8. class Client_Actions extends Controllers_ClientBase {
  9. /* Basket */
  10.  
  11. const SMS_ORDER_TEXT = 'New order no. %d. Total: %s. Products: %s. User: %s.';
  12. const DEFAULT_BASKET_QUANTITY = 1;
  13.  
  14. private $_shipping_id;
  15. private $_payment_id;
  16. private $_shipping_country;
  17.  
  18. /* Panel */
  19.  
  20. const ORDERS_LIMIT = 5;
  21.  
  22. /**
  23. * abstract methods that are not executed on $this but on $instance,
  24. * here they can be empty
  25. */
  26. protected function _handleFlashMessages($viewVariable = 'flash_messages') {
  27.  
  28. }
  29.  
  30. protected function actionsHelper() {
  31.  
  32. }
  33.  
  34. protected function addCachedVariables() {
  35.  
  36. }
  37.  
  38. protected function storeForRedirect($name, $var) {
  39.  
  40. }
  41.  
  42. private static function googleString($string) {
  43. if (0 == strlen($string))
  44. return '';
  45.  
  46. $string = preg_replace('/\s+/', ' ', $string);
  47. $array = explode(' ', $string);
  48. foreach ($array as $k => $v)
  49. $array[$k] = rawurlencode($v);
  50. $string = implode(',', $array);
  51.  
  52. return 'url=' . $string;
  53. }
  54.  
  55. /**
  56. * BasketController
  57. */
  58. public function Basket_indexAction($instance) {
  59. $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
  60. $session = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_SESSION);
  61.  
  62. if (false === Zend_Registry::get('enable_basket')) {
  63. $instance->_flashMessanger->addWarning(Locale_Manager::translate('Cart is disabled.'));
  64. $instance->_redirect($router->assemble(array(), 'index'));
  65. return;
  66. }
  67.  
  68. if (Zend_Registry::isRegistered(System_Bootstrap::REGISTRY_FACEBOOK) && isset($_GET['error_reason'][0]) && 'user_denied' == $_GET['error_reason']) {
  69. $instance->_flashMessanger->addWarning(Locale_Manager::translate('You cannot continue with this order without granting the application appropriate permissions.'));
  70. $instance->_redirect($router->assemble(array(), 'index'));
  71. return;
  72. }
  73.  
  74. $instance->_breadCrumbs->add(Locale_Manager::translate('Cart'), '');
  75.  
  76. $user = Logic_UserOnline::getUser();
  77.  
  78. if (is_int($session->shipping_id)) {
  79. $this->_shipping_id = $session->shipping_id;
  80. }
  81. if (is_int($session->payment_id)) {
  82. $this->_payment_id = $session->payment_id;
  83. }
  84.  
  85. if (is_string($session->shipping_country)) {
  86. $this->_shipping_country = $session->shipping_country;
  87. } else if ($user->user && $user->user->shippingAddress) {
  88. $this->_shipping_country = $user->user->shippingAddress->address->country_code;
  89. }
  90.  
  91. $recount = false;
  92. if ($instance->getRequest()->isPost() && isset($_POST['recount'][0]) && '1' === $_POST['recount']) {
  93. $recount = true;
  94. }
  95. $instance->view->recount = $recount;
  96.  
  97. if (false == $recount && $instance->_hasParam('recount') && 1 == (int) $instance->_getParam('recount')) {
  98. $this->Basket_checkQuantity($instance);
  99. }
  100.  
  101. if (count($user->basket) && $recount) {
  102. if (false == $this->Basket_recount($instance)) {
  103. $this->Basket_processBasket($instance);
  104. } else {
  105. if (isset($_POST['button1'][0])) {
  106.  
  107. if (is_string($session->last_product_page)) {
  108. if (preg_match('/^https?\:\/\/' . preg_quote($_SERVER['HTTP_HOST']) . '/i', $session->last_product_page))
  109. $url = $session->last_product_page;
  110. else
  111. $url = $router->assemble(array(), 'index');
  112. } else
  113. $url = $router->assemble(array(), 'index');
  114.  
  115. $instance->_redirect($url);
  116. return;
  117. } else if (isset($_POST['button2'][0])) {
  118.  
  119. if (true == $this->Basket_processBasket($instance, true)) {
  120. $session->shipping_id = $this->_shipping_id;
  121. $session->shipping_country = $this->_shipping_country;
  122. $session->payment_id = $this->_payment_id;
  123. $instance->_redirect($router->assemble(array(), 'basketStep2'));
  124. return;
  125. }
  126. } else {
  127. $this->Basket_processBasket($instance);
  128. }
  129. }
  130. } else {
  131. $quantity = array();
  132.  
  133. foreach ($user->basket as $basket_product) {
  134. $quantity[(int) $basket_product->getIdentifier()] = (float) $basket_product->basket->quantity;
  135. }
  136.  
  137. $instance->view->quantity = $quantity;
  138. $instance->view->quantity_error = array();
  139. $this->Basket_processBasket($instance);
  140. }
  141.  
  142. $instance->view->shipping_id = $this->_shipping_id;
  143. $instance->view->payment_id = $this->_payment_id;
  144. $instance->view->shipping_country = $this->_shipping_country;
  145. $instance->view->sum = $this->Basket_getSum();
  146. $instance->view->sum_noship = View_Smarty_Helper_Currency::currency(array(
  147. 'value' => $this->Basket_getSum(false),
  148. 'float' => true,
  149. ), null);
  150. $instance->view->currencymap = Locale_Manager::getCurrency()->toCurrency(1234.56);
  151. $instance->view->showpromocodes = (int) Config_Manager::getConfigValue('shopping', 'USE_PROMO_CODES');
  152. $instance->view->country = Config_Manager::getConfigValue('company', 'COUNTRY');
  153.  
  154. if (Loyalty_Program::orderGivesPoints()) {
  155. $points = $user->basket->loyaltyPointsForOrder();
  156. if ($points > 0) {
  157. $this->view->loyalty_points = View_Smarty_Helper_Float::float(array('value' => $points, 'precision' => 0), null);
  158. } else {
  159. $this->view->loyalty_points = false;
  160. }
  161. } else {
  162. $this->view->loyalty_points = false;
  163. }
  164.  
  165. foreach ($user->basket as $basket_product) {
  166. if ($basket_product->stock->stock->delivery_id) {
  167. $instance->view->showDelivery = true;
  168. }
  169. }
  170.  
  171. $instance->view->body_class = 'shop_basket';
  172. $instance->_handleFlashMessages();
  173. }
  174.  
  175. public function Basket_step2Action($instance) {
  176. $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
  177. $user = Logic_UserOnline::getUser();
  178.  
  179. if (false === Zend_Registry::get('enable_basket')) {
  180. $instance->_flashMessanger->addWarning(Locale_Manager::translate('Cart is disabled.'));
  181. $instance->_redirect($router->assemble(array(), 'index'));
  182. return;
  183. }
  184.  
  185. if (0 == count($user->basket)) {
  186. $instance->_redirect($router->assemble(array(), 'basket'));
  187. return;
  188. }
  189.  
  190. $instance->_breadCrumbs->add(Locale_Manager::translate('Cart'), $router->assemble(array(), 'basket'));
  191. $instance->_breadCrumbs->add(Locale_Manager::translate('Your details'), '');
  192.  
  193. if (Access_ClientManager::isLoggedIn()) {
  194. $instance->_forward('address', null, null, array('mode' => 'user'));
  195. return;
  196. }
  197.  
  198. if ($instance->getRequest()->isPost() && isset($_POST['loginform'][0])) {
  199. $form = new Form_Shop_Login();
  200. if ($form->isValid($_POST)) {
  201. $val = $form->getValues();
  202. $result = Access_ClientManager::authenticate($val['mail'], $val['pass']);
  203.  
  204. if ($result->isValid()) {
  205. if (Zend_Registry::isRegistered('user_login_product_recovery')) {
  206. $moved = (int) Zend_Registry::get('user_login_product_recovery');
  207. if ($moved > 0) {
  208. if ($moved > 1) {
  209. $instance->_flashMessanger->addInfo(Locale_Manager::translate('Products have been restored to your shopping cart from the previous session.', $moved));
  210. } else {
  211. $instance->_flashMessanger->addInfo(Locale_Manager::translate('Product has been restored to your shopping cart from the previous session.', $moved));
  212. }
  213. $instance->_redirect($router->assemble(array(), 'basket'));
  214. return;
  215. }
  216. }
  217. $instance->_forward('address', null, null, array('mode' => 'user'));
  218. return;
  219. } else {
  220. switch ($result->getCode()) {
  221. case Access_Auth_Result::FAILURE_USER_INACTIVE:
  222. $instance->_flashMessanger->addError(Locale_Manager::translate('Inactive account.'));
  223. break;
  224. case Access_Auth_Result::FAILURE_USER_NOT_VERIFIED:
  225. $instance->_flashMessanger->addError(Locale_Manager::translate('Your registration has not been confirmed. Check your e-mail and click the confirmation link.'));
  226. break;
  227. default:
  228. $instance->_flashMessanger->addError(Locale_Manager::translate('Incorrect login details'));
  229. break;
  230. }
  231. }
  232. } else {
  233. $instance->_flashMessanger->addError(Locale_Manager::translate('Incorrect login details'));
  234. Access_ClientManager::logout();
  235. }
  236. } elseif ($instance->getRequest()->isPost() && isset($_POST['addressform'][0])) {
  237. $instance->_forward('address', null, null, array('mode' => $_POST['addressform']));
  238. return;
  239. } elseif ($instance->getRequest()->isPost() && 0 == count($_POST) && 0 == count($_FILES) && 0 === strpos($_SERVER['HTTP_CONTENT_TYPE'], 'multipart/form-data')) {
  240.  
  241. $msg = Locale_Manager::translate('Invalid request. The file size limit has probably been exceeded. The size limit is %dMB.', Form_AdditionalFields::FILE_UPLOAD_LIMIT
  242. );
  243. $instance->_flashMessanger->addError($msg);
  244. }
  245.  
  246. $instance->view->allow_single = ( 1 == (int) Config_Manager::getConfigValue('shopping', 'ALLOW_TO_BUY_NOT_REG') );
  247. $instance->view->loyalty_order_gives_points = Loyalty_Program::orderGivesPoints();
  248. $instance->view->country = Config_Manager::getConfigValue('company', 'COUNTRY');
  249.  
  250. $instance->view->body_class = 'shop_basket_step2';
  251. $instance->_handleFlashMessages();
  252. }
  253.  
  254. public function Basket_addressAction($instance) {
  255. $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
  256. $session = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_SESSION);
  257. $user = Logic_UserOnline::getUser();
  258.  
  259. if (false === Zend_Registry::get('enable_basket')) {
  260. $instance->_flashMessanger->addWarning(Locale_Manager::translate('Cart is disabled.'));
  261. $instance->_redirect($router->assemble(array(), 'index'));
  262. return;
  263. }
  264.  
  265. $mode = $instance->_getParam('mode');
  266. if (!in_array($mode, array('user', 'register', 'single')) || 0 == count($user->basket)) {
  267. $instance->_redirect($router->assemble(array(), 'basket'));
  268. return;
  269. }
  270.  
  271. if ($mode === 'register' && !Zend_Registry::get('enable_register')) {
  272. $instance->_flashMessanger->addWarning(Locale_Manager::translate('Registration is temporarily unavailable'));
  273. $instance->_redirect(Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER)->assemble(array(), 'index'));
  274. return;
  275. }
  276.  
  277. if ('single' == $mode && 1 != (int) Config_Manager::getConfigValue('shopping', 'ALLOW_TO_BUY_NOT_REG')) {
  278. $instance->_flashMessanger->addWarning(Locale_Manager::translate('Purchase cannot be made without registration.'));
  279. $instance->_redirect($router->assemble(array(), 'basketStep2'));
  280. return;
  281. }
  282.  
  283. $table1 = array(
  284. 'name' => array(
  285. 'name' => 'name',
  286. 'obligatory' => true,
  287. 'label' => Locale_Manager::translate('First name'),
  288. 'type' => 'text',
  289. 'hint' => '',
  290. 'value' => '',
  291. 'rowspan' => 1,
  292. ),
  293. 'surname' => array(
  294. 'name' => 'surname',
  295. 'obligatory' => true,
  296. 'label' => Locale_Manager::translate('Last name'),
  297. 'type' => 'text',
  298. 'rowspan' => 1,
  299. ),
  300. 'phone' => array(
  301. 'name' => 'phone',
  302. 'obligatory' => true,
  303. 'label' => Locale_Manager::translate('Phone'),
  304. 'type' => 'text',
  305. 'hint' => Locale_Manager::translate('Number format, e.g.: 123456789'),
  306. 'rowspan' => 1,
  307. ),
  308. 'mail' => array(
  309. 'name' => 'mail',
  310. 'obligatory' => true,
  311. 'label' => Locale_Manager::translate('E-mail'),
  312. 'type' => 'text',
  313. 'rowspan' => 1,
  314. ),
  315. );
  316.  
  317. if ('register' == $mode) {
  318. $table1['pass1'] = array(
  319. 'name' => 'pass1',
  320. 'obligatory' => true,
  321. 'label' => Locale_Manager::translate('Password'),
  322. 'type' => 'password',
  323. 'hint' => Locale_Manager::translate('Minimum of 6 characters'),
  324. 'rowspan' => 1,
  325. );
  326. $table1['pass2'] = array(
  327. 'name' => 'pass2',
  328. 'obligatory' => true,
  329. 'label' => Locale_Manager::translate('Repeat password'),
  330. 'type' => 'password',
  331. 'rowspan' => 1,
  332. );
  333. }
  334.  
  335.  
  336.  
  337.  
  338. $table2 = array(
  339. 'coname' => array(
  340. 'name' => 'coname',
  341. 'obligatory' => true,
  342. 'label' => Locale_Manager::translate('Company name'),
  343. 'type' => 'text',
  344. 'rowspan' => 1,
  345. ),
  346. 'nip' => array(
  347. 'name' => 'nip',
  348. 'obligatory' => true,
  349. 'label' => Locale_Manager::translate('Tax ID'),
  350. 'type' => 'text',
  351. 'rowspan' => 1,
  352. ),
  353. 'pesel' => array(
  354. 'name' => 'pesel',
  355. 'label' => Locale_Manager::translate('Personal Identification Number'),
  356. 'type' => 'text',
  357. 'rowspan' => 1,
  358. ),
  359. 'other_address' => array(
  360. 'name' => 'other_address',
  361. 'obligatory' => true,
  362. 'label' => Locale_Manager::translate('Street and house no.'),
  363. 'type' => 'text',
  364. 'hint' => Locale_Manager::translate('For example: 115 Oxford Street'),
  365. 'rowspan' => 1,
  366. ),
  367. 'zip' => array(
  368. 'name' => 'zip',
  369. 'obligatory' => true,
  370. 'label' => Locale_Manager::translate('Postal code'),
  371. 'type' => 'text',
  372. 'hint' => Locale_Manager::translate('Postal code format'),
  373. 'rowspan' => 1,
  374. ),
  375. 'city' => array(
  376. 'name' => 'city',
  377. 'obligatory' => true,
  378. 'label' => Locale_Manager::translate('City'),
  379. 'type' => 'text',
  380. 'rowspan' => 1,
  381. ),
  382. 'country' => array(
  383. 'name' => 'country',
  384. 'obligatory' => false,
  385. 'label' => Locale_Manager::translate('Country'),
  386. 'type' => 'select',
  387. 'list' => Locale_Manager::getCountries(),
  388. 'rowspan' => 1,
  389. ),
  390. );
  391.  
  392.  
  393.  
  394.  
  395. $table3 = array(
  396. 'name2' => array(
  397. 'name' => 'name2',
  398. 'obligatory' => true,
  399. 'label' => Locale_Manager::translate('First name'),
  400. 'type' => 'text',
  401. 'rowspan' => 1,
  402. ),
  403. 'surname2' => array(
  404. 'name' => 'surname2',
  405. 'obligatory' => true,
  406. 'label' => Locale_Manager::translate('Last name'),
  407. 'type' => 'text',
  408. 'rowspan' => 1,
  409. ),
  410. 'phone2' => array(
  411. 'name' => 'phone2',
  412. 'obligatory' => true,
  413. 'label' => Locale_Manager::translate('Phone'),
  414. 'type' => 'text',
  415. 'hint' => Locale_Manager::translate('Number format, e.g.: 123456789'),
  416. 'rowspan' => 1,
  417. ),
  418. 'coname2' => array(
  419. 'name' => 'coname2',
  420. 'label' => Locale_Manager::translate('Company name'),
  421. 'type' => 'text',
  422. 'rowspan' => 1,
  423. ),
  424. 'other_address2' => array(
  425. 'name' => 'other_address2',
  426. 'obligatory' => true,
  427. 'label' => Locale_Manager::translate('Street and house no.'),
  428. 'type' => 'text',
  429. 'hint' => Locale_Manager::translate('For example: 115 Oxford Street'),
  430. 'rowspan' => 1,
  431. ),
  432. 'zip2' => array(
  433. 'name' => 'zip2',
  434. 'obligatory' => true,
  435. 'label' => Locale_Manager::translate('Postal code'),
  436. 'type' => 'text',
  437. 'hint' => Locale_Manager::translate('Postal code format'),
  438. 'rowspan' => 1,
  439. ),
  440. 'city2' => array(
  441. 'name' => 'city2',
  442. 'obligatory' => true,
  443. 'label' => Locale_Manager::translate('City'),
  444. 'type' => 'text',
  445. 'rowspan' => 1,
  446. ),
  447. 'country2' => array(
  448. 'name' => 'country2',
  449. 'obligatory' => false,
  450. 'label' => Locale_Manager::translate('Country'),
  451. 'type' => 'select',
  452. 'list' => $this->Basket_shippingCountries(),
  453. 'rowspan' => 1,
  454. ),
  455. );
  456.  
  457. $address_assign = array(
  458. 'name' => 'firstname',
  459. 'surname' => 'lastname',
  460. 'phone' => 'phone',
  461. 'coname' => 'company_name',
  462. 'nip' => 'tax_id',
  463. 'pesel' => 'pesel',
  464. 'other_address' => 'street_1',
  465. 'zip' => 'zip_code',
  466. 'city' => 'city',
  467. 'country' => 'country_code',
  468. );
  469.  
  470. if (Zend_Registry::isRegistered(System_Bootstrap::REGISTRY_MOBILE)) {
  471. $f = Zend_Registry::get(System_Bootstrap::REGISTRY_MOBILE);
  472. if ($f) {
  473. unset($table2['coname']['obligatory']);
  474. unset($table2['nip']['obligatory']);
  475. }
  476. }
  477.  
  478. $pesel = (1 == (int) Config_Manager::getConfigValue('shopping', 'SUPPORT_PESEL'));
  479. if (false === $pesel && isset($table2['pesel'])) {
  480. unset($table2['pesel']);
  481. unset($address_assign['pesel']);
  482. }
  483.  
  484. $country2shipping = array_keys($this->Basket_shippingCountries());
  485. $instance->view->country2shipping = Zend_Json::encode($country2shipping);
  486.  
  487. if ('single' == $mode || 'user' == $mode) {
  488. if ($mode == 'single') {
  489. $locate = Logic_AdditionalField::LOCATE_ORDER_WITHOUT_REGISTRATION;
  490. } else {
  491. $locate = Logic_AdditionalField::LOCATE_ORDER_LOGGED_ON_USER;
  492. }
  493. $fields = Logic_AdditionalField::getByLocate($locate, Locale_Manager::getLanguageId());
  494. } else { //register
  495. $locates = array(
  496. Logic_AdditionalField::LOCATE_USER_REGISTRATION,
  497. Logic_AdditionalField::LOCATE_ORDER_WITH_REGISTRATION
  498. );
  499.  
  500. $fields = Logic_AdditionalField::getByLocates($locates, Locale_Manager::getLanguageId());
  501. }
  502.  
  503. if ($instance->getRequest()->isPost() && isset($_POST['addressform'][0])) {
  504. $required = true;
  505.  
  506. if (isset($_POST['button1'][0])) {
  507. if ('user' == $mode && is_object($user->user))
  508. $instance->_redirect($router->assemble(array(), 'basket'));
  509. else
  510. $instance->_redirect($router->assemble(array(), 'basketStep2'));
  511. return;
  512. }
  513.  
  514. if ($user->user && ( isset($_POST['address_submit'][0]) || isset($_POST['address_submit2'][0]) )) {
  515. $n = isset($_POST['address_submit'][0]) ? '' : '2';
  516. $id = (int) $_POST['address' . $n];
  517.  
  518. $address = null;
  519. foreach ($user->user->addresses as $a)
  520. if ($id == (int) $a->getIdentifier())
  521. $address = $a;
  522.  
  523. if (is_object($address)) {
  524. $required = false;
  525. foreach ($address_assign as $k => $v)
  526. $_POST[$k . $n] = $address->address->$v;
  527. }
  528. }
  529.  
  530. foreach (array('phone', 'phone2') as $key) {
  531. if (isset($_POST[$key][0])) {
  532. if ('+' == $_POST[$key][0])
  533. $_POST[$key] = '00' . substr($_POST[$key], 1);
  534. $_POST[$key] = preg_replace('/[\.\s\(\)]/', '', $_POST[$key]);
  535. }
  536. }
  537.  
  538. $form = new Form_Shop_Address($mode, $required, array($table1, $table2, $table3, $fields));
  539.  
  540. if ($form->isValid($_POST)) {
  541. $val = $form->getValues();
  542.  
  543. $ok = true;
  544. $ck = (1 == (int) $val['different'] ? 'country2' : 'country' );
  545. if (false == in_array($val[$ck], $country2shipping)) {
  546. $instance->_flashMessanger->addError(Locale_Manager::translate('This country is not supported by the selected shipping method. Please enter a different delivery address.'));
  547. $ok = false;
  548. }
  549.  
  550. if (true == $ok && isset($_POST['button2'][0])) {
  551. $val['mode'] = $mode;
  552. $val['FILES'] = $_FILES;
  553.  
  554. $session->order_address_data = $val;
  555. $session->order_shipping_data = null;
  556. $session->step3_key = md5(serialize($val));
  557. Plugin_Manager::callShopEvent('BasketAddressToStep3');
  558. $instance->_redirect($router->assemble(array(), 'basketStep3'));
  559. return;
  560. }
  561. } else {
  562. $instance->_flashMessanger->addError(Locale_Manager::translate('Form contains errors.'));
  563. $val = $form->getUnfilteredValues();
  564. }
  565.  
  566. $session->step3_key = null;
  567.  
  568. foreach ($val as $k => $v) {
  569. if (isset($table1[$k]))
  570. $table1[$k]['value'] = $v;
  571. elseif (isset($table2[$k]))
  572. $table2[$k]['value'] = $v;
  573. elseif (isset($table3[$k]))
  574. $table3[$k]['value'] = $v;
  575. elseif (preg_match('/^additional/', $k))
  576. $additional[$k] = $v;
  577. elseif ('comment' == $k)
  578. $instance->view->comment_value = $v;
  579. elseif ('address_type' == $k)
  580. $instance->view->address_type = $v;
  581. elseif ('different' == $k)
  582. $instance->view->different_value = $v;
  583. elseif (preg_match('/^address2?$/', $k))
  584. $instance->view->{$k . '_value'} = $v;
  585. }
  586.  
  587. $additional_error = array();
  588. foreach ($form->getMessages() as $k => $v) {
  589. if (isset($table1[$k]))
  590. $table1[$k]['error'] = $v;
  591. elseif (isset($table2[$k]))
  592. $table2[$k]['error'] = $v;
  593. elseif (isset($table3[$k]))
  594. $table3[$k]['error'] = $v;
  595. elseif (preg_match('/^additional/', $k))
  596. $additional_error[$k] = $v;
  597. elseif ('comment' == $k)
  598. $instance->view->comment_error = $v;
  599. }
  600. $instance->view->additional_error = $additional_error;
  601. } else {
  602.  
  603. $additional = array();
  604. $instance->view->address_type = 1;
  605.  
  606. if (isset($session->shipping_country)) {
  607. $table2['country']['value'] = $session->shipping_country;
  608. $table3['country2']['value'] = $session->shipping_country;
  609. } else {
  610. $table2['country']['value'] = Locale_Manager::getRegion(); //Config_Manager::getConfigValue('company', 'COUNTRY');
  611. $table3['country2']['value'] = Locale_Manager::getRegion(); //Config_Manager::getConfigValue('company', 'COUNTRY');
  612. }
  613.  
  614. foreach ($fields as $field) {
  615. if (Logic_AdditionalField::TYPE_CHECKBOX == (int) $field->field->type && 1 == (int) $field->checkbox->checked) {
  616. $additional['additional_' . (int) $field->getIdentifier()] = 1;
  617. }
  618. }
  619.  
  620. if (is_array($session->order_address_data)) {
  621. foreach ($session->order_address_data as $k => $v) {
  622. if (isset($table1[$k]))
  623. $table1[$k]['value'] = $v;
  624. elseif (isset($table2[$k]))
  625. $table2[$k]['value'] = $v;
  626. elseif (isset($table3[$k]))
  627. $table3[$k]['value'] = $v;
  628. elseif (preg_match('/^additional/', $k))
  629. $additional[$k] = $v;
  630. elseif ('comment' == $k)
  631. $instance->view->comment_value = $v;
  632. elseif ('address_type' == $k)
  633. $instance->view->address_type = $v;
  634. elseif ('different' == $k)
  635. $instance->view->different_value = $v;
  636. elseif (preg_match('/^address2?$/', $k))
  637. $instance->view->{$k . '_value'} = $v;
  638. }
  639. } elseif (Access_ClientManager::isLoggedIn() && $user->user) {
  640. $table1['mail']['value'] = $user->user->userinfo->email;
  641.  
  642. if (is_object($user->user->address)) {
  643. foreach ($address_assign as $k => $v) {
  644. if (isset($table1[$k]))
  645. $table1[$k]['value'] = $user->user->address->address->$v;
  646.  
  647. if (isset($table2[$k]))
  648. $table2[$k]['value'] = $user->user->address->address->$v;
  649. }
  650.  
  651. $instance->view->address_value = $user->user->address->getIdentifier();
  652.  
  653. if ('' != $user->user->address->address->tax_id || '' != $user->user->address->address->company_name) {
  654. $instance->view->address_type = 2;
  655. }
  656.  
  657. if (is_object($user->user->shippingAddress) && $user->user->address->getIdentifier() != $user->user->shippingAddress->getIdentifier()) {
  658. foreach ($address_assign as $k => $v) {
  659. if (isset($table3[$k . '2']))
  660. $table3[$k . '2']['value'] = $user->user->shippingAddress->address->$v;
  661. }
  662. $instance->view->address2_value = $user->user->shippingAddress->getIdentifier();
  663. $instance->view->different_value = 1;
  664. }
  665. }
  666. }
  667. }
  668.  
  669. if (strlen($table3['country2']['value']) && !isset($table3['country2']['list'][$table3['country2']['value']])) {
  670. $table3['country2']['list'][''] = '';
  671. $table3['country2']['value'] = '';
  672. }
  673.  
  674. if (isset($table1['pass1']) && isset($table1['pass2']))
  675. $table1['pass1']['value'] = $table1['pass2']['value'] = '';
  676.  
  677. $instance->_breadCrumbs->add(Locale_Manager::translate('Cart'), $router->assemble(array(), 'basket'));
  678. $instance->_breadCrumbs->add(Locale_Manager::translate('Your details'), '');
  679.  
  680. $instance->view->mode = $mode;
  681. $instance->view->table1 = $table1;
  682. $instance->view->table2 = $table2;
  683. $instance->view->table3 = $table3;
  684. $instance->view->additional_fields = $fields;
  685. $instance->view->additional_value = $additional;
  686. $instance->view->shipping_data = json_encode($session->order_shipping_data);
  687.  
  688. if (isset($session->payment_id)) {
  689. $lPayment = Logic_PaymentMethod::loadInstance($session->payment_id);
  690. if ($lPayment->existsInDB()) {
  691. $instance->view->isCod = $lPayment->isCod();
  692. }
  693. }
  694.  
  695. $instance->view->body_class = 'shop_basket_address';
  696. Plugin_Manager::callShopEvent('BasketAddressEnd');
  697. $instance->_handleFlashMessages();
  698. }
  699.  
  700. public function Basket_step3Action($instance) {
  701. $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
  702. $session = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_SESSION);
  703. $user = Logic_UserOnline::getUser();
  704. $basket = $user->basket;
  705.  
  706. if (false === Zend_Registry::get('enable_basket')) {
  707. $session->order_address_data = null;
  708. $session->order_shipping_data = null;
  709. $session->step3_key = null;
  710. $instance->_flashMessanger->addWarning(Locale_Manager::translate('Cart is disabled.'));
  711. $instance->_redirect($router->assemble(array(), 'index'));
  712. return;
  713. }
  714.  
  715. if (0 == count($basket)) {
  716. $session->order_address_data = null;
  717. $session->order_shipping_data = null;
  718. $session->step3_key = null;
  719. $instance->_redirect($router->assemble(array(), 'basket'));
  720. return;
  721. }
  722.  
  723. if (!is_array($session->order_address_data) || !is_string($session->step3_key) ||
  724. $session->step3_key !== md5(serialize($session->order_address_data)) ||
  725. !is_int($session->shipping_id) || !is_int($session->payment_id)) {
  726. $session->order_address_data = null;
  727. $session->order_shipping_data = null;
  728. $session->step3_key = null;
  729. $instance->_redirect($router->assemble(array(), 'basket'));
  730. return;
  731. }
  732.  
  733. if ($instance->getRequest()->isPost() && isset($_POST['summaryform'][0])) {
  734. if (isset($_POST['button1'][0])) {
  735. $session->step3_key = null;
  736.  
  737. $url = $router->assemble(array(), 'basketStep2');
  738. if (isset($session->order_address_data['mode'][0])) {
  739. if ('register' == $session->order_address_data['mode'])
  740. $url = $router->assemble(array(), 'basketRegister');
  741. elseif ('single' == $session->order_address_data['mode'])
  742. $url = $router->assemble(array(), 'basketNoRegister');
  743. }
  744.  
  745. $instance->_redirect($url);
  746. return;
  747. } elseif (isset($_POST['button2'][0])) {
  748. $session->step4_key = md5($session->step3_key);
  749. $instance->_redirect($router->assemble(array(), 'basketStep4'));
  750. return;
  751. }
  752. }
  753.  
  754. $instance->_breadCrumbs->add(Locale_Manager::translate('Cart'), $router->assemble(array(), 'basket'));
  755. $instance->_breadCrumbs->add(Locale_Manager::translate('Your details'), $router->assemble(array(), 'basketStep2'));
  756. $instance->_breadCrumbs->add(Locale_Manager::translate('Summary'), '');
  757.  
  758. $data = $session->order_address_data;
  759. if (0 == (int) $data['different']) {
  760. foreach ($data as $k => $v)
  761. if (preg_match('/[a-z]+2$/i', $k)) {
  762. $data[$k] = $data[trim($k, '2')];
  763. }
  764. $session->order_address_data = $data;
  765. $session->step3_key = md5(serialize($data));
  766. }
  767.  
  768. $shippingData = $session->order_shipping_data;
  769. $this->_shipping_id = $session->shipping_id;
  770. $this->_shipping_country = $session->shipping_country;
  771. $this->_payment_id = $session->payment_id;
  772.  
  773. if (false == $this->Basket_processBasket($instance, true)) {
  774. $session->order_address_data = null;
  775. $session->order_shipping_data = null;
  776. $session->step3_key = null;
  777. $instance->_redirect($router->assemble(array(), 'basket'));
  778. return;
  779. }
  780.  
  781. $days = -1;
  782. $days_id = null;
  783. foreach ($basket as $b) {
  784. if (!$b->stock->delivery) {
  785. $days_id = null;
  786. break;
  787. }
  788.  
  789. if ($days < (int) $b->stock->delivery->delivery->days) {
  790. $days_id = (int) $b->stock->delivery->getIdentifier();
  791. $days = (int) $b->stock->delivery->delivery->days;
  792. }
  793. }
  794. if ($days_id > 0)
  795. $instance->view->delivery = new Logic_ProductDelivery($days_id);
  796.  
  797. $instance->view->shipping = new Logic_ShippingMethod($this->_shipping_id);
  798. $instance->view->payment = new Logic_PaymentMethod($this->_payment_id);
  799. $instance->view->discount_summary = $basket->getDiscount();
  800. $instance->view->data = $data;
  801. $instance->view->shipping_data = $shippingData;
  802. $instance->view->sum = $this->Basket_getSum();
  803. $instance->view->country = Config_Manager::getConfigValue('company', 'COUNTRY');
  804.  
  805. foreach ($basket as $b) {
  806. if ($b->stock->stock->delivery_id) {
  807. $instance->view->showDelivery = true;
  808. }
  809. }
  810.  
  811. $instance->view->body_class = 'shop_basket_step3';
  812. $instance->_handleFlashMessages();
  813. }
  814.  
  815. public function Basket_step4Action($instance) {
  816. $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
  817. $session = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_SESSION);
  818. $user = Logic_UserOnline::getUser();
  819.  
  820. if (false === Zend_Registry::get('enable_basket')) {
  821. $session->order_address_data = null;
  822. $session->order_shipping_data = null;
  823. $session->step3_key = null;
  824. $session->step4_key = null;
  825. $instance->_flashMessanger->addWarning(Locale_Manager::translate('Cart is disabled.'));
  826. $instance->_redirect($router->assemble(array(), 'index'));
  827. return;
  828. }
  829.  
  830. $mode = $session->order_address_data['mode'];
  831. if (!in_array($mode, array('user', 'register', 'single')) || 0 == count($user->basket) || ('user' == $mode && false === $user->user)) {
  832. $session->order_address_data = null;
  833. $session->order_shipping_data = null;
  834. $session->step3_key = null;
  835. $session->step4_key = null;
  836. $instance->_redirect($router->assemble(array(), 'basket'));
  837. return;
  838. }
  839.  
  840. if (!is_array($session->order_address_data) || !is_string($session->step3_key) ||
  841. $session->step3_key !== md5(serialize($session->order_address_data)) ||
  842. !is_string($session->step4_key) || $session->step4_key !== md5($session->step3_key) ||
  843. !is_int($session->shipping_id) || !is_int($session->payment_id)) {
  844. $session->order_address_data = null;
  845. $session->order_shipping_data = null;
  846. $session->step3_key = null;
  847. $session->step4_key = null;
  848. $instance->_redirect($router->assemble(array(), 'basket'));
  849. return;
  850. }
  851.  
  852. // todo start transakcji w przyszlosci tutaj, mozliwe problemy z deadlockami i koniecznosc restartu transakcji
  853.  
  854. $q = $this->Basket_checkQuantity($instance);
  855. if (false === $q) {
  856. $session->step3_key = null;
  857. $session->step4_key = null;
  858. $instance->_redirect($router->assemble(array(), 'basket'));
  859. return;
  860. }
  861.  
  862. System_Transaction::begin();
  863.  
  864. $this->_shipping_id = $session->shipping_id;
  865. $this->_payment_id = $session->payment_id;
  866. $this->_shipping_country = $session->shipping_country;
  867.  
  868. try {
  869. $shipping = new Logic_ShippingMethod($this->_shipping_id);
  870. $payment = new Logic_PaymentMethod($this->_payment_id);
  871. } catch (Exception $e) {
  872. $session->step3_key = null;
  873. $session->step4_key = null;
  874. $instance->_redirect($router->assemble(array(), 'basket'));
  875. return;
  876. }
  877.  
  878. if (false == $this->Basket_processBasket($instance, true) || $this->Basket_getSum() < 0) {
  879. $session->order_address_data = null;
  880. $session->order_shipping_data = null;
  881. $session->step3_key = null;
  882. $session->step4_key = null;
  883. $instance->_redirect($router->assemble(array(), 'basket'));
  884. return;
  885. }
  886.  
  887. if (( 0 == (int) Config_Manager::getConfigValue('shopping', 'PRODUCTS_ALLOW_ZERO') && $this->Basket_getSum() < 0.01 ) || $this->Basket_getSum() < 0) {
  888. $session->order_address_data = null;
  889. $session->order_shipping_data = null;
  890. $session->step3_key = null;
  891. $session->step4_key = null;
  892. $instance->_redirect($router->assemble(array(), 'basket'));
  893. return;
  894. }
  895.  
  896. $basket = $user->basket;
  897. $sum = $this->Basket_getSum();
  898. $val = $session->order_address_data;
  899.  
  900. if ('register' == $mode) {
  901. $u = new Logic_User();
  902. $u->create();
  903. $u->user->date_add = date('Y-m-d H:i:s');
  904. $u->save();
  905. $u->createInfo();
  906. $u->createSearch();
  907. $u->setPassword($val['pass1']);
  908. $u->userinfo->email = $val['mail'];
  909. $u->userinfo->firstname = $val['name'];
  910. $u->userinfo->lastname = $val['surname'];
  911. $u->userinfo->lang_id = Locale_Manager::getLanguageId();
  912. $u->userinfo->active = 1;
  913.  
  914. if (Zend_Registry::isRegistered(System_Bootstrap::REGISTRY_FACEBOOK)) {
  915. $u->user->origin = Origin_Manager::ORIGIN_FACEBOOK;
  916. } elseif (Zend_Registry::isRegistered(System_Bootstrap::REGISTRY_MOBILE)) {
  917. $u->user->origin = Origin_Manager::ORIGIN_MOBILE;
  918. }
  919.  
  920. $u->user->verify_email = 0;
  921. $mail_confirm = ( 1 == (int) Config_Manager::getConfigValue('registration', 'CONFIRM_REGISTER') );
  922. if ($mail_confirm) {
  923. $u->user->verify_code = md5($val['mail'] . microtime(true));
  924. }
  925.  
  926. foreach ($val as $k => $v) {
  927. if ('additional_' == substr($k, 0, 11) && strlen($v)) {
  928. $u->createAdditionalField(substr($k, 11), $v);
  929. }
  930. }
  931.  
  932. $u->save();
  933. $user->userOnline->is_user = 1;
  934. $user->userOnline->user_id = $u->getIdentifier();
  935. $user->save();
  936. $user->resetUser();
  937.  
  938. $autoGroup = 0;
  939. if (Config_Manager::hasConfigValue("registration", "auto_add_to_group")) {
  940. $group = Config_Manager::getConfigValue("registration", "auto_add_to_group");
  941. $uList = new Logic_UserGroupList();
  942. $uSelect = $uList->select();
  943. $uSelect->where("group_id = ?", $group);
  944. $uSelect->limit(1);
  945. $uList->fillFromSelect($uSelect);
  946. if (count($uList)) {
  947. $autoGroup = $group;
  948. }
  949. }
  950. if ($autoGroup > 0) {
  951. $table = new Entity_UserGroupsUsers();
  952. $table->insert(array(
  953. 'group_id' => $autoGroup,
  954. 'user_id' => $u->getIdentifier(),
  955. ));
  956. }
  957.  
  958. $template = Mail_Manager::getMailTemplate(Mail_Manager::MAIL_REGISTER);
  959. $message = new Mail_Message($template);
  960. $message->setVarArray(array(
  961. 'email' => $val['mail'],
  962. 'password' => $val['pass1'],
  963. 'link' => '',
  964. 'confirmation' => $mail_confirm,
  965. 'origin' => Origin_Manager::getOriginNameForKey($u->user->origin),
  966. ));
  967. $message->addRecipient($val['mail'], false);
  968.  
  969. if ($mail_confirm) {
  970. $url = $router->assemble(array(
  971. 'userId' => (int) $u->getIdentifier(),
  972. 'code' => $u->user->verify_code,
  973. ), 'registerStep2', System_Router::ROUTE_TYPE_CORE, true, array(), false, Zend_Registry::get(System_Bootstrap::REGISTRY_ROUTER_BASEURL));
  974. $message->setVar('link', $url);
  975. }
  976.  
  977. $metafields = new Metafield_Manager();
  978. foreach ($metafields->getMetafieldObjectList() as $m) {
  979. $key = "metafield.system." . $m->metafield->metafield->namespace . "." . $m->metafield->metafield->key;
  980. $message->setVar($key, Zend_Controller_Action_HelperBroker::getExistingHelper('ViewRenderer')->view->escape($m->value->value));
  981. }
  982.  
  983. try {
  984. Mail_Manager::send($message, true);
  985. } catch (Exception $e) {
  986. $instance->_errorLog->err($e);
  987. $instance->_flashMessanger->addWarning(Locale_Manager::translate('Error while sending a welcome e-mail message.'));
  988. }
  989.  
  990. if (1 == (int) Config_Manager::getConfigValue('mail', 'NOTIFY_EMAIL_NEW_CLIENT')) {
  991. try {
  992. $message = new Mail_Message(Mail_Manager::getMailTemplate(Mail_Manager::MAIL_ADMIN_REGISTER));
  993. $message->setVar('email', $val['mail']);
  994. $message->setVar('origin', Origin_Manager::getOriginNameForKey($user->user->origin));
  995. $message->addRecipient(Config_Manager::getConfigValue('company', 'COMPANY_EMAIL'), false);
  996. $message->setReplyTo($val['mail'], $val['name'] . ' ' . $val['surname']);
  997.  
  998. $metafields = new Metafield_Manager();
  999. foreach ($metafields->getMetafieldObjectList() as $m) {
  1000. $key = "metafield.system." . $m->metafield->metafield->namespace . "." . $m->metafield->metafield->key;
  1001. $message->setVar($key, Zend_Controller_Action_HelperBroker::getExistingHelper('ViewRenderer')->view->escape($m->value->value));
  1002. }
  1003. Mail_Manager::send($message, true);
  1004. } catch (Exception $e) {
  1005. $instance->_errorLog->err($e);
  1006. }
  1007. unset($message);
  1008. }
  1009. } elseif ('user' == $mode) {
  1010. if ('' == $user->user->userinfo->firstname)
  1011. $user->user->userinfo->firstname = $val['name'];
  1012. if ('' == $user->user->userinfo->lastname)
  1013. $user->user->userinfo->lastname = $val['surname'];
  1014. $user->user->save();
  1015. }
  1016.  
  1017. foreach (array('country', 'country2') as $key) {
  1018. if (!preg_match('/^[A-Z]{2}$/', $val[$key])) {
  1019. $c = Locale_Manager::reverseMapCountries(array($val[$key]));
  1020. $c = current($c);
  1021. if (is_string($c)) {
  1022. $val[$key] = $c;
  1023. } else {
  1024. $val[$key] = Locale_Manager::getRegion(); //Config_Manager::getConfigValue('company', 'COUNTRY');
  1025. }
  1026. }
  1027. }
  1028.  
  1029.  
  1030. $clist = Locale_Manager::getCountries();
  1031. $address1 = array(
  1032. 'company_name' => $val['coname'],
  1033. 'tax_id' => $val['nip'],
  1034. 'pesel' => $val['pesel'],
  1035. 'firstname' => $val['name'],
  1036. 'lastname' => $val['surname'],
  1037. 'street_1' => $val['other_address'],
  1038. 'street_2' => '',
  1039. 'city' => $val['city'],
  1040. 'zip_code' => $val['zip'],
  1041. 'state' => '',
  1042. 'country_code' => $val['country'],
  1043. 'country' => $clist[$val['country']],
  1044. 'phone' => $val['phone'],
  1045. );
  1046.  
  1047. $pesel = (1 == (int) Config_Manager::getConfigValue('shopping', 'SUPPORT_PESEL'));
  1048. if (false === $pesel) {
  1049. $address1['pesel'] = '';
  1050. }
  1051.  
  1052. if ('single' != $mode)
  1053. $user->user->processAddress($address1, (int) $val['address']);
  1054.  
  1055. if (1 == (int) $val['different']) {
  1056. $address2 = array(
  1057. 'company_name' => $val['coname2'],
  1058. 'firstname' => $val['name2'],
  1059. 'lastname' => $val['surname2'],
  1060. 'street_1' => $val['other_address2'],
  1061. 'street_2' => '',
  1062. 'city' => $val['city2'],
  1063. 'zip_code' => $val['zip2'],
  1064. 'state' => '',
  1065. 'country_code' => $val['country2'],
  1066. 'country' => $clist[$val['country2']],
  1067. 'phone' => $val['phone2'],
  1068. );
  1069.  
  1070. if ('single' != $mode)
  1071. $user->user->processAddress($address2, (int) $val['address2']);
  1072. } else {
  1073. $address2 = $address1;
  1074. }
  1075.  
  1076. if ('single' != $mode && !$user->user->address && count($user->user->addresses) > 0) {
  1077. $user->user->addresses[0]->address->default = 1;
  1078. $user->user->addresses[0]->save();
  1079. }
  1080.  
  1081. if ('single' != $mode && !$user->user->shippingAddress && count($user->user->addresses) > 0) {
  1082. $user->user->addresses[0]->address->shipping_default = 1;
  1083. $user->user->addresses[0]->save();
  1084. }
  1085.  
  1086. if (is_object($user->user)) {
  1087. $user->user->updateSearch();
  1088. }
  1089.  
  1090. $confirm = (1 == (int) Config_Manager::getConfigValue('shopping', 'CONFIRM_ORDER'));
  1091. $shipping = new Logic_ShippingMethod($this->_shipping_id);
  1092. $currency = Locale_Manager::getLogicCurrency();
  1093.  
  1094. $discounts = array(
  1095. 'client' => 0,
  1096. 'group' => 0,
  1097. 'levels' => 0,
  1098. 'code' => 0,
  1099. );
  1100.  
  1101. $bd = $basket->discountsInUse();
  1102. if (isset($bd['user'])) {
  1103. $discounts['client'] += $bd['user'];
  1104. }
  1105.  
  1106. if (isset($bd['loyalty'])) {
  1107. $discounts['client'] += $bd['loyalty'];
  1108. }
  1109.  
  1110. if (isset($bd['new'])) {
  1111. $discounts['client'] += $bd['new'];
  1112. }
  1113.  
  1114. if (isset($bd['group'])) {
  1115. $discounts['group'] += $bd['group'];
  1116. }
  1117.  
  1118. if (isset($bd['level'])) {
  1119. $discounts['levels'] += $bd['level'];
  1120. }
  1121.  
  1122. if (isset($bd['code'])) {
  1123. $discounts['code'] += $bd['code'];
  1124. }
  1125.  
  1126. $order = new Logic_Order();
  1127. $order->create();
  1128. $order->order->user_id = ($user->user ? $user->user->getIdentifier() : NULL);
  1129. $order->order->date = date('Y-m-d H:i:s');
  1130. $order->order->status_date = date('Y-m-d H:i:s');
  1131. $order->order->confirm_date = 0; /* ($confirm ? 0 : date('Y-m-d H:i:s')); */
  1132. $order->order->status_id = Logic_Status::getDefaultStatusForNewOrders()->getIdentifier();
  1133. $order->order->sum = $sum;
  1134. $order->order->payment_id = $this->_payment_id;
  1135. $order->order->shipping_id = $this->_shipping_id;
  1136. $order->order->shipping_cost = (float) $shipping->getCost($basket, $this->_payment_id);
  1137. $order->order->email = $val['mail'];
  1138. $order->order->code = md5($val['mail'] . microtime(true));
  1139. $order->order->confirm = 0; /* ($confirm ? 0 : 1); */
  1140. $order->order->notes = $val['comment'];
  1141. $order->order->currency_id = $currency->getIdentifier();
  1142. $order->order->currency_rate = (float) $currency->currency->rate;
  1143. $order->order->paid = 0;
  1144. $order->order->ip_address = $_SERVER['REMOTE_ADDR'];
  1145. foreach ($discounts as $k => $v) {
  1146. $order->order->{'discount_' . $k} = $v;
  1147. }
  1148. $order->order->shipping_vat = (int) $shipping->tax->getIdentifier();
  1149. $order->order->code_id = ( is_int($session->promocode_id) ? $session->promocode_id : NULL );
  1150. $order->order->user_order = ( 'single' == $mode ? 0 : ( 'register' == $mode ? 1 : 2 ) );
  1151. $order->order->lang_id = Locale_Manager::getLanguageId();
  1152.  
  1153. if (Zend_Registry::isRegistered(System_Bootstrap::REGISTRY_FACEBOOK)) {
  1154. $order->order->origin = Origin_Manager::ORIGIN_FACEBOOK;
  1155. } else if (Zend_Registry::isRegistered(System_Bootstrap::REGISTRY_MOBILE)) {
  1156. $order->order->origin = Origin_Manager::ORIGIN_MOBILE;
  1157. } else {
  1158. $order->order->origin = Origin_Manager::ORIGIN_SHOP;
  1159. }
  1160.  
  1161. $order->save();
  1162. $order->cleanProductsCache();
  1163.  
  1164. if (null !== $session->order_shipping_data) {
  1165. $order->setShippingData($session->order_shipping_data);
  1166. }
  1167.  
  1168. switch ($val['mode']) {
  1169. case 'single':
  1170. $locate = Logic_AdditionalField::LOCATE_ORDER_WITHOUT_REGISTRATION;
  1171. break;
  1172. case 'user':
  1173. $locate = Logic_AdditionalField::LOCATE_ORDER_LOGGED_ON_USER;
  1174. break;
  1175. default:
  1176. $locate = Logic_AdditionalField::LOCATE_ORDER_WITH_REGISTRATION;
  1177. break;
  1178. }
  1179.  
  1180. $additionalFields = array();
  1181. foreach ($val as $k => $v) {
  1182. if (strpos($k, 'additional_') === 0) {
  1183. $additionalFields[substr($k, 11)] = $v;
  1184. }
  1185. }
  1186.  
  1187. if (!empty($additionalFields)) {
  1188. $fields = Logic_AdditionalField::getByLocate($locate, Locale_Manager::getLanguageId());
  1189. $files = array();
  1190. if (isset($val['FILES'])) {
  1191. foreach ($val['FILES'] as $k => $v) {
  1192. if (strpos($k, 'additional_') === 0) {
  1193. $files[substr($k, 11)] = $v;
  1194. }
  1195. }
  1196. }
  1197. $order->createOrUpdateAdditionalFields($fields, $additionalFields, $files);
  1198. }
  1199.  
  1200. foreach ($basket as $prod) {
  1201. $order->addProduct($prod);
  1202. $prod->stock->changeSold((float) $prod->basket->quantity);
  1203. }
  1204.  
  1205. $order->addAddress($address1, 1);
  1206. if (1 == (int) $val['different']) {
  1207. $order->addAddress($address2, 2);
  1208. }
  1209.  
  1210. $foo = $order->billingAddress;
  1211. $foo = $order->deliveryAddress;
  1212. $order->save();
  1213. $order->calculateDeliveryTime();
  1214.  
  1215. if (1 == (int) Config_Manager::getConfigValue('shopping', 'UPDATE_STOCK_ON_BUY')) {
  1216. foreach ($basket as $prod) {
  1217. $prod->stock->changeStock(0 - (float) $prod->basket->quantity);
  1218. $prod->cleanStockCache();
  1219. }
  1220. }
  1221.  
  1222. if (is_int($session->promocode_id)) {
  1223. Logic_PromoCode::loadInstance($session->promocode_id)->cleanCache();
  1224. }
  1225.  
  1226. $send_invoice = (1 == (int) Config_Manager::getConfigValue('invoice', 'INVOICE_AUTO_SEND'));
  1227. $invoice = new Logic_Invoice();
  1228. $invoice->create();
  1229. $invoice->invoice->order_id = (int) $order->getIdentifier();
  1230. $invoice->invoice->created_at = $order->order->date;
  1231. $invoice->invoice->sent = ( $send_invoice ? Logic_Invoice::SENT_EMAIL : Logic_Invoice::SENT_NONE );
  1232. $invoice->discoverInvoiceNum();
  1233. $invoice->save();
  1234.  
  1235. /* todo: put it into the order queue */
  1236. $attachments = array();
  1237. if ($send_invoice) {
  1238. $pdf = new Invoice_Document($invoice);
  1239. $pdf->generate();
  1240. $a = new Zend_Mime_Part($pdf->render());
  1241. $a->type = 'application/pdf';
  1242. $a->filename = str_replace("/", "-", $invoice->invoiceNum()) . '.pdf';
  1243. $a->encoding = Zend_Mime::ENCODING_BASE64;
  1244. $a->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
  1245. $attachments[] = $a;
  1246. }
  1247.  
  1248. if ($order->user instanceof Logic_User) {
  1249. Loyalty_Program::orderEvent($order);
  1250. }
  1251.  
  1252. $arr = array(
  1253. 'payment_notify' => new Parser_Expr_TemplateHtml($order->payment->translation->notify_mail),
  1254. 'link' => '',
  1255. 'confirmation' => $confirm,
  1256. );
  1257.  
  1258. if ($confirm) {
  1259. $arr['link'] = $router->assemble(array(
  1260. 'orderId' => (int) $order->getIdentifier(),
  1261. 'code' => $order->order->code,
  1262. ), 'basketConfirm', System_Router::ROUTE_TYPE_CORE, true, array(), false, Zend_Registry::get(System_Bootstrap::REGISTRY_ROUTER_BASEURL));
  1263. }
  1264.  
  1265. if (1 == (int) Config_Manager::getConfigValue('mail', 'NOTIFY_EMAIL_NEW_ORDER')) {
  1266. try {
  1267. $order->sendMail(Mail_Manager::MAIL_ADMIN_ORDER, $arr);
  1268. } catch (Exception $e) {
  1269. $instance->_errorLog->err($e);
  1270. }
  1271. }
  1272.  
  1273. try {
  1274. $order->sendMail(Mail_Manager::MAIL_ORDER, $arr, $attachments);
  1275. /* $instance->_flashMessanger->addSuccess(Locale_Manager::translate('Order has been created. Check your e-mail and click on the confirmation link to confirm.')); */
  1276. } catch (Exception $e) {
  1277. $instance->_errorLog->err($e);
  1278. $instance->_flashMessanger->addWarning(Locale_Manager::translate('Error while sending e-mail message with order summary.'));
  1279. }
  1280.  
  1281. if (1 == (int) Config_Manager::getConfigValue('mail', 'NOTIFY_SMS_NEW_ORDER')) {
  1282. try {
  1283. $sms = sprintf(
  1284. Locale_Manager::translate(self::SMS_ORDER_TEXT), (int) $order->order->order_id, View_Smarty_Helper_Currency::currency(array(
  1285. 'value' => (float) $order->order->sum,
  1286. 'currency' => $order->currency->name,
  1287. ), null), $order->countProductsSum(), ( strlen($order->billingAddress->company) ?
  1288. $order->billingAddress->company : $order->billingAddress->firstname . ' ' . $order->billingAddress->lastname
  1289. )
  1290. );
  1291. Plugin_SmsGateway_Manager::sendMessage($sms);
  1292. } catch (Exception $e) {
  1293. $instance->_errorLog->err($e);
  1294. }
  1295. }
  1296. /* todo: put it into the order queue - end */
  1297.  
  1298. System_Transaction::commit();
  1299.  
  1300. $user->basketEmpty();
  1301. $session->order_address_data = null;
  1302. $session->order_shipping_data = null;
  1303. $session->step3_key = null;
  1304. $session->step4_key = null;
  1305. $session->promocode_id = null;
  1306.  
  1307. $order->process();
  1308.  
  1309. Plugin_Manager::callCoreEvent('addOrder', array($order));
  1310.  
  1311. $session->step5_key = md5($order->getIdentifier() . $order->order->date);
  1312. $instance->_redirect($router->assemble(array(
  1313. 'orderId' => (int) $order->getIdentifier(),
  1314. ), 'basketDone'));
  1315. }
  1316.  
  1317. public function Basket_confirmAction($instance) {
  1318. $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
  1319. $session = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_SESSION);
  1320.  
  1321. if ($instance->_hasParam('orderId') && $instance->_hasParam('code')) {
  1322. $id = (int) $instance->_getParam('orderId');
  1323. $code = $instance->_getParam('code');
  1324.  
  1325. if ($id > 0 && 32 == strlen($code)) {
  1326. try {
  1327. $order = new Logic_Order($id);
  1328.  
  1329. if ($order->order->code === $code) {
  1330. if (0 == (int) $order->order->confirm) {
  1331. $order->order->confirm = 1;
  1332. $order->order->confirm_date = date('Y-m-d H:i:s');
  1333. $order->save();
  1334. $instance->_flashMessanger->addSuccess(Locale_Manager::translate('Order has been confirmed.'));
  1335. } else {
  1336. $instance->_flashMessanger->addInfo(Locale_Manager::translate('Order has already been confirmed.'));
  1337. }
  1338.  
  1339. if (0 == (int) $order->order->paid && $order->hasOnlinePayment())
  1340. $session->step5_key = md5($order->getIdentifier() . $order->order->date);
  1341.  
  1342. $instance->_redirect($router->assemble(array(), 'index'));
  1343. return;
  1344. }
  1345. } catch (Exception $e) {
  1346.  
  1347. }
  1348. }
  1349. }
  1350.  
  1351. $instance->_flashMessanger->addError(Locale_Manager::translate('Invalid order confirmation code.'));
  1352. $instance->_redirect($router->assemble(array(), 'index'));
  1353. }
  1354.  
  1355. public function Basket_doneAction($instance) {
  1356. $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
  1357. $session = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_SESSION);
  1358. $user = Logic_UserOnline::getUser();
  1359.  
  1360. if (false === Zend_Registry::get('enable_basket')) {
  1361. $session->step5_key = null;
  1362. $instance->_flashMessanger->addWarning(Locale_Manager::translate('Cart is disabled.'));
  1363. $instance->_redirect($router->assemble(array(), 'index'));
  1364. return;
  1365. }
  1366.  
  1367. $instance->_breadCrumbs->add(Locale_Manager::translate('Cart'), '');
  1368. $instance->_breadCrumbs->add(Locale_Manager::translate('Your details'), '');
  1369. $instance->_breadCrumbs->add(Locale_Manager::translate('Summary'), '');
  1370. $instance->_breadCrumbs->add(Locale_Manager::translate('Confirmation'), '');
  1371.  
  1372. if ($instance->_hasParam('orderId') && is_string($session->step5_key)) {
  1373. $order = new Logic_Order((int) $instance->_getParam('orderId'));
  1374. if ($order->existsInDB() && md5($order->getIdentifier() . $order->order->date) == $session->step5_key) {
  1375.  
  1376. $handler = $order->payment->createHandler();
  1377. $handler->setOrder($order);
  1378.  
  1379. $vars = $order->getVariables(array(
  1380. 'ignored_variables' => array('shipments')
  1381. ));
  1382. if (Config_Manager::hasConfigValue('shopping', 'CONFIRM_ORDER')) {
  1383. $confirm = (bool) Config_Manager::getConfigValue('shopping', 'CONFIRM_ORDER');
  1384. } else {
  1385. $confirm = false;
  1386. }
  1387. $vars['confirmation'] = $confirm;
  1388.  
  1389. $snippet = Logic_Snippet::getCode(Logic_Snippet::TYPE_ORDER);
  1390. $instance->view->snippet_order = Parser_Processor::onetimeCompile($snippet, $vars, array(
  1391. 'ignore_non_breaking_space' => true,
  1392. 'is_html_template' => true
  1393. ));
  1394.  
  1395. $vars['payment_form'] = new Parser_Expr_TemplateHtml($handler->getForm(true));
  1396. $instance->view->payment_message = Parser_Processor::onetimeCompile($order->payment->translation->notify, $vars, array(
  1397. 'ignore_non_breaking_space' => true,
  1398. 'is_html_template' => true
  1399. ));
  1400.  
  1401. $instance->view->body_class = 'shop_basket_done';
  1402. $instance->_handleFlashMessages();
  1403. return;
  1404. }
  1405. }
  1406.  
  1407. $instance->_redirect($router->assemble(array(), 'index'));
  1408. }
  1409.  
  1410. public function Basket_removeAction($instance) {
  1411. if (false === Zend_Registry::get('enable_basket')) {
  1412. $instance->_flashMessanger->addWarning(Locale_Manager::translate('Cart is disabled.'));
  1413. $instance->_redirect(Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER)->assemble(array(), 'index'));
  1414. return;
  1415. }
  1416.  
  1417. if ($instance->_hasParam('basketId')) {
  1418. $id = (int) $instance->_getParam('basketId');
  1419. if ($id > 0) {
  1420. Logic_UserOnline::getUser()->basketRemove($id);
  1421. $instance->_flashMessanger->addSuccess(Locale_Manager::translate('Product removed from cart.'));
  1422. }
  1423. }
  1424.  
  1425. $instance->_redirect(Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER)->assemble(array(), 'basket'));
  1426. }
  1427.  
  1428. private function Basket_add($instance, $loyalty = false) {
  1429. $ret = array(
  1430. 'messages' => array(
  1431. 'warning' => array(),
  1432. 'error' => array(),
  1433. 'success' => array(),
  1434. 'info' => array(),
  1435. ),
  1436. 'added' => array(),
  1437. 'redirect' => false,
  1438. );
  1439.  
  1440. $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
  1441. $session = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_SESSION);
  1442. $productRoute = $loyalty ? 'assembleProductExchange' : 'assembleProduct';
  1443.  
  1444. if (false === $loyalty && false === Zend_Registry::get('enable_basket')) {
  1445. $ret['messages']['warning'][] = Locale_Manager::translate('Cart is disabled.');
  1446. $ret['redirect'] = $router->assemble(array(), 'index');
  1447. return $ret;
  1448. }
  1449.  
  1450. if (!$instance->_hasParam('stockId')) {
  1451. $ret['redirect'] = $router->assemble(array(), 'index');
  1452. return $ret;
  1453. }
  1454.  
  1455. $quant = self::DEFAULT_BASKET_QUANTITY;
  1456.  
  1457. $options = array();
  1458. foreach ($_POST as $k => $v) {
  1459. if (strpos($k, "option_") === 0) {
  1460. $i = substr($k, 7);
  1461. $options[$i] = $v;
  1462. }
  1463. }
  1464. foreach ($_FILES as $k => $v) {
  1465. if (strpos($k, "option_") === 0) {
  1466. $i = substr($k, 7);
  1467. $v['key'] = $k;
  1468. $options[$i] = $v;
  1469. }
  1470. }
  1471.  
  1472.  
  1473. if ('post' == $instance->_getParam('stockId') && $instance->getRequest()->isPost()) {
  1474.  
  1475. $form = new Form_Shop_Multifloat(array(array('stock_id'), 'quantity'), true, Logic_UserBasketList::QUANTITY_PRECISION);
  1476.  
  1477. if ($form->isValid($_POST)) {
  1478. $val = $form->getFloats();
  1479. $sids = $val['stock_id'];
  1480. if (is_float($sids)) {
  1481. $sids = array((int) $sids);
  1482. } else {
  1483. $sids = (array) $sids;
  1484. }
  1485.  
  1486. $added = 0;
  1487. foreach ($sids as $sid) {
  1488. if ($sid > 0) {
  1489. $stock = new Logic_ProductStock($sid);
  1490. if (false == $stock->existsInDB()) {
  1491. $ret['redirect'] = $router->assemble(array(), 'index');
  1492. return $ret;
  1493. }
  1494.  
  1495. if ($sid == $sids[0]) { /* first, main product */
  1496. $quant = (float) $val['quantity'];
  1497. }
  1498.  
  1499. // sprawdzic poprawnosc produkto-opcji
  1500. if (!$stock->product->validateOptionsValues($options)) {
  1501. $ret['messages']['error'][] = Locale_Manager::translate('Product is offered in different variants, select them before adding to cart.');
  1502. $ret['redirect'] = $router->$productRoute(array(
  1503. 'productId' => $stock->product->getIdentifier(),
  1504. 'productName' => $stock->product->translation->name,
  1505. ), $stock->product->getIdentifier());
  1506. return $ret;
  1507. }
  1508.  
  1509. $arr = array();
  1510. foreach ($_POST as $k => $v) {
  1511. if ('option_' == substr($k, 0, 7)) {
  1512. $k = (int) substr($k, 7);
  1513. $arr[$k] = (int) $v;
  1514. }
  1515. }
  1516.  
  1517. if (count($arr)) {
  1518. $stockByOptions = $stock->product->getStock($arr);
  1519. $stockOptionIds = $stock->product->filterOptionsToStockOnly($arr);
  1520.  
  1521. if ($sid == $sids[0] && isset($_POST['nojs'][0]) && 1 == (int) $_POST['nojs']) { /* first product, no JS for stock */
  1522. if ($stockByOptions instanceof Logic_ProductStock) {
  1523. $stock = $stockByOptions;
  1524. $sid = $stock->getIdentifier();
  1525. if (0 === (int) $stock->stock->active) {
  1526. $stockByOptions = null;
  1527. }
  1528. }
  1529. }
  1530.  
  1531. if (null === $stockByOptions && count($stockOptionIds) > 0) {
  1532. $ret['messages']['error'][] = Locale_Manager::translate('Selected variant does not exist. Enable JavaScript to select only from the existing options.');
  1533. $ret['redirect'] = $router->$productRoute(array(
  1534. 'productId' => $stock->product->getIdentifier(),
  1535. 'productName' => $stock->product->translation->name,
  1536. ), $stock->product->getIdentifier());
  1537. return $ret;
  1538. }
  1539. }
  1540.  
  1541.  
  1542. if (1 == (int) $stock->product->translation->active && 1 == (int) $stock->availability->availability->can_buy && $quant > 0) {
  1543. $pack = $stock->getPackage();
  1544. if (0 == (int) $stock->product->unit->unit->floating_point) {
  1545. $quant = (int) ceil($quant);
  1546. $pack = (int) ceil($pack);
  1547. }
  1548.  
  1549. $user = Logic_UserOnline::getUser();
  1550.  
  1551. $packs = $this->Basket_checkPack($pack, $quant);
  1552. if ($packs > 0) {
  1553. $quant = $packs;
  1554. $ret['messages']['success'][] = Locale_Manager::translate('This product can only be purchased in packages of %s %s', $stock->product->translation->name, Locale_Manager::getFloat($pack), $stock->product->unit->translation->name);
  1555. }
  1556. if ($loyalty) {
  1557. if ($stock->loyaltyPointsPrice() && $stock->loyaltyPointsPrice() * $quant <= $user->user->loyalty->sum()) {
  1558. if ($quant <= (float) $stock->stock->stock || 1 == (int) Config_Manager::getConfigValue('shopping', 'ALLOW_OVERSELLING')) {
  1559. Loyalty_Program::exchangeEvent($user->user->getIdentifier(), $stock, $quant);
  1560. $added++;
  1561. $ret['added'][] = array(
  1562. 'id' => (int) $sid,
  1563. 'name' => $stock->product->translation->name,
  1564. 'variant' => $stock->getName($options),
  1565. 'quantity' => $quant,
  1566. 'unit' => $stock->product->unit->translation->name,
  1567. 'price' => $stock->loyaltyPointsPrice(),
  1568. );
  1569. } else {
  1570. $ret['messages']['error'][] = Locale_Manager::translate('The required product quantity exceeds the stock.');
  1571. $ret['redirect'] = $router->$productRoute(array(
  1572. 'productId' => $stock->product->getIdentifier(),
  1573. 'productName' => $stock->product->translation->name,
  1574. ), $stock->product->getIdentifier());
  1575. return $ret;
  1576. }
  1577. } else {
  1578. $ret['messages']['error'][] = Locale_Manager::translate('You do not have enough points to exchange for this product.');
  1579. $ret['redirect'] = $router->$productRoute(array(
  1580. 'productId' => $stock->product->getIdentifier(),
  1581. 'productName' => $stock->product->translation->name,
  1582. ), $stock->product->getIdentifier());
  1583. return $ret;
  1584. }
  1585. } else {
  1586. $added++;
  1587. $bprod = $user->basketAdd($sid, $quant, $options);
  1588. $check = $this->Basket_checkQuantity($instance, $ret);
  1589. $ret['added'][] = array(
  1590. 'id' => (int) $sid,
  1591. 'name' => $bprod->product->translation->name,
  1592. 'variant' => $bprod->getName(),
  1593. 'quantity' => $quant,
  1594. 'unit' => $bprod->product->unit->translation->name,
  1595. 'price' => $bprod->getPrice(),
  1596. );
  1597. }
  1598. } else {
  1599. if ($quant > 0) {
  1600. $ret['messages']['error'][] = Locale_Manager::translate('This product is inactive and cannot be added to shopping cart.');
  1601. } else {
  1602. $ret['messages']['error'][] = Locale_Manager::translate('Incorrect quantity of products') . '.';
  1603. }
  1604. $ret['redirect'] = $router->$productRoute(array(
  1605. 'productId' => $stock->product->getIdentifier(),
  1606. 'productName' => $stock->product->translation->name,
  1607. ), $stock->product->getIdentifier());
  1608. return $ret;
  1609. }
  1610. } else {
  1611. $ret['redirect'] = $router->assemble(array(), 'index');
  1612. return $ret;
  1613. }
  1614. }
  1615.  
  1616. if (1 == $added) {
  1617. if ($loyalty) {
  1618. $ret['messages']['success'][] = Locale_Manager::translate('Product submitted for exchange.');
  1619. } else {
  1620. $ret['messages']['success'][] = Locale_Manager::translate('Product added to cart.');
  1621. }
  1622. } elseif ($added > 1) {
  1623. if ($loyalty) {
  1624. $ret['messages']['success'][] = sprintf(Locale_Manager::translate('Exchanged products: %d.'), $added);
  1625. } else {
  1626. $ret['messages']['success'][] = sprintf(Locale_Manager::translate('Products added to cart: %d.'), $added);
  1627. }
  1628. }
  1629. $session->last_product_page = $_SERVER['HTTP_REFERER'];
  1630.  
  1631. if (true == $check && 1 != (int) Config_Manager::getConfigValue('shopping', 'BASKET_ADDING') && isset($_SERVER['HTTP_REFERER'][0])) {
  1632. if (preg_match('/^https?\:\/\/' . preg_quote($_SERVER['HTTP_HOST']) . '/i', $_SERVER['HTTP_REFERER'])) {
  1633. $ret['redirect'] = $_SERVER['HTTP_REFERER'];
  1634. return $ret;
  1635. }
  1636. }
  1637.  
  1638. $ret['redirect'] = $router->assemble(array(), $loyalty ? 'panel' : 'basket');
  1639. return $ret;
  1640. } else {
  1641.  
  1642. $val = $form->getUnfilteredValues();
  1643.  
  1644. if (isset($val['stock_id'][0])) {
  1645. $sid = (int) $val['stock_id'];
  1646. if ($sid > 0) {
  1647. $stock = new Logic_ProductStock($sid);
  1648. if (false == $stock->existsInDB()) {
  1649. $ret['redirect'] = $router->assemble(array(), 'index');
  1650. return $ret;
  1651. }
  1652. $ret['messages']['error'][] = Locale_Manager::translate('Incorrect quantity of products') . '.';
  1653. $ret['redirect'] = $router->$productRoute(array(
  1654. 'productId' => $stock->product->getIdentifier(),
  1655. 'productName' => $stock->product->translation->name,
  1656. ), $stock->product->getIdentifier());
  1657. return $ret;
  1658. }
  1659. }
  1660.  
  1661. $ret['redirect'] = $router->assemble(array(), 'index');
  1662. return $ret;
  1663. }
  1664. } else {
  1665. $sid = (int) $instance->_getParam('stockId');
  1666. if ($sid > 0) {
  1667. $stock = new Logic_ProductStock($sid);
  1668. if (false == $stock->existsInDB()) {
  1669. $ret['redirect'] = $router->assemble(array(), 'index');
  1670. return $ret;
  1671. }
  1672.  
  1673. // sprawdzic poprawnosc produkto-opcji
  1674. if (!$stock->product->validateOptionsValues($options)) {
  1675. $ret['messages']['error'][] = Locale_Manager::translate('Product is offered in different variants, select them before adding to cart.');
  1676. $ret['redirect'] = $router->$productRoute(array(
  1677. 'productId' => $stock->product->getIdentifier(),
  1678. 'productName' => $stock->product->translation->name,
  1679. ), $stock->product->getIdentifier());
  1680. return $ret;
  1681. }
  1682.  
  1683. if (( 0 == count($stock->product->optionsStock) ) ||
  1684. ( 1 == count($stock->product->optionsStock) && $sid == (int) $stock->product->optionsStock[0]->getIdentifier() )) {
  1685.  
  1686. if (1 == (int) $stock->product->translation->active && 1 == (int) $stock->availability->availability->can_buy) {
  1687. $sid = (int) $stock->product->defaultStock->getIdentifier();
  1688. $user = Logic_UserOnline::getUser();
  1689. $session->last_product_page = $_SERVER['HTTP_REFERER'];
  1690.  
  1691. if ($loyalty) {
  1692. if ($stock->loyaltyPointsPrice() * $quant <= $user->user->loyalty->sum()) {
  1693. if ($quant <= (float) $stock->stock->stock || 1 == (int) Config_Manager::getConfigValue('shopping', 'ALLOW_OVERSELLING')) {
  1694. Loyalty_Program::exchangeEvent($user->user->getIdentifier(), $stock, $quant);
  1695. $ret['messages']['success'][] = Locale_Manager::translate('Product exchanged.');
  1696. $ret['added'][] = array(
  1697. 'id' => (int) $sid,
  1698. 'name' => $stock->product->translation->name,
  1699. 'variant' => $stock->getName($options),
  1700. 'quantity' => $quant,
  1701. 'unit' => $stock->product->unit->translation->name,
  1702. 'price' => $stock->loyaltyPointsPrice(),
  1703. );
  1704. } else {
  1705. $ret['messages']['error'][] = Locale_Manager::translate('The required product quantity exceeds the stock.');
  1706. $ret['redirect'] = $router->$productRoute(array(
  1707. 'productId' => $stock->product->getIdentifier(),
  1708. 'productName' => $stock->product->translation->name,
  1709. ), $stock->product->getIdentifier());
  1710. return $ret;
  1711. }
  1712. } else {
  1713. $ret['messages']['error'][] = Locale_Manager::translate('You do not have enough points to exchange for this product.');
  1714. $ret['redirect'] = $router->$productRoute(array(
  1715. 'productId' => $stock->product->getIdentifier(),
  1716. 'productName' => $stock->product->translation->name,
  1717. ), $stock->product->getIdentifier());
  1718. return $ret;
  1719. }
  1720. } else {
  1721. $pack = $stock->getPackage();
  1722. if (0 == (int) $stock->product->unit->unit->floating_point) {
  1723. $quant = (int) ceil($quant);
  1724. $pack = (int) ceil($pack);
  1725. }
  1726.  
  1727. $packs = $this->Basket_checkPack($pack, $quant);
  1728. if ($packs > 0) {
  1729. $quant = $packs;
  1730. $ret['messages']['success'][] = Locale_Manager::translate('This product can only be purchased in packages of %s %s', $stock->product->translation->name, Locale_Manager::getFloat($pack), $stock->product->unit->translation->name);
  1731. }
  1732.  
  1733. $bprod = $user->basketAdd($sid, $quant, $options);
  1734. $check = $this->Basket_checkQuantity($instance, $ret);
  1735. $ret['messages']['success'][] = Locale_Manager::translate('Product added to cart.');
  1736. $ret['added'][] = array(
  1737. 'id' => (int) $sid,
  1738. 'name' => $bprod->product->translation->name,
  1739. 'variant' => $stock->getName($options),
  1740. 'quantity' => $quant,
  1741. 'unit' => $bprod->product->unit->translation->name,
  1742. 'price' => $bprod->getPrice(),
  1743. );
  1744. }
  1745.  
  1746. if (true == $check && 1 != (int) Config_Manager::getConfigValue('shopping', 'BASKET_ADDING') && isset($_SERVER['HTTP_REFERER'][0])) {
  1747. if (preg_match('/^https?\:\/\/' . preg_quote($_SERVER['HTTP_HOST']) . '/i', $_SERVER['HTTP_REFERER'])) {
  1748. $ret['redirect'] = $_SERVER['HTTP_REFERER'];
  1749. return $ret;
  1750. }
  1751. }
  1752.  
  1753. $ret['redirect'] = $router->assemble(array(), 'basket');
  1754. return $ret;
  1755. } else {
  1756. $ret['messages']['error'][] = Locale_Manager::translate('This product is inactive and cannot be added to shopping cart.');
  1757. $ret['redirect'] = $router->$productRoute(array(
  1758. 'productId' => $stock->product->getIdentifier(),
  1759. 'productName' => $stock->product->translation->name,
  1760. ), $stock->product->getIdentifier());
  1761. return $ret;
  1762. }
  1763. } else {
  1764. if ($loyalty) {
  1765. $ret['messages']['info'][] = Locale_Manager::translate('This product is available in different variants, select them before the exchange.');
  1766. } else {
  1767. $ret['messages']['info'][] = Locale_Manager::translate('Product is offered in different variants, select them before adding to cart.');
  1768. }
  1769.  
  1770. $ret['redirect'] = $router->$productRoute(array(
  1771. 'productId' => $stock->product->getIdentifier(),
  1772. 'productName' => $stock->product->translation->name,
  1773. ), $stock->product->getIdentifier());
  1774. return $ret;
  1775. }
  1776. } else {
  1777. $ret['redirect'] = $router->assemble(array(), 'index');
  1778. return $ret;
  1779. }
  1780. }
  1781.  
  1782. return $ret;
  1783. }
  1784.  
  1785. public function Basket_checkPack($pack, $quant, $floating = false) {
  1786. if ($pack > 0) {
  1787. $precision = 2;
  1788.  
  1789. $epsilon = round($quant - $pack, $precision);
  1790. if ($epsilon < 0) {
  1791. return $pack;
  1792. } else if ($epsilon == 0) {
  1793. return 0;
  1794. } else {
  1795. $quotent = $quant / $pack;
  1796. $epsilon = round(((int) $quotent) - $quotent, $precision);
  1797. if ($epsilon == 0) {
  1798. return 0;
  1799. } else {
  1800. return ((int) $quotent + 1) * $pack;
  1801. }
  1802. }
  1803. }
  1804. return 0;
  1805. }
  1806.  
  1807. public function Basket_ajaxAction($instance) {
  1808. $ret = $this->Basket_add($instance);
  1809.  
  1810. foreach ($ret['added'] as &$p) {
  1811. $p['price'] = View_Smarty_Helper_Currency::currency(array(
  1812. 'value' => $p['price'],
  1813. ), null);
  1814. }
  1815.  
  1816. $user = Logic_UserOnline::getUser();
  1817. $ret['basket'] = array();
  1818. $ret['basket']['url'] = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER)->assemble(array(), 'basketRecount');
  1819. $ret['basket']['count'] = $user->basket->countProducts();
  1820. $ret['basket']['sum'] = View_Smarty_Helper_Currency::currency(array(
  1821. 'value' => $user->basket->sumProducts(),
  1822. ), null);
  1823.  
  1824. $user->basket->discoverDiscounts($user, true);
  1825. $ret['basket']['sum_after_discounts'] = View_Smarty_Helper_Currency::currency(array(
  1826. 'value' => $user->basket->sumProducts(),
  1827. ), null);
  1828. $ba = array();
  1829. foreach ($user->basket as $b) {
  1830. $c = array();
  1831. $c['image_url'] = View_Smarty_Helper_ImageUrl::imageUrl(array('type' => 'productGfx', 'width' => 75, 'height' => 75, 'image' => $b->stock->mainImageName(), 'overlay' => 1), null);
  1832. $c['name'] = $b->product->translation->name;
  1833. $c['product_id'] = $b->product->product->product_id;
  1834. $c['variant_name'] = $b->getName();
  1835. $c['quantity'] = View_Smarty_Helper_Float::float(array('precision' => Logic_UserBasketList::QUANTITY_PRECISION, "trim" => true, "noformat" => true, "value" => (float) $b->basket->quantity), null);
  1836. $c['unit'] = $b->product->unit->translation->name;
  1837. $c['price'] = View_Smarty_Helper_Currency::currency(array('value' => $b->getPrice()), null);
  1838. $c['price_all'] = View_Smarty_Helper_Currency::currency(array('value' => $b->getPriceForAll()), null);
  1839. $c['url'] = View_Smarty_Helper_Route::route(array("function" => "product", "key" => $b->product->product->product_id, "productName" => $b->product->unit->translation->name, "productId" => $b->product->product->product_id), null);
  1840. $c['remove_url'] = View_Smarty_Helper_Route::route(array("key" => "basketRemove", "basketId" => $b->getIdentifier()), null);
  1841. $ba[] = $c;
  1842. }
  1843. $ret['basket']['products'] = $ba;
  1844.  
  1845. header('Content-type: application/json');
  1846. echo json_encode($ret);
  1847. }
  1848.  
  1849. public function Basket_addAction($instance) {
  1850. if ($instance->getRequest()->isXmlHttpRequest()) {
  1851. $this->Basket_ajaxAction($instance);
  1852. return;
  1853. }
  1854.  
  1855. $ret = $this->Basket_add($instance);
  1856.  
  1857. foreach ($ret['messages'] as $f => $msgs) {
  1858. $f = 'add' . ucfirst($f);
  1859. foreach ($msgs as $msg) {
  1860. $instance->_flashMessanger->$f($msg);
  1861. }
  1862. }
  1863.  
  1864. if (!is_string($ret['redirect'])) {
  1865. $ret['redirect'] = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER)->assemble(array(), 'index');
  1866. }
  1867. $instance->_redirect($ret['redirect']);
  1868. }
  1869.  
  1870. public function Basket_finishedAction($instance) {
  1871. $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
  1872.  
  1873. if ($instance->_hasParam('status') && $instance->_hasParam('paymentid') && $instance->_hasParam('orderid')) {
  1874. $status = $instance->_getParam('status');
  1875. if (isset($_GET['status'])) {
  1876. $status = strtolower($_GET['status']);
  1877. }
  1878. $oid = (int) $instance->_getParam('orderid');
  1879. $order = new Logic_Order($oid);
  1880. if (false == $order->existsInDB()) {
  1881. $instance->_flashMessanger->addWarning(Locale_Manager::translate('Order has not been found.'));
  1882. $instance->_redirect($router->assemble(array(), 'index'));
  1883. return;
  1884. }
  1885.  
  1886. $handler = $order->payment->createHandler();
  1887.  
  1888. if ($handler instanceof Plugin_Payment_Online_Abstract) {
  1889. $handler->setOrder($order);
  1890. $msg = '';
  1891. if ('ok' == $status) {
  1892. $output = $handler->transactionCompleted($instance->getRequest());
  1893. $msg = Locale_Manager::translate('The order has been paid for.');
  1894. } elseif ('fail' == $status) {
  1895. $output = $handler->transactionFailed($instance->getRequest());
  1896. $msg = Locale_Manager::translate('Payment system error. The transaction failed.');
  1897. } else {
  1898. $instance->_redirect($router->assemble(array(), 'index'));
  1899. return;
  1900. }
  1901.  
  1902. $instance->view->payment_output = (string) $output;
  1903. $instance->view->msg = (string) $msg;
  1904. $instance->view->body_class = 'shop_basket_finished';
  1905. $instance->_handleFlashMessages();
  1906. return;
  1907. }
  1908. }
  1909.  
  1910. $instance->_redirect($router->assemble(array(), 'index'));
  1911. }
  1912.  
  1913. private function Basket_recount($instance) {
  1914. if (false === Zend_Registry::get('enable_basket')) {
  1915. $instance->_flashMessanger->addWarning(Locale_Manager::translate('Cart is disabled.'));
  1916. $instance->_redirect(Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER)->assemble(array(), 'index'));
  1917. return false;
  1918. }
  1919.  
  1920. $session = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_SESSION);
  1921.  
  1922. $array = array();
  1923. foreach ($_POST as $k => $v)
  1924. if (preg_match('/^quantity_[0-9]+$/i', $k))
  1925. $array[] = $k;
  1926.  
  1927. $err = array();
  1928. $err_products = array();
  1929. $user = Logic_UserOnline::getUser();
  1930.  
  1931. $form = new Form_Shop_Multifloat($array, true, Logic_UserBasketList::QUANTITY_PRECISION);
  1932. if ($form->isValid($_POST)) {
  1933. $val = $form->getFloats();
  1934.  
  1935. foreach ($val as $k => $v) {
  1936. $id = (int) substr($k, 9);
  1937. $b = new Logic_UserBasket($id);
  1938. if ($b->existsInDB()) {
  1939. $p = $b->stock->getPackage();
  1940. if (0 == (int) $b->product->unit->unit->floating_point) {
  1941. $v = $val[$k] = ceil($v);
  1942. $p = (int) ceil($p);
  1943. }
  1944.  
  1945. if ($v < Logic_UserBasketList::MIN_QUANTITY) {
  1946. $err[$id] = true;
  1947. $err_products[] = $b->product->translation->name;
  1948. }
  1949.  
  1950. $packs = $this->Basket_checkPack($p, $v);
  1951. if ($packs > 0) {
  1952. $val[$k] = $packs;
  1953. $instance->_flashMessanger->addSuccess(Locale_Manager::translate('This product can only be purchased in packages of %s %s', $b->product->translation->name, Locale_Manager::getFloat($p), $b->product->unit->translation->name));
  1954. }
  1955. }
  1956. }
  1957.  
  1958. if (0 == count($err)) {
  1959. foreach ($val as $k => $v) {
  1960. $k = (int) substr($k, 9);
  1961. $user->basketChange($k, $v);
  1962. }
  1963. }
  1964. } else {
  1965. $val = $form->getUnfilteredValues();
  1966. foreach ($val as $k => $v)
  1967. if ($v > 2147483647) {
  1968. $id = (int) substr($k, 9);
  1969. $b = new Logic_UserBasket($id);
  1970. if ($b->existsInDB()) {
  1971. $val[$k] = (float) $b->basket->quantity;
  1972. }
  1973. }
  1974.  
  1975. foreach (array_keys($form->getMessages()) as $k) {
  1976. $id = (int) substr($k, 9);
  1977. $err[$id] = true;
  1978. $b = new Logic_UserBasket($id);
  1979. if ($b->existsInDB()) {
  1980. $err_products[] = $b->product->translation->name;
  1981. }
  1982. }
  1983. }
  1984.  
  1985. if (count($err)) {
  1986. if (0 == count($err_products))
  1987. $instance->_flashMessanger->addError(Locale_Manager::translate('Incorrect quantity of products') . '.');
  1988. else
  1989. $instance->_flashMessanger->addError(Locale_Manager::translate('Incorrect quantity of products') . ': ' . implode(', ', $err_products));
  1990. }
  1991.  
  1992. $quantity = array();
  1993. foreach ($val as $k => $v)
  1994. if (preg_match('/^quantity_[0-9]+$/i', $k))
  1995. $quantity[(int) substr($k, 9)] = $v;
  1996. $instance->view->quantity = $quantity;
  1997. $instance->view->quantity_error = $err;
  1998.  
  1999.  
  2000.  
  2001.  
  2002.  
  2003. $form = new Form_Shop_Multifloat(array('shipping_id', 'payment_id'), false, 0);
  2004. if ($form->isValid($_POST)) {
  2005. $val = $form->getFloats();
  2006. if (isset($val['shipping_id']))
  2007. $this->_shipping_id = (int) $val['shipping_id'];
  2008. if (isset($val['payment_id']))
  2009. $this->_payment_id = (int) $val['payment_id'];
  2010. if (isset($_POST['shipping_country'][1]) && preg_match('/^[a-z]{2}$/i', $_POST['shipping_country']))
  2011. $this->_shipping_country = $_POST['shipping_country'];
  2012. }
  2013.  
  2014.  
  2015. if (1 === (int) Config_Manager::getConfigValue('shopping', 'USE_PROMO_CODES')) {
  2016. if (isset($_POST['promocode'][0]) || is_int($session->promocode_id)) {
  2017.  
  2018. if (isset($_POST['promocode'][0])) {
  2019. $form = new Form_Shop_Multistring(array('promocode'), false);
  2020. if ($form->isValid($_POST)) {
  2021. $val = $form->getValues();
  2022. $list = new Logic_PromoCodeList();
  2023. $select = $list->select();
  2024. $select->where('active = ?', 1);
  2025. $select->where('code = ?', $val['promocode']);
  2026. $list->fillFromSelect($select);
  2027. if (count($list) > 0) {
  2028. $promo = $list[0];
  2029. } else {
  2030. $promo = null;
  2031. }
  2032. } else {
  2033. $promo = null;
  2034. }
  2035. } else {
  2036. $promo = new Logic_PromoCode($session->promocode_id);
  2037. if (!$promo->existsInDb()) {
  2038. $promo = null;
  2039. }
  2040. }
  2041.  
  2042. $ok = false;
  2043. if ($promo instanceof Logic_PromoCode) {
  2044. $ret = $promo->testBasket($user->basket);
  2045. } else {
  2046. $ret = Logic_PromoCode::TEST_FAIL;
  2047. }
  2048.  
  2049. if (Logic_PromoCode::TEST_OK & $ret) {
  2050. $instance->view->promocode_error = false;
  2051. $session->promocode_id = (int) $promo->getIdentifier();
  2052. } elseif (Logic_PromoCode::TEST_FAIL & $ret) {
  2053. $instance->view->promocode_error = true;
  2054. $session->promocode_id = null;
  2055.  
  2056. if (Logic_PromoCode::TEST_FAIL_FACEBOOK & $ret) {
  2057. if (Zend_Registry::isRegistered(System_Bootstrap::REGISTRY_FACEBOOK_SKIN)) {
  2058. $skin = Zend_Registry::get(System_Bootstrap::REGISTRY_FACEBOOK_SKIN);
  2059. $msg = Locale_Manager::translate('Before using this code you have to press "Like it" on %sshop\'s fan page%s.');
  2060. $msg = sprintf($msg, '<a href="http://www.facebook.com/profile.php?id=' . $skin->getSettings()->facebook->pageid . '" target="_blank">', '</a>');
  2061. $instance->_flashMessanger->addError($msg);
  2062. } else {
  2063. $instance->_flashMessanger->addError(Locale_Manager::translate('This discount code can only be used on Facebook.'));
  2064. }
  2065. } else {
  2066. $instance->_flashMessanger->addError(Locale_Manager::translate('The coupon code you have entered is incorrect or has already been used.'));
  2067. }
  2068. }
  2069. } else {
  2070. $session->promocode_id = null;
  2071. }
  2072. } else {
  2073. $session->promocode_id = null;
  2074. }
  2075.  
  2076. return (0 == count($err)) && $this->Basket_checkQuantity($instance);
  2077. }
  2078.  
  2079. private function Basket_checkQuantity($instance, &$ret = null) {
  2080. $user = Logic_UserOnline::getUser();
  2081. $ok = true;
  2082. $msg = null;
  2083.  
  2084. $over = array();
  2085. $partial = array();
  2086.  
  2087. foreach ($user->basket as $x) {
  2088. $max = (float) $x->stock->getStockValue();
  2089. $id = (int) $x->stock->getIdentifier();
  2090. $q = (float) $x->basket->quantity;
  2091.  
  2092. if (isset($partial[$id])) {
  2093. $partial[$id] += $q;
  2094. } else {
  2095. $partial[$id] = $q;
  2096. }
  2097.  
  2098. if ($partial[$id] <= $max || 1 == (int) Config_Manager::getConfigValue('shopping', 'ALLOW_OVERSELLING')) {
  2099. continue;
  2100. }
  2101.  
  2102. $over[] = array($x, $max);
  2103. $ok = false;
  2104. }
  2105.  
  2106. if (1 == count($over)) {
  2107. $options = array();
  2108. foreach ($over[0][0]->stock->values as $value) {
  2109. $options[] = $value->option->translation->name . ': ' . $value->ovalue->translation->value;
  2110. }
  2111. if (!empty($options)) {
  2112. $strOptions = '[' . implode('; ', $options) . ']';
  2113. } else {
  2114. $strOptions = '';
  2115. }
  2116.  
  2117. $msg = Locale_Manager::translate(
  2118. 'Number of products in cart exceeds the stock. %s Current stock is: %s - %s %s %s', '<br />', $over[0][0]->product->translation->name, $over[0][1], $over[0][0]->product->unit->translation->name, $strOptions
  2119. );
  2120. $msg = rtrim($msg, '.') . '.'; // X szt..
  2121. } elseif (count($over) > 1) {
  2122. $msg = Locale_Manager::translate('Number of products in cart exceeds the stock. %s Current stock is:', '<br />');
  2123.  
  2124. foreach ($over as $o) {
  2125. $options = array();
  2126. $values = $o[0]->stock->values;
  2127. foreach ($values as $value) {
  2128. $options[] = $value->option->translation->name . ': ' . $value->ovalue->translation->value;
  2129. }
  2130. if (empty($options)) {
  2131. $strOptions = '';
  2132. } else {
  2133. $strOptions = '[' . implode('; ', $options) . ']';
  2134. }
  2135.  
  2136. $msg .= Locale_Manager::translate('%s - %s %s of %s %s', '<br />', $o[1], $o[0]->product->unit->translation->name, $o[0]->product->translation->name, $strOptions);
  2137. }
  2138. }
  2139.  
  2140. if (null !== $msg) {
  2141. if (null === $ret) {
  2142. $instance->_flashMessanger->addWarning($msg);
  2143. } else {
  2144. $ret['messages']['warning'][] = $msg;
  2145. }
  2146. }
  2147.  
  2148. return $ok;
  2149. }
  2150.  
  2151. private function Basket_getSum($shipping = true) {
  2152. $basket = Logic_UserOnline::getUser()->basket;
  2153. $sum = $basket->sumProducts();
  2154.  
  2155. if ($shipping && $this->_shipping_id > 0) {
  2156. $shipping = new Logic_ShippingMethod($this->_shipping_id);
  2157. $sum += $shipping->getCost($basket, $this->_payment_id);
  2158. }
  2159.  
  2160.  
  2161. return $sum;
  2162. }
  2163.  
  2164. private function Basket_shippingCountries() {
  2165. $session = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_SESSION);
  2166. $arr = array();
  2167. if (is_int($session->shipping_id)) {
  2168. $s = new Logic_ShippingMethod((int) $session->shipping_id);
  2169. $arr = Locale_Manager::mapCountries($s->getCountries());
  2170. }
  2171. asort($arr);
  2172. return $arr;
  2173. }
  2174.  
  2175. private function Basket_processBasket($instance, $check_limits = false) {
  2176.  
  2177. $instance->view->shippings = array();
  2178. $instance->view->payments = array();
  2179. $instance->view->shipping2payment = '[]';
  2180. $instance->view->country2shipping = '[]';
  2181. $instance->view->shippingvalue = '[]';
  2182. $instance->view->paymentadditional = '[]';
  2183. $instance->view->promocode = false;
  2184.  
  2185. $curr_id = (int) Locale_Manager::getLogicCurrency()->getIdentifier();
  2186. $user = Logic_UserOnline::getUser();
  2187. $sum = $this->Basket_getSum(false);
  2188. $quantity = $user->basket->countProducts();
  2189. $weight = $user->basket->weightProducts();
  2190.  
  2191. $ret = $user->basket->discoverDiscounts($user, true);
  2192.  
  2193. $instance->view->promos = $user->basket->getDiscountsMessages();
  2194.  
  2195. if ($ret & Logic_PromoCode::TEST_FAIL) {
  2196. $instance->view->promocode = false;
  2197. $instance->view->promocode_error = true;
  2198. $instance->_flashMessanger->addError(Locale_Manager::translate('The coupon code you have entered is incorrect or has already been used.'));
  2199. } else {
  2200. $instance->view->promocode = $user->basket->getPromocode();
  2201. }
  2202.  
  2203.  
  2204. /* Shipping & Payment */
  2205. $list = new Logic_ShippingMethodList();
  2206. $select = $list->select(false)->distinct();
  2207. list($hasEmptyGaugeId, $gauges) = $user->getRequiredGauges();
  2208.  
  2209. $select->join('shipping_payment', 'shipping_method.shipping_id = shipping_payment.shipping_id', null);
  2210. $select->join('payment_method_translations', 'shipping_payment.payment_id = payment_method_translations.payment_id', null);
  2211. $select->join('payment_currency', 'payment_method_translations.payment_id = payment_currency.payment_id', null);
  2212. $select->where('shipping_method.active = ?', 1);
  2213. $select->where('shipping_method.lang_id = ?', Locale_Manager::getLanguageId());
  2214. $select->where('payment_method_translations.active = ?', 1);
  2215. $select->where('payment_method_translations.lang_id = ?', Locale_Manager::getLanguageId());
  2216. $select->where('payment_currency.currency_id = ?', $curr_id);
  2217. $select->where('shipping_method.visible = ?', 1);
  2218. if (Zend_Registry::isRegistered(System_Bootstrap::REGISTRY_MOBILE)) {
  2219. $select->where('shipping_method.mobile = ?', 1);
  2220. }
  2221.  
  2222. $select->order('order ASC');
  2223.  
  2224. $fields = array(
  2225. 'shipping_id',
  2226. 'totalNullShippingGauges' => '(' .
  2227. 'SELECT COUNT(id) FROM shipping_gauges ' .
  2228. 'WHERE shipping_gauges.shipping_id = t.shipping_id ' .
  2229. 'AND shipping_gauges.gauge_id IS NULL' .
  2230. ')',
  2231. 'totalNotNullShippingGauges' => '(' .
  2232. 'SELECT COUNT(id) FROM shipping_gauges ' .
  2233. 'WHERE shipping_gauges.shipping_id = t.shipping_id ' .
  2234. 'AND shipping_gauges.gauge_id IS NOT NULL' .
  2235. ')'
  2236. );
  2237.  
  2238. if (!empty($gauges)) {
  2239. $fields['shippingGauges'] = '(' .
  2240. 'SELECT COUNT(id) FROM shipping_gauges ' .
  2241. 'WHERE shipping_gauges.shipping_id = t.shipping_id ' .
  2242. 'AND gauge_id IN (' . implode(',', $gauges) . ') ' .
  2243. 'AND shipping_gauges.gauge_id IS NOT NULL' .
  2244. ')';
  2245. } else {
  2246. $fields['shippingGauges'] = '(SELECT 0)';
  2247. }
  2248.  
  2249. $select2 = $list->select(false);
  2250. $select2->from(array('t' => new Zend_Db_Expr('(' . $select . ')')), $fields);
  2251. $select2->setIntegrityCheck(false);
  2252.  
  2253. // totalNotNullShippingGauges = 0 AND totalNullShippingGauges = 0 -> dla każdego
  2254. // totalNullShippingGauges > 0 -> brak
  2255.  
  2256. if (!empty($gauges) && !$hasEmptyGaugeId) { // gabaryt(1) + gabaryt(2) + ... + gabaryt(n)
  2257. $select2->having('(totalNotNullShippingGauges = 0 AND totalNullShippingGauges = 0) OR shippingGauges = ?', count($gauges));
  2258. } elseif (!empty($gauges) && $hasEmptyGaugeId) { // gabaryt(1) + gabaryt(2) + ... + gabaryt(n) + brak
  2259. $select2->having('(totalNotNullShippingGauges = 0 AND totalNullShippingGauges = 0) OR (shippingGauges = ? AND totalNullShippingGauges > 0)', count($gauges));
  2260. } else { // brak
  2261. $select2->having('(totalNotNullShippingGauges = 0 AND totalNullShippingGauges = 0) OR totalNullShippingGauges > 0');
  2262. }
  2263.  
  2264. $list->fillFromSelect($select2);
  2265.  
  2266. $shippings = array();
  2267. foreach ($list as $k => $s) {
  2268. $max = (float) $s->shipping->max_cost;
  2269. if ($max > 0 && $sum > $max)
  2270. continue;
  2271.  
  2272. $max = (float) $s->shipping->max_weight;
  2273. if ($max > 0 && $weight > $max)
  2274. continue;
  2275.  
  2276. $min = (float) $s->shipping->min_weight;
  2277. if ($min > 0 && $weight < $min)
  2278. continue;
  2279.  
  2280. $shippings[] = (int) $s->getIdentifier();
  2281. }
  2282.  
  2283. if (0 == count($shippings)) {
  2284. $instance->_flashMessanger->addWarning(Locale_Manager::translate('Store administrator has not defined a shipping method that meets the criteria of your order.'));
  2285. return false;
  2286. }
  2287.  
  2288. $list->clean()->fillFromDataSet($shippings);
  2289.  
  2290. $p = array();
  2291. foreach ($list as $s) {
  2292. foreach ($s->payments as $payment) {
  2293. $p[(int) $payment->getIdentifier()] = 1;
  2294. }
  2295. }
  2296.  
  2297. $shipping_countries = Locale_Manager::mapCountries($list->getCountries());
  2298. if (0 == count($shipping_countries)) {
  2299. $instance->_flashMessanger->addWarning(
  2300. Locale_Manager::translate('Store Administrator has not defined any country supported by the shipping methods.')
  2301. );
  2302. return false;
  2303. }
  2304. $instance->view->shipping_countries = $shipping_countries;
  2305.  
  2306.  
  2307. $payments = new Logic_PaymentMethodList();
  2308. $select = $payments->select();
  2309. $select->join('payment_method_translations', 'payment_method_translations.payment_id = payment_method.payment_id', null);
  2310. $select->join('payment_currency', 'payment_method.payment_id = payment_currency.payment_id', null);
  2311. $select->where('payment_method_translations.active = ?', 1);
  2312. $select->where('payment_method_translations.lang_id = ?', Locale_Manager::getLanguageId());
  2313. $select->where('currency_id = ?', $curr_id);
  2314. $select->where('name != ?', 'zero');
  2315. $select->order('payment_method.order ASC');
  2316. $payments->fillFromSelect($select);
  2317.  
  2318. $payments_ids = array();
  2319.  
  2320. foreach ($payments as $k => $payment) {
  2321. $id = (int) $payment->getIdentifier();
  2322. if (!isset($p[$id])) {
  2323. continue;
  2324. }
  2325.  
  2326. if (!$payment->supportsCurrency($curr_id)) {
  2327. continue;
  2328. }
  2329.  
  2330. if (!$payment->supportsBasket($user->basket)) {
  2331. continue;
  2332. }
  2333.  
  2334. $payments_ids[] = $id;
  2335. }
  2336.  
  2337. if (0 == $sum) {
  2338. $zeropayid = $payments->select()->where('name = ?', 'zero')->query()->fetch(PDO::FETCH_NUM);
  2339. if (is_array($zeropayid) && isset($zeropayid[0][0])) {
  2340. $zeropayid = (int) $zeropayid[0];
  2341. $payments_ids[] = $zeropayid;
  2342. } else {
  2343. $zeropayid = false;
  2344. }
  2345. } else {
  2346. $zeropayid = false;
  2347. }
  2348.  
  2349. $payments->clean()->fillFromDataSet($payments_ids);
  2350.  
  2351. $c2s = array();
  2352. foreach ($shipping_countries as $k => $v) {
  2353. $c2s[$k] = array();
  2354. }
  2355.  
  2356. $s2p = array();
  2357. $sv = array();
  2358. $unset = array();
  2359. $payadd = array();
  2360. $addPaymentCost = (int) Config_Manager::getConfigValue('shipping', 'ADD_PAYMENT_COST_TO_FREE_SHIPPING');
  2361.  
  2362. foreach ($list as $k => $shipping) {
  2363. try {
  2364. $cost4ship = $shipping->getCost($user->basket);
  2365. if (0 == $sum && 0 == $cost4ship) {
  2366. $i = array($zeropayid);
  2367. } else {
  2368. $i = array_intersect($shipping->getPaymentsIds(), $payments_ids);
  2369. }
  2370. } catch (Exception $e) {
  2371. $instance->_errorLog->err($e);
  2372. $i = array();
  2373. }
  2374.  
  2375. if (0 == count($i)) {
  2376. $unset[] = $k;
  2377. continue;
  2378. } else {
  2379. $s2p['s' . $shipping->getIdentifier()] = array_values($i);
  2380. $sv['s' . $shipping->getIdentifier()] = View_Smarty_Helper_Currency::currency(array(
  2381. 'value' => $cost4ship,
  2382. 'float' => true,
  2383. ), null);
  2384. }
  2385.  
  2386. foreach ($shipping->getCountries() as $c) {
  2387. $c2s[$c][] = (int) $shipping->getIdentifier();
  2388. }
  2389. foreach ($i as $id) {
  2390. $c = $shipping->getCostForPayment($id);
  2391. if ($c && 0 == $cost4ship && 0 == $addPaymentCost) {
  2392. $c = false;
  2393. }
  2394.  
  2395. if ($c && $c['cost'] > 0) {
  2396. if (true == $c['percent']) {
  2397. $t = $c['cost'];
  2398. $c = $user->basket->sumProducts() * $c['cost'];
  2399. $p = $t * 100 . '%';
  2400. } else {
  2401. $c = $c['cost'];
  2402. $t = $c;
  2403. $p = null;
  2404. }
  2405.  
  2406. $payadd['s' . $shipping->getIdentifier()]['p' . $id] = array(
  2407. 'v' => View_Smarty_Helper_Currency::currency(array(
  2408. 'value' => (float) $c,
  2409. 'float' => true,
  2410. ), null),
  2411. 't' => View_Smarty_Helper_Currency::currency(array(
  2412. 'value' => (float) $c
  2413. ), null)
  2414. );
  2415.  
  2416. if ($p != null) {
  2417. if ($p > 0) {
  2418. $p = '+' . $p;
  2419. }
  2420. $payadd['s' . $shipping->getIdentifier()]['p' . $id]['p'] = $p;
  2421. }
  2422. }
  2423. }
  2424. }
  2425.  
  2426. foreach ($unset as $x) {
  2427. unset($list[$x]);
  2428. }
  2429.  
  2430. if (is_null($this->_shipping_id) || !in_array($this->_shipping_id, $list->getIdentifiers())) {
  2431. foreach ($list as $s) {
  2432. if (1 == (int) $s->shipping->is_default) {
  2433. $this->_shipping_id = (int) $s->getIdentifier();
  2434. break;
  2435. }
  2436. }
  2437. }
  2438.  
  2439. if (count($list) > 0 && ( is_null($this->_shipping_id) || !in_array($this->_shipping_id, $list->getIdentifiers()) )) {
  2440. $list->rewind();
  2441.  
  2442. $defaultShippingId = (int) $list->current()->getIdentifier();
  2443. foreach ($list as $shippingMethod) {
  2444. if ($shippingMethod->shipping->is_default == 1) {
  2445. $defaultShippingId = $shippingMethod->getIdentifier();
  2446. break;
  2447. }
  2448. }
  2449. $this->_shipping_id = $defaultShippingId;
  2450. }
  2451.  
  2452. if (is_null($this->_shipping_country)) {
  2453. $this->_shipping_country = Locale_Manager::getRegion(); //Config_Manager::getConfigValue('company', 'COUNTRY');
  2454. }
  2455.  
  2456. $instance->view->shipping_id = $this->_shipping_id;
  2457. $instance->view->shipping_country = $this->_shipping_country;
  2458. $instance->view->shippings = $list;
  2459. $instance->view->shipping2payment = Zend_Json::encode($s2p);
  2460. $instance->view->country2shipping = Zend_Json::encode($c2s);
  2461. $instance->view->shippingvalue = Zend_Json::encode($sv);
  2462. $instance->view->paymentadditional = Zend_Json::encode($payadd);
  2463.  
  2464.  
  2465. if (0 == count($payments)) {
  2466. $instance->_flashMessanger->addWarning(Locale_Manager::translate('Store administrator has not defined a payment method that meets the criteria of your order.'));
  2467. return false;
  2468. }
  2469.  
  2470. $instance->view->payments = $payments;
  2471. if (is_null($this->_payment_id) || !in_array($this->_payment_id, $payments->getIdentifiers()))
  2472. $this->_payment_id = (int) $payments[0]->getIdentifier();
  2473.  
  2474.  
  2475.  
  2476.  
  2477. /* No JS $_POST check */
  2478.  
  2479. if ($this->getRequest()->isPost() && $this->_shipping_id > 0 && $this->_payment_id > 0 && strlen($this->_shipping_country) > 0) {
  2480. $current_shipping = new Logic_ShippingMethod($this->_shipping_id);
  2481. $current_payment = new Logic_PaymentMethod($this->_payment_id);
  2482.  
  2483. if (0 == $sum && 0 == $current_shipping->getCost($user->basket) && $zeropayid > 0) {
  2484. $payments_ids = array($zeropayid);
  2485. } else {
  2486. $payments_ids = $current_shipping->getPaymentsIds();
  2487. }
  2488.  
  2489. if (!in_array($this->_payment_id, $payments_ids)) {
  2490. $instance->_flashMessanger->addWarning(sprintf(
  2491. Locale_Manager::translate('"%s" shipping method does not support "%s" payment method. Enable JavaScript in your browser to facilitate the selection.'), $current_shipping->shipping->name, $current_payment->translation->title
  2492. ));
  2493. return false;
  2494. }
  2495.  
  2496. if (!in_array($this->_shipping_country, $current_shipping->getCountries())) {
  2497. $c = Locale_Manager::mapCountries(array($this->_shipping_country));
  2498. $instance->_flashMessanger->addWarning(sprintf(
  2499. Locale_Manager::translate('"%s" shipping method does not work within %s. Enable JavaScript in your browser to facilitate the selection.'), $current_shipping->shipping->name, current($c)
  2500. ));
  2501. return false;
  2502. }
  2503. }
  2504.  
  2505.  
  2506. //cleanup
  2507. $cleaned = false;
  2508. foreach ($user->basket as $p) {
  2509. if (!$p || !$p->product->translation || 0 == (int) $p->stock->stock->active || 0 == (int) $p->product->translation->active || !$p->stock->availability->availability->can_buy) {
  2510.  
  2511. $id = (int) $p->basket->id;
  2512. if ($id > 0) {
  2513. $user->basketRemove($id);
  2514. $p->free();
  2515. $cleaned = true;
  2516. }
  2517. }
  2518. }
  2519.  
  2520. if ($cleaned) {
  2521. $user->resetBasket();
  2522. }
  2523.  
  2524. if (false == $check_limits) {
  2525. return true;
  2526. }
  2527.  
  2528. if (0 == (int) Config_Manager::getConfigValue('shopping', 'PRODUCTS_ALLOW_ZERO')) {
  2529. $min_value = (float) Locale_Manager::getFloat(Config_Manager::getConfigValue('shopping', 'MIN_ORDER_VALUE'));
  2530. if ($min_value > 0 && $user->basket->sumProducts() < $min_value) {
  2531. $instance->_flashMessanger->addWarning(Locale_Manager::translate('The minimum required order amount is') . ': ' .
  2532. View_Smarty_Helper_Currency::currency(array('value' => $min_value), null)
  2533. );
  2534. return false;
  2535. }
  2536. }
  2537.  
  2538.  
  2539. $quantity = $user->basket->countProducts();
  2540. if (Config_Manager::hasConfigValue('shopping', 'MIN_PROD_QUANTITY')) {
  2541. $min_quantity = (float) Config_Manager::getConfigValue('shopping', 'MIN_PROD_QUANTITY');
  2542. if ($min_quantity > 0 && $quantity < $min_quantity) {
  2543. $instance->_flashMessanger->addWarning(Locale_Manager::translate('The minimum required number of items in the cart is') . ': ' . $min_quantity);
  2544. return false;
  2545. }
  2546. }
  2547.  
  2548. return true;
  2549. }
  2550.  
  2551. public function Login_loginAction($instance) {
  2552. $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
  2553.  
  2554. if (Access_ClientManager::isLoggedIn()) {
  2555. $instance->_redirect($router->assemble(array(), 'index'));
  2556. return;
  2557. }
  2558.  
  2559. $instance->_breadCrumbs->add(Locale_Manager::translate('Sign in'), '');
  2560.  
  2561. View_Smarty::setCacheTag(array(
  2562. 'Logic_UserList', 'Logic_User', 'Logic_AdditionalField', 'Logic_AdditionalFieldList'
  2563. ));
  2564.  
  2565. $this->view->last_url = $_SERVER['HTTP_REFERER'];
  2566.  
  2567. if ($instance->getRequest()->isPost() && 'index' == $instance->getRequest()->action) {
  2568. $this->view->last_url = $_POST['last_url'];
  2569. $form = new Form_Shop_Login();
  2570.  
  2571. if ($form->isValid($_POST)) {
  2572. $val = $form->getValues();
  2573.  
  2574. $result = Access_ClientManager::authenticate($val['mail'], $val['pass']);
  2575.  
  2576. if ($result->isValid()) {
  2577. Plugin_Manager::callShopEvent('userLoginSuccess', array($result->getIdentity()));
  2578.  
  2579. if (Zend_Registry::isRegistered('user_login_product_recovery')) {
  2580. $moved = (int) Zend_Registry::get('user_login_product_recovery');
  2581. if ($moved > 0) {
  2582. if ($moved > 1) {
  2583. $instance->_flashMessanger->addInfo(Locale_Manager::translate('Products have been restored to your shopping cart from the previous session.', $moved));
  2584. } else {
  2585. $instance->_flashMessanger->addInfo(Locale_Manager::translate('Product has been restored to your shopping cart from the previous session.', $moved));
  2586. }
  2587. //$instance->_redirect( $router->assemble(array(), 'basket') );
  2588. //return;
  2589. }
  2590. }
  2591.  
  2592. $session = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_SESSION);
  2593. if (is_string($val['last_url']) && strlen($val['last_url'])) {
  2594. $instance->_redirect($val['last_url']);
  2595. return;
  2596. }
  2597.  
  2598. $instance->_redirect($router->assemble(array(), 'index'));
  2599. return;
  2600. } else {
  2601. switch ($result->getCode()) {
  2602. case Access_Auth_Result::FAILURE_USER_INACTIVE:
  2603. $instance->_flashMessanger->addError(Locale_Manager::translate('Inactive account.'));
  2604. break;
  2605. case Access_Auth_Result::FAILURE_USER_NOT_VERIFIED:
  2606. $instance->_flashMessanger->addError(Locale_Manager::translate('Your registration has not been confirmed. Check your e-mail and click the confirmation link.'));
  2607. break;
  2608. default:
  2609. $instance->_flashMessanger->addError(Locale_Manager::translate('Incorrect login details'));
  2610. break;
  2611. }
  2612. }
  2613. } else {
  2614. $instance->_flashMessanger->addError(Locale_Manager::translate('Incorrect login details'));
  2615. Access_ClientManager::logout();
  2616. }
  2617. }
  2618.  
  2619. $instance->view->passlink = $router->assemble(array(), 'passremind');
  2620.  
  2621. $instance->view->body_class = 'shop_login';
  2622. $instance->_handleFlashMessages();
  2623. }
  2624.  
  2625. public function Login_logoutAction($instance) {
  2626. Access_ClientManager::logout();
  2627. Zend_Session::regenerateId();
  2628. Logic_UserOnline::recreate();
  2629. $instance->_flashMessanger->addSuccess(Locale_Manager::translate('You have been successfully logged out.'));
  2630. $instance->_redirect(Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER)->assemble(array(), 'index'));
  2631. }
  2632.  
  2633. public function Login_passremindAction($instance) {
  2634.  
  2635. $instance->_breadCrumbs->add(Locale_Manager::translate('Password change'), '');
  2636. $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
  2637.  
  2638. if ($instance->getRequest()->isPost()) {
  2639.  
  2640. $form = new Form_Shop_Passremind();
  2641.  
  2642. if ($form->isValid($_POST)) {
  2643. $val = $form->getValues();
  2644.  
  2645. $ui = new Entity_UserInfo();
  2646. $select = $ui->select()->from($ui, 'user_id');
  2647. $select->where('email = ?', $val['remindmail']);
  2648. $list = new Logic_UserList();
  2649. $list->fillFromSelect($select);
  2650.  
  2651. if (1 == $list->count()) {
  2652. $user = $list[0];
  2653.  
  2654. $url = $router->assemble(array(
  2655. 'userId' => (int) $user->getIdentifier(),
  2656. 'code' => self::Login_passCode($user),
  2657. ), 'passremindStep2', System_Router::ROUTE_TYPE_CORE, true, array(), false, Zend_Registry::get(System_Bootstrap::REGISTRY_ROUTER_BASEURL));
  2658.  
  2659. $template = Mail_Manager::getMailTemplate(Mail_Manager::MAIL_PASSWORD_REMINDER);
  2660. $message = new Mail_Message($template);
  2661. $message->setVarArray(array(
  2662. 'email' => $user->userinfo->email,
  2663. 'link' => $url,
  2664. ));
  2665. $message->addRecipient($user->userinfo->email, false);
  2666.  
  2667. $metafields = new Metafield_Manager();
  2668. foreach ($metafields->getMetafieldObjectList() as $m) {
  2669. $key = "metafield.system." . $m->metafield->metafield->namespace . "." . $m->metafield->metafield->key;
  2670. $message->setVar($key, Zend_Controller_Action_HelperBroker::getExistingHelper('ViewRenderer')->view->escape($m->value->value));
  2671. }
  2672.  
  2673. $metafields = $user->metafields;
  2674. foreach ($metafields->getMetafieldObjectList() as $m) {
  2675. $key = "metafield.user." . $m->metafield->metafield->namespace . "." . $m->metafield->metafield->key;
  2676. $message->setVar($key, Zend_Controller_Action_HelperBroker::getExistingHelper('ViewRenderer')->view->escape($m->value->value));
  2677. }
  2678.  
  2679. try {
  2680. Mail_Manager::send($message, true);
  2681. Access_ClientManager::logout();
  2682. $instance->_flashMessanger->addSuccess(Locale_Manager::translate('E-mail message has been sent.'));
  2683. $instance->_redirect($router->assemble(array(), 'index'));
  2684. return;
  2685. } catch (Exception $e) {
  2686. $instance->_errorLog->err($e);
  2687. $instance->_flashMessanger->addWarning(Locale_Manager::translate('Error while sending e-mail.'));
  2688. }
  2689. } else
  2690. $instance->_flashMessanger->addWarning(Locale_Manager::translate('Error while sending e-mail.'));
  2691. } else {
  2692. $uv = $form->getUnfilteredValues();
  2693. $instance->view->remindmail = $uv['remindmail'];
  2694. $instance->view->data_error = $form->getMessages();
  2695. $instance->_flashMessanger->addError(Locale_Manager::translate('There is no such e-mail address in the database.'));
  2696. }
  2697. }
  2698.  
  2699. $instance->view->body_class = 'shop_login_passremind';
  2700. $instance->_handleFlashMessages();
  2701. }
  2702.  
  2703. public function Login_passremind2Action($instance) {
  2704. $session = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_SESSION);
  2705. $instance->_breadCrumbs->add(Locale_Manager::translate('Password change'), '');
  2706.  
  2707. if ($instance->_hasParam('userId') && $instance->_hasParam('code')) {
  2708. $uid = (int) $instance->_getParam('userId');
  2709. $code = $instance->_getParam('code');
  2710.  
  2711. if ($uid > 0 && 40 == strlen($code)) {
  2712. try {
  2713. $user = new Logic_User($uid);
  2714.  
  2715. if (self::Login_passCode($user) === $code) {
  2716. $session->passchange_uid = $uid;
  2717. return;
  2718. }
  2719. } catch (Exception $e) {
  2720.  
  2721. }
  2722. }
  2723. } elseif ($instance->getRequest()->isPost() && is_int($session->passchange_uid)) {
  2724.  
  2725. $form = new Form_Shop_Passchange();
  2726.  
  2727. if ($form->isValid($_POST)) {
  2728. $val = $form->getValues();
  2729. $pass = $val['pass1'];
  2730.  
  2731. try {
  2732. $user = new Logic_User($session->passchange_uid);
  2733. $user->setPassword($pass);
  2734. $instance->_flashMessanger->addSuccess(Locale_Manager::translate('Password has been changed. You can now sign in.'));
  2735. $instance->_redirect(Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER)->assemble(array(), 'login'));
  2736. } catch (Exception $e) {
  2737.  
  2738. }
  2739. } else {
  2740. $instance->view->data_error = $form->getMessages();
  2741. $instance->_flashMessanger->addError(Locale_Manager::translate('Form contains errors.'));
  2742. }
  2743.  
  2744. return;
  2745. }
  2746.  
  2747. $instance->_flashMessanger->addError(Locale_Manager::translate('Invalid authorization code.'));
  2748. $instance->_forward('passremind');
  2749. }
  2750.  
  2751. public function Login_registerAction($instance) {
  2752. if (Access_ClientManager::isLoggedIn()) {
  2753. $instance->_redirect(Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER)->assemble(array(), 'index'));
  2754. return;
  2755. }
  2756.  
  2757. if (!Zend_Registry::get('enable_register')) {
  2758. $instance->_flashMessanger->addWarning(Locale_Manager::translate('Registration is temporarily unavailable'));
  2759. $instance->_redirect(Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER)->assemble(array(), 'index'));
  2760. return;
  2761. }
  2762.  
  2763. $instance->_breadCrumbs->add(Locale_Manager::translate('Registration'), '');
  2764.  
  2765. if (Config_Manager::hasConfigValue('registration', 'REQUIRE_ADDRESS') &&
  2766. 1 == (int) Config_Manager::getConfigValue('registration', 'REQUIRE_ADDRESS')) {
  2767. $mode = 'full';
  2768. } else {
  2769. $mode = 'simple';
  2770. }
  2771.  
  2772. $fields = Logic_AdditionalField::getByLocate(
  2773. Logic_AdditionalField::LOCATE_USER_REGISTRATION, Locale_Manager::getLanguageId()
  2774. );
  2775. $instance->view->additional_fields = $fields;
  2776.  
  2777. if ('full' == $mode)
  2778. $table1 = array(
  2779. 'name' => array(
  2780. 'name' => 'name',
  2781. 'obligatory' => true,
  2782. 'label' => Locale_Manager::translate('First name'),
  2783. 'type' => 'text',
  2784. 'hint' => '',
  2785. 'value' => '',
  2786. 'rowspan' => 1,
  2787. ),
  2788. 'surname' => array(
  2789. 'name' => 'surname',
  2790. 'obligatory' => true,
  2791. 'label' => Locale_Manager::translate('Last name'),
  2792. 'type' => 'text',
  2793. 'rowspan' => 1,
  2794. ),
  2795. 'phone' => array(
  2796. 'name' => 'phone',
  2797. 'obligatory' => true,
  2798. 'label' => Locale_Manager::translate('Phone'),
  2799. 'type' => 'text',
  2800. 'hint' => Locale_Manager::translate('Number format, e.g.: 123456789'),
  2801. 'rowspan' => 1,
  2802. ),
  2803. );
  2804. else
  2805. $table1 = array();
  2806.  
  2807. $table1['mail'] = array(
  2808. 'name' => 'mail',
  2809. 'obligatory' => true,
  2810. 'label' => Locale_Manager::translate('E-mail'),
  2811. 'type' => 'text',
  2812. 'rowspan' => 1,
  2813. );
  2814. $table1['pass1'] = array(
  2815. 'name' => 'pass1',
  2816. 'obligatory' => true,
  2817. 'label' => Locale_Manager::translate('Password'),
  2818. 'type' => 'password',
  2819. 'hint' => Locale_Manager::translate('Minimum of 6 characters'),
  2820. 'rowspan' => 1,
  2821. );
  2822. $table1['pass2'] = array(
  2823. 'name' => 'pass2',
  2824. 'obligatory' => true,
  2825. 'label' => Locale_Manager::translate('Repeat password'),
  2826. 'type' => 'password',
  2827. 'rowspan' => 1,
  2828. );
  2829.  
  2830.  
  2831. if ('simple' == $mode)
  2832. $table2 = array();
  2833. else
  2834. $table2 = array(
  2835. 'coname' => array(
  2836. 'name' => 'coname',
  2837. 'obligatory' => true,
  2838. 'label' => Locale_Manager::translate('Company name'),
  2839. 'type' => 'text',
  2840. 'rowspan' => 1,
  2841. ),
  2842. 'nip' => array(
  2843. 'name' => 'nip',
  2844. 'obligatory' => true,
  2845. 'label' => Locale_Manager::translate('Tax ID'),
  2846. 'type' => 'text',
  2847. 'rowspan' => 1,
  2848. ),
  2849. 'pesel' => array(
  2850. 'name' => 'pesel',
  2851. 'label' => Locale_Manager::translate('Personal Identification Number'),
  2852. 'type' => 'text',
  2853. 'rowspan' => 1,
  2854. ),
  2855. 'other_address' => array(
  2856. 'name' => 'other_address',
  2857. 'obligatory' => true,
  2858. 'label' => Locale_Manager::translate('Street and house no.'),
  2859. 'type' => 'text',
  2860. 'hint' => Locale_Manager::translate('For example: 115 Oxford Street'),
  2861. 'rowspan' => 1,
  2862. ),
  2863. 'zip' => array(
  2864. 'name' => 'zip',
  2865. 'obligatory' => true,
  2866. 'label' => Locale_Manager::translate('Postal code'),
  2867. 'type' => 'text',
  2868. 'hint' => Locale_Manager::translate('Postal code format'),
  2869. 'rowspan' => 1,
  2870. ),
  2871. 'city' => array(
  2872. 'name' => 'city',
  2873. 'obligatory' => true,
  2874. 'label' => Locale_Manager::translate('City'),
  2875. 'type' => 'text',
  2876. 'rowspan' => 1,
  2877. ),
  2878. 'country' => array(
  2879. 'name' => 'country',
  2880. 'obligatory' => false,
  2881. 'label' => Locale_Manager::translate('Country'),
  2882. 'type' => 'select',
  2883. 'list' => Locale_Manager::getCountries(),
  2884. 'rowspan' => 1,
  2885. ),
  2886. );
  2887.  
  2888. if (Zend_Registry::isRegistered(System_Bootstrap::REGISTRY_MOBILE)) {
  2889. $f = Zend_Registry::get(System_Bootstrap::REGISTRY_MOBILE);
  2890. if ($f) {
  2891. unset($table2['coname']['obligatory']);
  2892. unset($table2['nip']['obligatory']);
  2893. }
  2894. }
  2895.  
  2896. $pesel = (1 == (int) Config_Manager::getConfigValue('shopping', 'SUPPORT_PESEL'));
  2897. if (false === $pesel && isset($table2['pesel'])) {
  2898. unset($table2['pesel']);
  2899. }
  2900.  
  2901.  
  2902.  
  2903. if ($instance->getRequest()->isPost()) {
  2904.  
  2905. $form = new Form_Shop_Register(array($table1, $table2, $fields));
  2906.  
  2907. if (isset($_POST['phone'][0])) {
  2908. if ('+' == $_POST['phone'][0])
  2909. $_POST['phone'] = '00' . substr($_POST['phone'], 1);
  2910. $_POST['phone'] = preg_replace('/[\.\s\(\)]/', '', $_POST['phone']);
  2911. }
  2912.  
  2913. if ($form->isValid($_POST)) {
  2914. $val = $form->getValues();
  2915.  
  2916. $user = new Logic_User();
  2917. $user->create();
  2918. $user->user->date_add = date('Y-m-d H:i:s');
  2919. $user->save();
  2920.  
  2921. $autoGroup = 0;
  2922. if (Config_Manager::hasConfigValue("registration", "auto_add_to_group")) {
  2923. $group = Config_Manager::getConfigValue("registration", "auto_add_to_group");
  2924. $uList = new Logic_UserGroupList();
  2925. $uSelect = $uList->select();
  2926. $uSelect->where("group_id = ?", $group);
  2927. $uSelect->limit(1);
  2928. $uList->fillFromSelect($uSelect);
  2929. if (count($uList)) {
  2930. $autoGroup = $group;
  2931. }
  2932. }
  2933. if ($autoGroup > 0) {
  2934. $table = new Entity_UserGroupsUsers();
  2935. $table->insert(array(
  2936. 'group_id' => $autoGroup,
  2937. 'user_id' => $user->getIdentifier(),
  2938. ));
  2939. $grp = Logic_UserGroup::loadInstance($autoGroup);
  2940. $grp->removeCachedObject();
  2941. }
  2942.  
  2943. $user->createInfo();
  2944. $user->createSearch();
  2945. $user->setPassword($val['pass1']);
  2946. $user->userinfo->email = $val['mail'];
  2947. if ('full' == $mode) {
  2948. $user->userinfo->firstname = $val['name'];
  2949. $user->userinfo->lastname = $val['surname'];
  2950. }
  2951. $user->userinfo->lang_id = Locale_Manager::getLanguageId();
  2952. $user->userinfo->active = 1;
  2953.  
  2954. $user->user->verify_email = 0;
  2955. $confirm = ( 1 == (int) Config_Manager::getConfigValue('registration', 'CONFIRM_REGISTER') );
  2956. if ($confirm) {
  2957. $user->user->verify_code = md5($val['mail'] . microtime(true));
  2958. }
  2959.  
  2960. foreach ($val as $k => $v)
  2961. if ('additional_' == substr($k, 0, 11) && strlen($v))
  2962. $user->createAdditionalField(substr($k, 11), $v);
  2963.  
  2964. $user->save();
  2965.  
  2966. if ('full' == $mode) {
  2967. $clist = Locale_Manager::getCountries();
  2968. $address = array(
  2969. 'company_name' => $val['coname'],
  2970. 'tax_id' => $val['nip'],
  2971. 'firstname' => $val['name'],
  2972. 'lastname' => $val['surname'],
  2973. 'street_1' => $val['other_address'],
  2974. 'street_2' => '',
  2975. 'city' => $val['city'],
  2976. 'zip_code' => $val['zip'],
  2977. 'state' => '',
  2978. 'country' => $clist[$val['country']],
  2979. 'country_code' => $val['country'],
  2980. 'phone' => $val['phone'],
  2981. 'default' => 1,
  2982. 'shipping_default' => 1,
  2983. );
  2984.  
  2985. if (true === $pesel) {
  2986. $address['pesel'] = $val['pesel'];
  2987. }
  2988.  
  2989. $user->processAddress($address);
  2990. }
  2991.  
  2992. $user->updateSearch();
  2993.  
  2994. if (Zend_Registry::isRegistered(System_Bootstrap::REGISTRY_FACEBOOK)) {
  2995. $f = Zend_Registry::get(System_Bootstrap::REGISTRY_FACEBOOK);
  2996. if ($f) {
  2997. $user->user->origin = Origin_Manager::ORIGIN_FACEBOOK;
  2998. $user->user->save();
  2999. }
  3000. }
  3001.  
  3002. if (Zend_Registry::isRegistered(System_Bootstrap::REGISTRY_MOBILE)) {
  3003. $f = Zend_Registry::get(System_Bootstrap::REGISTRY_MOBILE);
  3004. if ($f) {
  3005. $user->user->origin = Origin_Manager::ORIGIN_MOBILE;
  3006. $user->user->save();
  3007. }
  3008. }
  3009.  
  3010. $fields = array();
  3011. $additional_fields = array();
  3012. foreach ($user->fields as $field) {
  3013. $fid = (int) $field->field_id;
  3014. if ($fid > 0) {
  3015. $fields[$fid] = $field->value;
  3016. }
  3017. }
  3018.  
  3019. foreach ($fields as $fid => $value) {
  3020. $f = new Logic_AdditionalField($fid);
  3021. if ($f->existsInDB() && 1 == (int) $f->field->active) {
  3022. $additional_fields['additional_' . $fid . '_desc'] = $f->translation->description;
  3023.  
  3024. switch ((int) $f->field->type) {
  3025. case Logic_AdditionalField::TYPE_TEXT:
  3026. case Logic_AdditionalField::TYPE_SELECT:
  3027. $additional_fields['additional_' . $fid . '_value'] = $value;
  3028. break;
  3029.  
  3030. case Logic_AdditionalField::TYPE_CHECKBOX:
  3031. $additional_fields['additional_' . $fid . '_value'] = Locale_Manager::translate(1 == (int) $value ? 'yes' : 'no');
  3032. break;
  3033. }
  3034. }
  3035. }
  3036.  
  3037. if (1 == (int) Config_Manager::getConfigValue('mail', 'NOTIFY_EMAIL_NEW_CLIENT')) {
  3038. try {
  3039. $message = new Mail_Message(Mail_Manager::getMailTemplate(Mail_Manager::MAIL_ADMIN_REGISTER));
  3040. $message->setVar('email', $val['mail']);
  3041. $message->setVar('origin', Origin_Manager::getOriginNameForKey($user->user->origin));
  3042. $message->setVarArray($additional_fields);
  3043. $message->addRecipient(Config_Manager::getConfigValue('company', 'COMPANY_EMAIL'), false);
  3044. $message->setReplyTo($val['mail'], $val['name'] . ' ' . $val['surname']);
  3045.  
  3046. $metafields = new Metafield_Manager();
  3047. foreach ($metafields->getMetafieldObjectList() as $m) {
  3048. $key = "metafield.system." . $m->metafield->metafield->namespace . "." . $m->metafield->metafield->key;
  3049. $message->setVar($key, Zend_Controller_Action_HelperBroker::getExistingHelper('ViewRenderer')->view->escape($m->value->value));
  3050. }
  3051.  
  3052. Mail_Manager::send($message, true);
  3053. } catch (Exception $e) {
  3054. $instance->_errorLog->err($e);
  3055. }
  3056. unset($message);
  3057. }
  3058.  
  3059. Plugin_Manager::callShopEvent('userRegisterSuccess', array($user));
  3060.  
  3061. try {
  3062. $template = Mail_Manager::getMailTemplate(Mail_Manager::MAIL_REGISTER);
  3063. } catch (Exception $e) {
  3064. $template = false;
  3065. $instance->_errorLog->err($e);
  3066. if ($confirm) {
  3067. $instance->_flashMessanger->addWarning(Locale_Manager::translate('Error while sending e-mail message with an activation code.'));
  3068. } else {
  3069. $instance->_flashMessanger->addWarning(Locale_Manager::translate('Error while sending a welcome e-mail message.'));
  3070. }
  3071. }
  3072.  
  3073. if ($template) {
  3074. $message = new Mail_Message($template);
  3075. $message->setVarArray(array(
  3076. 'email' => $val['mail'],
  3077. 'password' => $val['pass1'],
  3078. 'link' => '',
  3079. 'confirmation' => $confirm,
  3080. 'origin' => Origin_Manager::getOriginNameForKey($user->user->origin),
  3081. ));
  3082. $message->setVarArray($additional_fields);
  3083. $message->addRecipient($val['mail'], false);
  3084.  
  3085. $metafields = new Metafield_Manager();
  3086. foreach ($metafields->getMetafieldObjectList() as $m) {
  3087. $key = "metafield.system." . $m->metafield->metafield->namespace . "." . $m->metafield->metafield->key;
  3088. $message->setVar($key, Zend_Controller_Action_HelperBroker::getExistingHelper('ViewRenderer')->view->escape($m->value->value));
  3089. }
  3090.  
  3091. if ($confirm) {
  3092.  
  3093. $url = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER)->assemble(array(
  3094. 'userId' => (int) $user->getIdentifier(),
  3095. 'code' => $user->user->verify_code,
  3096. ), 'registerStep2', System_Router::ROUTE_TYPE_CORE, true, array(), false, Zend_Registry::get(System_Bootstrap::REGISTRY_ROUTER_BASEURL));
  3097. $message->setVar('link', $url);
  3098.  
  3099. try {
  3100. Mail_Manager::send($message, true);
  3101. $instance->_flashMessanger->addSuccess(Locale_Manager::translate('Account has been created. To sign in to the store, check e-mail and click on the confirmation link to verify your e-mail address.'));
  3102. $instance->_redirect(Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER)->assemble(array(), 'index'));
  3103. return;
  3104. } catch (Exception $e) {
  3105. $instance->_errorLog->err($e);
  3106. $instance->_flashMessanger->addWarning(Locale_Manager::translate('Error while sending e-mail message with an activation code.'));
  3107. }
  3108. } else {
  3109.  
  3110. try {
  3111. Mail_Manager::send($message, true);
  3112. } catch (Exception $e) {
  3113. $instance->_errorLog->err($e);
  3114. $instance->_flashMessanger->addWarning(Locale_Manager::translate('Error while sending a welcome e-mail message.'));
  3115. }
  3116.  
  3117. $instance->_flashMessanger->addSuccess(Locale_Manager::translate('Thank you for creating an account.'));
  3118. $result = Access_ClientManager::authenticate($val['mail'], $val['pass1']);
  3119.  
  3120. if ($result->isValid()) {
  3121. $instance->_redirect(Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER)->assemble(array(), 'index'));
  3122. return;
  3123. }
  3124. }
  3125. }
  3126. } else {
  3127. $val = $form->getUnfilteredValues();
  3128. $instance->_flashMessanger->addError(Locale_Manager::translate('The registration form contains errors.'));
  3129. }
  3130.  
  3131. foreach ($val as $k => $v) {
  3132. if (isset($table1[$k]))
  3133. $table1[$k]['value'] = $v;
  3134. elseif (isset($table2[$k]))
  3135. $table2[$k]['value'] = $v;
  3136. elseif (preg_match('/^additional/', $k))
  3137. $additional[$k] = $v;
  3138. elseif ('address_type' == $k)
  3139. $instance->view->address_type = $v;
  3140. }
  3141.  
  3142. $additional_error = array();
  3143. foreach ($form->getMessages() as $k => $v) {
  3144. if (isset($table1[$k]))
  3145. $table1[$k]['error'] = $v;
  3146. elseif (isset($table2[$k]))
  3147. $table2[$k]['error'] = $v;
  3148. elseif (preg_match('/^additional/', $k))
  3149. $additional_error[$k] = $v;
  3150. }
  3151. $instance->view->additional_error = $additional_error;
  3152. } else {
  3153. $instance->view->address_type = 1;
  3154. $table2['country']['value'] = Locale_Manager::getRegion(); //Config_Manager::getConfigValue('company', 'COUNTRY');
  3155. foreach ($fields as $field) {
  3156. if (Logic_AdditionalField::TYPE_CHECKBOX == (int) $field->field->type && 1 == (int) $field->checkbox->checked) {
  3157. $additional['additional_' . (int) $field->getIdentifier()] = 1;
  3158. }
  3159. }
  3160. }
  3161.  
  3162. $table1['pass1']['value'] = $table1['pass2']['value'] = '';
  3163.  
  3164.  
  3165. $instance->view->mode = $mode;
  3166. $instance->view->table1 = $table1;
  3167. $instance->view->table2 = $table2;
  3168. $instance->view->additional_value = $additional;
  3169.  
  3170. $instance->view->body_class = 'shop_login_register';
  3171. $instance->_handleFlashMessages();
  3172. }
  3173.  
  3174. /**
  3175. * IndexController::register2Action()
  3176. *
  3177. * @return void
  3178. */
  3179. public function Login_register2Action($instance) {
  3180. if (Access_ClientManager::isLoggedIn()) {
  3181. $instance->_redirect(Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER)->assemble(array(), 'index'));
  3182. return;
  3183. }
  3184.  
  3185. if ($instance->_hasParam('userId') && $instance->_hasParam('code')) {
  3186. $uid = (int) $instance->_getParam('userId');
  3187. $code = $instance->_getParam('code');
  3188.  
  3189. if ($uid > 0 && 32 == strlen($code)) {
  3190. try {
  3191. $user = new Logic_User($uid);
  3192.  
  3193. if (0 == (int) $user->user->verify_email && $user->user->verify_code === $code) {
  3194. $user->user->verify_email = 1;
  3195. $user->save();
  3196. $instance->_flashMessanger->addSuccess(Locale_Manager::translate('E-mail address has been confirmed.'));
  3197.  
  3198. $result = Access_ClientManager::authenticate($user->userinfo->email, '', true);
  3199. if ($result->isValid()) {
  3200. $instance->_redirect(Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER)->assemble(array(), 'index'));
  3201. } else
  3202. $instance->_forward('login');
  3203.  
  3204. return;
  3205. }
  3206. } catch (Exception $e) {
  3207.  
  3208. }
  3209. }
  3210. }
  3211.  
  3212. $instance->_flashMessanger->addError(Locale_Manager::translate('Invalid authorization code.'));
  3213. $instance->_forward('login');
  3214. }
  3215.  
  3216. private static function Login_passCode($user) {
  3217. return sha1('passremind' . $user->user->date_add . $user->user->salt);
  3218. }
  3219.  
  3220. public function Panel_indexAction($instance) {
  3221. $instance->_breadCrumbs->add(Locale_Manager::translate('Customer panel'), '');
  3222.  
  3223. View_Smarty::setCacheTag(array(
  3224. ));
  3225.  
  3226. $user = Logic_UserOnline::getUser();
  3227. $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
  3228.  
  3229. if (!$user->user instanceof Logic_User) {
  3230. $instance->_redirect($router->assemble(array(), 'login'));
  3231. return;
  3232. }
  3233.  
  3234. //Orders
  3235. $list = new Logic_OrderList();
  3236. $select = $list->select();
  3237. $select->where('user_id = ?', $user->user->getIdentifier())
  3238. ->where('parent_order_id is null')
  3239. ->order('date DESC')
  3240. ->limit(self::ORDERS_LIMIT);
  3241.  
  3242. $list->fillFromSelect($select);
  3243. $instance->view->orders = $list;
  3244.  
  3245. $links = array();
  3246. foreach ($list as $order)
  3247. $links[$order->getIdentifier()] = $router->assemble(array('orderId' => $order->getIdentifier()), 'panelOrder');
  3248. $instance->view->orders_links = $links;
  3249.  
  3250. $instance->view->orders_alllink = ( count($user->user->orders) > self::ORDERS_LIMIT );
  3251. $instance->view->orders_count = count($user->user->orders);
  3252.  
  3253.  
  3254. //Addresses
  3255. if ($user->user->address instanceof Logic_UserAddress)
  3256. $instance->view->billing_address = $user->user->address;
  3257.  
  3258. if ($user->user->shippingAddress instanceof Logic_UserAddress)
  3259. $instance->view->shipping_address = $user->user->shippingAddress;
  3260.  
  3261.  
  3262. //Comments
  3263. $instance->view->comments_count = count($user->user->comments);
  3264.  
  3265. //Favourites
  3266. $instance->view->favourites_count = count($user->user->favourites);
  3267.  
  3268. if ($user->user && Loyalty_Program::isEnabled()) {
  3269. $sum = $user->user->loyalty->sum();
  3270. $this->view->loyalty = true;
  3271. $this->view->loyalty_points = View_Smarty_Helper_Float::float(array('value' => $sum, 'precision' => 0), null);
  3272. ;
  3273.  
  3274. $this->view->loyalty_discount = $ld = Loyalty_Program::exchangeModeDiscounts();
  3275. if ($ld) {
  3276. $next = false;
  3277. $this->view->loyalty_level = $ll = Loyalty_Program::getDiscountFromPoints($sum, true);
  3278.  
  3279. if (is_array($ll) && $ll['level']) {
  3280. $next = Loyalty_Program::getNextDiscountFromPoints($sum);
  3281. } else {
  3282. $next = Loyalty_Program::getNextDiscountFromPoints(0);
  3283. }
  3284.  
  3285.  
  3286. if (is_array($next) && $next['level'] && $next['level'] > $sum) {
  3287. $this->view->loyalty_next_level = View_Smarty_Helper_Float::float(array('value' => ($next['level'] - $sum), 'precision' => 0), null);
  3288. } else {
  3289. $this->view->loyalty_next_level = false;
  3290. }
  3291. }
  3292.  
  3293. $this->view->loyalty_exchange = $le = Loyalty_Program::exchangeModeProducts();
  3294. } else {
  3295. $this->view->loyalty = false;
  3296. }
  3297.  
  3298. $this->view->QUANTITY_PRECISION = Logic_UserBasketList::QUANTITY_PRECISION;
  3299.  
  3300. $instance->view->body_class = 'shop_panel';
  3301. $instance->_handleFlashMessages();
  3302. }
  3303.  
  3304. public function Panel_ordersAction($instance) {
  3305. View_Smarty::setCacheTag(array(
  3306. ));
  3307.  
  3308. $user = Logic_UserOnline::getUser();
  3309. $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
  3310.  
  3311. if (!$user->user instanceof Logic_User) {
  3312. $instance->_redirect($router->assemble(array(), 'login'));
  3313. return;
  3314. }
  3315.  
  3316. if (0 == count($user->user->orders)) {
  3317. $instance->_redirect($router->assemble(array(), 'panel'));
  3318. return;
  3319. }
  3320.  
  3321. $instance->_breadCrumbs->add(Locale_Manager::translate('Customer panel'), $router->assemble(array(), 'panel'));
  3322. $instance->_breadCrumbs->add(Locale_Manager::translate('Order history'), '');
  3323.  
  3324.  
  3325. $instance->view->orders = $user->user->orders;
  3326.  
  3327. //Config confirm
  3328. $instance->view->config_confirm = (1 == (int) Config_Manager::getConfigValue('shopping', 'CONFIRM_ORDER'));
  3329. $instance->view->show_invoice = (1 == (int) Config_Manager::getConfigValue('invoice', 'INVOICE_ON'));
  3330.  
  3331. $instance->view->body_class = 'shop_panel_orders';
  3332. $instance->_handleFlashMessages();
  3333. }
  3334.  
  3335. public function Panel_orderAction($instance) {
  3336. View_Smarty::setCacheTag(array(
  3337. ));
  3338.  
  3339. $user = Logic_UserOnline::getUser();
  3340. $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
  3341. $id = (int) $instance->_getParam('orderId');
  3342. $token = (string) $instance->_getParam('token');
  3343.  
  3344. $order = new Logic_Order($id);
  3345.  
  3346. if (strlen($token)) {
  3347. if (false === Config_Manager::hasConfigValue('shopping', 'ORDER_VIA_TOKEN') || 1 !== (int) Config_Manager::getConfigValue('shopping', 'ORDER_VIA_TOKEN')) {
  3348. $instance->_redirect($router->assemble(array(), 'index'));
  3349. return;
  3350. }
  3351.  
  3352. if (true !== $order->existsInDB() || 0 !== (int) $order->order->user_order || null !== $order->order->user_id || strlen($order->order->code) < 32 || $token !== $order->getAccessToken()) {
  3353. $instance->_redirect($router->assemble(array(), 'index'));
  3354. return;
  3355. }
  3356. } else {
  3357. if (!$user->user instanceof Logic_User || $id < 1) {
  3358. $instance->_redirect($router->assemble(array(), 'login'));
  3359. }
  3360.  
  3361. if (!$order->existsInDB() || $order->order->user_id !== $user->user->getIdentifier()) {
  3362. $instance->_redirect($router->assemble(array(), 'index'));
  3363. }
  3364.  
  3365. $instance->_breadCrumbs->add(Locale_Manager::translate('Customer panel'), $router->assemble(array(), 'panel'));
  3366. if (count($user->user->orders) > self::ORDERS_LIMIT) {
  3367. $instance->_breadCrumbs->add(Locale_Manager::translate('Order history'), $router->assemble(array(), 'panelOrders'));
  3368. }
  3369.  
  3370. $token = false;
  3371. }
  3372.  
  3373. if ($order->hasParentOrder()) {
  3374. $instance->_flashMessanger->addError(Locale_Manager::translate('The order has been combined with another'));
  3375. $instance->_redirect($router->assemble(array(), 'index'));
  3376. }
  3377.  
  3378. $shippingHandler = $order->shipping->handler;
  3379. $shippingHandler->setOrder($order);
  3380.  
  3381. $instance->view->shippingHandler = $shippingHandler;
  3382. $instance->view->order = $order;
  3383. $instance->view->token = $token;
  3384. $instance->_breadCrumbs->add(Locale_Manager::translate('Order no. %d', $id), '');
  3385.  
  3386. //Config confirm
  3387. $instance->view->config_confirm = (1 == (int) Config_Manager::getConfigValue('shopping', 'CONFIRM_ORDER'));
  3388. $instance->view->show_invoice = (1 == (int) Config_Manager::getConfigValue('invoice', 'INVOICE_ON'));
  3389.  
  3390. $instance->view->body_class = 'shop_panel_order';
  3391. $instance->view->body_id = 'shop_panel_order' . $id;
  3392. $instance->_handleFlashMessages();
  3393. }
  3394.  
  3395. public function Panel_digitalAction($instance) {
  3396.  
  3397. $user = Logic_UserOnline::getUser();
  3398. $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
  3399.  
  3400. $did = (int) $instance->_getParam('digitalId');
  3401. $pid = (int) $instance->_getParam('prodId');
  3402.  
  3403. if ($instance->_hasParam('hash')) {
  3404. $hash = preg_replace('/[^a-z0-9]/i', '', $instance->_getParam('hash'));
  3405. } else {
  3406. $hash = '';
  3407. }
  3408.  
  3409. if ($pid < 1 || $did < 1) {
  3410. $instance->_redirect($router->assemble(array(), 'index'));
  3411. return;
  3412. }
  3413.  
  3414. $ok = false;
  3415. $hashok = false;
  3416. $p = Logic_OrderProduct::loadInstance($pid);
  3417. $o = $p->order;
  3418.  
  3419. if ($p instanceof Logic_OrderProduct && $p->productObject) {
  3420.  
  3421. $type = (int) $o->order->user_order;
  3422. if ($type > 0) {
  3423. if (!$user->user instanceof Logic_User) {
  3424. $instance->_redirect($router->assemble(array(), 'login'));
  3425. return;
  3426. }
  3427. $hashok = ($user->user->getIdentifier() === $o->order->user_id); //user logged, don't need to check hash, we have authentication
  3428. } else {
  3429. $hashok = $p->verifyDigitalHash($hash, $did);
  3430. }
  3431.  
  3432. if ($hashok && $o->isDigital() && $o->isDownloadReady()) {
  3433. $d = Logic_ProductDigital::loadInstance($did);
  3434. if ($d->existsInDB() && (int) $p->productObject->getIdentifier() === (int) $d->product->getIdentifier()) {
  3435. $ok = true;
  3436. }
  3437. }
  3438. }
  3439.  
  3440.  
  3441. if (false == $ok) {
  3442. $instance->_redirect($router->assemble(array(), 'index'));
  3443. return;
  3444. }
  3445.  
  3446. $dl = (int) Config_Manager::getConfigValue('digitalProducts', 'LINK_EXPIRATION_TIME');
  3447. if ($dl > 0) {
  3448. $time = strtotime($o->order->status_date) + $dl * 86400;
  3449. if (time() > $time) {
  3450. $instance->_flashMessanger->addError(Locale_Manager::translate('Time limit to download this file has been exceeded.'));
  3451. $instance->_redirect($router->assemble(array(
  3452. 'orderId' => (int) $o->getIdentifier(),
  3453. ), 'panelOrder'));
  3454. return;
  3455. }
  3456. }
  3457.  
  3458. $ul = (int) Config_Manager::getConfigValue('digitalProducts', 'NUMBER_OF_DOWNLOADS');
  3459. $ul *= (int) $p->product->quantity;
  3460. if ($ul > 0) {
  3461. if ($user->user instanceof Logic_User && $type > 0) {
  3462. $count = $d->countDownloads($user->user->getIdentifier(), $o->getIdentifier());
  3463. if ($count >= $ul) {
  3464. $instance->_flashMessanger->addError(Locale_Manager::translate('The limit of downloads for this file has been reached.'));
  3465. $instance->_redirect($router->assemble(array(
  3466. 'orderId' => (int) $o->getIdentifier(),
  3467. ), 'panelOrder'));
  3468. return;
  3469. }
  3470. } else {
  3471. $count = $d->countDownloads(null, $o->getIdentifier());
  3472. if ($count >= $ul) {
  3473. $instance->_flashMessanger->addError(Locale_Manager::translate('The limit of downloads for this file has been reached.'));
  3474. $instance->_redirect($router->assemble(array(), 'index'));
  3475. return;
  3476. }
  3477. }
  3478. }
  3479.  
  3480.  
  3481. $path = $d->getPath(true);
  3482. if ($path) {
  3483. if ($user->user instanceof Logic_User && $type > 0) {
  3484. $d->logDownload($user->user->getIdentifier(), $o->getIdentifier());
  3485. } else {
  3486. $d->logDownload(null, $o->getIdentifier());
  3487. }
  3488. Download_Manager::handle($path);
  3489. } else {
  3490. $instance->_redirect($router->assemble(array(), 'index'));
  3491. return;
  3492. }
  3493. }
  3494.  
  3495. public function Panel_paymentAction($instance) {
  3496. View_Smarty::setCacheTag(array(
  3497. ));
  3498.  
  3499. $user = Logic_UserOnline::getUser();
  3500. $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
  3501. $id = (int) $instance->_getParam('orderId');
  3502. $token = (string) $instance->_getParam('token');
  3503.  
  3504. if (strlen($token)) {
  3505. $order = new Logic_Order($id);
  3506.  
  3507. if (true !== $order->existsInDB() || 0 !== (int) $order->order->user_order || null !== $order->order->user_id || strlen($order->order->code) < 32 || $token !== $order->getAccessToken()) {
  3508. $instance->_redirect($router->assemble(array(), 'index'));
  3509. return;
  3510. }
  3511. } else {
  3512.  
  3513. if (!$user->user instanceof Logic_User || $id < 1) {
  3514. $instance->_redirect($router->assemble(array(), 'login'));
  3515. return;
  3516. }
  3517.  
  3518. $instance->_breadCrumbs->add(Locale_Manager::translate('Customer panel'), $router->assemble(array(), 'panel'));
  3519. if (count($user->user->orders) > self::ORDERS_LIMIT)
  3520. $instance->_breadCrumbs->add(Locale_Manager::translate('Order history'), $router->assemble(array(), 'panelOrders'));
  3521.  
  3522. $order = null;
  3523.  
  3524. foreach ($user->user->orders as $o) {
  3525. if ($id == (int) $o->getIdentifier()) {
  3526. $order = $o;
  3527. break;
  3528. }
  3529. }
  3530.  
  3531. if (is_null($order)) {
  3532. $instance->_redirect($router->assemble(array(), 'login'));
  3533. return;
  3534. }
  3535.  
  3536. $token = false;
  3537. }
  3538.  
  3539. if ($order->sumOrder() * 100 > $order->order->paid * 100 && $order->hasOnlinePayment()) {
  3540. /** @var Plugin_Payment_Online_Abstract $onlinePayment */
  3541. $onlinePayment = $order->getOnlinePayment();
  3542. if ($onlinePayment->isFinished() && $onlinePayment->isStarted()) {
  3543. $instance->_flashMessanger->addWarning(Locale_Manager::translate('Order has been already paid'));
  3544. $instance->_redirect($router->assemble(array(), 'index'));
  3545. return;
  3546. }
  3547. }
  3548.  
  3549. $instance->_breadCrumbs->add(Locale_Manager::translate('Order no. %d', $id), $router->assemble(array('orderId' => $id, 'token' => $token), 'panelOrder'));
  3550. $instance->_breadCrumbs->add(Locale_Manager::translate('Payment'), '');
  3551.  
  3552. $instance->view->order = $order;
  3553. $instance->view->token = $token;
  3554. $handler = $order->payment->createHandler();
  3555. $handler->setOrder($order);
  3556. if ($handler instanceof Plugin_Payment_Online_Abstract) {
  3557. $instance->view->payment_form = $handler->getForm();
  3558. } else {
  3559. $instance->view->payment_message = $order->payment->translation->notify;
  3560. }
  3561.  
  3562. $instance->view->body_class = 'shop_panel_payment';
  3563. $instance->view->body_id = 'shop_panel_payment' . $id;
  3564. $instance->_handleFlashMessages();
  3565. }
  3566.  
  3567. public function Panel_commentsAction($instance) {
  3568. View_Smarty::setCacheTag(array(
  3569. ));
  3570.  
  3571. $user = Logic_UserOnline::getUser();
  3572. $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
  3573.  
  3574. if (!$user->user instanceof Logic_User) {
  3575. $instance->_redirect($router->assemble(array(), 'login'));
  3576. return;
  3577. }
  3578.  
  3579. if (0 == count($user->user->comments)) {
  3580. $instance->_redirect($router->assemble(array(), 'panel'));
  3581. return;
  3582. }
  3583.  
  3584.  
  3585. $instance->_breadCrumbs->add(Locale_Manager::translate('Customer panel'), $router->assemble(array(), 'panel'));
  3586. $instance->_breadCrumbs->add(Locale_Manager::translate('Products reviews'), '');
  3587.  
  3588. $instance->view->body_class = 'shop_panel_comments';
  3589. $instance->_handleFlashMessages();
  3590. }
  3591.  
  3592. public function Panel_favouritesAction($instance) {
  3593. View_Smarty::setCacheTag(array(
  3594. ));
  3595.  
  3596. $user = Logic_UserOnline::getUser();
  3597. $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
  3598.  
  3599. if (!$user->user instanceof Logic_User) {
  3600. $instance->_redirect($router->assemble(array(), 'login'));
  3601. return;
  3602. }
  3603.  
  3604. if (0 == count($user->user->favourites)) {
  3605. $instance->_redirect($router->assemble(array(), 'panel'));
  3606. return;
  3607. }
  3608.  
  3609. $instance->_breadCrumbs->add(Locale_Manager::translate('Customer panel'), $router->assemble(array(), 'panel'));
  3610. $instance->_breadCrumbs->add(Locale_Manager::translate('Products on wishlist'), '');
  3611.  
  3612. $instance->view->body_class = 'shop_panel_favourites';
  3613. $instance->_handleFlashMessages();
  3614. }
  3615.  
  3616. public function Panel_removefavAction($instance) {
  3617. $user = Logic_UserOnline::getUser();
  3618. $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
  3619.  
  3620. $id = (int) $instance->_getParam('stockId');
  3621. if (!$user->user instanceof Logic_User || 0 == count($user->user->favourites) || $id < 1) {
  3622. $instance->_redirect($router->assemble(array(), 'login'));
  3623. return;
  3624. }
  3625.  
  3626. $ent = new Entity_UserFavourites();
  3627. $ret = $ent->delete(array(
  3628. 'stock_id = ?' => $id,
  3629. 'user_id = ?' => (int) $user->user->getIdentifier(),
  3630. ));
  3631.  
  3632. if (1 == $ret)
  3633. $instance->_flashMessanger->addSuccess(Locale_Manager::translate('Product removed from wish list.'));
  3634.  
  3635. $instance->_redirect($router->assemble(array(), 'panelFavourites'));
  3636. }
  3637.  
  3638. public function Panel_addressAction($instance) {
  3639. View_Smarty::setCacheTag(array(
  3640. ));
  3641.  
  3642. $user = Logic_UserOnline::getUser();
  3643. $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
  3644.  
  3645. if (!$user->user instanceof Logic_User) {
  3646. $instance->_redirect($router->assemble(array(), 'login'));
  3647. return;
  3648. }
  3649.  
  3650. $instance->_breadCrumbs->add(Locale_Manager::translate('Customer panel'), $router->assemble(array(), 'panel'));
  3651. $instance->_breadCrumbs->add(Locale_Manager::translate('List of addresses'), '');
  3652.  
  3653. $instance->view->body_class = 'shop_panel_addresses';
  3654. $instance->_handleFlashMessages();
  3655. }
  3656.  
  3657. public function Panel_addressdefaultAction($instance) {
  3658. $user = Logic_UserOnline::getUser();
  3659. $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
  3660.  
  3661. $id = (int) $instance->_getParam('addressId');
  3662. if (!$user->user instanceof Logic_User || 0 == count($user->user->addresses) || $id < 1) {
  3663. $instance->_redirect($router->assemble(array(), 'panelAddressList'));
  3664. return;
  3665. }
  3666.  
  3667. foreach ($user->user->addresses as $address) {
  3668. $d = (int) ($id == (int) $address->getIdentifier());
  3669. if ($d != (int) $address->address->default) {
  3670. $address->address->default = $d;
  3671. $address->save();
  3672. }
  3673. }
  3674.  
  3675. $instance->_flashMessanger->addSuccess(Locale_Manager::translate('Address has been set as default.'));
  3676. $instance->_redirect($router->assemble(array(), 'panelAddressList'));
  3677. }
  3678.  
  3679. public function Panel_addressshippingAction($instance) {
  3680. $user = Logic_UserOnline::getUser();
  3681. $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
  3682.  
  3683. $id = (int) $instance->_getParam('addressId');
  3684. if (!$user->user instanceof Logic_User || 0 == count($user->user->addresses) || $id < 1) {
  3685. $instance->_redirect($router->assemble(array(), 'panelAddressList'));
  3686. return;
  3687. }
  3688.  
  3689. foreach ($user->user->addresses as $address) {
  3690. $d = (int) ($id == (int) $address->getIdentifier());
  3691. if ($d != (int) $address->address->shipping_default) {
  3692. $address->address->shipping_default = $d;
  3693. $address->save();
  3694. }
  3695. }
  3696.  
  3697. $instance->_flashMessanger->addSuccess(Locale_Manager::translate('Address has been set as default.'));
  3698. $instance->_redirect($router->assemble(array(), 'panelAddressList'));
  3699. }
  3700.  
  3701. public function Panel_addressremoveAction($instance) {
  3702. $user = Logic_UserOnline::getUser();
  3703. $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
  3704.  
  3705. $id = (int) $instance->_getParam('addressId');
  3706. if (!$user->user instanceof Logic_User || 0 == count($user->user->addresses) || $id < 1) {
  3707. $instance->_redirect($router->assemble(array(), 'panelAddressList'));
  3708. return;
  3709. }
  3710.  
  3711. foreach ($user->user->addresses as $address) {
  3712. if ($id == (int) $address->getIdentifier()) {
  3713.  
  3714. $def = (1 == (int) $address->address->default);
  3715. $ship = (1 == (int) $address->address->shipping_default);
  3716. $address->delete();
  3717. $user->user->forgetAddresses();
  3718.  
  3719. if (count($user->user->addresses) && ($def || $ship)) {
  3720. if ($def)
  3721. $user->user->addresses[0]->address->default = 1;
  3722. if ($ship)
  3723. $user->user->addresses[0]->address->shipping_default = 1;
  3724. $user->user->addresses[0]->save();
  3725. }
  3726.  
  3727. $instance->_flashMessanger->addSuccess(Locale_Manager::translate('Address has been removed.'));
  3728. }
  3729. }
  3730.  
  3731. $user->user->updateSearch();
  3732. $instance->_redirect($router->assemble(array(), 'panelAddressList'));
  3733. }
  3734.  
  3735. public function Panel_addresseditAction($instance) {
  3736. $user = Logic_UserOnline::getUser();
  3737. $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
  3738.  
  3739. $id = (int) $instance->_getParam('addressId');
  3740. if (!$user->user instanceof Logic_User || $id < 0) {
  3741. $instance->_redirect($router->assemble(array(), 'panelAddressList'));
  3742. return;
  3743. }
  3744.  
  3745. $address = null;
  3746. if ($id > 0)
  3747. foreach ($user->user->addresses as $a)
  3748. if ($id == (int) $a->getIdentifier()) {
  3749. $address = $a;
  3750. break;
  3751. }
  3752.  
  3753. if (($id > 0 && is_null($address)) || ($instance->getRequest()->isPost() && isset($_POST['button1'][0]))) {
  3754. $instance->_redirect($router->assemble(array(), 'panelAddressList'));
  3755. return;
  3756. }
  3757.  
  3758. $instance->_breadCrumbs->add(Locale_Manager::translate('Customer panel'), $router->assemble(array(), 'panel'));
  3759. $instance->_breadCrumbs->add(Locale_Manager::translate('List of addresses'), $router->assemble(array(), 'panelAddressList'));
  3760. $instance->_breadCrumbs->add($id > 0 ? Locale_Manager::translate('Edycja adresu') : Locale_Manager::translate('New address'), '');
  3761. $instance->view->address_id = $id;
  3762.  
  3763.  
  3764.  
  3765. $table = array(
  3766. 'name' => array(
  3767. 'name' => 'name',
  3768. 'obligatory' => true,
  3769. 'label' => Locale_Manager::translate('First name'),
  3770. 'type' => 'text',
  3771. 'rowspan' => 1,
  3772. ),
  3773. 'surname' => array(
  3774. 'name' => 'surname',
  3775. 'obligatory' => true,
  3776. 'label' => Locale_Manager::translate('Last name'),
  3777. 'type' => 'text',
  3778. 'rowspan' => 1,
  3779. ),
  3780. 'phone' => array(
  3781. 'name' => 'phone',
  3782. 'obligatory' => true,
  3783. 'label' => Locale_Manager::translate('Phone'),
  3784. 'type' => 'text',
  3785. 'hint' => Locale_Manager::translate('Number format, e.g.: 123456789'),
  3786. 'rowspan' => 1,
  3787. ),
  3788. 'coname' => array(
  3789. 'name' => 'coname',
  3790. 'label' => Locale_Manager::translate('Company name'),
  3791. 'type' => 'text',
  3792. 'rowspan' => 1,
  3793. ),
  3794. 'nip' => array(
  3795. 'name' => 'nip',
  3796. 'label' => Locale_Manager::translate('Tax ID'),
  3797. 'type' => 'text',
  3798. 'rowspan' => 1,
  3799. ),
  3800. 'pesel' => array(
  3801. 'name' => 'pesel',
  3802. 'label' => Locale_Manager::translate('Personal Identification Number'),
  3803. 'type' => 'text',
  3804. 'rowspan' => 1,
  3805. ),
  3806. 'other_address' => array(
  3807. 'name' => 'other_address',
  3808. 'obligatory' => true,
  3809. 'label' => Locale_Manager::translate('Street and house no.'),
  3810. 'type' => 'text',
  3811. 'hint' => Locale_Manager::translate('For example: 115 Oxford Street'),
  3812. 'rowspan' => 1,
  3813. ),
  3814. 'zip' => array(
  3815. 'name' => 'zip',
  3816. 'obligatory' => true,
  3817. 'label' => Locale_Manager::translate('Postal code'),
  3818. 'type' => 'text',
  3819. 'hint' => Locale_Manager::translate('Postal code format'),
  3820. 'rowspan' => 1,
  3821. ),
  3822. 'city' => array(
  3823. 'name' => 'city',
  3824. 'obligatory' => true,
  3825. 'label' => Locale_Manager::translate('City'),
  3826. 'type' => 'text',
  3827. 'rowspan' => 1,
  3828. ),
  3829. 'country' => array(
  3830. 'name' => 'country',
  3831. 'obligatory' => false,
  3832. 'label' => Locale_Manager::translate('Country'),
  3833. 'type' => 'select',
  3834. 'list' => Locale_Manager::getCountries(),
  3835. 'rowspan' => 1,
  3836. 'value' => Locale_Manager::getRegion(),
  3837. ),
  3838. );
  3839.  
  3840. $address_assign = array(
  3841. 'name' => 'firstname',
  3842. 'surname' => 'lastname',
  3843. 'phone' => 'phone',
  3844. 'coname' => 'company_name',
  3845. 'nip' => 'tax_id',
  3846. 'pesel' => 'pesel',
  3847. 'other_address' => 'street_1',
  3848. 'zip' => 'zip_code',
  3849. 'city' => 'city',
  3850. 'country' => 'country_code',
  3851. );
  3852.  
  3853. $pesel = (1 == (int) Config_Manager::getConfigValue('shopping', 'SUPPORT_PESEL'));
  3854. if (false === $pesel) {
  3855. unset($table['pesel']);
  3856. unset($address_assign['pesel']);
  3857. }
  3858.  
  3859. if ($instance->getRequest()->isPost() && isset($_POST['addressform'][0])) {
  3860.  
  3861. if (isset($_POST['phone'][0])) {
  3862. if ('+' == $_POST['phone'][0])
  3863. $_POST['phone'] = '00' . substr($_POST['phone'], 1);
  3864. $_POST['phone'] = preg_replace('/[\.\s\(\)]/', '', $_POST['phone']);
  3865. }
  3866.  
  3867. $form = new Form_Shop_Singleaddress($table);
  3868. if ($form->isValid($_POST)) {
  3869. $val = $form->getValues();
  3870.  
  3871. if (is_null($address)) {
  3872. $address = new Logic_UserAddress();
  3873. $address->create();
  3874. $address->address->user_id = (int) $user->user->getIdentifier();
  3875. }
  3876.  
  3877. foreach ($address_assign as $k => $v)
  3878. if (isset($val[$k]))
  3879. $address->address->$v = $val[$k];
  3880.  
  3881. $clist = Locale_Manager::getCountries();
  3882. $address->address->country = $clist[$val['country']];
  3883.  
  3884. if (strlen($address->address->company_name) > 0)
  3885. $name = $address->address->company_name;
  3886. else
  3887. $name = $address->address->firstname . ' ' . $address->address->lastname;
  3888. $name .= ', ' . $address->address->street_1 . ', ' . $address->address->city;
  3889.  
  3890. $address->address->address_name = trim($name);
  3891. $address->address->sortkey = trim($address->address->company_name . ' ' . $address->address->lastname . ' ' . $address->address->firstname);
  3892.  
  3893. if (is_object($user->user->address)) {
  3894. if (1 == $val['default1'] && 0 == (int) $address->address->default) {
  3895. $address->address->default = 1;
  3896. foreach ($user->user->addresses as $a) {
  3897. if ($id != (int) $a->getIdentifier()) {
  3898. $a->address->default = 0;
  3899. $a->save();
  3900. }
  3901. }
  3902. }
  3903. } else
  3904. $address->address->default = 1;
  3905.  
  3906. if (is_object($user->user->shippingAddress)) {
  3907. if (1 == $val['default2'] && 0 == (int) $address->address->shipping_default) {
  3908. $address->address->shipping_default = 1;
  3909. foreach ($user->user->addresses as $a) {
  3910. if ($id != (int) $a->getIdentifier()) {
  3911. $a->address->shipping_default = 0;
  3912. $a->save();
  3913. }
  3914. }
  3915. }
  3916. } else
  3917. $address->address->shipping_default = 1;
  3918.  
  3919. $address->save();
  3920. if (is_object($user->user)) {
  3921. $user->user->updateSearch();
  3922. }
  3923.  
  3924. if ($id > 0)
  3925. $instance->_flashMessanger->addSuccess(Locale_Manager::translate('Address has been saved.'));
  3926. else
  3927. $instance->_flashMessanger->addSuccess(Locale_Manager::translate('Address has been added.'));
  3928.  
  3929. $instance->_redirect($router->assemble(array(), 'panelAddressList'));
  3930. return;
  3931. } else {
  3932. $instance->_flashMessanger->addError(Locale_Manager::translate('Form contains errors.'));
  3933. $val = $form->getUnfilteredValues();
  3934.  
  3935. foreach ($val as $k => $v)
  3936. if (isset($table[$k]))
  3937. $table[$k]['value'] = $v;
  3938.  
  3939. foreach ($form->getMessages() as $k => $v)
  3940. if (isset($table[$k]))
  3941. $table[$k]['error'] = $v;
  3942.  
  3943. $instance->view->default1 = $val['default1'];
  3944. $instance->view->default2 = $val['default2'];
  3945. }
  3946. } elseif ($id > 0) {
  3947. foreach ($address_assign as $k => $v)
  3948. if (isset($table[$k]))
  3949. $table[$k]['value'] = $address->address->$v;
  3950. }
  3951.  
  3952. if ($id > 0) {
  3953. $instance->view->show_default1 = (0 == (int) $address->address->default);
  3954. $instance->view->show_default2 = (0 == (int) $address->address->shipping_default);
  3955. } else {
  3956. $instance->view->show_default1 = is_object($user->user->address);
  3957. $instance->view->show_default2 = is_object($user->user->shippingAddress);
  3958. }
  3959.  
  3960. $instance->view->table = $table;
  3961.  
  3962. $instance->view->body_class = 'shop_panel_address';
  3963. $instance->view->body_id = 'shop_panel_address' . $id;
  3964. $instance->_handleFlashMessages();
  3965. }
  3966.  
  3967. public function Panel_passwordAction($instance) {
  3968. View_Smarty::setCacheTag(array(
  3969. ));
  3970.  
  3971. $user = Logic_UserOnline::getUser();
  3972. $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
  3973.  
  3974. if (!$user->user instanceof Logic_User) {
  3975. $instance->_redirect($router->assemble(array(), 'login'));
  3976. return;
  3977. }
  3978.  
  3979. $instance->_breadCrumbs->add(Locale_Manager::translate('Customer panel'), $router->assemble(array(), 'panel'));
  3980. $instance->_breadCrumbs->add(Locale_Manager::translate('Password change'), '');
  3981.  
  3982. if ($instance->getRequest()->isPost()) {
  3983. $form = new Form_Shop_Passchange(true);
  3984.  
  3985. if ($form->isValid($_POST)) {
  3986. $val = $form->getValues();
  3987.  
  3988. $oldpass = $val['pass'];
  3989. $newpass = $val['pass1'];
  3990.  
  3991. $adapter = new Access_Auth_Test_Hash(Access_ClientManager::getInstance()); // todo: move it to Access_CLientManager
  3992. if ($adapter->test($user->user->user->login, $user->user->user->pass, $user->user->user->salt, $oldpass)) {
  3993. Access_ClientManager::logout();
  3994. Zend_Session::regenerateId();
  3995. $user->user->setPassword($newpass);
  3996. $instance->_flashMessanger->addSuccess(Locale_Manager::translate('Password has been changed. Please sign in again.'));
  3997. $instance->_redirect($router->assemble(array(), 'login'));
  3998. return;
  3999. } else {
  4000. $de = (array) $form->getMessages();
  4001. if (!isset($de['pass']))
  4002. $de['pass'] = array();
  4003. $de['pass']['wrong'] = Locale_Manager::translate('Incorrect password.');
  4004. $instance->view->data_error = $de;
  4005. $instance->_flashMessanger->addError(Locale_Manager::translate('Form contains errors.'));
  4006. }
  4007. } else {
  4008. $instance->view->data_error = $form->getMessages();
  4009. $instance->_flashMessanger->addError(Locale_Manager::translate('Form contains errors.'));
  4010. }
  4011. }
  4012.  
  4013. $instance->view->body_class = 'shop_panel_password';
  4014. $instance->_handleFlashMessages();
  4015. }
  4016.  
  4017. public function Panel_editAction($instance) {
  4018. View_Smarty::setCacheTag(array(
  4019. ));
  4020.  
  4021. $user = Logic_UserOnline::getUser();
  4022. $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
  4023.  
  4024. if (!$user->user instanceof Logic_User) {
  4025. $instance->_redirect($router->assemble(array(), 'login'));
  4026. return;
  4027. }
  4028.  
  4029. $instance->_breadCrumbs->add(Locale_Manager::translate('Customer panel'), $router->assemble(array(), 'panel'));
  4030. $instance->_breadCrumbs->add(Locale_Manager::translate('Edit your profile'), '');
  4031.  
  4032. $fields = Logic_AdditionalField::getByLocate(
  4033. Logic_AdditionalField::LOCATE_USER_ACCOUNT, Locale_Manager::getLanguageId()
  4034. );
  4035. $instance->view->additional_fields = $fields;
  4036.  
  4037. if ($instance->getRequest()->isPost()) {
  4038. $form = new Form_Shop_UserEdit($user->user->getIdentifier());
  4039. if ($form->isValid($_POST)) {
  4040. $vals = $form->getValues();
  4041. $data = array(
  4042. 'firstname' => $vals['name'],
  4043. 'lastname' => $vals['surname'],
  4044. 'email' => $vals['mail']
  4045. );
  4046.  
  4047. $data['additional_fields'] = array();
  4048. foreach ($fields as $field) {
  4049. $id = (int) $field->getIdentifier();
  4050. $x = 'additional_' . $id;
  4051. if (isset($vals[$x])) {
  4052. $data['additional_fields'][$id] = $vals[$x];
  4053. }
  4054. }
  4055.  
  4056. Logic_User::createOrSaveUser($user->user, $data, $fields);
  4057.  
  4058. $instance->_flashMessanger->addSuccess(Locale_Manager::translate('Profile changes have been saved.'));
  4059. $instance->_redirect($router->assemble(array(), 'panel'));
  4060. return;
  4061. } else {
  4062. $instance->view->data = $form->getUnfilteredValues();
  4063. $instance->view->data_error = $form->getMessages();
  4064. $instance->_flashMessanger->addError(Locale_Manager::translate('The registration form contains errors.'));
  4065. }
  4066. } else {
  4067. $data = array(
  4068. 'name' => $user->user->userinfo->firstname,
  4069. 'surname' => $user->user->userinfo->lastname,
  4070. 'mail' => $user->user->userinfo->email,
  4071. );
  4072. foreach ($user->user->fields as $field) {
  4073. $data['additional_' . $field->field_id] = $field->value;
  4074. }
  4075. $instance->view->data = $data;
  4076. }
  4077.  
  4078. $instance->view->body_class = 'shop_panel_edit';
  4079. $instance->_handleFlashMessages();
  4080. }
  4081.  
  4082. public function Panel_getaddressAction($instance) {
  4083. header('Content-type: application/json');
  4084.  
  4085. try {
  4086. Access_ClientManager::reValidate();
  4087. if (!Access_ClientManager::isLoggedIn()) {
  4088. echo 0;
  4089. return;
  4090. }
  4091.  
  4092. $id = (int) $instance->_getParam('id');
  4093. if ($id <= 0) {
  4094. echo 0;
  4095. return;
  4096. }
  4097.  
  4098. $user = Logic_UserOnline::getUser();
  4099. if (!is_object($user->user)) {
  4100. echo 0;
  4101. return;
  4102. }
  4103.  
  4104. $address = null;
  4105. foreach ($user->user->addresses as $a)
  4106. if ($id == (int) $a->getIdentifier())
  4107. $address = $a;
  4108.  
  4109. if (!is_object($address)) {
  4110. echo 0;
  4111. return;
  4112. }
  4113.  
  4114. $ret = array(
  4115. 'name' => (string) $address->address->firstname,
  4116. 'surname' => (string) $address->address->lastname,
  4117. 'phone' => (string) $address->address->phone,
  4118. 'coname' => (string) $address->address->company_name,
  4119. 'nip' => (string) $address->address->tax_id,
  4120. 'pesel' => (string) $address->address->pesel,
  4121. 'other_address' => (string) $address->address->street_1,
  4122. 'zip' => (string) $address->address->zip_code,
  4123. 'city' => (string) $address->address->city,
  4124. 'country' => (string) $address->address->country_code,
  4125. );
  4126.  
  4127. $pesel = (1 == (int) Config_Manager::getConfigValue('shopping', 'SUPPORT_PESEL'));
  4128. if (false === $pesel) {
  4129. unset($ret['pesel']);
  4130. }
  4131.  
  4132. echo Zend_Json::encode($ret);
  4133. } catch (Exception $e) {
  4134. $instance->_errorLog->debug('Error while downloading user address (' . date('Y-m-d H:i:s') . '): ' . $e->getMessage());
  4135. echo 0;
  4136. }
  4137. }
  4138.  
  4139. /**
  4140. * ProductController
  4141. */
  4142.  
  4143.  
  4144. public function Product_listAction($instance) {
  4145. //elo
  4146. View_Smarty::setCacheTag(array(
  4147. 'Logic_ProductList', 'Logic_Product', 'Logic_ProductStockList', 'Logic_ProductStock', 'Logic_Category', 'Logic_CategoryList',
  4148. 'productImages', 'productFiles', 'productAttributes', 'productVote', 'productTranslation',
  4149. 'Logic_ProductDelivery', 'Logic_ProductDeliveryList', 'Logic_ProductAvailability', 'Logic_ProductAvailabilityList',
  4150. 'Logic_ProductStock', 'Logic_ProductStockList',
  4151. ));
  4152. View_Smarty::skipCache();
  4153.  
  4154. $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
  4155.  
  4156. $page = $instance->_hasParam('page') ? (int) $instance->_getParam('page') : 1;
  4157. if ($page < 1)
  4158. $page = 1;
  4159.  
  4160. $view = $instance->_hasParam('view') ? $instance->_getParam('view') : null;
  4161. if (!in_array($view, System_Router::$view_modes) || 'default' == $view) {
  4162. $view = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_LAYOUT_MANAGER)->getSkin()->getSettings()->productlist->mode;
  4163. }
  4164. if ('default' == $view) {
  4165. $view = 'full';
  4166. }
  4167.  
  4168. $sort = $instance->_hasParam('sort') ? (int) $instance->_getParam('sort') : 1;
  4169. if ($sort > 5 || $sort < 1) {
  4170. $sort = 1;
  4171. }
  4172.  
  4173. $session = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_SESSION);
  4174. $instance->view->settingsgroup = 'productlist';
  4175. $instance->view->loyalty_exchange = false;
  4176.  
  4177. $groups = null;
  4178.  
  4179. $has_filer_box = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_LAYOUT_MANAGER)->hasBox('Filter');
  4180.  
  4181. if (Zend_Registry::isRegistered('products') && Zend_Registry::isRegistered('list_type') && !isset($_SESSION['poicvbgh'])) {
  4182. $products = Zend_Registry::get('products');
  4183. $list_type = Zend_Registry::get('list_type');
  4184.  
  4185. switch ($list_type) {
  4186. case 'promo':
  4187. $instance->_breadCrumbs->add(Locale_Manager::translate('Only On Sale products'), '');
  4188. $instance->view->router_name = 'promotions';
  4189. $instance->handleSeo(array('promo' => true));
  4190. break;
  4191. case 'new':
  4192. $instance->_breadCrumbs->add(Locale_Manager::translate('New products'), '');
  4193. $instance->view->router_name = 'productNew';
  4194. $instance->handleSeo(array('new' => true));
  4195. break;
  4196. case 'day':
  4197. $instance->_breadCrumbs->add(Locale_Manager::translate('Products of the day'), '');
  4198. $instance->view->router_name = 'productDay';
  4199. $instance->handleSeo(array('day' => true));
  4200. break;
  4201. case 'producer':
  4202. $manuf = new Logic_Manufacturer((int) $instance->_getParam('producerId'));
  4203. if (false == $manuf->existsInDB()) {
  4204. $instance->_redirect($router->assemble(array(), 'index'));
  4205. return;
  4206. }
  4207. $manuf->setStats();
  4208. $instance->_breadCrumbs->add(str_replace('%s', $manuf->manufacturer->name, Locale_Manager::translate('"%s" products')), '');
  4209. $instance->view->router_name = 'producer';
  4210. $instance->handleSEO($manuf);
  4211. break;
  4212. case 'loyalty':
  4213. $instance->_breadCrumbs->add(Locale_Manager::translate('Exchangeable products in the loyalty program'), '');
  4214. $instance->view->router_name = 'loyaltyList';
  4215. $instance->view->loyalty_exchange = true;
  4216. $instance->view->basketAddRoute = 'loyaltyExchange';
  4217. $instance->view->productRoute = 'productExchange';
  4218. break;
  4219. }
  4220. } else {
  4221.  
  4222. $id = $instance->_hasParam('categoryId') ? (int) $instance->_getParam('categoryId') : 0;
  4223. Zend_Registry::set('categoryId', $id);
  4224.  
  4225. $instance->view->sort_links = true;
  4226. $list_type = 'category';
  4227. if ($instance->_hasParam('searchquery')) {
  4228. if ($id <= 0) {
  4229. $instance->view->router_name = 'searchQuery';
  4230. }
  4231. $instance->view->google = '';
  4232. }
  4233. $products = new Logic_ProductList();
  4234. $cm_ent = new Entity_CategoriesMap();
  4235. $pc_ent = new Entity_ProductsCategories();
  4236.  
  4237. if ($id > 0) {
  4238. $cat = new Logic_Category($id);
  4239. if (!isset($_SESSION['poicvbgh']) && !$cat->translation->active && !($instance->_hasParam('preview') && Zend_Controller_Front::getInstance()->getParam(Access_Manager::ADMIN_IS_LOGGED_IN))) {
  4240. $instance->_redirect($router->assemble(array(), 'index'));
  4241. return;
  4242. }
  4243. if (true == $cat->missedLanguage()) {
  4244. $instance->_redirect($router->assemble(array(), 'index'));
  4245. return;
  4246. }
  4247.  
  4248. $cat->setStats();
  4249.  
  4250. if (strlen($cat->translation->description))
  4251. $instance->view->category_description = $cat->translation->description;
  4252.  
  4253. $category_links = array();
  4254. foreach ($cat->getCategoryPath(false) as $c)
  4255. $category_links[$c->translation->name] = $router->assembleCategory(array(
  4256. 'categoryName' => $c->translation->name,
  4257. 'categoryId' => $c->category->category_id,
  4258. 'page' => 1,
  4259. 'view' => $view,
  4260. 'sort' => 1,
  4261. ), $c->category->category_id);
  4262.  
  4263. foreach ($category_links as $k => $v)
  4264. $instance->_breadCrumbs->add($k, $v);
  4265. $instance->_breadCrumbs->add($cat->translation->name, '');
  4266.  
  4267. if (Zend_Controller_Front::getInstance()->getParam(Access_Manager::ADMIN_IS_LOGGED_IN) && $this->_getParam('preview') || isset($_SESSION['poicvbgh'])) {
  4268. View_Smarty::skipCache();
  4269. $select = Search_Filter_Products::getProductsSearchSelect($cat->getIdentifier(), false);
  4270. } else {
  4271. $select = Search_Filter_Products::getProductsSearchSelect($cat->getIdentifier());
  4272. }
  4273.  
  4274. $request = Zend_Controller_Front::getInstance()->getRequest();
  4275.  
  4276. if (Access_ClientManager::isLoggedIn() && $_SESSION['only_my_products'] == true || $request->getParam('only_my_products') == 1) {
  4277. if ($request->getParam('only_my_products') != 2) {
  4278. // Entity_UserMyproducts::cleanFlyweight();
  4279. // Entity_ProductsCategories::cleanFlyweight();
  4280. $user = Logic_UserOnline::getUser();
  4281. $user = $user->toArray();
  4282. $select->setUseCache(false);
  4283. $user_id = $user['__userOnline']['data']['user_id'];
  4284. $select->joinRight('user_myproducts', 'user_myproducts.stock_id = products_categories.product_id', null);
  4285. $select->where('user_myproducts.user_id = ?', $user_id);
  4286. // Entity_UserMyproducts::cleanFlyweight();
  4287. }
  4288. }
  4289.  
  4290. if (1 == $sort or 5 == $sort)
  4291. $select->order(array('products_translations.order DESC', Locale_Manager::collatedOrder('products_translations.name ASC')));
  4292. elseif (2 == $sort)
  4293. $select->order(Locale_Manager::collatedOrder('products_translations.name DESC'));
  4294. elseif ($sort == 3 or $sort == 4) {
  4295. $select->join(array('priceorder' => 'products_stock'), 'products.product_id = priceorder.product_id and priceorder.default = 1', null);
  4296.  
  4297. $select->order('priceorder.comp_promo_price ' . (3 == $sort ? 'ASC' : 'DESC'));
  4298. }
  4299. $filter = Zend_Registry::get('Search_Filter_Products');
  4300. if ($filter->hasData()) {
  4301. View_Smarty::skipCache();
  4302. $products = $filter->search(array($id), $select);
  4303.  
  4304. } else {
  4305. $products->fillFromSelect($select);
  4306.  
  4307. }
  4308. if ($instance->_hasParam('searchquery')) {
  4309. $instance->_breadCrumbs->add(Locale_Manager::translate('Products found: %d', $products->count()), '');
  4310. }
  4311. if ($has_filer_box) {
  4312. $groups = $filter->buildFilter(array($id), null, array(), false, Config_Manager::getConfigValue('filters', 'counter'));
  4313. //$instance->view->filter_groups = $groups;
  4314. $instance->view->filter_type = Config_Manager::getConfigValue('filters', 'type');
  4315. $instance->view->filter_counter = (int) Config_Manager::getConfigValue('filters', 'counter');
  4316. }
  4317.  
  4318. $instance->view->sort_links = true;
  4319. $instance->view->category_name = $cat->translation->name;
  4320. $instance->view->category_id = (int) $cat->getIdentifier();
  4321.  
  4322. $instance->handleSeo($cat);
  4323. } else {
  4324.  
  4325. if ($instance->_hasParam('searchquery')) {
  4326. $s = preg_replace('/\s+/', ' ', (string) $instance->_getParam('searchquery'));
  4327. $s = explode(' ', $s);
  4328. $instance->handleSeo(array('search' => implode(', ', $s)));
  4329. }
  4330.  
  4331. if (Zend_Registry::isRegistered('Search_Filter_Products')) {
  4332. $filter = Zend_Registry::get('Search_Filter_Products');
  4333. if ($filter->hasData()) {
  4334. View_Smarty::skipCache();
  4335. $list = new Logic_CategoryList();
  4336. $select2 = $list->select();
  4337. $select2->where('root = ?', 1);
  4338. $select2->join('categories_translations', 'categories_translations.category_id = categories.category_id', null);
  4339. $select2->where('categories_translations.lang_id = ?', Locale_Manager::getLanguageId());
  4340.  
  4341. if (!isset($_SESSION['poicvbgh'])) {
  4342. $select2->where('categories_translations.active = ?', 1);
  4343. }
  4344. $select2->order('order ASC');
  4345. $list->fillFromSelect($select2);
  4346. if ($list->count() == 0) {
  4347. $list->fillAll();
  4348. }
  4349. if ($list->count() == 0) {
  4350. $products = new Logic_ProductList();
  4351. } else {
  4352. $select = Search_Filter_Products::getProductsSearchSelect($list->getIdentifiers());
  4353.  
  4354. if (1 == $sort or 5 == $sort)
  4355. $select->order(array('products_translations.order DESC', Locale_Manager::collatedOrder('products_translations.name ASC')));
  4356. elseif (2 == $sort)
  4357. $select->order(Locale_Manager::collatedOrder('products_translations.name DESC'));
  4358. elseif ($sort == 3 or $sort == 4) {
  4359. $select->join(array('priceorder' => 'products_stock'), 'products.product_id = priceorder.product_id and priceorder.default = 1', null);
  4360. $select->order('priceorder.comp_promo_price ' . (3 == $sort ? 'ASC' : 'DESC'));
  4361. }
  4362.  
  4363. $products = $filter->search($list->getIdentifiers(), $select);
  4364. if ($instance->_hasParam('searchquery')) {
  4365. $instance->_breadCrumbs->add(Locale_Manager::translate('Products found: %d', $products->count()), '');
  4366. }
  4367.  
  4368. if ($has_filer_box) {
  4369. $providers = array();
  4370.  
  4371. if (Config_Manager::getConfigValue('filters', 'category_search')) {
  4372. if (!$filter->hasProvider('Search_Filter_Products_Provider_Category')) {
  4373. $filter->addProvider('Search_Filter_Products_Provider_Category');
  4374. }
  4375. $provider = $filter->getProvider('Search_Filter_Products_Provider_Category');
  4376. $provider->setDepth(0);
  4377. $providers[] = $provider;
  4378. } else {
  4379. if ($filter->hasProvider('Search_Filter_Products_Provider_Category')) {
  4380. $filter->removeProvider('Search_Filter_Products_Provider_Category');
  4381. }
  4382. }
  4383. if ($filter->hasProvider('Search_Filter_Products_Provider_Producer')) {
  4384. $provider = $filter->getProvider('Search_Filter_Products_Provider_Producer');
  4385. $providers[] = $provider;
  4386. }
  4387. if ($filter->hasProvider('Search_Filter_Products_Provider_Price')) {
  4388. $provider = $filter->getProvider('Search_Filter_Products_Provider_Price');
  4389. $provider->createRanges(false);
  4390. $providers[] = $provider;
  4391. }
  4392. if (count($providers)) {
  4393. $groups = $filter->buildFilter($list->getIdentifiers(), null, array(), false, Config_Manager::getConfigValue('filters', 'counter'), $providers);
  4394. //$instance->view->filter_groups = $groups;
  4395. $instance->view->filter_type = Config_Manager::getConfigValue('filters', 'type');
  4396. $instance->view->filter_counter = (int) Config_Manager::getConfigValue('filters', 'counter');
  4397. }
  4398. }
  4399. }
  4400. }
  4401. }
  4402. }
  4403. }
  4404.  
  4405.  
  4406. if (!is_null($groups) and $has_filer_box) {
  4407. $cgid = null;
  4408. foreach ($groups as $k => &$g) {
  4409. switch ($g['provider']) {
  4410. case 'Search_Filter_Products_Provider_Category':
  4411. $cgid = $k;
  4412. break;
  4413. case 'Search_Filter_Products_Provider_Price':
  4414. if (0 == count($products) && 0 == count($g['items'])) {
  4415. unset($groups[$k]);
  4416. }
  4417. if ((0 == (int) Config_Manager::getConfigValue('filters', 'price'))) {
  4418. $groups[$k]['items'] = array();
  4419. }
  4420. break;
  4421. }
  4422. }
  4423.  
  4424. if (Config_Manager::getConfigValue('filters', 'category') && $id > 0 && $cat instanceof Logic_Category) {
  4425.  
  4426. $url = null;
  4427. if ($instance->_hasParam('searchquery')) {
  4428. $url = $router->assemble(array(), 'searchQuery');
  4429. } elseif ($cat->getParent() > 0) {
  4430. $pcat = $cat->getParentCategory();
  4431. $url = $router->assembleCategory(array(
  4432. 'categoryId' => (int) $pcat->getIdentifier(),
  4433. 'categoryName' => $pcat->translation->name,
  4434. ), $pcat->getIdentifier());
  4435. }
  4436.  
  4437. if (null === $cgid) {
  4438. array_unshift($groups, array(
  4439. 'name' => Locale_Manager::translate('Categories'),
  4440. 'items' => array(
  4441. array(
  4442. 'name' => $cat->translation->name,
  4443. 'active' => true,
  4444. 'link_add' => null,
  4445. 'link_remove' => $url,
  4446. 'link_solo' => null,
  4447. 'counter' => $products->count(),
  4448. ),
  4449. ),
  4450. 'provider' => 'Search_Filter_Products_Provider_Category',
  4451. ));
  4452. } elseif (null !== $url) {
  4453. foreach ($groups[$cgid]['items'] as &$i) {
  4454. $i['indent'] = true;
  4455. }
  4456.  
  4457. array_unshift($groups[$cgid]['items'], array(
  4458. 'name' => $cat->translation->name,
  4459. 'active' => true,
  4460. 'link_add' => null,
  4461. 'link_remove' => $url,
  4462. 'link_solo' => null,
  4463. 'counter' => $products->count(),
  4464. ));
  4465. }
  4466. }
  4467.  
  4468.  
  4469. SEO_Handler::setFilterGroups($groups);
  4470. $instance->view->filter_groups = $groups;
  4471. }
  4472. //my query
  4473. $modelAdapter = Entity_Abstract::getDefaultAdapter();
  4474. $getDescription = $modelAdapter->fetchAssoc('SELECT a.product_id, a.category_id, a.description FROM product_description a JOIN products_translations b ON b.product_id = a.product_id ');
  4475.  
  4476. $instance->view->view = $view;
  4477. $instance->view->sort = $sort;
  4478. $instance->view->list_type = $list_type;
  4479. $router->routeParams($instance->getRequest()->getParams());
  4480.  
  4481. $paginator = Zend_Paginator::factory($products);
  4482. $paginator->setCurrentPageNumber($page);
  4483. $paginator->setItemCountPerPage((int) Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_LAYOUT_MANAGER)->getSkin()->getSettings()->productlist->productspersite);
  4484. $paginator->setPageRange(5);
  4485. $instance->view->products = $paginator;
  4486. $instance->view->pages = $paginator->getPages();
  4487. $instance->handleSEO($paginator, 'paginator');
  4488.  
  4489. if (!View_Smarty::isCached()) {
  4490. $snippet = Logic_Snippet::getCode(Logic_Snippet::TYPE_PRODUCT_LIST);
  4491. if ($snippet) {
  4492. $vars = array(
  4493. 'products' => array()
  4494. );
  4495. foreach ($paginator as $p) {
  4496. $vars['products'][] = $p->getVariables();
  4497. }
  4498. $instance->view->snippet_product_list = Parser_Processor::onetimeCompile($snippet, $vars, array(
  4499. 'ignore_non_breaking_space' => true,
  4500. 'is_html_template' => true
  4501. ));
  4502. } else {
  4503. $instance->view->snippet_product_list = "";
  4504. }
  4505. }
  4506.  
  4507.  
  4508. $instance->view->description = $getDescription;
  4509. if (is_null($instance->view->body_class)) {
  4510. $instance->view->body_class = 'shop_product_list';
  4511. $instance->view->body_id = 'shop_category' . $id;
  4512. }
  4513.  
  4514. $instance->_handleFlashMessages();
  4515. }
  4516.  
  4517. public function Product_positionAction($instance) {
  4518.  
  4519. if ($_SESSION['auth']['mode']) {
  4520. $product_id = $_POST['product_id'];
  4521. $category_id=$_POST['category_id'];
  4522. $content = $_POST['text'];
  4523. if(!empty($product_id) && !empty($category_id) && !empty($content)) {
  4524.  
  4525. $modelAdapter = Entity_Abstract::getDefaultAdapter();
  4526. $getDescription = $modelAdapter->fetchAssoc('SELECT product_id, category_id, description FROM `product_description` WHERE `product_id` = '.$product_id.' and `category_id` = '.$category_id);
  4527. if($getDescription){
  4528. $data = 'isset';
  4529. }else{
  4530. $data = 'empty';
  4531. $modelAdapter->query('INSERT INTO `product_description` VALUES(null,'.$product_id.','.$category_id.',"'.$content.'") ');
  4532. }
  4533. }else{
  4534. $data = 'empty data';
  4535. }
  4536. }else{
  4537. $data = 'permission';
  4538. }
  4539. echo Zend_Json::encode(array('status' => $data));
  4540. }
  4541.  
  4542. public function Product_mailfriendAction($instance) {
  4543. View_Smarty::skipCache();
  4544. $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
  4545.  
  4546. if ($instance->_hasParam('productId') && $id = (int) $instance->_getParam('productId')) {
  4547.  
  4548. $instance->view->prod_id = $id;
  4549.  
  4550. if ($instance->getRequest()->isPost()) {
  4551.  
  4552. $form = new Form_Shop_MailFriend();
  4553.  
  4554. if ($form->isValid($_POST)) {
  4555.  
  4556. $val = $form->getValues();
  4557. foreach ($val as $k => $v)
  4558. $val[$k] = Purifier_HTML::strip_tags($v);
  4559.  
  4560. $template = Mail_Manager::getMailTemplate(Mail_Manager::MAIL_FRIEND);
  4561. $prod = new Logic_Product($id);
  4562. if (false == $prod->existsInDB()) {
  4563. $instance->_redirect($router->assemble(array(), 'index'));
  4564. return;
  4565. }
  4566.  
  4567. $template->mail->from_name = $val['from'];
  4568.  
  4569. $url = $router->assembleProduct(array(
  4570. 'productName' => $prod->translation->name,
  4571. 'productId' => $id,
  4572. ), $id, true);
  4573.  
  4574. $message = new Mail_Message($template, true);
  4575. $message->setVarArray(array(
  4576. 'product_name' => $prod->translation->name,
  4577. 'product_link' => $url,
  4578. 'from' => $val['from'],
  4579. ));
  4580. $message->addRecipient($val['email'], false);
  4581.  
  4582. try {
  4583. $metafields = new Metafield_Manager();
  4584. foreach ($metafields->getMetafieldObjectList() as $m) {
  4585. $key = "metafield.system." . $m->metafield->metafield->namespace . "." . $m->metafield->metafield->key;
  4586. $message->setVar($key, Zend_Controller_Action_HelperBroker::getExistingHelper('ViewRenderer')->view->escape($m->value->value));
  4587. }
  4588.  
  4589. $metafields = $prod->metafields;
  4590. foreach ($metafields->getMetafieldObjectList() as $m) {
  4591. $key = "metafield.product." . $m->metafield->metafield->namespace . "." . $m->metafield->metafield->key;
  4592. $message->setVar($key, Zend_Controller_Action_HelperBroker::getExistingHelper('ViewRenderer')->view->escape($m->value->value));
  4593. }
  4594.  
  4595. Mail_Manager::send($message, true);
  4596. $instance->_flashMessanger->addSuccess(Locale_Manager::translate('E-mail message has been sent.'));
  4597. $instance->_redirect($url);
  4598. return;
  4599. } catch (Exception $e) {
  4600. $instance->_errorLog->err($e);
  4601. $instance->_flashMessanger->addError(Locale_Manager::translate('Error while sending e-mail.'));
  4602. $instance->view->data = $val;
  4603. }
  4604. } else {
  4605. $instance->_flashMessanger->addError(Locale_Manager::translate('Filled form contains errors.'));
  4606. $instance->view->data = $form->getUnfilteredValues();
  4607. $instance->view->data_error = $form->getMessages();
  4608. }
  4609. }
  4610.  
  4611. $instance->view->body_class = 'shop_product_mailfriend';
  4612. $instance->_handleFlashMessages();
  4613. } else {
  4614. $instance->_redirect($router->assemble(array(), 'index'));
  4615. }
  4616. }
  4617.  
  4618. public function Product_indexAction($instance) {
  4619. View_Smarty::skipCache();
  4620. $instance->addCachedVariables();
  4621.  
  4622. $session = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_SESSION);
  4623. $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
  4624. $view = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_LAYOUT_MANAGER)->getSkin()->getSettings()->productlist->mode;
  4625. $user = Logic_UserOnline::getUser();
  4626.  
  4627. $id = (int) $instance->_getParam('productId');
  4628. $p = Logic_Product::loadInstance($id);
  4629. if (false == $p->existsInDB() || true == $p->missedLanguage()) {
  4630. $instance->_redirect($router->assemble(array(), 'index'));
  4631. return;
  4632. }
  4633. $p->setStats();
  4634.  
  4635. $options = Zend_Session::getOptions();
  4636. if (is_array($options) && isset($options['name'][0])) {
  4637. $cn = 'lastProducts-' . Locale_Manager::getLocale();
  4638. } else {
  4639. $cn = '';
  4640. }
  4641. if (isset($cn[0]) && isset($_COOKIE[$cn][0])) {
  4642. $lp = explode(',', $_COOKIE[$cn]);
  4643. } else {
  4644. $lp = array();
  4645. }
  4646.  
  4647. $cp = '/' . trim(Config_Manager::getConfigValue('core', 'SITE_PATH'), '/');
  4648. array_unshift($lp, $id);
  4649. $lp = array_unique($lp);
  4650. if (count($lp) > 30) {
  4651. $lp = array_slice($lp, 0, 30);
  4652. }
  4653.  
  4654. try {
  4655. $skin = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_LAYOUT_MANAGER)->getSkin();
  4656. if ($skin->hasRecentBox() && !Zend_Registry::isRegistered(System_Bootstrap::REGISTRY_INDEX_MEMCACHED_NGINX)) {
  4657. setcookie($cn, implode(',', $lp), mktime(0, 0, 0, 1, 1, 2 + date('Y')), $cp);
  4658. }
  4659. } catch (Exception $e) {
  4660. $instance->_errorLog->err($e);
  4661. }
  4662.  
  4663. $cat_id = (int) $p->defaultCategory->getIdentifier();
  4664. Zend_Registry::set('categoryId', $cat_id);
  4665.  
  4666. $category_links = array();
  4667. foreach ($p->defaultCategory->getCategoryPath() as $c) {
  4668. if (strlen($c->translation->name)) {
  4669. $category_links[$c->translation->name] = $router->assembleCategory(array(
  4670. 'categoryName' => $c->translation->name,
  4671. 'categoryId' => $c->category->category_id,
  4672. 'page' => 1,
  4673. 'view' => $view,
  4674. 'sort' => 1,
  4675. ), $c->category->category_id);
  4676. }
  4677. }
  4678.  
  4679. /* $instance->_breadCrumbs->add(Locale_Manager::translate('All products'), Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER)->assemble(array(
  4680. 'categoryName' => Locale_Manager::translate('All products'),
  4681. 'categoryId' => 0,
  4682. 'page' => 1,
  4683. 'view' => 1,
  4684. 'sort' => 1,
  4685. ), 'category')); */
  4686.  
  4687. foreach ($category_links as $k => $v)
  4688. $instance->_breadCrumbs->add($k, $v);
  4689. $instance->_breadCrumbs->add($p->translation->name, '');
  4690. Entity_UserMyproducts::cleanFlyweight();
  4691. $instance->view->id = $id;
  4692. $instance->view->product = $p;
  4693. $instance->view->category_link = $v;
  4694. $instance->view->stock_id = $p->defaultStock->stock->stock_id;
  4695.  
  4696. $precats = $p->defaultCategory->getCategoryPath(false)->toArray();
  4697. $this->view->precategories = array_reverse($precats);
  4698.  
  4699. if (!isset($_SESSION['poicvbgh']) && 0 == (int) $p->translation->active && !(Zend_Controller_Front::getInstance()->getParam(Access_Manager::ADMIN_IS_LOGGED_IN) && $this->_getParam('preview'))) {
  4700. return;
  4701. }
  4702.  
  4703.  
  4704.  
  4705. $attrs = array();
  4706. $names = array();
  4707. if (count($p->attributes) > 0) {
  4708. foreach ($p->attributes as $attrib) {
  4709. $presid = (int) $attrib['pres_id'];
  4710. $pres = Logic_Presentation::loadInstance($presid);
  4711. if (1 == (int) $pres->presentation->active) {
  4712. $x = (int) $attrib['attribute_id'];
  4713. if (!isset($names[$x])) {
  4714. $names[$x] = Logic_Attribute::loadInstance($x);
  4715. }
  4716. if (1 == (int) $names[$x]->attribute->active) {
  4717. $value = '';
  4718.  
  4719. switch ((int) $names[$x]->attribute->type) {
  4720. case 2:
  4721. foreach ($names[$x]->options as $o)
  4722. if ($attrib['value'] == (int) $o->option_id)
  4723. $value = $o->value;
  4724. break;
  4725.  
  4726. case 1:
  4727. $value = (int) $attrib['value'];
  4728. break;
  4729.  
  4730. case 0:
  4731. $value = $attrib['value'];
  4732. break;
  4733. }
  4734.  
  4735. $attrs[] = array(
  4736. 'name' => $names[$x]->attribute->name,
  4737. 'type' => (int) $names[$x]->attribute->type,
  4738. 'value' => $value,
  4739. );
  4740. }
  4741. }
  4742. }
  4743. }
  4744.  
  4745. $instance->view->attrs = $attrs;
  4746.  
  4747. $instance->view->gallery = $p->galleryImages;
  4748. $instance->view->jsgallery = true;
  4749.  
  4750. $instance->view->view = $view;
  4751. $instance->view->can_vote = !isset($_COOKIE['product_vote_' . $id]);
  4752. $instance->view->vote_stars = $p->getVoteStars();
  4753.  
  4754. if (1 == (int) Config_Manager::getConfigValue('comments', 'COMMENTS_ON')) {
  4755. $comments = new Logic_ProductCommentList();
  4756. $select = $comments->select();
  4757. $select->where('product_id = ?', (int) $p->getIdentifier());
  4758. $select->where('lang_id = ?', Locale_Manager::getLanguageId());
  4759. if (1 == (int) Config_Manager::getConfigValue('comments', 'COMMENTS_MODERATION'))
  4760. $select->where('validated = ?', 1);
  4761. $comments->fillFromSelect($select, false);
  4762. $instance->view->product_comments = $comments;
  4763. $instance->view->can_comment = ( 0 == (int) Config_Manager::getConfigValue('comments', 'COMMENTS_FOR_USERS') || Access_ClientManager::isLoggedIn() );
  4764. } else {
  4765. $instance->view->product_comments = null;
  4766. $instance->view->can_comment = false;
  4767. }
  4768.  
  4769.  
  4770.  
  4771. $related_products = new Logic_ProductList();
  4772. $ent = new Entity_ProductsRelated();
  4773. $select = $ent->select()->from($ent, 'product2');
  4774. $select->join('products_translations', 'products_translations.product_id = products_related.product2', null);
  4775. if (!isset($_SESSION['poicvbgh'])) {
  4776. $select->where('products_translations.active = ?', 1);
  4777. }
  4778. $select->where('products_translations.lang_id = ?', Locale_Manager::getLanguageId());
  4779. $select->where('products_related.product1 = ?', $p->getIdentifier());
  4780. $select->order('products_related.order ASC');
  4781. $related_products->fillFromSelect($select, false);
  4782. $instance->view->related_products = $related_products;
  4783. //chuj
  4784. $modelSpare = new Entity_SpareProduct();
  4785. $select = $modelSpare->select();
  4786. $select->where('product_id = ?', (int) $id);
  4787. $productSpare = $modelSpare->fetchAll($select);
  4788.  
  4789. $instance->view->spare = $productSpare;
  4790.  
  4791. if (count($p->optionsStock)) {
  4792. $options = array();
  4793. $default = array();
  4794. foreach ($p->optionsStock as $stock) {
  4795. if (1 == (int) $stock->stock->active || isset($_SESSION['poicvbgh'])) {
  4796. $x = array();
  4797. foreach ($stock->values as $value) {
  4798. $x[] = $value->ovalue->value->ovalue_id;
  4799. }
  4800. $options['stock_' . (int) $stock->stock->stock_id] = $x;
  4801.  
  4802. if (1 == (int) $stock->stock->default) {
  4803. $default = $x;
  4804. }
  4805. }
  4806. }
  4807. $instance->view->options_configuration = base64_encode(Zend_Json::encode($options));
  4808. $instance->view->options_default = base64_encode(Zend_Json::encode($default));
  4809. }
  4810.  
  4811. $body_class = 'shop_product';
  4812. if ($cat_id > 0) {
  4813. $body_class .= ' shop_product_from_cat_' . $cat_id;
  4814. }
  4815.  
  4816. $instance->view->body_class = $body_class;
  4817. $instance->view->body_id = 'shop_product' . $id;
  4818. $instance->_handleFlashMessages();
  4819. $instance->handleSeo($p);
  4820.  
  4821. $og = array();
  4822. $host = $instance->getRequest()->getServer();
  4823. $host = 'http' . ($instance->getRequest()->isSecure() ? 's' : '') . '://' . $host['HTTP_HOST'];
  4824. $url = $host . $instance->getRequest()->getRequestUri();
  4825. $og['type'] = 'product';
  4826. $og['url'] = $url;
  4827. $og['site_name'] = Config_Manager::getConfigValue('network', 'SHOP_NAME');
  4828. $og['title'] = $p->translation->name;
  4829. $photo = $p->mainImageName();
  4830. if (false != $photo) {
  4831. $og['image'] = $host . View_Smarty_Helper_ImageUrl::imageUrl(array(
  4832. 'type' => 'productGfx',
  4833. 'width' => 300,
  4834. 'height' => 300,
  4835. 'image' => $photo,
  4836. 'noupscale' => true,
  4837. ), null);
  4838. }
  4839. if (strlen($p->translation->short_description)) {
  4840. $og['description'] = strip_tags($p->translation->short_description);
  4841. } elseif (strlen($p->translation->description)) {
  4842. $og['description'] = strip_tags($p->translation->description);
  4843. } else {
  4844. $og['description'] = $p->translation->name;
  4845. }
  4846. if (strlen($og['description']) > 100) {
  4847. $w = explode("\n", wordwrap($og['description'], 100, "\n"));
  4848. $og['description'] = $w[0];
  4849. }
  4850.  
  4851. $cp = '';
  4852. if (Config_Manager::hasConfigValue('company', 'COMPANY_PHONE')) {
  4853. $cp = Config_Manager::getConfigValue('company', 'COMPANY_PHONE');
  4854. $cp = preg_replace('/[^0-9\+]/', '', $cp);
  4855. }
  4856. $instance->view->company_phone = $cp;
  4857.  
  4858. $instance->view->opengraph_header = $og;
  4859.  
  4860. $skinset = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_LAYOUT_MANAGER)->getSkin()->getSettings()->productdetails;
  4861. if (1 == (int) $skinset->fb_like || 1 == (int) $skinset->fb_chat || 1 == (int) $skinset->fb_send) {
  4862. $instance->view->xfbml = true;
  4863. }
  4864.  
  4865. if (Zend_Controller_Front::getInstance()->getParam(Access_Manager::ADMIN_IS_LOGGED_IN) && $instance->_getParam('preview')) {
  4866. $instance->view->adminPreview = true;
  4867. }
  4868.  
  4869. if (1 == (int) $instance->_getParam('exchange', 0)) {
  4870. if (!$user->user instanceof Logic_User || !Loyalty_Program::isEnabled() || !Loyalty_Program::exchangeModeProducts()) {
  4871. $instance->_redirect($router->assembleProduct(array(
  4872. 'productId' => $p->getIdentifier(),
  4873. 'productName' => $p->translation->name,
  4874. ), $p->getIdentifier()));
  4875. return;
  4876. }
  4877.  
  4878. $instance->view->basketAddRoute = 'loyaltyExchange';
  4879. $instance->view->productRoute = 'productExchange';
  4880. $instance->view->loyalty_points = false;
  4881. $instance->view->loyalty_exchange = true;
  4882. } else {
  4883. if (Loyalty_Program::orderGivesPoints()) {
  4884. $points = $p->defaultStock->loyaltyPointsForOrder();
  4885. if (false !== $points) {
  4886. $instance->view->loyalty_points = View_Smarty_Helper_Float::float(array('value' => $points, 'precision' => 0), null);
  4887. $instance->view->loyalty_msg_title = Locale_Manager::translate('Loyalty program points');
  4888. $loyalty_msgs = array(
  4889. Locale_Manager::translate('By purchasing products included in the loyalty program, you gain points, which then can be exchanged to other products available in the store or for a permanent discount.'),
  4890. );
  4891. if (!$user->user) {
  4892. $loyalty_msgs[] = Locale_Manager::translate('Only available to registered customers.');
  4893. }
  4894. $instance->view->loyalty_msgs = $loyalty_msgs;
  4895. } else {
  4896. $instance->view->loyalty_points = false;
  4897. }
  4898. } else {
  4899. $instance->view->loyalty_points = false;
  4900. }
  4901. $instance->view->loyalty_exchange = false;
  4902. }
  4903.  
  4904. $comparisonField = Logic_ProductAdditionalFieldList::getComparisonField();
  4905. $productCode = null;
  4906.  
  4907. if ($comparisonField != 'code') {
  4908. $productCode = $p->stock->getAdditionalField($comparisonField);
  4909. }
  4910.  
  4911. if ($productCode === null) {
  4912. $productCode = $p->stock->stock->code;
  4913. }
  4914.  
  4915. $instance->view->product_code = $productCode;
  4916.  
  4917. if (!View_Smarty::isCached()) {
  4918. $snippet = Logic_Snippet::getCode(Logic_Snippet::TYPE_PRODUCT);
  4919. if ($snippet) {
  4920. $instance->view->snippet_product = Parser_Processor::onetimeCompile($snippet, $p->getVariables(), array(
  4921. 'ignore_non_breaking_space' => true,
  4922. 'is_html_template' => true
  4923. ));
  4924. } else {
  4925. $instance->view->snippet_product = "";
  4926. }
  4927. }
  4928. }
  4929.  
  4930. public function Product_questionAction($instance) {
  4931. $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
  4932. $id = (int) $instance->_getParam('productId');
  4933.  
  4934. $product = new Logic_Product($id);
  4935. if (false == $product->existsInDB()) {
  4936. $instance->_redirect($router->assemble(array(), 'index'));
  4937. return;
  4938. }
  4939.  
  4940. $instance->view->productId = $id;
  4941.  
  4942. if ($instance->getRequest()->isPost()) {
  4943. $form = new Form_Shop_Question();
  4944. if ($form->isValid($_POST)) {
  4945. $val = $form->getValues();
  4946. $val['question'] = Purifier_HTML::strip_tags($val['question'], ENT_NOQUOTES);
  4947. $val['from'] = Purifier_HTML::strip_tags($val['name'], ENT_NOQUOTES);
  4948. $val['reply'] = $val['mail'];
  4949. $val['ip'] = $_SERVER['REMOTE_ADDR'];
  4950. $val['product_id'] = $id;
  4951. $val['product_name'] = $product->translation->name;
  4952. $val['product_link'] = $router->assembleProduct(array(
  4953. 'productName' => $product->translation->name,
  4954. 'productId' => $id,
  4955. ), $id, true);
  4956.  
  4957. $template = Mail_Manager::getMailTemplate(Mail_Manager::MAIL_PRODUCT_QUESTION);
  4958. $template->mail->from_name = $val['from'];
  4959. $message = new Mail_Message($template, true);
  4960. $message->setReplyTo($val['reply']);
  4961. $message->setVarArray($val);
  4962. $message->addRecipient(Config_Manager::getConfigValue('company', 'COMPANY_EMAIL'), false);
  4963.  
  4964. $metafields = new Metafield_Manager();
  4965. foreach ($metafields->getMetafieldObjectList() as $m) {
  4966. $key = "metafield.system." . $m->metafield->metafield->namespace . "." . $m->metafield->metafield->key;
  4967. $message->setVar($key, Zend_Controller_Action_HelperBroker::getExistingHelper('ViewRenderer')->view->escape($m->value->value));
  4968. }
  4969.  
  4970. $metafields = $product->metafields;
  4971. foreach ($metafields->getMetafieldObjectList() as $m) {
  4972. $key = "metafield.product." . $m->metafield->metafield->namespace . "." . $m->metafield->metafield->key;
  4973. $message->setVar($key, Zend_Controller_Action_HelperBroker::getExistingHelper('ViewRenderer')->view->escape($m->value->value));
  4974. }
  4975.  
  4976. try {
  4977. Mail_Manager::send($message, true);
  4978. $instance->_flashMessanger->addSuccess(Locale_Manager::translate('Thank you for your inquiry, we will contact you as soon as possible.'));
  4979. $instance->view->mail_send = true;
  4980. } catch (Exception $e) {
  4981. $instance->_errorLog->err($e);
  4982. $instance->_flashMessanger->addError(Locale_Manager::translate('Error while sending e-mail.'));
  4983. $instance->view->data = $val;
  4984. }
  4985. } else {
  4986. $instance->_flashMessanger->addError(Locale_Manager::translate('Filled form contains errors.'));
  4987. $instance->view->data = $form->getUnfilteredValues();
  4988. $instance->view->data_error = $form->getMessages();
  4989. }
  4990. }
  4991. $instance->_handleFlashMessages();
  4992. }
  4993.  
  4994. public function Product_getrecommendedAction($instance) {
  4995. if ($instance->getRequest()->isOptions()) {
  4996. header('Access-Control-Allow-Headers: origin, content-type, accept, x-requested-with');
  4997. header('Access-Control-Allow-Method: GET');
  4998. header('Access-Control-Allow-Origin: *');
  4999. return;
  5000. }
  5001.  
  5002. header('Access-Control-Allow-Origin: *');
  5003. header('Content-type: application/json');
  5004.  
  5005. //$settings = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_LAYOUT_MANAGER)->getSkin()->getSettings();
  5006. //$random = (1 == (int) $settings->main->random);
  5007. $random = false; /* ToDo: ----^ */
  5008.  
  5009. $entity = new Entity_ProductsTranslations();
  5010. $select = $entity->select()->from($entity, 'product_id');
  5011. $select->where('lang_id = ?', Locale_Manager::getLanguageId());
  5012. $select->where('active = ?', 1);
  5013. $select->where('main_page = ?', 1);
  5014.  
  5015. if (!$random) {
  5016. $select->order(array('main_page_order DESC', 'name ASC'));
  5017. $products = new Logic_ProductList();
  5018. $products->fillFromSelect($select);
  5019. } else {
  5020. $query = $select->query();
  5021. $identifiers = array();
  5022. while ($identifier = $query->fetch(PDO::FETCH_NUM)) {
  5023. $identifiers[] = $identifier[0];
  5024. }
  5025. shuffle($identifiers);
  5026. $products = new Logic_ProductList($identifiers);
  5027. }
  5028.  
  5029.  
  5030. $page = $this->_hasParam('page') ? (int) $this->_getParam('page') : 1;
  5031. if ($page < 1) {
  5032. $page = 1;
  5033. }
  5034.  
  5035. $paginator = Zend_Paginator::factory($products);
  5036. $paginator->setCurrentPageNumber($page);
  5037. //$paginator->setItemCountPerPage( (int) $settings->main->productspersite ); /* ToDo */
  5038. $paginator->setItemCountPerPage(30);
  5039. $paginator->setPageRange(5);
  5040.  
  5041. foreach ($paginator as $prod) {
  5042. $prods[] = $prod->toArrayForJSON();
  5043. }
  5044.  
  5045. echo Zend_Json::encode($prods);
  5046. }
  5047.  
  5048. public function Product_getproductAction($instance) {
  5049. header('Content-type: application/json');
  5050.  
  5051. try {
  5052. Access_ClientManager::reValidate();
  5053. if (!Access_ClientManager::isLoggedIn()) {
  5054. //echo 0;
  5055. //return;
  5056. }
  5057.  
  5058. $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
  5059.  
  5060. if ($this->_hasParam('id')) {
  5061. $id = (int) $this->_getParam('id');
  5062. if ($id <= 0) {
  5063. echo 0;
  5064. return;
  5065. }
  5066. } else {
  5067. echo 0;
  5068. return;
  5069. }
  5070.  
  5071. $product = Logic_Product::loadInstance($id);
  5072. if (false === $product->existsInDb() || 0 === (int) $product->translation->active || isset($_SESSION['poicvbgh'])) {
  5073. echo 0;
  5074. return;
  5075. }
  5076.  
  5077.  
  5078. $json = array(
  5079. 'id' => (int) $product->getIdentifier(),
  5080. 'name' => $product->translation->name,
  5081. 'code' => $product->getDefaultCode(),
  5082. 'active' => (int) $product->translation->active,
  5083. 'unit' => $product->unit->translation->name,
  5084. 'rate' => (float) $product->vote->rate,
  5085. 'votes' => (float) $product->vote->votes,
  5086. 'stockId' => (int) $product->defaultStock->getIdentifier(),
  5087. 'url' => $router->assembleProduct(array(
  5088. 'productName' => $product->translation->name,
  5089. 'productId' => $product->getIdentifier(),
  5090. ), $product->getIdentifier(), System_Router::ROUTE_TYPE_DEFAULT, true, null, true),
  5091. );
  5092.  
  5093. if ($product->defaultStockOnly()) {
  5094. $json['basket'] = $router->assemble(array(
  5095. 'stockId' => 'post',
  5096. ), 'basketAdd', System_Router::ROUTE_TYPE_DEFAULT, false, null, true);
  5097. } else {
  5098. $json['basket'] = $router->assemble(array(
  5099. 'stockId' => (int) $product->defaultStock->getIdentifier(),
  5100. ), 'basketAdd', System_Router::ROUTE_TYPE_DEFAULT, false, null, true);
  5101. }
  5102.  
  5103. $json['availability']['name'] = $product->defaultStock->availability->translation->name;
  5104. if ($product->defaultStock->availability->availability->photo) {
  5105. $json['availability']['img'] = $product->defaultStock->availability->getUrl();
  5106. }
  5107.  
  5108. if ($product->defaultStock->delivery) {
  5109. $json['delivery'] = $product->defaultStock->delivery->translation->name;
  5110. }
  5111.  
  5112. $json['price'] = array(
  5113. 'gross' => array(
  5114. 'base' => View_Smarty_Helper_Currency::currency(array('value' => $product->defaultStock->getPrice(false)), null),
  5115. 'base_float' => (float) $product->defaultStock->getPrice(false),
  5116. ),
  5117. 'net' => array(
  5118. 'base' => View_Smarty_Helper_Currency::currency(array('value' => $product->defaultStock->getPrice(true)), null),
  5119. 'base_float' => (float) $product->defaultStock->getPrice(true),
  5120. ),
  5121. );
  5122.  
  5123. if ($product->specialOffer) {
  5124. $json['price']['gross']['promo'] = View_Smarty_Helper_Currency::currency(array('value' => $product->defaultStock->getSpecialOfferPrice(false)), null);
  5125. $json['price']['gross']['promo_float'] = (float) $product->defaultStock->getSpecialOfferPrice(false);
  5126. $json['price']['gross']['final'] = $json['price']['gross']['promo'];
  5127. $json['price']['gross']['final_float'] = $json['price']['gross']['promo_float'];
  5128.  
  5129. $json['price']['net']['promo'] = View_Smarty_Helper_Currency::currency(array('value' => $product->defaultStock->getSpecialOfferPrice(true)), null);
  5130. $json['price']['gross']['promo_float'] = (float) $product->defaultStock->getSpecialOfferPrice(true);
  5131. $json['price']['net']['final'] = $json['price']['net']['promo'];
  5132. $json['price']['net']['final_float'] = $json['price']['net']['promo_float'];
  5133. } else {
  5134. $json['price']['gross']['final'] = $json['price']['gross']['base'];
  5135. $json['price']['gross']['final_float'] = $json['price']['gross']['base_float'];
  5136.  
  5137. $json['price']['net']['final'] = $json['price']['net']['base'];
  5138. $json['price']['net']['final_float'] = $json['price']['net']['base_float'];
  5139. }
  5140.  
  5141. if ($product->product->other_price > 0) {
  5142. $json['price']['other'] = View_Smarty_Helper_Currency::currency(array('value' => $product->product->other_price), null);
  5143. $json['price']['other_float'] = (float) $product->product->other_price;
  5144. }
  5145.  
  5146. if ($product->product->producer_id) {
  5147. $json['producer'] = array(
  5148. 'name' => $product->producer->manufacturer->name,
  5149. );
  5150. if ($product->producer->manufacturer->web) {
  5151. $json['producer']['url'] = $product->producer->manufacturer->web;
  5152. } else {
  5153. $json['producer']['url'] = $router->assembleProducer(array(
  5154. 'producerName' => $product->producer->manufacturer->name,
  5155. 'producerId' => $product->producer->getIdentifier(),
  5156. ), $product->producer->getIdentifier(), System_Router::ROUTE_TYPE_DEFAULT, true, null, true);
  5157. }
  5158.  
  5159. if ($product->producer->manufacturer->gfx) {
  5160. $sp = trim(Config_Manager::getConfigValue('core', 'SITE_PATH'), '/');
  5161. if (strlen($sp)) {
  5162. $sp = '/' . $sp;
  5163. }
  5164. $json['producer']['img'] = $sp . '/' . $product->producer->getUrl();
  5165. }
  5166. }
  5167.  
  5168. $json['newProduct'] = $product->isNew();
  5169. $json['description'] = $product->translation->description;
  5170. $json['short_description'] = $product->translation->short_description;
  5171. $json['additional_description'] = $product->translation->additional_description;
  5172. //$json['options'] = $product->getOptionsConfigurationStruct();
  5173.  
  5174. echo Zend_Json::encode($json);
  5175. } catch (Exception $e) {
  5176. $instance->_errorLog->debug('Error while downloading product (' . $id . '): ' . $e->getMessage());
  5177. echo 0;
  5178. }
  5179. }
  5180.  
  5181. public function Product_getstockAction($instance) {
  5182. header('Content-type: application/json');
  5183.  
  5184. try {
  5185. Access_ClientManager::reValidate();
  5186. if (!Access_ClientManager::isLoggedIn()) {
  5187. //echo 0;
  5188. //return;
  5189. }
  5190.  
  5191. $id = (int) $instance->_getParam('stock');
  5192. if ($id <= 0) {
  5193. echo 0;
  5194. return;
  5195. }
  5196.  
  5197.  
  5198. $options = array();
  5199. $currentOv = $currentOid = null;
  5200.  
  5201. if ($instance->_hasParam('currentVirt')) {
  5202. $virt = explode('=', $instance->_getParam('currentVirt'));
  5203. if (count($virt) === 2) {
  5204. $currentOid = (int) $virt[0];
  5205. $currentOv = (int) $virt[1];
  5206. }
  5207. }
  5208.  
  5209. if ($instance->_hasParam('virt')) {
  5210. $virt = explode('&', $instance->_getParam('virt'));
  5211. foreach ($virt as $v) {
  5212. $v = explode('=', $v);
  5213. if (2 == count($v)) {
  5214. $oid = (int) $v[0];
  5215. $ov = (int) $v[1];
  5216.  
  5217. if ($oid && $ov) {
  5218. $options[$oid] = $ov;
  5219. }
  5220. }
  5221. }
  5222.  
  5223. $virt = array(); //stack up again for return to JSON
  5224. foreach ($options as $k => $v) {
  5225. $virt[] = $k . '=' . $v;
  5226. }
  5227. $virt = implode('&', $virt);
  5228. } else {
  5229. $virt = 'default';
  5230. }
  5231.  
  5232.  
  5233. $p = new Logic_ProductStock($id);
  5234. if (!$p->existsInDB()) {
  5235. echo 0;
  5236. return;
  5237. }
  5238.  
  5239. $photo = $p->mainImageName($currentOid, $currentOv);
  5240. $photoOrig = $photo;
  5241.  
  5242. if (false != $photo) {
  5243. $photoOrig = View_Smarty_Helper_ImageUrl::imageUrl(array(
  5244. 'type' => 'productGfx',
  5245. 'image' => $photo
  5246. ), null);
  5247.  
  5248. $photo = View_Smarty_Helper_ImageUrl::imageUrl(array(
  5249. 'type' => 'productGfx',
  5250. 'width' => (int) $instance->_getParam('imgwidth'),
  5251. 'height' => (int) $instance->_getParam('imgheight'),
  5252. 'image' => $photo,
  5253. 'overlay' => 1,
  5254. ), null);
  5255. }
  5256.  
  5257. $buying = (1 !== (int) Config_Manager::getConfigValue('shopping', 'OFF_SHOPPING'));
  5258.  
  5259. $ret = array(
  5260. 'sid' => (int) $p->getIdentifier(),
  5261. 'photo' => $photo,
  5262. 'photo_orig' => $photoOrig,
  5263. 'photo_id' => $p->mainImageId(),
  5264. 'availability_photo' => $p->availability->getUrl(true),
  5265. 'availability' => $p->availability->translation->name,
  5266. 'delivery' => ( $p->delivery ? $p->delivery->translation->name : false ),
  5267. 'price' => View_Smarty_Helper_Currency::currency(
  5268. array('value' => $p->getPrice(false, $options)), null),
  5269. 'net_price' => View_Smarty_Helper_Currency::currency(
  5270. array('value' => $p->getPrice(true, $options)), null),
  5271. 'special_offer' => ( $p->product->specialOffer ?
  5272. View_Smarty_Helper_Currency::currency(
  5273. array('value' => $p->getSpecialOfferPrice(false, $options), 'ceil' => 2), null) : false ),
  5274. 'net_special_offer' => ( $p->product->specialOffer ?
  5275. View_Smarty_Helper_Currency::currency(
  5276. array('value' => $p->getSpecialOfferPrice(true, $options), 'ceil' => 2), null) : false ),
  5277. 'can_buy' => ($buying && 1 == (int) $p->availability->availability->can_buy),
  5278. 'unit' => $p->product->unit->translation->name,
  5279. 'code' => ( strlen($p->stock->code) ? $p->stock->code : $p->product->stock->stock->code ),
  5280. 'ean' => ( strlen($p->stock->ean) ? $p->stock->ean : $p->product->stock->stock->ean ),
  5281. 'loyaltypts_float' => $p->loyaltyPointsForOrder(false, $options),
  5282. 'loyaltypts' => $p->loyaltyPointsForOrder(true, $options),
  5283. 'loyaltyprice' => $p->loyaltyPointsPrice(true, $options),
  5284. 'stock' => (float) $p->stock->stock,
  5285. 'virt' => $virt,
  5286. );
  5287.  
  5288. if (Access_ClientManager::isLoggedIn()) {
  5289. $ret['is_subscribed'] = ($p->getAvailabilityNotifyByUser() !== null);
  5290. } else {
  5291. $ret['is_subscribed'] = false;
  5292. }
  5293.  
  5294. echo Zend_Json::encode($ret);
  5295. } catch (Exception $e) {
  5296. $instance->_errorLog->debug('Error while downloading product stock (' . $id . '): ' . $e->getMessage());
  5297. echo 0;
  5298. }
  5299. }
  5300.  
  5301. public function Product_voteAction($instance) {
  5302. header('Content-type: application/json');
  5303.  
  5304. try {
  5305. Access_ClientManager::reValidate();
  5306. if (!Access_ClientManager::isLoggedIn()) {
  5307. //echo 0;
  5308. //return;
  5309. }
  5310.  
  5311. $id = (int) $instance->_getParam('prod');
  5312. if ($id <= 0) {
  5313. echo 0;
  5314. return;
  5315. }
  5316.  
  5317. if (isset($_COOKIE['product_vote_' . $id])) {
  5318. echo 0;
  5319. return;
  5320. }
  5321.  
  5322. $vote = (int) $instance->_getParam('vote');
  5323. if ($vote <= 0 || $vote > 5) {
  5324. echo 0;
  5325. return;
  5326. }
  5327.  
  5328. $p = new Logic_Product($id);
  5329. $p->vote->rate = ( ( floatval($p->vote->rate) * intval($p->vote->votes) ) + $vote ) / ( intval($p->vote->votes) + 1 );
  5330. $p->vote->votes = intval($p->vote->votes) + 1;
  5331. $p->vote->save();
  5332. $p->removeCachedObject();
  5333.  
  5334. $path = Config_Manager::getConfigValue('core', 'SITE_PATH');
  5335. if (!isset($path[0]))
  5336. $path = '/';
  5337. setcookie('product_vote_' . $id, $vote, time() + 86400 * 365, $path);
  5338.  
  5339. echo 1;
  5340. } catch (Exception $e) {
  5341. $instance->_errorLog->debug('Error while voting (' . date('Y-m-d H:i:s') . '): ' . $e->getMessage());
  5342. echo 0;
  5343. }
  5344. }
  5345.  
  5346. public function Product_commentAction($instance) {
  5347. $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
  5348.  
  5349. if (1 == (int) Config_Manager::getConfigValue('comments', 'COMMENTS_ON') &&
  5350. ( 0 == (int) Config_Manager::getConfigValue('comments', 'COMMENTS_FOR_USERS') || Access_ClientManager::isLoggedIn() ) &&
  5351. 1 == (int) Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_LAYOUT_MANAGER)->getSkin()->getSettings()->productdetails->comments &&
  5352. $instance->getRequest()->isPost() && $instance->_hasParam('productId')) {
  5353.  
  5354. $id = (int) $instance->_getParam('productId');
  5355. $product = new Logic_Product($id);
  5356. if (false == $product->existsInDB()) {
  5357. $instance->_redirect($router->assemble(array(), 'index'));
  5358. return;
  5359. }
  5360. $form = new Form_Shop_Comment();
  5361.  
  5362. if ($form->isValid($_POST)) {
  5363. $val = $form->getValues();
  5364.  
  5365. $comm = new Logic_ProductComment();
  5366. $comm->create();
  5367. $comm->comment->product_id = $id;
  5368. $comm->comment->user_name = Purifier_HTML::strip_tags($val['user']);
  5369. $comm->comment->date = date('Y-m-d H:i:s');
  5370. $comm->comment->content = Purifier_HTML::strip_tags($val['comment']);
  5371. $comm->comment->lang_id = Locale_Manager::getLanguageId();
  5372. $comm->comment->user_id = Access_ClientManager::isLoggedIn() ? Logic_UserOnline::getUser()->user->user->user_id : NULL;
  5373. $comm->comment->validated = 0; //intval(1 != (int) Config_Manager::getConfigValue('comments', 'COMMENTS_MODERATION'));
  5374. $comm->save();
  5375. $commid = '#comment' . (int) $comm->getIdentifier();
  5376.  
  5377. if (1 == (int) Config_Manager::getConfigValue('comments', 'COMMENTS_MODERATION'))
  5378. $instance->_flashMessanger->addSuccess(Locale_Manager::translate('Your comment has been added. To display it in the store, it must be approved by the administrator.'));
  5379. else
  5380. $instance->_flashMessanger->addSuccess(Locale_Manager::translate('Your comment has been added. Thank you.'));
  5381. } else {
  5382. $instance->_flashMessanger->addError(Locale_Manager::translate('The content of your review cannot be blank.'));
  5383. $this->storeForRedirect('data', $form->getValues());
  5384. $this->storeForRedirect('data_error', $form->getMessages());
  5385. $commid = '#commentform';
  5386. }
  5387.  
  5388. $instance->_redirect($router->assembleProduct(array(
  5389. 'productName' => $product->translation->name,
  5390. 'productId' => $id,
  5391. ), 'product') . $commid);
  5392. return;
  5393. }
  5394.  
  5395. $instance->_redirect($router->assemble(array(), 'index'));
  5396. }
  5397.  
  5398. public function Product_searchAction($instance) {
  5399. View_Smarty::setCacheTag(array(
  5400. 'Logic_ProductList', 'Logic_Product', 'Logic_ProductStockList', 'Logic_ProductStock', 'Logic_Category', 'Logic_CategoryList',
  5401. 'productImages', 'productFiles', 'productAttributes', 'productVote', 'productTranslation',
  5402. 'Logic_ProductDelivery', 'Logic_ProductDeliveryList', 'Logic_ProductAvailability', 'Logic_ProductAvailabilityList',
  5403. 'Logic_ProductStock', 'Logic_ProductStockList',
  5404. ));
  5405. View_Smarty::skipCache();
  5406.  
  5407. if ($instance->getRequest()->isPost()) {
  5408.  
  5409. $form = new Form_Shop_Search();
  5410.  
  5411. if ($form->isValid($_POST)) {
  5412. $val = $form->getValues();
  5413.  
  5414. if (!isset($val['search'][0])) {
  5415. $instance->_flashMessanger->addError(Locale_Manager::translate('Search field cannot be blank'));
  5416. } else {
  5417. $val['search'] = trim($val['search'], "%");
  5418. $val['search'] = str_replace("/", "%2f", $val['search']);
  5419. $val['search'] = str_replace(":", " ", $val['search']);
  5420. $val['search'] = str_replace("#", "%23", $val['search']);
  5421. $val['search'] = str_replace("\\", "%5c", $val['search']);
  5422. $view = isset($_POST['view'][0]) ? $_POST['view'] : Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_LAYOUT_MANAGER)->getSkin()->getSettings()->productlist->mode;
  5423. $params = array(
  5424. 'page' => 1,
  5425. 'view' => $view,
  5426. 'sort' => 5,
  5427. 'searchquery' => (string) $val['search'],
  5428. );
  5429.  
  5430. $route = 'searchQuery';
  5431. if (isset($val['category'][0])) {
  5432. $id = (int) $val['category'];
  5433. $c = new Logic_Category($id);
  5434. if ($c->existsInDB()) {
  5435. $route = 'category';
  5436. $params['categoryId'] = $id;
  5437. $params['categoryName'] = $c->translation->name;
  5438. }
  5439. }
  5440.  
  5441. if (isset($val['priceto'][0])) {
  5442. $p = (float) Locale_Manager::getFloat($val['priceto']);
  5443. $params['priceto'] = (string) $p;
  5444. }
  5445. if (isset($val['pricefrom'][0])) {
  5446. $p = (float) Locale_Manager::getFloat($val['pricefrom']);
  5447. $params['pricefrom'] = (string) $p;
  5448. }
  5449. if (isset($val['promotion']) && 1 == (int) $val['promotion']) {
  5450. $params['promotion'] = 1;
  5451. }
  5452. if (isset($val['producer'][0])) {
  5453. $params['f_producer_' . $val['producer']] = 1;
  5454. }
  5455. $url = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER)->assemble($params, $route) . '?' . self::googleString($val['search']);
  5456. $instance->_redirect($url);
  5457. return;
  5458. }
  5459. } else {
  5460. $instance->view->data = $form->getUnfilteredValues();
  5461. $instance->view->data_error = $form->getMessages();
  5462. $instance->_flashMessanger->addError(Locale_Manager::translate('Incorrect search criteria.'));
  5463. }
  5464. }
  5465.  
  5466.  
  5467. $producers = new Logic_ManufacturerList();
  5468. $select = $producers->select();
  5469. $select->order('name ASC');
  5470. $producers->fillFromSelect($select);
  5471. $instance->view->producers = $producers;
  5472.  
  5473. $categories = new Logic_CategoryList();
  5474. $ent = new Entity_CategoriesTranslations();
  5475. $select = $ent->select()->from($ent, 'category_id');
  5476. $select->join('categories', 'categories.category_id = categories_translations.category_id', null);
  5477. if (!isset($_SESSION['poicvbgh'])) {
  5478. $select->where('active = ?', 1);
  5479. }
  5480. $select->where('root = ?', 1);
  5481. $select->where('lang_id = ?', Locale_Manager::getLanguageId());
  5482. $select->order('categories.order ASC');
  5483. $instance->view->categories = $categories->fillFromSelect($select);
  5484.  
  5485. $instance->view->filter_price = Config_Manager::getConfigValue('filters', 'PRICE') == 1;
  5486. $instance->view->filter_producer = Config_Manager::getConfigValue('filters', 'PRODUCER') == 1;
  5487. $instance->view->filter_promotion = Config_Manager::getConfigValue('filters', 'PROMOTION') == 1;
  5488.  
  5489. $instance->_breadCrumbs->add(Locale_Manager::translate('Product search'), '');
  5490. $instance->view->body_class = 'shop_product_search';
  5491. $instance->_handleFlashMessages();
  5492. }
  5493.  
  5494. public function Product_exchangeAction($instance) {
  5495.  
  5496. $user = Logic_UserOnline::getUser();
  5497. $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
  5498.  
  5499. if (!$user->user instanceof Logic_User || !Loyalty_Program::isEnabled() || !Loyalty_Program::exchangeModeProducts()) {
  5500. $instance->_redirect($router->assemble(array(), 'index'));
  5501. return;
  5502. }
  5503.  
  5504. $ret = $this->Basket_add($instance, true);
  5505.  
  5506. foreach ($ret['messages'] as $f => $msgs) {
  5507. $f = 'add' . ucfirst($f);
  5508. foreach ($msgs as $msg) {
  5509. $instance->_flashMessanger->$f($msg);
  5510. }
  5511. }
  5512.  
  5513. if (!is_string($ret['redirect'])) {
  5514. $ret['redirect'] = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER)->assemble(array(), 'loyaltyList');
  5515. }
  5516.  
  5517. $instance->_redirect($ret['redirect']);
  5518. }
  5519.  
  5520. public function Product_availabilitysubAction(Zend_Controller_Action $instance) {
  5521. if (!$instance->getRequest()->isXmlHttpRequest()) {
  5522. return;
  5523. }
  5524.  
  5525. if ($instance->getRequest()->isPost()) {
  5526. $form = new Form_Shop_ProductAvailabilitySub();
  5527. if ($form->isValid($_POST)) {
  5528. $data = $form->getValues();
  5529. $data['user_id'] = null;
  5530. $lObject = null;
  5531.  
  5532. if (Access_ClientManager::isLoggedIn()) {
  5533. $lUser = Logic_UserOnline::getUser()->user;
  5534. $data['user_id'] = $lUser->getIdentifier();
  5535. $data['email'] = $lUser->userinfo->email;
  5536. $lObject = Logic_ProductAvailabilityNotify::getNotifyByStockIdAndUserId($data['stock_id'], $data['user_id']);
  5537. }
  5538.  
  5539. if ($lObject === null) {
  5540. $lObject = Logic_ProductAvailabilityNotify::getNotifyByStockIdAndEmail($data['stock_id'], $data['email']);
  5541. if ($lObject === null || Access_ClientManager::isLoggedIn()) {
  5542. Logic_ProductAvailabilityNotify::createOrUpdateNotify($lObject, $data);
  5543. $ret = 1;
  5544. } else {
  5545. $ret = 2;
  5546. }
  5547. } else {
  5548. $ret = 2;
  5549. }
  5550. } else {
  5551. $ret = $form->getMessages();
  5552. }
  5553. }
  5554.  
  5555. header('Content-type: application/json');
  5556. echo json_encode($ret);
  5557. }
  5558.  
  5559. public function Product_availabilityunsubAction(Zend_Controller_Action $instance) {
  5560. if (!$instance->getRequest()->isXmlHttpRequest()) {
  5561. return;
  5562. }
  5563.  
  5564. if (Access_ClientManager::isLoggedIn()) {
  5565. if ($instance->getRequest()->isPost()) {
  5566. $form = new Form_Shop_ProductAvailabilityUnsub();
  5567. if ($form->isValid($_POST)) {
  5568. $data = $form->getValues();
  5569. $lObject = Logic_ProductAvailabilityNotify::getNotifyByStockIdAndUserId(
  5570. $data['stock_id'], Logic_UserOnline::getUser()->user->getIdentifier()
  5571. );
  5572.  
  5573. if ($lObject === null) {
  5574. $ret = 0;
  5575. } else {
  5576. $lObject->delete();
  5577. $ret = 1;
  5578. }
  5579. } else {
  5580. $ret = $form->getMessages();
  5581. }
  5582. }
  5583. } else {
  5584. $ret = -1;
  5585. }
  5586.  
  5587. header('Content-type: application/json');
  5588. echo json_encode($ret);
  5589. }
  5590.  
  5591. public function loyaltyProducts($instance) {
  5592. $user = Logic_UserOnline::getUser();
  5593. $products = new Logic_ProductList();
  5594. $select = $products->select();
  5595.  
  5596. $select->join('products_translations', 'products_translations.product_id = products.product_id', null);
  5597. $select->where('products_translations.lang_id = ?', Locale_Manager::getLocaleId());
  5598. $select->where('products_translations.active = ?', 1);
  5599.  
  5600. $select->join('products_stock', 'products_stock.product_id = products.product_id', null);
  5601. $select->where('products_stock.extended = ?', 0);
  5602. $select->where('products_stock.price > 0 OR products.loyalty_price IS NOT NULL');
  5603.  
  5604. if (Loyalty_Program::exchangeModeProductsExplicit()) {
  5605. $select->where('in_loyalty = ?', 1);
  5606. } elseif (Loyalty_Program::exchangeModeProductsProducers()) {
  5607. $select->join('producers', 'producers.producer_id = products.producer_id', null);
  5608. $select->where('producers.in_loyalty = ?', 1);
  5609. } elseif (Loyalty_Program::exchangeModeProductsCategories()) {
  5610. $select->join('products_categories', 'products_categories.product_id = products.product_id', null);
  5611. $select->join('categories', 'categories.category_id = products_categories.category_id', null);
  5612. $select->where('categories.in_loyalty = ?', 1);
  5613. }
  5614.  
  5615. $sort = $instance->_hasParam('sort') ? (int) $instance->_getParam('sort') : 1;
  5616. if ($sort > 5 || $sort < 1) {
  5617. $sort = 5;
  5618. }
  5619.  
  5620. $filter = $instance->_hasParam('filter') ? (int) $instance->_getParam('filter') : 0;
  5621. $sum = (float) $user->user->loyalty->sum();
  5622.  
  5623. $ratio = Loyalty_Program::getExchangeRatio();
  5624. if ($ratio['amount'] > 0 && $ratio['points'] > 0) {
  5625. $ratio['ratio'] = (float) $ratio['points'] / (float) $ratio['amount'];
  5626. } else {
  5627. $ratio = false;
  5628. }
  5629.  
  5630. if (1 == $filter && $ratio) {
  5631. if ($sum < $ratio['points']) {
  5632. return $products; //now enough points for first exchange level
  5633. }
  5634. $select->where('((loyalty_price IS NULL) * price * ' . $ratio['ratio'] . ' + IFNULL(loyalty_price, 0)) <= ?', $sum);
  5635. }
  5636.  
  5637. if (5 == $sort) {
  5638. if ($ratio) {
  5639. $select->order('((loyalty_price IS NULL) * price * ' . $ratio['ratio'] . ' + IFNULL(loyalty_price, 0)) ASC');
  5640. } else {
  5641. $select->order(Locale_Manager::collatedOrder('products_translations.name ASC'));
  5642. }
  5643. } elseif ($sort > 2) {
  5644. $select->order('products_stock.price ' . (3 == $sort ? 'ASC' : 'DESC'));
  5645. } else {
  5646. $select->order(Locale_Manager::collatedOrder('products_translations.name ' . (1 == $sort ? 'ASC' : 'DESC')));
  5647. }
  5648.  
  5649. $products->fillFromSelect($select);
  5650. return $products;
  5651. }
  5652.  
  5653. public function Product_loyaltyAction($instance) {
  5654.  
  5655. $user = Logic_UserOnline::getUser();
  5656. $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
  5657.  
  5658. if (!$user->user instanceof Logic_User || !Loyalty_Program::isEnabled() || !Loyalty_Program::exchangeModeProducts()) {
  5659. $instance->_redirect($router->assemble(array(), 'index'));
  5660. return;
  5661. }
  5662.  
  5663. $instance->view->user_points = View_Smarty_Helper_Float::float(array('value' => $user->user->loyalty->sum(), 'precision' => 0), null);
  5664. $instance->view->loyalty_filter = $instance->_hasParam('filter') ? (int) $instance->_getParam('filter') : 0;
  5665.  
  5666. $loyalty_msgs = array();
  5667. // 'text' is not put through |escape in .tpl !
  5668. if (Loyalty_Program::orderGivesPoints()) {
  5669. $loyalty_msgs[] = array(
  5670. 'title' => Locale_Manager::translate('Placing orders'),
  5671. 'text' => htmlspecialchars(Loyalty_Program::exchangeModeDiscounts() ?
  5672. Locale_Manager::translate('for the purchase of every product available in the loyalty program you gain points, which then covert to permanent discount in the store.') :
  5673. Locale_Manager::translate('for the purchase of every product available in the loyalty program you gain points, which you can exchange for other products.')
  5674. ),
  5675. );
  5676. }
  5677. if (Loyalty_Program::commentGivesPoints()) {
  5678. $loyalty_msgs[] = array(
  5679. 'title' => Locale_Manager::translate('Reviewing a product'),
  5680. 'text' => sprintf(
  5681. htmlspecialchars(
  5682. Locale_Manager::translate('select a product and write a review about it. You will gain %s %s points. %s')
  5683. ), '<b>', Loyalty_Program::commentHowManyPoints(true), '</b>'
  5684. ),
  5685. );
  5686. }
  5687. if (Loyalty_Program::newsletterGivesPoints()) {
  5688. $url = $router->assemble(array(), 'newsletterSign');
  5689. $loyalty_msgs[] = array(
  5690. 'title' => Locale_Manager::translate('Subscribing to our newsletter'),
  5691. 'text' => sprintf(
  5692. htmlspecialchars(
  5693. Locale_Manager::translate('%s subscribe%s, and you will gain %s %s points. %s')
  5694. ), '<a href="' . $url . '">', '</a>', '<b>', Loyalty_Program::newsletterHowManyPoints(true), '</b>'
  5695. ),
  5696. );
  5697. }
  5698. $instance->view->loyalty_msgs = $loyalty_msgs;
  5699.  
  5700. Zend_Registry::set('products', $this->loyaltyProducts($instance));
  5701. Zend_Registry::set('list_type', 'loyalty');
  5702. $instance->view->sort_links = true;
  5703. $instance->view->body_class = 'shop_product_list shop_product_loyaltylist';
  5704. $instance->view->body_id = 'shop_product_loyaltylist';
  5705. $instance->_forward('list');
  5706. }
  5707.  
  5708. public function Product_producerAction($instance) {
  5709. $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
  5710.  
  5711. if ($instance->_hasParam('producerId') && $id = (int) $instance->_getParam('producerId')) {
  5712.  
  5713. $p = new Logic_Manufacturer($id);
  5714. if (false == $p->existsInDB()) {
  5715. $instance->_redirect($router->assemble(array(), 'index'));
  5716. return;
  5717. }
  5718.  
  5719. $products = new Logic_ProductList();
  5720. $select = $products->select();
  5721. $select->where('products.producer_id = ?', $id);
  5722.  
  5723. $select->join('products_translations', 'products_translations.product_id = products.product_id', null);
  5724. $select->where('products_translations.lang_id = ?', Locale_Manager::getLocaleId());
  5725. $select->where('products_translations.active = ?', 1);
  5726.  
  5727. $sort = $instance->_hasParam('sort') ? (int) $instance->_getParam('sort') : 1;
  5728. if ($sort > 4 || $sort < 1)
  5729. $sort = 1;
  5730.  
  5731. if (1 == $sort)
  5732. $select->order('products_translations.order DESC');
  5733.  
  5734. if ($sort > 2) {
  5735. $select->join('products_stock', 'products_stock.product_id = products.product_id', null);
  5736. $select->where('products_stock.extended = ?', 0);
  5737. $select->order('products_stock.price ' . (3 == $sort ? 'ASC' : 'DESC'));
  5738. } else
  5739. $select->order(Locale_Manager::collatedOrder('products_translations.name ' . (1 == $sort ? 'ASC' : 'DESC')));
  5740.  
  5741. $products->fillFromSelect($select);
  5742. Zend_Registry::set('products', $products);
  5743. Zend_Registry::set('list_type', 'producer');
  5744. $instance->view->sort_links = true;
  5745. $instance->view->body_class = 'shop_product_list shop_product_producer';
  5746. $instance->view->body_id = 'shop_product_producer' . $id;
  5747. $instance->_forward('list');
  5748. } else {
  5749. $instance->_redirect($router->assemble(array(), 'index'));
  5750. }
  5751. }
  5752.  
  5753. public function Product_promotionsAction($instance) {
  5754. $products = new Logic_ProductList();
  5755.  
  5756. $select = $products->select();
  5757. $select->join('products_translations', 'products_translations.product_id = products.product_id', null);
  5758. $select->where('products_translations.lang_id = ?', Locale_Manager::getLocaleId());
  5759. $select->where('products_translations.active = ?', 1);
  5760.  
  5761. $select->join('special_offers_conditions', 'special_offers_conditions.object_id = products.product_id', null);
  5762. $select->join('special_offers', 'special_offers_conditions.promo_id = special_offers.promo_id', null);
  5763. $select->where('special_offers_conditions.condition_type = ?', 3);
  5764. $select->where('special_offers.date_to >= ?', date('Y-m-d H:i') . ':00');
  5765. $select->where('special_offers.date_from <= ?', date('Y-m-d H:i') . ':59');
  5766.  
  5767. $sort = $instance->_hasParam('sort') ? (int) $instance->_getParam('sort') : 1;
  5768. if ($sort > 4 || $sort < 1)
  5769. $sort = 1;
  5770.  
  5771. if ($sort > 2) {
  5772. $select->join(array('priceorder' => 'products_stock'), 'products.product_id = priceorder.product_id and priceorder.default = 1', null);
  5773. $select->order('priceorder.comp_promo_price ' . (3 == $sort ? 'ASC' : 'DESC'));
  5774. } else
  5775. $select->order(Locale_Manager::collatedOrder('products_translations.name ' . (1 == $sort ? 'ASC' : 'DESC')));
  5776.  
  5777. $products->fillFromSelect($select, true, array('Logic_SpecialOfferList'));
  5778. Zend_Registry::set('products', $products);
  5779. Zend_Registry::set('list_type', 'promo');
  5780. $instance->view->sort_links = true;
  5781. $instance->view->body_class = 'shop_product_list shop_product_promo';
  5782. $instance->_forward('list');
  5783. }
  5784.  
  5785. public function Product_newAction($instance) {
  5786. $products = new Logic_ProductList();
  5787. $select = $products->select();
  5788. $select->join('products_translations', 'products_translations.product_id = products.product_id', null);
  5789. $select->where('products_translations.lang_id = ?', Locale_Manager::getLocaleId());
  5790. if (!isset($_SESSION['poicvbgh'])) {
  5791. $select->where('products_translations.active = ?', 1);
  5792. }
  5793.  
  5794. $mode = (bool) Config_Manager::getConfigValue('shopping', 'NEWPRODUCTS_MODE');
  5795. if ($mode == 0) {
  5796. $select->where('products.newproduct = ?', 1);
  5797. } else {
  5798. if (Config_Manager::hasConfigValue('shopping', 'NEWPRODUCTS_DAYS')) {
  5799. $days = (int) Config_Manager::getConfigValue('shopping', 'NEWPRODUCTS_DAYS');
  5800. } else {
  5801. $days = 0;
  5802. }
  5803. $limit = mktime(0, 0, 0) - 86400 * $days;
  5804. $select->where('add_date >= ?', date('Y-m-d', $limit));
  5805. }
  5806.  
  5807. $sort = $instance->_hasParam('sort') ? (int) $instance->_getParam('sort') : 5;
  5808. if ($sort > 5 || $sort < 1)
  5809. $sort = 5;
  5810.  
  5811. if (5 == $sort) {
  5812. $select->order('products.add_date DESC');
  5813. } elseif ($sort > 2) {
  5814. $select->join(array('priceorder' => 'products_stock'), 'products.product_id = priceorder.product_id and priceorder.default = 1', null);
  5815. $select->order('priceorder.comp_promo_price ' . (3 == $sort ? 'ASC' : 'DESC'));
  5816. } else {
  5817. $select->order(Locale_Manager::collatedOrder('products_translations.name ' . (1 == $sort ? 'ASC' : 'DESC')));
  5818. }
  5819.  
  5820. $products->fillFromSelect($select);
  5821. Zend_Registry::set('products', $products);
  5822. Zend_Registry::set('list_type', 'new');
  5823. $instance->view->sort_links = true;
  5824. $instance->view->body_class = 'shop_product_list shop_product_new';
  5825. $instance->_forward('list');
  5826. }
  5827.  
  5828. public function Product_dayAction($instance) {
  5829. $products = new Logic_ProductList();
  5830.  
  5831. $ent = new Entity_ProductsPotd();
  5832. $select = $ent->select()->from($ent, 'product_id');
  5833. $select->join('products_translations', 'products_translations.product_id = products_potd.product_id', null);
  5834. $select->where('products_translations.lang_id = ?', Locale_Manager::getLocaleId());
  5835. $select->where('products_translations.active = ?', 1);
  5836.  
  5837. $sort = $instance->_hasParam('sort') ? (int) $instance->_getParam('sort') : 5;
  5838. if ($sort > 4 || $sort < 1)
  5839. $sort = 1;
  5840.  
  5841. if ($sort > 2) {
  5842. $select->join(array('priceorder' => 'products_stock'), 'products.product_id = priceorder.product_id and priceorder.default = 1', null);
  5843. $select->order('priceorder.comp_promo_price ' . (3 == $sort ? 'ASC' : 'DESC'));
  5844. } else {
  5845. $select->order(Locale_Manager::collatedOrder('products_translations.name ' . (1 == $sort ? 'ASC' : 'DESC')));
  5846. }
  5847.  
  5848. $products->fillFromSelect($select);
  5849. Zend_Registry::set('products', $products);
  5850. Zend_Registry::set('list_type', 'day');
  5851. $instance->view->sort_links = true;
  5852. $instance->view->body_class = 'shop_product_list shop_product_day';
  5853. $instance->_forward('list');
  5854. }
  5855.  
  5856. public function Info_indexAction($instance) {
  5857. View_Smarty::setCacheTag(array(
  5858. 'Logic_AboutPageList', 'Logic_AboutPage'
  5859. ));
  5860.  
  5861. $ok = false;
  5862.  
  5863. if ($id = (int) $instance->_getParam('pageId')) {
  5864. $page = new Logic_AboutPage($id);
  5865. if (false == $page->existsInDB()) {
  5866. $instance->_redirect(Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER)->assemble(array(), 'index'));
  5867. return;
  5868. }
  5869. $page->setStats();
  5870. if (isset($_SESSION['poicvbgh']) || 1 == (int) $page->page->active || (Zend_Controller_Front::getInstance()->getParam(Access_Manager::ADMIN_IS_LOGGED_IN) && $this->_getParam('preview'))) {
  5871. $instance->_breadCrumbs->add($page->page->name, '');
  5872. $instance->view->page = $page;
  5873. $ok = true;
  5874. }
  5875. }
  5876.  
  5877. if (!$ok) {
  5878. $instance->_redirect(Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER)->assemble(array(), 'index'));
  5879. return;
  5880. }
  5881.  
  5882. $instance->view->body_class = 'shop_infopage';
  5883. $instance->view->body_id = 'shop_infopage' . $id;
  5884. $instance->handleSeo($page);
  5885. $instance->_handleFlashMessages();
  5886. }
  5887.  
  5888. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement