Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * @package Core.Client
- * @author michal
- * @access public
- */
- class Client_Actions extends Controllers_ClientBase {
- /* Basket */
- const SMS_ORDER_TEXT = 'New order no. %d. Total: %s. Products: %s. User: %s.';
- const DEFAULT_BASKET_QUANTITY = 1;
- private $_shipping_id;
- private $_payment_id;
- private $_shipping_country;
- /* Panel */
- const ORDERS_LIMIT = 5;
- /**
- * abstract methods that are not executed on $this but on $instance,
- * here they can be empty
- */
- protected function _handleFlashMessages($viewVariable = 'flash_messages') {
- }
- protected function actionsHelper() {
- }
- protected function addCachedVariables() {
- }
- protected function storeForRedirect($name, $var) {
- }
- private static function googleString($string) {
- if (0 == strlen($string))
- return '';
- $string = preg_replace('/\s+/', ' ', $string);
- $array = explode(' ', $string);
- foreach ($array as $k => $v)
- $array[$k] = rawurlencode($v);
- $string = implode(',', $array);
- return 'url=' . $string;
- }
- /**
- * BasketController
- */
- public function Basket_indexAction($instance) {
- $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
- $session = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_SESSION);
- if (false === Zend_Registry::get('enable_basket')) {
- $instance->_flashMessanger->addWarning(Locale_Manager::translate('Cart is disabled.'));
- $instance->_redirect($router->assemble(array(), 'index'));
- return;
- }
- if (Zend_Registry::isRegistered(System_Bootstrap::REGISTRY_FACEBOOK) && isset($_GET['error_reason'][0]) && 'user_denied' == $_GET['error_reason']) {
- $instance->_flashMessanger->addWarning(Locale_Manager::translate('You cannot continue with this order without granting the application appropriate permissions.'));
- $instance->_redirect($router->assemble(array(), 'index'));
- return;
- }
- $instance->_breadCrumbs->add(Locale_Manager::translate('Cart'), '');
- $user = Logic_UserOnline::getUser();
- if (is_int($session->shipping_id)) {
- $this->_shipping_id = $session->shipping_id;
- }
- if (is_int($session->payment_id)) {
- $this->_payment_id = $session->payment_id;
- }
- if (is_string($session->shipping_country)) {
- $this->_shipping_country = $session->shipping_country;
- } else if ($user->user && $user->user->shippingAddress) {
- $this->_shipping_country = $user->user->shippingAddress->address->country_code;
- }
- $recount = false;
- if ($instance->getRequest()->isPost() && isset($_POST['recount'][0]) && '1' === $_POST['recount']) {
- $recount = true;
- }
- $instance->view->recount = $recount;
- if (false == $recount && $instance->_hasParam('recount') && 1 == (int) $instance->_getParam('recount')) {
- $this->Basket_checkQuantity($instance);
- }
- if (count($user->basket) && $recount) {
- if (false == $this->Basket_recount($instance)) {
- $this->Basket_processBasket($instance);
- } else {
- if (isset($_POST['button1'][0])) {
- if (is_string($session->last_product_page)) {
- if (preg_match('/^https?\:\/\/' . preg_quote($_SERVER['HTTP_HOST']) . '/i', $session->last_product_page))
- $url = $session->last_product_page;
- else
- $url = $router->assemble(array(), 'index');
- } else
- $url = $router->assemble(array(), 'index');
- $instance->_redirect($url);
- return;
- } else if (isset($_POST['button2'][0])) {
- if (true == $this->Basket_processBasket($instance, true)) {
- $session->shipping_id = $this->_shipping_id;
- $session->shipping_country = $this->_shipping_country;
- $session->payment_id = $this->_payment_id;
- $instance->_redirect($router->assemble(array(), 'basketStep2'));
- return;
- }
- } else {
- $this->Basket_processBasket($instance);
- }
- }
- } else {
- $quantity = array();
- foreach ($user->basket as $basket_product) {
- $quantity[(int) $basket_product->getIdentifier()] = (float) $basket_product->basket->quantity;
- }
- $instance->view->quantity = $quantity;
- $instance->view->quantity_error = array();
- $this->Basket_processBasket($instance);
- }
- $instance->view->shipping_id = $this->_shipping_id;
- $instance->view->payment_id = $this->_payment_id;
- $instance->view->shipping_country = $this->_shipping_country;
- $instance->view->sum = $this->Basket_getSum();
- $instance->view->sum_noship = View_Smarty_Helper_Currency::currency(array(
- 'value' => $this->Basket_getSum(false),
- 'float' => true,
- ), null);
- $instance->view->currencymap = Locale_Manager::getCurrency()->toCurrency(1234.56);
- $instance->view->showpromocodes = (int) Config_Manager::getConfigValue('shopping', 'USE_PROMO_CODES');
- $instance->view->country = Config_Manager::getConfigValue('company', 'COUNTRY');
- if (Loyalty_Program::orderGivesPoints()) {
- $points = $user->basket->loyaltyPointsForOrder();
- if ($points > 0) {
- $this->view->loyalty_points = View_Smarty_Helper_Float::float(array('value' => $points, 'precision' => 0), null);
- } else {
- $this->view->loyalty_points = false;
- }
- } else {
- $this->view->loyalty_points = false;
- }
- foreach ($user->basket as $basket_product) {
- if ($basket_product->stock->stock->delivery_id) {
- $instance->view->showDelivery = true;
- }
- }
- $instance->view->body_class = 'shop_basket';
- $instance->_handleFlashMessages();
- }
- public function Basket_step2Action($instance) {
- $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
- $user = Logic_UserOnline::getUser();
- if (false === Zend_Registry::get('enable_basket')) {
- $instance->_flashMessanger->addWarning(Locale_Manager::translate('Cart is disabled.'));
- $instance->_redirect($router->assemble(array(), 'index'));
- return;
- }
- if (0 == count($user->basket)) {
- $instance->_redirect($router->assemble(array(), 'basket'));
- return;
- }
- $instance->_breadCrumbs->add(Locale_Manager::translate('Cart'), $router->assemble(array(), 'basket'));
- $instance->_breadCrumbs->add(Locale_Manager::translate('Your details'), '');
- if (Access_ClientManager::isLoggedIn()) {
- $instance->_forward('address', null, null, array('mode' => 'user'));
- return;
- }
- if ($instance->getRequest()->isPost() && isset($_POST['loginform'][0])) {
- $form = new Form_Shop_Login();
- if ($form->isValid($_POST)) {
- $val = $form->getValues();
- $result = Access_ClientManager::authenticate($val['mail'], $val['pass']);
- if ($result->isValid()) {
- if (Zend_Registry::isRegistered('user_login_product_recovery')) {
- $moved = (int) Zend_Registry::get('user_login_product_recovery');
- if ($moved > 0) {
- if ($moved > 1) {
- $instance->_flashMessanger->addInfo(Locale_Manager::translate('Products have been restored to your shopping cart from the previous session.', $moved));
- } else {
- $instance->_flashMessanger->addInfo(Locale_Manager::translate('Product has been restored to your shopping cart from the previous session.', $moved));
- }
- $instance->_redirect($router->assemble(array(), 'basket'));
- return;
- }
- }
- $instance->_forward('address', null, null, array('mode' => 'user'));
- return;
- } else {
- switch ($result->getCode()) {
- case Access_Auth_Result::FAILURE_USER_INACTIVE:
- $instance->_flashMessanger->addError(Locale_Manager::translate('Inactive account.'));
- break;
- case Access_Auth_Result::FAILURE_USER_NOT_VERIFIED:
- $instance->_flashMessanger->addError(Locale_Manager::translate('Your registration has not been confirmed. Check your e-mail and click the confirmation link.'));
- break;
- default:
- $instance->_flashMessanger->addError(Locale_Manager::translate('Incorrect login details'));
- break;
- }
- }
- } else {
- $instance->_flashMessanger->addError(Locale_Manager::translate('Incorrect login details'));
- Access_ClientManager::logout();
- }
- } elseif ($instance->getRequest()->isPost() && isset($_POST['addressform'][0])) {
- $instance->_forward('address', null, null, array('mode' => $_POST['addressform']));
- return;
- } elseif ($instance->getRequest()->isPost() && 0 == count($_POST) && 0 == count($_FILES) && 0 === strpos($_SERVER['HTTP_CONTENT_TYPE'], 'multipart/form-data')) {
- $msg = Locale_Manager::translate('Invalid request. The file size limit has probably been exceeded. The size limit is %dMB.', Form_AdditionalFields::FILE_UPLOAD_LIMIT
- );
- $instance->_flashMessanger->addError($msg);
- }
- $instance->view->allow_single = ( 1 == (int) Config_Manager::getConfigValue('shopping', 'ALLOW_TO_BUY_NOT_REG') );
- $instance->view->loyalty_order_gives_points = Loyalty_Program::orderGivesPoints();
- $instance->view->country = Config_Manager::getConfigValue('company', 'COUNTRY');
- $instance->view->body_class = 'shop_basket_step2';
- $instance->_handleFlashMessages();
- }
- public function Basket_addressAction($instance) {
- $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
- $session = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_SESSION);
- $user = Logic_UserOnline::getUser();
- if (false === Zend_Registry::get('enable_basket')) {
- $instance->_flashMessanger->addWarning(Locale_Manager::translate('Cart is disabled.'));
- $instance->_redirect($router->assemble(array(), 'index'));
- return;
- }
- $mode = $instance->_getParam('mode');
- if (!in_array($mode, array('user', 'register', 'single')) || 0 == count($user->basket)) {
- $instance->_redirect($router->assemble(array(), 'basket'));
- return;
- }
- if ($mode === 'register' && !Zend_Registry::get('enable_register')) {
- $instance->_flashMessanger->addWarning(Locale_Manager::translate('Registration is temporarily unavailable'));
- $instance->_redirect(Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER)->assemble(array(), 'index'));
- return;
- }
- if ('single' == $mode && 1 != (int) Config_Manager::getConfigValue('shopping', 'ALLOW_TO_BUY_NOT_REG')) {
- $instance->_flashMessanger->addWarning(Locale_Manager::translate('Purchase cannot be made without registration.'));
- $instance->_redirect($router->assemble(array(), 'basketStep2'));
- return;
- }
- $table1 = array(
- 'name' => array(
- 'name' => 'name',
- 'obligatory' => true,
- 'label' => Locale_Manager::translate('First name'),
- 'type' => 'text',
- 'hint' => '',
- 'value' => '',
- 'rowspan' => 1,
- ),
- 'surname' => array(
- 'name' => 'surname',
- 'obligatory' => true,
- 'label' => Locale_Manager::translate('Last name'),
- 'type' => 'text',
- 'rowspan' => 1,
- ),
- 'phone' => array(
- 'name' => 'phone',
- 'obligatory' => true,
- 'label' => Locale_Manager::translate('Phone'),
- 'type' => 'text',
- 'hint' => Locale_Manager::translate('Number format, e.g.: 123456789'),
- 'rowspan' => 1,
- ),
- 'mail' => array(
- 'name' => 'mail',
- 'obligatory' => true,
- 'label' => Locale_Manager::translate('E-mail'),
- 'type' => 'text',
- 'rowspan' => 1,
- ),
- );
- if ('register' == $mode) {
- $table1['pass1'] = array(
- 'name' => 'pass1',
- 'obligatory' => true,
- 'label' => Locale_Manager::translate('Password'),
- 'type' => 'password',
- 'hint' => Locale_Manager::translate('Minimum of 6 characters'),
- 'rowspan' => 1,
- );
- $table1['pass2'] = array(
- 'name' => 'pass2',
- 'obligatory' => true,
- 'label' => Locale_Manager::translate('Repeat password'),
- 'type' => 'password',
- 'rowspan' => 1,
- );
- }
- $table2 = array(
- 'coname' => array(
- 'name' => 'coname',
- 'obligatory' => true,
- 'label' => Locale_Manager::translate('Company name'),
- 'type' => 'text',
- 'rowspan' => 1,
- ),
- 'nip' => array(
- 'name' => 'nip',
- 'obligatory' => true,
- 'label' => Locale_Manager::translate('Tax ID'),
- 'type' => 'text',
- 'rowspan' => 1,
- ),
- 'pesel' => array(
- 'name' => 'pesel',
- 'label' => Locale_Manager::translate('Personal Identification Number'),
- 'type' => 'text',
- 'rowspan' => 1,
- ),
- 'other_address' => array(
- 'name' => 'other_address',
- 'obligatory' => true,
- 'label' => Locale_Manager::translate('Street and house no.'),
- 'type' => 'text',
- 'hint' => Locale_Manager::translate('For example: 115 Oxford Street'),
- 'rowspan' => 1,
- ),
- 'zip' => array(
- 'name' => 'zip',
- 'obligatory' => true,
- 'label' => Locale_Manager::translate('Postal code'),
- 'type' => 'text',
- 'hint' => Locale_Manager::translate('Postal code format'),
- 'rowspan' => 1,
- ),
- 'city' => array(
- 'name' => 'city',
- 'obligatory' => true,
- 'label' => Locale_Manager::translate('City'),
- 'type' => 'text',
- 'rowspan' => 1,
- ),
- 'country' => array(
- 'name' => 'country',
- 'obligatory' => false,
- 'label' => Locale_Manager::translate('Country'),
- 'type' => 'select',
- 'list' => Locale_Manager::getCountries(),
- 'rowspan' => 1,
- ),
- );
- $table3 = array(
- 'name2' => array(
- 'name' => 'name2',
- 'obligatory' => true,
- 'label' => Locale_Manager::translate('First name'),
- 'type' => 'text',
- 'rowspan' => 1,
- ),
- 'surname2' => array(
- 'name' => 'surname2',
- 'obligatory' => true,
- 'label' => Locale_Manager::translate('Last name'),
- 'type' => 'text',
- 'rowspan' => 1,
- ),
- 'phone2' => array(
- 'name' => 'phone2',
- 'obligatory' => true,
- 'label' => Locale_Manager::translate('Phone'),
- 'type' => 'text',
- 'hint' => Locale_Manager::translate('Number format, e.g.: 123456789'),
- 'rowspan' => 1,
- ),
- 'coname2' => array(
- 'name' => 'coname2',
- 'label' => Locale_Manager::translate('Company name'),
- 'type' => 'text',
- 'rowspan' => 1,
- ),
- 'other_address2' => array(
- 'name' => 'other_address2',
- 'obligatory' => true,
- 'label' => Locale_Manager::translate('Street and house no.'),
- 'type' => 'text',
- 'hint' => Locale_Manager::translate('For example: 115 Oxford Street'),
- 'rowspan' => 1,
- ),
- 'zip2' => array(
- 'name' => 'zip2',
- 'obligatory' => true,
- 'label' => Locale_Manager::translate('Postal code'),
- 'type' => 'text',
- 'hint' => Locale_Manager::translate('Postal code format'),
- 'rowspan' => 1,
- ),
- 'city2' => array(
- 'name' => 'city2',
- 'obligatory' => true,
- 'label' => Locale_Manager::translate('City'),
- 'type' => 'text',
- 'rowspan' => 1,
- ),
- 'country2' => array(
- 'name' => 'country2',
- 'obligatory' => false,
- 'label' => Locale_Manager::translate('Country'),
- 'type' => 'select',
- 'list' => $this->Basket_shippingCountries(),
- 'rowspan' => 1,
- ),
- );
- $address_assign = array(
- 'name' => 'firstname',
- 'surname' => 'lastname',
- 'phone' => 'phone',
- 'coname' => 'company_name',
- 'nip' => 'tax_id',
- 'pesel' => 'pesel',
- 'other_address' => 'street_1',
- 'zip' => 'zip_code',
- 'city' => 'city',
- 'country' => 'country_code',
- );
- if (Zend_Registry::isRegistered(System_Bootstrap::REGISTRY_MOBILE)) {
- $f = Zend_Registry::get(System_Bootstrap::REGISTRY_MOBILE);
- if ($f) {
- unset($table2['coname']['obligatory']);
- unset($table2['nip']['obligatory']);
- }
- }
- $pesel = (1 == (int) Config_Manager::getConfigValue('shopping', 'SUPPORT_PESEL'));
- if (false === $pesel && isset($table2['pesel'])) {
- unset($table2['pesel']);
- unset($address_assign['pesel']);
- }
- $country2shipping = array_keys($this->Basket_shippingCountries());
- $instance->view->country2shipping = Zend_Json::encode($country2shipping);
- if ('single' == $mode || 'user' == $mode) {
- if ($mode == 'single') {
- $locate = Logic_AdditionalField::LOCATE_ORDER_WITHOUT_REGISTRATION;
- } else {
- $locate = Logic_AdditionalField::LOCATE_ORDER_LOGGED_ON_USER;
- }
- $fields = Logic_AdditionalField::getByLocate($locate, Locale_Manager::getLanguageId());
- } else { //register
- $locates = array(
- Logic_AdditionalField::LOCATE_USER_REGISTRATION,
- Logic_AdditionalField::LOCATE_ORDER_WITH_REGISTRATION
- );
- $fields = Logic_AdditionalField::getByLocates($locates, Locale_Manager::getLanguageId());
- }
- if ($instance->getRequest()->isPost() && isset($_POST['addressform'][0])) {
- $required = true;
- if (isset($_POST['button1'][0])) {
- if ('user' == $mode && is_object($user->user))
- $instance->_redirect($router->assemble(array(), 'basket'));
- else
- $instance->_redirect($router->assemble(array(), 'basketStep2'));
- return;
- }
- if ($user->user && ( isset($_POST['address_submit'][0]) || isset($_POST['address_submit2'][0]) )) {
- $n = isset($_POST['address_submit'][0]) ? '' : '2';
- $id = (int) $_POST['address' . $n];
- $address = null;
- foreach ($user->user->addresses as $a)
- if ($id == (int) $a->getIdentifier())
- $address = $a;
- if (is_object($address)) {
- $required = false;
- foreach ($address_assign as $k => $v)
- $_POST[$k . $n] = $address->address->$v;
- }
- }
- foreach (array('phone', 'phone2') as $key) {
- if (isset($_POST[$key][0])) {
- if ('+' == $_POST[$key][0])
- $_POST[$key] = '00' . substr($_POST[$key], 1);
- $_POST[$key] = preg_replace('/[\.\s\(\)]/', '', $_POST[$key]);
- }
- }
- $form = new Form_Shop_Address($mode, $required, array($table1, $table2, $table3, $fields));
- if ($form->isValid($_POST)) {
- $val = $form->getValues();
- $ok = true;
- $ck = (1 == (int) $val['different'] ? 'country2' : 'country' );
- if (false == in_array($val[$ck], $country2shipping)) {
- $instance->_flashMessanger->addError(Locale_Manager::translate('This country is not supported by the selected shipping method. Please enter a different delivery address.'));
- $ok = false;
- }
- if (true == $ok && isset($_POST['button2'][0])) {
- $val['mode'] = $mode;
- $val['FILES'] = $_FILES;
- $session->order_address_data = $val;
- $session->order_shipping_data = null;
- $session->step3_key = md5(serialize($val));
- Plugin_Manager::callShopEvent('BasketAddressToStep3');
- $instance->_redirect($router->assemble(array(), 'basketStep3'));
- return;
- }
- } else {
- $instance->_flashMessanger->addError(Locale_Manager::translate('Form contains errors.'));
- $val = $form->getUnfilteredValues();
- }
- $session->step3_key = null;
- foreach ($val as $k => $v) {
- if (isset($table1[$k]))
- $table1[$k]['value'] = $v;
- elseif (isset($table2[$k]))
- $table2[$k]['value'] = $v;
- elseif (isset($table3[$k]))
- $table3[$k]['value'] = $v;
- elseif (preg_match('/^additional/', $k))
- $additional[$k] = $v;
- elseif ('comment' == $k)
- $instance->view->comment_value = $v;
- elseif ('address_type' == $k)
- $instance->view->address_type = $v;
- elseif ('different' == $k)
- $instance->view->different_value = $v;
- elseif (preg_match('/^address2?$/', $k))
- $instance->view->{$k . '_value'} = $v;
- }
- $additional_error = array();
- foreach ($form->getMessages() as $k => $v) {
- if (isset($table1[$k]))
- $table1[$k]['error'] = $v;
- elseif (isset($table2[$k]))
- $table2[$k]['error'] = $v;
- elseif (isset($table3[$k]))
- $table3[$k]['error'] = $v;
- elseif (preg_match('/^additional/', $k))
- $additional_error[$k] = $v;
- elseif ('comment' == $k)
- $instance->view->comment_error = $v;
- }
- $instance->view->additional_error = $additional_error;
- } else {
- $additional = array();
- $instance->view->address_type = 1;
- if (isset($session->shipping_country)) {
- $table2['country']['value'] = $session->shipping_country;
- $table3['country2']['value'] = $session->shipping_country;
- } else {
- $table2['country']['value'] = Locale_Manager::getRegion(); //Config_Manager::getConfigValue('company', 'COUNTRY');
- $table3['country2']['value'] = Locale_Manager::getRegion(); //Config_Manager::getConfigValue('company', 'COUNTRY');
- }
- foreach ($fields as $field) {
- if (Logic_AdditionalField::TYPE_CHECKBOX == (int) $field->field->type && 1 == (int) $field->checkbox->checked) {
- $additional['additional_' . (int) $field->getIdentifier()] = 1;
- }
- }
- if (is_array($session->order_address_data)) {
- foreach ($session->order_address_data as $k => $v) {
- if (isset($table1[$k]))
- $table1[$k]['value'] = $v;
- elseif (isset($table2[$k]))
- $table2[$k]['value'] = $v;
- elseif (isset($table3[$k]))
- $table3[$k]['value'] = $v;
- elseif (preg_match('/^additional/', $k))
- $additional[$k] = $v;
- elseif ('comment' == $k)
- $instance->view->comment_value = $v;
- elseif ('address_type' == $k)
- $instance->view->address_type = $v;
- elseif ('different' == $k)
- $instance->view->different_value = $v;
- elseif (preg_match('/^address2?$/', $k))
- $instance->view->{$k . '_value'} = $v;
- }
- } elseif (Access_ClientManager::isLoggedIn() && $user->user) {
- $table1['mail']['value'] = $user->user->userinfo->email;
- if (is_object($user->user->address)) {
- foreach ($address_assign as $k => $v) {
- if (isset($table1[$k]))
- $table1[$k]['value'] = $user->user->address->address->$v;
- if (isset($table2[$k]))
- $table2[$k]['value'] = $user->user->address->address->$v;
- }
- $instance->view->address_value = $user->user->address->getIdentifier();
- if ('' != $user->user->address->address->tax_id || '' != $user->user->address->address->company_name) {
- $instance->view->address_type = 2;
- }
- if (is_object($user->user->shippingAddress) && $user->user->address->getIdentifier() != $user->user->shippingAddress->getIdentifier()) {
- foreach ($address_assign as $k => $v) {
- if (isset($table3[$k . '2']))
- $table3[$k . '2']['value'] = $user->user->shippingAddress->address->$v;
- }
- $instance->view->address2_value = $user->user->shippingAddress->getIdentifier();
- $instance->view->different_value = 1;
- }
- }
- }
- }
- if (strlen($table3['country2']['value']) && !isset($table3['country2']['list'][$table3['country2']['value']])) {
- $table3['country2']['list'][''] = '';
- $table3['country2']['value'] = '';
- }
- if (isset($table1['pass1']) && isset($table1['pass2']))
- $table1['pass1']['value'] = $table1['pass2']['value'] = '';
- $instance->_breadCrumbs->add(Locale_Manager::translate('Cart'), $router->assemble(array(), 'basket'));
- $instance->_breadCrumbs->add(Locale_Manager::translate('Your details'), '');
- $instance->view->mode = $mode;
- $instance->view->table1 = $table1;
- $instance->view->table2 = $table2;
- $instance->view->table3 = $table3;
- $instance->view->additional_fields = $fields;
- $instance->view->additional_value = $additional;
- $instance->view->shipping_data = json_encode($session->order_shipping_data);
- if (isset($session->payment_id)) {
- $lPayment = Logic_PaymentMethod::loadInstance($session->payment_id);
- if ($lPayment->existsInDB()) {
- $instance->view->isCod = $lPayment->isCod();
- }
- }
- $instance->view->body_class = 'shop_basket_address';
- Plugin_Manager::callShopEvent('BasketAddressEnd');
- $instance->_handleFlashMessages();
- }
- public function Basket_step3Action($instance) {
- $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
- $session = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_SESSION);
- $user = Logic_UserOnline::getUser();
- $basket = $user->basket;
- if (false === Zend_Registry::get('enable_basket')) {
- $session->order_address_data = null;
- $session->order_shipping_data = null;
- $session->step3_key = null;
- $instance->_flashMessanger->addWarning(Locale_Manager::translate('Cart is disabled.'));
- $instance->_redirect($router->assemble(array(), 'index'));
- return;
- }
- if (0 == count($basket)) {
- $session->order_address_data = null;
- $session->order_shipping_data = null;
- $session->step3_key = null;
- $instance->_redirect($router->assemble(array(), 'basket'));
- return;
- }
- if (!is_array($session->order_address_data) || !is_string($session->step3_key) ||
- $session->step3_key !== md5(serialize($session->order_address_data)) ||
- !is_int($session->shipping_id) || !is_int($session->payment_id)) {
- $session->order_address_data = null;
- $session->order_shipping_data = null;
- $session->step3_key = null;
- $instance->_redirect($router->assemble(array(), 'basket'));
- return;
- }
- if ($instance->getRequest()->isPost() && isset($_POST['summaryform'][0])) {
- if (isset($_POST['button1'][0])) {
- $session->step3_key = null;
- $url = $router->assemble(array(), 'basketStep2');
- if (isset($session->order_address_data['mode'][0])) {
- if ('register' == $session->order_address_data['mode'])
- $url = $router->assemble(array(), 'basketRegister');
- elseif ('single' == $session->order_address_data['mode'])
- $url = $router->assemble(array(), 'basketNoRegister');
- }
- $instance->_redirect($url);
- return;
- } elseif (isset($_POST['button2'][0])) {
- $session->step4_key = md5($session->step3_key);
- $instance->_redirect($router->assemble(array(), 'basketStep4'));
- return;
- }
- }
- $instance->_breadCrumbs->add(Locale_Manager::translate('Cart'), $router->assemble(array(), 'basket'));
- $instance->_breadCrumbs->add(Locale_Manager::translate('Your details'), $router->assemble(array(), 'basketStep2'));
- $instance->_breadCrumbs->add(Locale_Manager::translate('Summary'), '');
- $data = $session->order_address_data;
- if (0 == (int) $data['different']) {
- foreach ($data as $k => $v)
- if (preg_match('/[a-z]+2$/i', $k)) {
- $data[$k] = $data[trim($k, '2')];
- }
- $session->order_address_data = $data;
- $session->step3_key = md5(serialize($data));
- }
- $shippingData = $session->order_shipping_data;
- $this->_shipping_id = $session->shipping_id;
- $this->_shipping_country = $session->shipping_country;
- $this->_payment_id = $session->payment_id;
- if (false == $this->Basket_processBasket($instance, true)) {
- $session->order_address_data = null;
- $session->order_shipping_data = null;
- $session->step3_key = null;
- $instance->_redirect($router->assemble(array(), 'basket'));
- return;
- }
- $days = -1;
- $days_id = null;
- foreach ($basket as $b) {
- if (!$b->stock->delivery) {
- $days_id = null;
- break;
- }
- if ($days < (int) $b->stock->delivery->delivery->days) {
- $days_id = (int) $b->stock->delivery->getIdentifier();
- $days = (int) $b->stock->delivery->delivery->days;
- }
- }
- if ($days_id > 0)
- $instance->view->delivery = new Logic_ProductDelivery($days_id);
- $instance->view->shipping = new Logic_ShippingMethod($this->_shipping_id);
- $instance->view->payment = new Logic_PaymentMethod($this->_payment_id);
- $instance->view->discount_summary = $basket->getDiscount();
- $instance->view->data = $data;
- $instance->view->shipping_data = $shippingData;
- $instance->view->sum = $this->Basket_getSum();
- $instance->view->country = Config_Manager::getConfigValue('company', 'COUNTRY');
- foreach ($basket as $b) {
- if ($b->stock->stock->delivery_id) {
- $instance->view->showDelivery = true;
- }
- }
- $instance->view->body_class = 'shop_basket_step3';
- $instance->_handleFlashMessages();
- }
- public function Basket_step4Action($instance) {
- $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
- $session = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_SESSION);
- $user = Logic_UserOnline::getUser();
- if (false === Zend_Registry::get('enable_basket')) {
- $session->order_address_data = null;
- $session->order_shipping_data = null;
- $session->step3_key = null;
- $session->step4_key = null;
- $instance->_flashMessanger->addWarning(Locale_Manager::translate('Cart is disabled.'));
- $instance->_redirect($router->assemble(array(), 'index'));
- return;
- }
- $mode = $session->order_address_data['mode'];
- if (!in_array($mode, array('user', 'register', 'single')) || 0 == count($user->basket) || ('user' == $mode && false === $user->user)) {
- $session->order_address_data = null;
- $session->order_shipping_data = null;
- $session->step3_key = null;
- $session->step4_key = null;
- $instance->_redirect($router->assemble(array(), 'basket'));
- return;
- }
- if (!is_array($session->order_address_data) || !is_string($session->step3_key) ||
- $session->step3_key !== md5(serialize($session->order_address_data)) ||
- !is_string($session->step4_key) || $session->step4_key !== md5($session->step3_key) ||
- !is_int($session->shipping_id) || !is_int($session->payment_id)) {
- $session->order_address_data = null;
- $session->order_shipping_data = null;
- $session->step3_key = null;
- $session->step4_key = null;
- $instance->_redirect($router->assemble(array(), 'basket'));
- return;
- }
- // todo start transakcji w przyszlosci tutaj, mozliwe problemy z deadlockami i koniecznosc restartu transakcji
- $q = $this->Basket_checkQuantity($instance);
- if (false === $q) {
- $session->step3_key = null;
- $session->step4_key = null;
- $instance->_redirect($router->assemble(array(), 'basket'));
- return;
- }
- System_Transaction::begin();
- $this->_shipping_id = $session->shipping_id;
- $this->_payment_id = $session->payment_id;
- $this->_shipping_country = $session->shipping_country;
- try {
- $shipping = new Logic_ShippingMethod($this->_shipping_id);
- $payment = new Logic_PaymentMethod($this->_payment_id);
- } catch (Exception $e) {
- $session->step3_key = null;
- $session->step4_key = null;
- $instance->_redirect($router->assemble(array(), 'basket'));
- return;
- }
- if (false == $this->Basket_processBasket($instance, true) || $this->Basket_getSum() < 0) {
- $session->order_address_data = null;
- $session->order_shipping_data = null;
- $session->step3_key = null;
- $session->step4_key = null;
- $instance->_redirect($router->assemble(array(), 'basket'));
- return;
- }
- if (( 0 == (int) Config_Manager::getConfigValue('shopping', 'PRODUCTS_ALLOW_ZERO') && $this->Basket_getSum() < 0.01 ) || $this->Basket_getSum() < 0) {
- $session->order_address_data = null;
- $session->order_shipping_data = null;
- $session->step3_key = null;
- $session->step4_key = null;
- $instance->_redirect($router->assemble(array(), 'basket'));
- return;
- }
- $basket = $user->basket;
- $sum = $this->Basket_getSum();
- $val = $session->order_address_data;
- if ('register' == $mode) {
- $u = new Logic_User();
- $u->create();
- $u->user->date_add = date('Y-m-d H:i:s');
- $u->save();
- $u->createInfo();
- $u->createSearch();
- $u->setPassword($val['pass1']);
- $u->userinfo->email = $val['mail'];
- $u->userinfo->firstname = $val['name'];
- $u->userinfo->lastname = $val['surname'];
- $u->userinfo->lang_id = Locale_Manager::getLanguageId();
- $u->userinfo->active = 1;
- if (Zend_Registry::isRegistered(System_Bootstrap::REGISTRY_FACEBOOK)) {
- $u->user->origin = Origin_Manager::ORIGIN_FACEBOOK;
- } elseif (Zend_Registry::isRegistered(System_Bootstrap::REGISTRY_MOBILE)) {
- $u->user->origin = Origin_Manager::ORIGIN_MOBILE;
- }
- $u->user->verify_email = 0;
- $mail_confirm = ( 1 == (int) Config_Manager::getConfigValue('registration', 'CONFIRM_REGISTER') );
- if ($mail_confirm) {
- $u->user->verify_code = md5($val['mail'] . microtime(true));
- }
- foreach ($val as $k => $v) {
- if ('additional_' == substr($k, 0, 11) && strlen($v)) {
- $u->createAdditionalField(substr($k, 11), $v);
- }
- }
- $u->save();
- $user->userOnline->is_user = 1;
- $user->userOnline->user_id = $u->getIdentifier();
- $user->save();
- $user->resetUser();
- $autoGroup = 0;
- if (Config_Manager::hasConfigValue("registration", "auto_add_to_group")) {
- $group = Config_Manager::getConfigValue("registration", "auto_add_to_group");
- $uList = new Logic_UserGroupList();
- $uSelect = $uList->select();
- $uSelect->where("group_id = ?", $group);
- $uSelect->limit(1);
- $uList->fillFromSelect($uSelect);
- if (count($uList)) {
- $autoGroup = $group;
- }
- }
- if ($autoGroup > 0) {
- $table = new Entity_UserGroupsUsers();
- $table->insert(array(
- 'group_id' => $autoGroup,
- 'user_id' => $u->getIdentifier(),
- ));
- }
- $template = Mail_Manager::getMailTemplate(Mail_Manager::MAIL_REGISTER);
- $message = new Mail_Message($template);
- $message->setVarArray(array(
- 'email' => $val['mail'],
- 'password' => $val['pass1'],
- 'link' => '',
- 'confirmation' => $mail_confirm,
- 'origin' => Origin_Manager::getOriginNameForKey($u->user->origin),
- ));
- $message->addRecipient($val['mail'], false);
- if ($mail_confirm) {
- $url = $router->assemble(array(
- 'userId' => (int) $u->getIdentifier(),
- 'code' => $u->user->verify_code,
- ), 'registerStep2', System_Router::ROUTE_TYPE_CORE, true, array(), false, Zend_Registry::get(System_Bootstrap::REGISTRY_ROUTER_BASEURL));
- $message->setVar('link', $url);
- }
- $metafields = new Metafield_Manager();
- foreach ($metafields->getMetafieldObjectList() as $m) {
- $key = "metafield.system." . $m->metafield->metafield->namespace . "." . $m->metafield->metafield->key;
- $message->setVar($key, Zend_Controller_Action_HelperBroker::getExistingHelper('ViewRenderer')->view->escape($m->value->value));
- }
- try {
- Mail_Manager::send($message, true);
- } catch (Exception $e) {
- $instance->_errorLog->err($e);
- $instance->_flashMessanger->addWarning(Locale_Manager::translate('Error while sending a welcome e-mail message.'));
- }
- if (1 == (int) Config_Manager::getConfigValue('mail', 'NOTIFY_EMAIL_NEW_CLIENT')) {
- try {
- $message = new Mail_Message(Mail_Manager::getMailTemplate(Mail_Manager::MAIL_ADMIN_REGISTER));
- $message->setVar('email', $val['mail']);
- $message->setVar('origin', Origin_Manager::getOriginNameForKey($user->user->origin));
- $message->addRecipient(Config_Manager::getConfigValue('company', 'COMPANY_EMAIL'), false);
- $message->setReplyTo($val['mail'], $val['name'] . ' ' . $val['surname']);
- $metafields = new Metafield_Manager();
- foreach ($metafields->getMetafieldObjectList() as $m) {
- $key = "metafield.system." . $m->metafield->metafield->namespace . "." . $m->metafield->metafield->key;
- $message->setVar($key, Zend_Controller_Action_HelperBroker::getExistingHelper('ViewRenderer')->view->escape($m->value->value));
- }
- Mail_Manager::send($message, true);
- } catch (Exception $e) {
- $instance->_errorLog->err($e);
- }
- unset($message);
- }
- } elseif ('user' == $mode) {
- if ('' == $user->user->userinfo->firstname)
- $user->user->userinfo->firstname = $val['name'];
- if ('' == $user->user->userinfo->lastname)
- $user->user->userinfo->lastname = $val['surname'];
- $user->user->save();
- }
- foreach (array('country', 'country2') as $key) {
- if (!preg_match('/^[A-Z]{2}$/', $val[$key])) {
- $c = Locale_Manager::reverseMapCountries(array($val[$key]));
- $c = current($c);
- if (is_string($c)) {
- $val[$key] = $c;
- } else {
- $val[$key] = Locale_Manager::getRegion(); //Config_Manager::getConfigValue('company', 'COUNTRY');
- }
- }
- }
- $clist = Locale_Manager::getCountries();
- $address1 = array(
- 'company_name' => $val['coname'],
- 'tax_id' => $val['nip'],
- 'pesel' => $val['pesel'],
- 'firstname' => $val['name'],
- 'lastname' => $val['surname'],
- 'street_1' => $val['other_address'],
- 'street_2' => '',
- 'city' => $val['city'],
- 'zip_code' => $val['zip'],
- 'state' => '',
- 'country_code' => $val['country'],
- 'country' => $clist[$val['country']],
- 'phone' => $val['phone'],
- );
- $pesel = (1 == (int) Config_Manager::getConfigValue('shopping', 'SUPPORT_PESEL'));
- if (false === $pesel) {
- $address1['pesel'] = '';
- }
- if ('single' != $mode)
- $user->user->processAddress($address1, (int) $val['address']);
- if (1 == (int) $val['different']) {
- $address2 = array(
- 'company_name' => $val['coname2'],
- 'firstname' => $val['name2'],
- 'lastname' => $val['surname2'],
- 'street_1' => $val['other_address2'],
- 'street_2' => '',
- 'city' => $val['city2'],
- 'zip_code' => $val['zip2'],
- 'state' => '',
- 'country_code' => $val['country2'],
- 'country' => $clist[$val['country2']],
- 'phone' => $val['phone2'],
- );
- if ('single' != $mode)
- $user->user->processAddress($address2, (int) $val['address2']);
- } else {
- $address2 = $address1;
- }
- if ('single' != $mode && !$user->user->address && count($user->user->addresses) > 0) {
- $user->user->addresses[0]->address->default = 1;
- $user->user->addresses[0]->save();
- }
- if ('single' != $mode && !$user->user->shippingAddress && count($user->user->addresses) > 0) {
- $user->user->addresses[0]->address->shipping_default = 1;
- $user->user->addresses[0]->save();
- }
- if (is_object($user->user)) {
- $user->user->updateSearch();
- }
- $confirm = (1 == (int) Config_Manager::getConfigValue('shopping', 'CONFIRM_ORDER'));
- $shipping = new Logic_ShippingMethod($this->_shipping_id);
- $currency = Locale_Manager::getLogicCurrency();
- $discounts = array(
- 'client' => 0,
- 'group' => 0,
- 'levels' => 0,
- 'code' => 0,
- );
- $bd = $basket->discountsInUse();
- if (isset($bd['user'])) {
- $discounts['client'] += $bd['user'];
- }
- if (isset($bd['loyalty'])) {
- $discounts['client'] += $bd['loyalty'];
- }
- if (isset($bd['new'])) {
- $discounts['client'] += $bd['new'];
- }
- if (isset($bd['group'])) {
- $discounts['group'] += $bd['group'];
- }
- if (isset($bd['level'])) {
- $discounts['levels'] += $bd['level'];
- }
- if (isset($bd['code'])) {
- $discounts['code'] += $bd['code'];
- }
- $order = new Logic_Order();
- $order->create();
- $order->order->user_id = ($user->user ? $user->user->getIdentifier() : NULL);
- $order->order->date = date('Y-m-d H:i:s');
- $order->order->status_date = date('Y-m-d H:i:s');
- $order->order->confirm_date = 0; /* ($confirm ? 0 : date('Y-m-d H:i:s')); */
- $order->order->status_id = Logic_Status::getDefaultStatusForNewOrders()->getIdentifier();
- $order->order->sum = $sum;
- $order->order->payment_id = $this->_payment_id;
- $order->order->shipping_id = $this->_shipping_id;
- $order->order->shipping_cost = (float) $shipping->getCost($basket, $this->_payment_id);
- $order->order->email = $val['mail'];
- $order->order->code = md5($val['mail'] . microtime(true));
- $order->order->confirm = 0; /* ($confirm ? 0 : 1); */
- $order->order->notes = $val['comment'];
- $order->order->currency_id = $currency->getIdentifier();
- $order->order->currency_rate = (float) $currency->currency->rate;
- $order->order->paid = 0;
- $order->order->ip_address = $_SERVER['REMOTE_ADDR'];
- foreach ($discounts as $k => $v) {
- $order->order->{'discount_' . $k} = $v;
- }
- $order->order->shipping_vat = (int) $shipping->tax->getIdentifier();
- $order->order->code_id = ( is_int($session->promocode_id) ? $session->promocode_id : NULL );
- $order->order->user_order = ( 'single' == $mode ? 0 : ( 'register' == $mode ? 1 : 2 ) );
- $order->order->lang_id = Locale_Manager::getLanguageId();
- if (Zend_Registry::isRegistered(System_Bootstrap::REGISTRY_FACEBOOK)) {
- $order->order->origin = Origin_Manager::ORIGIN_FACEBOOK;
- } else if (Zend_Registry::isRegistered(System_Bootstrap::REGISTRY_MOBILE)) {
- $order->order->origin = Origin_Manager::ORIGIN_MOBILE;
- } else {
- $order->order->origin = Origin_Manager::ORIGIN_SHOP;
- }
- $order->save();
- $order->cleanProductsCache();
- if (null !== $session->order_shipping_data) {
- $order->setShippingData($session->order_shipping_data);
- }
- switch ($val['mode']) {
- case 'single':
- $locate = Logic_AdditionalField::LOCATE_ORDER_WITHOUT_REGISTRATION;
- break;
- case 'user':
- $locate = Logic_AdditionalField::LOCATE_ORDER_LOGGED_ON_USER;
- break;
- default:
- $locate = Logic_AdditionalField::LOCATE_ORDER_WITH_REGISTRATION;
- break;
- }
- $additionalFields = array();
- foreach ($val as $k => $v) {
- if (strpos($k, 'additional_') === 0) {
- $additionalFields[substr($k, 11)] = $v;
- }
- }
- if (!empty($additionalFields)) {
- $fields = Logic_AdditionalField::getByLocate($locate, Locale_Manager::getLanguageId());
- $files = array();
- if (isset($val['FILES'])) {
- foreach ($val['FILES'] as $k => $v) {
- if (strpos($k, 'additional_') === 0) {
- $files[substr($k, 11)] = $v;
- }
- }
- }
- $order->createOrUpdateAdditionalFields($fields, $additionalFields, $files);
- }
- foreach ($basket as $prod) {
- $order->addProduct($prod);
- $prod->stock->changeSold((float) $prod->basket->quantity);
- }
- $order->addAddress($address1, 1);
- if (1 == (int) $val['different']) {
- $order->addAddress($address2, 2);
- }
- $foo = $order->billingAddress;
- $foo = $order->deliveryAddress;
- $order->save();
- $order->calculateDeliveryTime();
- if (1 == (int) Config_Manager::getConfigValue('shopping', 'UPDATE_STOCK_ON_BUY')) {
- foreach ($basket as $prod) {
- $prod->stock->changeStock(0 - (float) $prod->basket->quantity);
- $prod->cleanStockCache();
- }
- }
- if (is_int($session->promocode_id)) {
- Logic_PromoCode::loadInstance($session->promocode_id)->cleanCache();
- }
- $send_invoice = (1 == (int) Config_Manager::getConfigValue('invoice', 'INVOICE_AUTO_SEND'));
- $invoice = new Logic_Invoice();
- $invoice->create();
- $invoice->invoice->order_id = (int) $order->getIdentifier();
- $invoice->invoice->created_at = $order->order->date;
- $invoice->invoice->sent = ( $send_invoice ? Logic_Invoice::SENT_EMAIL : Logic_Invoice::SENT_NONE );
- $invoice->discoverInvoiceNum();
- $invoice->save();
- /* todo: put it into the order queue */
- $attachments = array();
- if ($send_invoice) {
- $pdf = new Invoice_Document($invoice);
- $pdf->generate();
- $a = new Zend_Mime_Part($pdf->render());
- $a->type = 'application/pdf';
- $a->filename = str_replace("/", "-", $invoice->invoiceNum()) . '.pdf';
- $a->encoding = Zend_Mime::ENCODING_BASE64;
- $a->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
- $attachments[] = $a;
- }
- if ($order->user instanceof Logic_User) {
- Loyalty_Program::orderEvent($order);
- }
- $arr = array(
- 'payment_notify' => new Parser_Expr_TemplateHtml($order->payment->translation->notify_mail),
- 'link' => '',
- 'confirmation' => $confirm,
- );
- if ($confirm) {
- $arr['link'] = $router->assemble(array(
- 'orderId' => (int) $order->getIdentifier(),
- 'code' => $order->order->code,
- ), 'basketConfirm', System_Router::ROUTE_TYPE_CORE, true, array(), false, Zend_Registry::get(System_Bootstrap::REGISTRY_ROUTER_BASEURL));
- }
- if (1 == (int) Config_Manager::getConfigValue('mail', 'NOTIFY_EMAIL_NEW_ORDER')) {
- try {
- $order->sendMail(Mail_Manager::MAIL_ADMIN_ORDER, $arr);
- } catch (Exception $e) {
- $instance->_errorLog->err($e);
- }
- }
- try {
- $order->sendMail(Mail_Manager::MAIL_ORDER, $arr, $attachments);
- /* $instance->_flashMessanger->addSuccess(Locale_Manager::translate('Order has been created. Check your e-mail and click on the confirmation link to confirm.')); */
- } catch (Exception $e) {
- $instance->_errorLog->err($e);
- $instance->_flashMessanger->addWarning(Locale_Manager::translate('Error while sending e-mail message with order summary.'));
- }
- if (1 == (int) Config_Manager::getConfigValue('mail', 'NOTIFY_SMS_NEW_ORDER')) {
- try {
- $sms = sprintf(
- Locale_Manager::translate(self::SMS_ORDER_TEXT), (int) $order->order->order_id, View_Smarty_Helper_Currency::currency(array(
- 'value' => (float) $order->order->sum,
- 'currency' => $order->currency->name,
- ), null), $order->countProductsSum(), ( strlen($order->billingAddress->company) ?
- $order->billingAddress->company : $order->billingAddress->firstname . ' ' . $order->billingAddress->lastname
- )
- );
- Plugin_SmsGateway_Manager::sendMessage($sms);
- } catch (Exception $e) {
- $instance->_errorLog->err($e);
- }
- }
- /* todo: put it into the order queue - end */
- System_Transaction::commit();
- $user->basketEmpty();
- $session->order_address_data = null;
- $session->order_shipping_data = null;
- $session->step3_key = null;
- $session->step4_key = null;
- $session->promocode_id = null;
- $order->process();
- Plugin_Manager::callCoreEvent('addOrder', array($order));
- $session->step5_key = md5($order->getIdentifier() . $order->order->date);
- $instance->_redirect($router->assemble(array(
- 'orderId' => (int) $order->getIdentifier(),
- ), 'basketDone'));
- }
- public function Basket_confirmAction($instance) {
- $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
- $session = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_SESSION);
- if ($instance->_hasParam('orderId') && $instance->_hasParam('code')) {
- $id = (int) $instance->_getParam('orderId');
- $code = $instance->_getParam('code');
- if ($id > 0 && 32 == strlen($code)) {
- try {
- $order = new Logic_Order($id);
- if ($order->order->code === $code) {
- if (0 == (int) $order->order->confirm) {
- $order->order->confirm = 1;
- $order->order->confirm_date = date('Y-m-d H:i:s');
- $order->save();
- $instance->_flashMessanger->addSuccess(Locale_Manager::translate('Order has been confirmed.'));
- } else {
- $instance->_flashMessanger->addInfo(Locale_Manager::translate('Order has already been confirmed.'));
- }
- if (0 == (int) $order->order->paid && $order->hasOnlinePayment())
- $session->step5_key = md5($order->getIdentifier() . $order->order->date);
- $instance->_redirect($router->assemble(array(), 'index'));
- return;
- }
- } catch (Exception $e) {
- }
- }
- }
- $instance->_flashMessanger->addError(Locale_Manager::translate('Invalid order confirmation code.'));
- $instance->_redirect($router->assemble(array(), 'index'));
- }
- public function Basket_doneAction($instance) {
- $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
- $session = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_SESSION);
- $user = Logic_UserOnline::getUser();
- if (false === Zend_Registry::get('enable_basket')) {
- $session->step5_key = null;
- $instance->_flashMessanger->addWarning(Locale_Manager::translate('Cart is disabled.'));
- $instance->_redirect($router->assemble(array(), 'index'));
- return;
- }
- $instance->_breadCrumbs->add(Locale_Manager::translate('Cart'), '');
- $instance->_breadCrumbs->add(Locale_Manager::translate('Your details'), '');
- $instance->_breadCrumbs->add(Locale_Manager::translate('Summary'), '');
- $instance->_breadCrumbs->add(Locale_Manager::translate('Confirmation'), '');
- if ($instance->_hasParam('orderId') && is_string($session->step5_key)) {
- $order = new Logic_Order((int) $instance->_getParam('orderId'));
- if ($order->existsInDB() && md5($order->getIdentifier() . $order->order->date) == $session->step5_key) {
- $handler = $order->payment->createHandler();
- $handler->setOrder($order);
- $vars = $order->getVariables(array(
- 'ignored_variables' => array('shipments')
- ));
- if (Config_Manager::hasConfigValue('shopping', 'CONFIRM_ORDER')) {
- $confirm = (bool) Config_Manager::getConfigValue('shopping', 'CONFIRM_ORDER');
- } else {
- $confirm = false;
- }
- $vars['confirmation'] = $confirm;
- $snippet = Logic_Snippet::getCode(Logic_Snippet::TYPE_ORDER);
- $instance->view->snippet_order = Parser_Processor::onetimeCompile($snippet, $vars, array(
- 'ignore_non_breaking_space' => true,
- 'is_html_template' => true
- ));
- $vars['payment_form'] = new Parser_Expr_TemplateHtml($handler->getForm(true));
- $instance->view->payment_message = Parser_Processor::onetimeCompile($order->payment->translation->notify, $vars, array(
- 'ignore_non_breaking_space' => true,
- 'is_html_template' => true
- ));
- $instance->view->body_class = 'shop_basket_done';
- $instance->_handleFlashMessages();
- return;
- }
- }
- $instance->_redirect($router->assemble(array(), 'index'));
- }
- public function Basket_removeAction($instance) {
- if (false === Zend_Registry::get('enable_basket')) {
- $instance->_flashMessanger->addWarning(Locale_Manager::translate('Cart is disabled.'));
- $instance->_redirect(Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER)->assemble(array(), 'index'));
- return;
- }
- if ($instance->_hasParam('basketId')) {
- $id = (int) $instance->_getParam('basketId');
- if ($id > 0) {
- Logic_UserOnline::getUser()->basketRemove($id);
- $instance->_flashMessanger->addSuccess(Locale_Manager::translate('Product removed from cart.'));
- }
- }
- $instance->_redirect(Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER)->assemble(array(), 'basket'));
- }
- private function Basket_add($instance, $loyalty = false) {
- $ret = array(
- 'messages' => array(
- 'warning' => array(),
- 'error' => array(),
- 'success' => array(),
- 'info' => array(),
- ),
- 'added' => array(),
- 'redirect' => false,
- );
- $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
- $session = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_SESSION);
- $productRoute = $loyalty ? 'assembleProductExchange' : 'assembleProduct';
- if (false === $loyalty && false === Zend_Registry::get('enable_basket')) {
- $ret['messages']['warning'][] = Locale_Manager::translate('Cart is disabled.');
- $ret['redirect'] = $router->assemble(array(), 'index');
- return $ret;
- }
- if (!$instance->_hasParam('stockId')) {
- $ret['redirect'] = $router->assemble(array(), 'index');
- return $ret;
- }
- $quant = self::DEFAULT_BASKET_QUANTITY;
- $options = array();
- foreach ($_POST as $k => $v) {
- if (strpos($k, "option_") === 0) {
- $i = substr($k, 7);
- $options[$i] = $v;
- }
- }
- foreach ($_FILES as $k => $v) {
- if (strpos($k, "option_") === 0) {
- $i = substr($k, 7);
- $v['key'] = $k;
- $options[$i] = $v;
- }
- }
- if ('post' == $instance->_getParam('stockId') && $instance->getRequest()->isPost()) {
- $form = new Form_Shop_Multifloat(array(array('stock_id'), 'quantity'), true, Logic_UserBasketList::QUANTITY_PRECISION);
- if ($form->isValid($_POST)) {
- $val = $form->getFloats();
- $sids = $val['stock_id'];
- if (is_float($sids)) {
- $sids = array((int) $sids);
- } else {
- $sids = (array) $sids;
- }
- $added = 0;
- foreach ($sids as $sid) {
- if ($sid > 0) {
- $stock = new Logic_ProductStock($sid);
- if (false == $stock->existsInDB()) {
- $ret['redirect'] = $router->assemble(array(), 'index');
- return $ret;
- }
- if ($sid == $sids[0]) { /* first, main product */
- $quant = (float) $val['quantity'];
- }
- // sprawdzic poprawnosc produkto-opcji
- if (!$stock->product->validateOptionsValues($options)) {
- $ret['messages']['error'][] = Locale_Manager::translate('Product is offered in different variants, select them before adding to cart.');
- $ret['redirect'] = $router->$productRoute(array(
- 'productId' => $stock->product->getIdentifier(),
- 'productName' => $stock->product->translation->name,
- ), $stock->product->getIdentifier());
- return $ret;
- }
- $arr = array();
- foreach ($_POST as $k => $v) {
- if ('option_' == substr($k, 0, 7)) {
- $k = (int) substr($k, 7);
- $arr[$k] = (int) $v;
- }
- }
- if (count($arr)) {
- $stockByOptions = $stock->product->getStock($arr);
- $stockOptionIds = $stock->product->filterOptionsToStockOnly($arr);
- if ($sid == $sids[0] && isset($_POST['nojs'][0]) && 1 == (int) $_POST['nojs']) { /* first product, no JS for stock */
- if ($stockByOptions instanceof Logic_ProductStock) {
- $stock = $stockByOptions;
- $sid = $stock->getIdentifier();
- if (0 === (int) $stock->stock->active) {
- $stockByOptions = null;
- }
- }
- }
- if (null === $stockByOptions && count($stockOptionIds) > 0) {
- $ret['messages']['error'][] = Locale_Manager::translate('Selected variant does not exist. Enable JavaScript to select only from the existing options.');
- $ret['redirect'] = $router->$productRoute(array(
- 'productId' => $stock->product->getIdentifier(),
- 'productName' => $stock->product->translation->name,
- ), $stock->product->getIdentifier());
- return $ret;
- }
- }
- if (1 == (int) $stock->product->translation->active && 1 == (int) $stock->availability->availability->can_buy && $quant > 0) {
- $pack = $stock->getPackage();
- if (0 == (int) $stock->product->unit->unit->floating_point) {
- $quant = (int) ceil($quant);
- $pack = (int) ceil($pack);
- }
- $user = Logic_UserOnline::getUser();
- $packs = $this->Basket_checkPack($pack, $quant);
- if ($packs > 0) {
- $quant = $packs;
- $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);
- }
- if ($loyalty) {
- if ($stock->loyaltyPointsPrice() && $stock->loyaltyPointsPrice() * $quant <= $user->user->loyalty->sum()) {
- if ($quant <= (float) $stock->stock->stock || 1 == (int) Config_Manager::getConfigValue('shopping', 'ALLOW_OVERSELLING')) {
- Loyalty_Program::exchangeEvent($user->user->getIdentifier(), $stock, $quant);
- $added++;
- $ret['added'][] = array(
- 'id' => (int) $sid,
- 'name' => $stock->product->translation->name,
- 'variant' => $stock->getName($options),
- 'quantity' => $quant,
- 'unit' => $stock->product->unit->translation->name,
- 'price' => $stock->loyaltyPointsPrice(),
- );
- } else {
- $ret['messages']['error'][] = Locale_Manager::translate('The required product quantity exceeds the stock.');
- $ret['redirect'] = $router->$productRoute(array(
- 'productId' => $stock->product->getIdentifier(),
- 'productName' => $stock->product->translation->name,
- ), $stock->product->getIdentifier());
- return $ret;
- }
- } else {
- $ret['messages']['error'][] = Locale_Manager::translate('You do not have enough points to exchange for this product.');
- $ret['redirect'] = $router->$productRoute(array(
- 'productId' => $stock->product->getIdentifier(),
- 'productName' => $stock->product->translation->name,
- ), $stock->product->getIdentifier());
- return $ret;
- }
- } else {
- $added++;
- $bprod = $user->basketAdd($sid, $quant, $options);
- $check = $this->Basket_checkQuantity($instance, $ret);
- $ret['added'][] = array(
- 'id' => (int) $sid,
- 'name' => $bprod->product->translation->name,
- 'variant' => $bprod->getName(),
- 'quantity' => $quant,
- 'unit' => $bprod->product->unit->translation->name,
- 'price' => $bprod->getPrice(),
- );
- }
- } else {
- if ($quant > 0) {
- $ret['messages']['error'][] = Locale_Manager::translate('This product is inactive and cannot be added to shopping cart.');
- } else {
- $ret['messages']['error'][] = Locale_Manager::translate('Incorrect quantity of products') . '.';
- }
- $ret['redirect'] = $router->$productRoute(array(
- 'productId' => $stock->product->getIdentifier(),
- 'productName' => $stock->product->translation->name,
- ), $stock->product->getIdentifier());
- return $ret;
- }
- } else {
- $ret['redirect'] = $router->assemble(array(), 'index');
- return $ret;
- }
- }
- if (1 == $added) {
- if ($loyalty) {
- $ret['messages']['success'][] = Locale_Manager::translate('Product submitted for exchange.');
- } else {
- $ret['messages']['success'][] = Locale_Manager::translate('Product added to cart.');
- }
- } elseif ($added > 1) {
- if ($loyalty) {
- $ret['messages']['success'][] = sprintf(Locale_Manager::translate('Exchanged products: %d.'), $added);
- } else {
- $ret['messages']['success'][] = sprintf(Locale_Manager::translate('Products added to cart: %d.'), $added);
- }
- }
- $session->last_product_page = $_SERVER['HTTP_REFERER'];
- if (true == $check && 1 != (int) Config_Manager::getConfigValue('shopping', 'BASKET_ADDING') && isset($_SERVER['HTTP_REFERER'][0])) {
- if (preg_match('/^https?\:\/\/' . preg_quote($_SERVER['HTTP_HOST']) . '/i', $_SERVER['HTTP_REFERER'])) {
- $ret['redirect'] = $_SERVER['HTTP_REFERER'];
- return $ret;
- }
- }
- $ret['redirect'] = $router->assemble(array(), $loyalty ? 'panel' : 'basket');
- return $ret;
- } else {
- $val = $form->getUnfilteredValues();
- if (isset($val['stock_id'][0])) {
- $sid = (int) $val['stock_id'];
- if ($sid > 0) {
- $stock = new Logic_ProductStock($sid);
- if (false == $stock->existsInDB()) {
- $ret['redirect'] = $router->assemble(array(), 'index');
- return $ret;
- }
- $ret['messages']['error'][] = Locale_Manager::translate('Incorrect quantity of products') . '.';
- $ret['redirect'] = $router->$productRoute(array(
- 'productId' => $stock->product->getIdentifier(),
- 'productName' => $stock->product->translation->name,
- ), $stock->product->getIdentifier());
- return $ret;
- }
- }
- $ret['redirect'] = $router->assemble(array(), 'index');
- return $ret;
- }
- } else {
- $sid = (int) $instance->_getParam('stockId');
- if ($sid > 0) {
- $stock = new Logic_ProductStock($sid);
- if (false == $stock->existsInDB()) {
- $ret['redirect'] = $router->assemble(array(), 'index');
- return $ret;
- }
- // sprawdzic poprawnosc produkto-opcji
- if (!$stock->product->validateOptionsValues($options)) {
- $ret['messages']['error'][] = Locale_Manager::translate('Product is offered in different variants, select them before adding to cart.');
- $ret['redirect'] = $router->$productRoute(array(
- 'productId' => $stock->product->getIdentifier(),
- 'productName' => $stock->product->translation->name,
- ), $stock->product->getIdentifier());
- return $ret;
- }
- if (( 0 == count($stock->product->optionsStock) ) ||
- ( 1 == count($stock->product->optionsStock) && $sid == (int) $stock->product->optionsStock[0]->getIdentifier() )) {
- if (1 == (int) $stock->product->translation->active && 1 == (int) $stock->availability->availability->can_buy) {
- $sid = (int) $stock->product->defaultStock->getIdentifier();
- $user = Logic_UserOnline::getUser();
- $session->last_product_page = $_SERVER['HTTP_REFERER'];
- if ($loyalty) {
- if ($stock->loyaltyPointsPrice() * $quant <= $user->user->loyalty->sum()) {
- if ($quant <= (float) $stock->stock->stock || 1 == (int) Config_Manager::getConfigValue('shopping', 'ALLOW_OVERSELLING')) {
- Loyalty_Program::exchangeEvent($user->user->getIdentifier(), $stock, $quant);
- $ret['messages']['success'][] = Locale_Manager::translate('Product exchanged.');
- $ret['added'][] = array(
- 'id' => (int) $sid,
- 'name' => $stock->product->translation->name,
- 'variant' => $stock->getName($options),
- 'quantity' => $quant,
- 'unit' => $stock->product->unit->translation->name,
- 'price' => $stock->loyaltyPointsPrice(),
- );
- } else {
- $ret['messages']['error'][] = Locale_Manager::translate('The required product quantity exceeds the stock.');
- $ret['redirect'] = $router->$productRoute(array(
- 'productId' => $stock->product->getIdentifier(),
- 'productName' => $stock->product->translation->name,
- ), $stock->product->getIdentifier());
- return $ret;
- }
- } else {
- $ret['messages']['error'][] = Locale_Manager::translate('You do not have enough points to exchange for this product.');
- $ret['redirect'] = $router->$productRoute(array(
- 'productId' => $stock->product->getIdentifier(),
- 'productName' => $stock->product->translation->name,
- ), $stock->product->getIdentifier());
- return $ret;
- }
- } else {
- $pack = $stock->getPackage();
- if (0 == (int) $stock->product->unit->unit->floating_point) {
- $quant = (int) ceil($quant);
- $pack = (int) ceil($pack);
- }
- $packs = $this->Basket_checkPack($pack, $quant);
- if ($packs > 0) {
- $quant = $packs;
- $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);
- }
- $bprod = $user->basketAdd($sid, $quant, $options);
- $check = $this->Basket_checkQuantity($instance, $ret);
- $ret['messages']['success'][] = Locale_Manager::translate('Product added to cart.');
- $ret['added'][] = array(
- 'id' => (int) $sid,
- 'name' => $bprod->product->translation->name,
- 'variant' => $stock->getName($options),
- 'quantity' => $quant,
- 'unit' => $bprod->product->unit->translation->name,
- 'price' => $bprod->getPrice(),
- );
- }
- if (true == $check && 1 != (int) Config_Manager::getConfigValue('shopping', 'BASKET_ADDING') && isset($_SERVER['HTTP_REFERER'][0])) {
- if (preg_match('/^https?\:\/\/' . preg_quote($_SERVER['HTTP_HOST']) . '/i', $_SERVER['HTTP_REFERER'])) {
- $ret['redirect'] = $_SERVER['HTTP_REFERER'];
- return $ret;
- }
- }
- $ret['redirect'] = $router->assemble(array(), 'basket');
- return $ret;
- } else {
- $ret['messages']['error'][] = Locale_Manager::translate('This product is inactive and cannot be added to shopping cart.');
- $ret['redirect'] = $router->$productRoute(array(
- 'productId' => $stock->product->getIdentifier(),
- 'productName' => $stock->product->translation->name,
- ), $stock->product->getIdentifier());
- return $ret;
- }
- } else {
- if ($loyalty) {
- $ret['messages']['info'][] = Locale_Manager::translate('This product is available in different variants, select them before the exchange.');
- } else {
- $ret['messages']['info'][] = Locale_Manager::translate('Product is offered in different variants, select them before adding to cart.');
- }
- $ret['redirect'] = $router->$productRoute(array(
- 'productId' => $stock->product->getIdentifier(),
- 'productName' => $stock->product->translation->name,
- ), $stock->product->getIdentifier());
- return $ret;
- }
- } else {
- $ret['redirect'] = $router->assemble(array(), 'index');
- return $ret;
- }
- }
- return $ret;
- }
- public function Basket_checkPack($pack, $quant, $floating = false) {
- if ($pack > 0) {
- $precision = 2;
- $epsilon = round($quant - $pack, $precision);
- if ($epsilon < 0) {
- return $pack;
- } else if ($epsilon == 0) {
- return 0;
- } else {
- $quotent = $quant / $pack;
- $epsilon = round(((int) $quotent) - $quotent, $precision);
- if ($epsilon == 0) {
- return 0;
- } else {
- return ((int) $quotent + 1) * $pack;
- }
- }
- }
- return 0;
- }
- public function Basket_ajaxAction($instance) {
- $ret = $this->Basket_add($instance);
- foreach ($ret['added'] as &$p) {
- $p['price'] = View_Smarty_Helper_Currency::currency(array(
- 'value' => $p['price'],
- ), null);
- }
- $user = Logic_UserOnline::getUser();
- $ret['basket'] = array();
- $ret['basket']['url'] = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER)->assemble(array(), 'basketRecount');
- $ret['basket']['count'] = $user->basket->countProducts();
- $ret['basket']['sum'] = View_Smarty_Helper_Currency::currency(array(
- 'value' => $user->basket->sumProducts(),
- ), null);
- $user->basket->discoverDiscounts($user, true);
- $ret['basket']['sum_after_discounts'] = View_Smarty_Helper_Currency::currency(array(
- 'value' => $user->basket->sumProducts(),
- ), null);
- $ba = array();
- foreach ($user->basket as $b) {
- $c = array();
- $c['image_url'] = View_Smarty_Helper_ImageUrl::imageUrl(array('type' => 'productGfx', 'width' => 75, 'height' => 75, 'image' => $b->stock->mainImageName(), 'overlay' => 1), null);
- $c['name'] = $b->product->translation->name;
- $c['product_id'] = $b->product->product->product_id;
- $c['variant_name'] = $b->getName();
- $c['quantity'] = View_Smarty_Helper_Float::float(array('precision' => Logic_UserBasketList::QUANTITY_PRECISION, "trim" => true, "noformat" => true, "value" => (float) $b->basket->quantity), null);
- $c['unit'] = $b->product->unit->translation->name;
- $c['price'] = View_Smarty_Helper_Currency::currency(array('value' => $b->getPrice()), null);
- $c['price_all'] = View_Smarty_Helper_Currency::currency(array('value' => $b->getPriceForAll()), null);
- $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);
- $c['remove_url'] = View_Smarty_Helper_Route::route(array("key" => "basketRemove", "basketId" => $b->getIdentifier()), null);
- $ba[] = $c;
- }
- $ret['basket']['products'] = $ba;
- header('Content-type: application/json');
- echo json_encode($ret);
- }
- public function Basket_addAction($instance) {
- if ($instance->getRequest()->isXmlHttpRequest()) {
- $this->Basket_ajaxAction($instance);
- return;
- }
- $ret = $this->Basket_add($instance);
- foreach ($ret['messages'] as $f => $msgs) {
- $f = 'add' . ucfirst($f);
- foreach ($msgs as $msg) {
- $instance->_flashMessanger->$f($msg);
- }
- }
- if (!is_string($ret['redirect'])) {
- $ret['redirect'] = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER)->assemble(array(), 'index');
- }
- $instance->_redirect($ret['redirect']);
- }
- public function Basket_finishedAction($instance) {
- $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
- if ($instance->_hasParam('status') && $instance->_hasParam('paymentid') && $instance->_hasParam('orderid')) {
- $status = $instance->_getParam('status');
- if (isset($_GET['status'])) {
- $status = strtolower($_GET['status']);
- }
- $oid = (int) $instance->_getParam('orderid');
- $order = new Logic_Order($oid);
- if (false == $order->existsInDB()) {
- $instance->_flashMessanger->addWarning(Locale_Manager::translate('Order has not been found.'));
- $instance->_redirect($router->assemble(array(), 'index'));
- return;
- }
- $handler = $order->payment->createHandler();
- if ($handler instanceof Plugin_Payment_Online_Abstract) {
- $handler->setOrder($order);
- $msg = '';
- if ('ok' == $status) {
- $output = $handler->transactionCompleted($instance->getRequest());
- $msg = Locale_Manager::translate('The order has been paid for.');
- } elseif ('fail' == $status) {
- $output = $handler->transactionFailed($instance->getRequest());
- $msg = Locale_Manager::translate('Payment system error. The transaction failed.');
- } else {
- $instance->_redirect($router->assemble(array(), 'index'));
- return;
- }
- $instance->view->payment_output = (string) $output;
- $instance->view->msg = (string) $msg;
- $instance->view->body_class = 'shop_basket_finished';
- $instance->_handleFlashMessages();
- return;
- }
- }
- $instance->_redirect($router->assemble(array(), 'index'));
- }
- private function Basket_recount($instance) {
- if (false === Zend_Registry::get('enable_basket')) {
- $instance->_flashMessanger->addWarning(Locale_Manager::translate('Cart is disabled.'));
- $instance->_redirect(Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER)->assemble(array(), 'index'));
- return false;
- }
- $session = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_SESSION);
- $array = array();
- foreach ($_POST as $k => $v)
- if (preg_match('/^quantity_[0-9]+$/i', $k))
- $array[] = $k;
- $err = array();
- $err_products = array();
- $user = Logic_UserOnline::getUser();
- $form = new Form_Shop_Multifloat($array, true, Logic_UserBasketList::QUANTITY_PRECISION);
- if ($form->isValid($_POST)) {
- $val = $form->getFloats();
- foreach ($val as $k => $v) {
- $id = (int) substr($k, 9);
- $b = new Logic_UserBasket($id);
- if ($b->existsInDB()) {
- $p = $b->stock->getPackage();
- if (0 == (int) $b->product->unit->unit->floating_point) {
- $v = $val[$k] = ceil($v);
- $p = (int) ceil($p);
- }
- if ($v < Logic_UserBasketList::MIN_QUANTITY) {
- $err[$id] = true;
- $err_products[] = $b->product->translation->name;
- }
- $packs = $this->Basket_checkPack($p, $v);
- if ($packs > 0) {
- $val[$k] = $packs;
- $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));
- }
- }
- }
- if (0 == count($err)) {
- foreach ($val as $k => $v) {
- $k = (int) substr($k, 9);
- $user->basketChange($k, $v);
- }
- }
- } else {
- $val = $form->getUnfilteredValues();
- foreach ($val as $k => $v)
- if ($v > 2147483647) {
- $id = (int) substr($k, 9);
- $b = new Logic_UserBasket($id);
- if ($b->existsInDB()) {
- $val[$k] = (float) $b->basket->quantity;
- }
- }
- foreach (array_keys($form->getMessages()) as $k) {
- $id = (int) substr($k, 9);
- $err[$id] = true;
- $b = new Logic_UserBasket($id);
- if ($b->existsInDB()) {
- $err_products[] = $b->product->translation->name;
- }
- }
- }
- if (count($err)) {
- if (0 == count($err_products))
- $instance->_flashMessanger->addError(Locale_Manager::translate('Incorrect quantity of products') . '.');
- else
- $instance->_flashMessanger->addError(Locale_Manager::translate('Incorrect quantity of products') . ': ' . implode(', ', $err_products));
- }
- $quantity = array();
- foreach ($val as $k => $v)
- if (preg_match('/^quantity_[0-9]+$/i', $k))
- $quantity[(int) substr($k, 9)] = $v;
- $instance->view->quantity = $quantity;
- $instance->view->quantity_error = $err;
- $form = new Form_Shop_Multifloat(array('shipping_id', 'payment_id'), false, 0);
- if ($form->isValid($_POST)) {
- $val = $form->getFloats();
- if (isset($val['shipping_id']))
- $this->_shipping_id = (int) $val['shipping_id'];
- if (isset($val['payment_id']))
- $this->_payment_id = (int) $val['payment_id'];
- if (isset($_POST['shipping_country'][1]) && preg_match('/^[a-z]{2}$/i', $_POST['shipping_country']))
- $this->_shipping_country = $_POST['shipping_country'];
- }
- if (1 === (int) Config_Manager::getConfigValue('shopping', 'USE_PROMO_CODES')) {
- if (isset($_POST['promocode'][0]) || is_int($session->promocode_id)) {
- if (isset($_POST['promocode'][0])) {
- $form = new Form_Shop_Multistring(array('promocode'), false);
- if ($form->isValid($_POST)) {
- $val = $form->getValues();
- $list = new Logic_PromoCodeList();
- $select = $list->select();
- $select->where('active = ?', 1);
- $select->where('code = ?', $val['promocode']);
- $list->fillFromSelect($select);
- if (count($list) > 0) {
- $promo = $list[0];
- } else {
- $promo = null;
- }
- } else {
- $promo = null;
- }
- } else {
- $promo = new Logic_PromoCode($session->promocode_id);
- if (!$promo->existsInDb()) {
- $promo = null;
- }
- }
- $ok = false;
- if ($promo instanceof Logic_PromoCode) {
- $ret = $promo->testBasket($user->basket);
- } else {
- $ret = Logic_PromoCode::TEST_FAIL;
- }
- if (Logic_PromoCode::TEST_OK & $ret) {
- $instance->view->promocode_error = false;
- $session->promocode_id = (int) $promo->getIdentifier();
- } elseif (Logic_PromoCode::TEST_FAIL & $ret) {
- $instance->view->promocode_error = true;
- $session->promocode_id = null;
- if (Logic_PromoCode::TEST_FAIL_FACEBOOK & $ret) {
- if (Zend_Registry::isRegistered(System_Bootstrap::REGISTRY_FACEBOOK_SKIN)) {
- $skin = Zend_Registry::get(System_Bootstrap::REGISTRY_FACEBOOK_SKIN);
- $msg = Locale_Manager::translate('Before using this code you have to press "Like it" on %sshop\'s fan page%s.');
- $msg = sprintf($msg, '<a href="http://www.facebook.com/profile.php?id=' . $skin->getSettings()->facebook->pageid . '" target="_blank">', '</a>');
- $instance->_flashMessanger->addError($msg);
- } else {
- $instance->_flashMessanger->addError(Locale_Manager::translate('This discount code can only be used on Facebook.'));
- }
- } else {
- $instance->_flashMessanger->addError(Locale_Manager::translate('The coupon code you have entered is incorrect or has already been used.'));
- }
- }
- } else {
- $session->promocode_id = null;
- }
- } else {
- $session->promocode_id = null;
- }
- return (0 == count($err)) && $this->Basket_checkQuantity($instance);
- }
- private function Basket_checkQuantity($instance, &$ret = null) {
- $user = Logic_UserOnline::getUser();
- $ok = true;
- $msg = null;
- $over = array();
- $partial = array();
- foreach ($user->basket as $x) {
- $max = (float) $x->stock->getStockValue();
- $id = (int) $x->stock->getIdentifier();
- $q = (float) $x->basket->quantity;
- if (isset($partial[$id])) {
- $partial[$id] += $q;
- } else {
- $partial[$id] = $q;
- }
- if ($partial[$id] <= $max || 1 == (int) Config_Manager::getConfigValue('shopping', 'ALLOW_OVERSELLING')) {
- continue;
- }
- $over[] = array($x, $max);
- $ok = false;
- }
- if (1 == count($over)) {
- $options = array();
- foreach ($over[0][0]->stock->values as $value) {
- $options[] = $value->option->translation->name . ': ' . $value->ovalue->translation->value;
- }
- if (!empty($options)) {
- $strOptions = '[' . implode('; ', $options) . ']';
- } else {
- $strOptions = '';
- }
- $msg = Locale_Manager::translate(
- '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
- );
- $msg = rtrim($msg, '.') . '.'; // X szt..
- } elseif (count($over) > 1) {
- $msg = Locale_Manager::translate('Number of products in cart exceeds the stock. %s Current stock is:', '<br />');
- foreach ($over as $o) {
- $options = array();
- $values = $o[0]->stock->values;
- foreach ($values as $value) {
- $options[] = $value->option->translation->name . ': ' . $value->ovalue->translation->value;
- }
- if (empty($options)) {
- $strOptions = '';
- } else {
- $strOptions = '[' . implode('; ', $options) . ']';
- }
- $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);
- }
- }
- if (null !== $msg) {
- if (null === $ret) {
- $instance->_flashMessanger->addWarning($msg);
- } else {
- $ret['messages']['warning'][] = $msg;
- }
- }
- return $ok;
- }
- private function Basket_getSum($shipping = true) {
- $basket = Logic_UserOnline::getUser()->basket;
- $sum = $basket->sumProducts();
- if ($shipping && $this->_shipping_id > 0) {
- $shipping = new Logic_ShippingMethod($this->_shipping_id);
- $sum += $shipping->getCost($basket, $this->_payment_id);
- }
- return $sum;
- }
- private function Basket_shippingCountries() {
- $session = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_SESSION);
- $arr = array();
- if (is_int($session->shipping_id)) {
- $s = new Logic_ShippingMethod((int) $session->shipping_id);
- $arr = Locale_Manager::mapCountries($s->getCountries());
- }
- asort($arr);
- return $arr;
- }
- private function Basket_processBasket($instance, $check_limits = false) {
- $instance->view->shippings = array();
- $instance->view->payments = array();
- $instance->view->shipping2payment = '[]';
- $instance->view->country2shipping = '[]';
- $instance->view->shippingvalue = '[]';
- $instance->view->paymentadditional = '[]';
- $instance->view->promocode = false;
- $curr_id = (int) Locale_Manager::getLogicCurrency()->getIdentifier();
- $user = Logic_UserOnline::getUser();
- $sum = $this->Basket_getSum(false);
- $quantity = $user->basket->countProducts();
- $weight = $user->basket->weightProducts();
- $ret = $user->basket->discoverDiscounts($user, true);
- $instance->view->promos = $user->basket->getDiscountsMessages();
- if ($ret & Logic_PromoCode::TEST_FAIL) {
- $instance->view->promocode = false;
- $instance->view->promocode_error = true;
- $instance->_flashMessanger->addError(Locale_Manager::translate('The coupon code you have entered is incorrect or has already been used.'));
- } else {
- $instance->view->promocode = $user->basket->getPromocode();
- }
- /* Shipping & Payment */
- $list = new Logic_ShippingMethodList();
- $select = $list->select(false)->distinct();
- list($hasEmptyGaugeId, $gauges) = $user->getRequiredGauges();
- $select->join('shipping_payment', 'shipping_method.shipping_id = shipping_payment.shipping_id', null);
- $select->join('payment_method_translations', 'shipping_payment.payment_id = payment_method_translations.payment_id', null);
- $select->join('payment_currency', 'payment_method_translations.payment_id = payment_currency.payment_id', null);
- $select->where('shipping_method.active = ?', 1);
- $select->where('shipping_method.lang_id = ?', Locale_Manager::getLanguageId());
- $select->where('payment_method_translations.active = ?', 1);
- $select->where('payment_method_translations.lang_id = ?', Locale_Manager::getLanguageId());
- $select->where('payment_currency.currency_id = ?', $curr_id);
- $select->where('shipping_method.visible = ?', 1);
- if (Zend_Registry::isRegistered(System_Bootstrap::REGISTRY_MOBILE)) {
- $select->where('shipping_method.mobile = ?', 1);
- }
- $select->order('order ASC');
- $fields = array(
- 'shipping_id',
- 'totalNullShippingGauges' => '(' .
- 'SELECT COUNT(id) FROM shipping_gauges ' .
- 'WHERE shipping_gauges.shipping_id = t.shipping_id ' .
- 'AND shipping_gauges.gauge_id IS NULL' .
- ')',
- 'totalNotNullShippingGauges' => '(' .
- 'SELECT COUNT(id) FROM shipping_gauges ' .
- 'WHERE shipping_gauges.shipping_id = t.shipping_id ' .
- 'AND shipping_gauges.gauge_id IS NOT NULL' .
- ')'
- );
- if (!empty($gauges)) {
- $fields['shippingGauges'] = '(' .
- 'SELECT COUNT(id) FROM shipping_gauges ' .
- 'WHERE shipping_gauges.shipping_id = t.shipping_id ' .
- 'AND gauge_id IN (' . implode(',', $gauges) . ') ' .
- 'AND shipping_gauges.gauge_id IS NOT NULL' .
- ')';
- } else {
- $fields['shippingGauges'] = '(SELECT 0)';
- }
- $select2 = $list->select(false);
- $select2->from(array('t' => new Zend_Db_Expr('(' . $select . ')')), $fields);
- $select2->setIntegrityCheck(false);
- // totalNotNullShippingGauges = 0 AND totalNullShippingGauges = 0 -> dla każdego
- // totalNullShippingGauges > 0 -> brak
- if (!empty($gauges) && !$hasEmptyGaugeId) { // gabaryt(1) + gabaryt(2) + ... + gabaryt(n)
- $select2->having('(totalNotNullShippingGauges = 0 AND totalNullShippingGauges = 0) OR shippingGauges = ?', count($gauges));
- } elseif (!empty($gauges) && $hasEmptyGaugeId) { // gabaryt(1) + gabaryt(2) + ... + gabaryt(n) + brak
- $select2->having('(totalNotNullShippingGauges = 0 AND totalNullShippingGauges = 0) OR (shippingGauges = ? AND totalNullShippingGauges > 0)', count($gauges));
- } else { // brak
- $select2->having('(totalNotNullShippingGauges = 0 AND totalNullShippingGauges = 0) OR totalNullShippingGauges > 0');
- }
- $list->fillFromSelect($select2);
- $shippings = array();
- foreach ($list as $k => $s) {
- $max = (float) $s->shipping->max_cost;
- if ($max > 0 && $sum > $max)
- continue;
- $max = (float) $s->shipping->max_weight;
- if ($max > 0 && $weight > $max)
- continue;
- $min = (float) $s->shipping->min_weight;
- if ($min > 0 && $weight < $min)
- continue;
- $shippings[] = (int) $s->getIdentifier();
- }
- if (0 == count($shippings)) {
- $instance->_flashMessanger->addWarning(Locale_Manager::translate('Store administrator has not defined a shipping method that meets the criteria of your order.'));
- return false;
- }
- $list->clean()->fillFromDataSet($shippings);
- $p = array();
- foreach ($list as $s) {
- foreach ($s->payments as $payment) {
- $p[(int) $payment->getIdentifier()] = 1;
- }
- }
- $shipping_countries = Locale_Manager::mapCountries($list->getCountries());
- if (0 == count($shipping_countries)) {
- $instance->_flashMessanger->addWarning(
- Locale_Manager::translate('Store Administrator has not defined any country supported by the shipping methods.')
- );
- return false;
- }
- $instance->view->shipping_countries = $shipping_countries;
- $payments = new Logic_PaymentMethodList();
- $select = $payments->select();
- $select->join('payment_method_translations', 'payment_method_translations.payment_id = payment_method.payment_id', null);
- $select->join('payment_currency', 'payment_method.payment_id = payment_currency.payment_id', null);
- $select->where('payment_method_translations.active = ?', 1);
- $select->where('payment_method_translations.lang_id = ?', Locale_Manager::getLanguageId());
- $select->where('currency_id = ?', $curr_id);
- $select->where('name != ?', 'zero');
- $select->order('payment_method.order ASC');
- $payments->fillFromSelect($select);
- $payments_ids = array();
- foreach ($payments as $k => $payment) {
- $id = (int) $payment->getIdentifier();
- if (!isset($p[$id])) {
- continue;
- }
- if (!$payment->supportsCurrency($curr_id)) {
- continue;
- }
- if (!$payment->supportsBasket($user->basket)) {
- continue;
- }
- $payments_ids[] = $id;
- }
- if (0 == $sum) {
- $zeropayid = $payments->select()->where('name = ?', 'zero')->query()->fetch(PDO::FETCH_NUM);
- if (is_array($zeropayid) && isset($zeropayid[0][0])) {
- $zeropayid = (int) $zeropayid[0];
- $payments_ids[] = $zeropayid;
- } else {
- $zeropayid = false;
- }
- } else {
- $zeropayid = false;
- }
- $payments->clean()->fillFromDataSet($payments_ids);
- $c2s = array();
- foreach ($shipping_countries as $k => $v) {
- $c2s[$k] = array();
- }
- $s2p = array();
- $sv = array();
- $unset = array();
- $payadd = array();
- $addPaymentCost = (int) Config_Manager::getConfigValue('shipping', 'ADD_PAYMENT_COST_TO_FREE_SHIPPING');
- foreach ($list as $k => $shipping) {
- try {
- $cost4ship = $shipping->getCost($user->basket);
- if (0 == $sum && 0 == $cost4ship) {
- $i = array($zeropayid);
- } else {
- $i = array_intersect($shipping->getPaymentsIds(), $payments_ids);
- }
- } catch (Exception $e) {
- $instance->_errorLog->err($e);
- $i = array();
- }
- if (0 == count($i)) {
- $unset[] = $k;
- continue;
- } else {
- $s2p['s' . $shipping->getIdentifier()] = array_values($i);
- $sv['s' . $shipping->getIdentifier()] = View_Smarty_Helper_Currency::currency(array(
- 'value' => $cost4ship,
- 'float' => true,
- ), null);
- }
- foreach ($shipping->getCountries() as $c) {
- $c2s[$c][] = (int) $shipping->getIdentifier();
- }
- foreach ($i as $id) {
- $c = $shipping->getCostForPayment($id);
- if ($c && 0 == $cost4ship && 0 == $addPaymentCost) {
- $c = false;
- }
- if ($c && $c['cost'] > 0) {
- if (true == $c['percent']) {
- $t = $c['cost'];
- $c = $user->basket->sumProducts() * $c['cost'];
- $p = $t * 100 . '%';
- } else {
- $c = $c['cost'];
- $t = $c;
- $p = null;
- }
- $payadd['s' . $shipping->getIdentifier()]['p' . $id] = array(
- 'v' => View_Smarty_Helper_Currency::currency(array(
- 'value' => (float) $c,
- 'float' => true,
- ), null),
- 't' => View_Smarty_Helper_Currency::currency(array(
- 'value' => (float) $c
- ), null)
- );
- if ($p != null) {
- if ($p > 0) {
- $p = '+' . $p;
- }
- $payadd['s' . $shipping->getIdentifier()]['p' . $id]['p'] = $p;
- }
- }
- }
- }
- foreach ($unset as $x) {
- unset($list[$x]);
- }
- if (is_null($this->_shipping_id) || !in_array($this->_shipping_id, $list->getIdentifiers())) {
- foreach ($list as $s) {
- if (1 == (int) $s->shipping->is_default) {
- $this->_shipping_id = (int) $s->getIdentifier();
- break;
- }
- }
- }
- if (count($list) > 0 && ( is_null($this->_shipping_id) || !in_array($this->_shipping_id, $list->getIdentifiers()) )) {
- $list->rewind();
- $defaultShippingId = (int) $list->current()->getIdentifier();
- foreach ($list as $shippingMethod) {
- if ($shippingMethod->shipping->is_default == 1) {
- $defaultShippingId = $shippingMethod->getIdentifier();
- break;
- }
- }
- $this->_shipping_id = $defaultShippingId;
- }
- if (is_null($this->_shipping_country)) {
- $this->_shipping_country = Locale_Manager::getRegion(); //Config_Manager::getConfigValue('company', 'COUNTRY');
- }
- $instance->view->shipping_id = $this->_shipping_id;
- $instance->view->shipping_country = $this->_shipping_country;
- $instance->view->shippings = $list;
- $instance->view->shipping2payment = Zend_Json::encode($s2p);
- $instance->view->country2shipping = Zend_Json::encode($c2s);
- $instance->view->shippingvalue = Zend_Json::encode($sv);
- $instance->view->paymentadditional = Zend_Json::encode($payadd);
- if (0 == count($payments)) {
- $instance->_flashMessanger->addWarning(Locale_Manager::translate('Store administrator has not defined a payment method that meets the criteria of your order.'));
- return false;
- }
- $instance->view->payments = $payments;
- if (is_null($this->_payment_id) || !in_array($this->_payment_id, $payments->getIdentifiers()))
- $this->_payment_id = (int) $payments[0]->getIdentifier();
- /* No JS $_POST check */
- if ($this->getRequest()->isPost() && $this->_shipping_id > 0 && $this->_payment_id > 0 && strlen($this->_shipping_country) > 0) {
- $current_shipping = new Logic_ShippingMethod($this->_shipping_id);
- $current_payment = new Logic_PaymentMethod($this->_payment_id);
- if (0 == $sum && 0 == $current_shipping->getCost($user->basket) && $zeropayid > 0) {
- $payments_ids = array($zeropayid);
- } else {
- $payments_ids = $current_shipping->getPaymentsIds();
- }
- if (!in_array($this->_payment_id, $payments_ids)) {
- $instance->_flashMessanger->addWarning(sprintf(
- 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
- ));
- return false;
- }
- if (!in_array($this->_shipping_country, $current_shipping->getCountries())) {
- $c = Locale_Manager::mapCountries(array($this->_shipping_country));
- $instance->_flashMessanger->addWarning(sprintf(
- 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)
- ));
- return false;
- }
- }
- //cleanup
- $cleaned = false;
- foreach ($user->basket as $p) {
- if (!$p || !$p->product->translation || 0 == (int) $p->stock->stock->active || 0 == (int) $p->product->translation->active || !$p->stock->availability->availability->can_buy) {
- $id = (int) $p->basket->id;
- if ($id > 0) {
- $user->basketRemove($id);
- $p->free();
- $cleaned = true;
- }
- }
- }
- if ($cleaned) {
- $user->resetBasket();
- }
- if (false == $check_limits) {
- return true;
- }
- if (0 == (int) Config_Manager::getConfigValue('shopping', 'PRODUCTS_ALLOW_ZERO')) {
- $min_value = (float) Locale_Manager::getFloat(Config_Manager::getConfigValue('shopping', 'MIN_ORDER_VALUE'));
- if ($min_value > 0 && $user->basket->sumProducts() < $min_value) {
- $instance->_flashMessanger->addWarning(Locale_Manager::translate('The minimum required order amount is') . ': ' .
- View_Smarty_Helper_Currency::currency(array('value' => $min_value), null)
- );
- return false;
- }
- }
- $quantity = $user->basket->countProducts();
- if (Config_Manager::hasConfigValue('shopping', 'MIN_PROD_QUANTITY')) {
- $min_quantity = (float) Config_Manager::getConfigValue('shopping', 'MIN_PROD_QUANTITY');
- if ($min_quantity > 0 && $quantity < $min_quantity) {
- $instance->_flashMessanger->addWarning(Locale_Manager::translate('The minimum required number of items in the cart is') . ': ' . $min_quantity);
- return false;
- }
- }
- return true;
- }
- public function Login_loginAction($instance) {
- $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
- if (Access_ClientManager::isLoggedIn()) {
- $instance->_redirect($router->assemble(array(), 'index'));
- return;
- }
- $instance->_breadCrumbs->add(Locale_Manager::translate('Sign in'), '');
- View_Smarty::setCacheTag(array(
- 'Logic_UserList', 'Logic_User', 'Logic_AdditionalField', 'Logic_AdditionalFieldList'
- ));
- $this->view->last_url = $_SERVER['HTTP_REFERER'];
- if ($instance->getRequest()->isPost() && 'index' == $instance->getRequest()->action) {
- $this->view->last_url = $_POST['last_url'];
- $form = new Form_Shop_Login();
- if ($form->isValid($_POST)) {
- $val = $form->getValues();
- $result = Access_ClientManager::authenticate($val['mail'], $val['pass']);
- if ($result->isValid()) {
- Plugin_Manager::callShopEvent('userLoginSuccess', array($result->getIdentity()));
- if (Zend_Registry::isRegistered('user_login_product_recovery')) {
- $moved = (int) Zend_Registry::get('user_login_product_recovery');
- if ($moved > 0) {
- if ($moved > 1) {
- $instance->_flashMessanger->addInfo(Locale_Manager::translate('Products have been restored to your shopping cart from the previous session.', $moved));
- } else {
- $instance->_flashMessanger->addInfo(Locale_Manager::translate('Product has been restored to your shopping cart from the previous session.', $moved));
- }
- //$instance->_redirect( $router->assemble(array(), 'basket') );
- //return;
- }
- }
- $session = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_SESSION);
- if (is_string($val['last_url']) && strlen($val['last_url'])) {
- $instance->_redirect($val['last_url']);
- return;
- }
- $instance->_redirect($router->assemble(array(), 'index'));
- return;
- } else {
- switch ($result->getCode()) {
- case Access_Auth_Result::FAILURE_USER_INACTIVE:
- $instance->_flashMessanger->addError(Locale_Manager::translate('Inactive account.'));
- break;
- case Access_Auth_Result::FAILURE_USER_NOT_VERIFIED:
- $instance->_flashMessanger->addError(Locale_Manager::translate('Your registration has not been confirmed. Check your e-mail and click the confirmation link.'));
- break;
- default:
- $instance->_flashMessanger->addError(Locale_Manager::translate('Incorrect login details'));
- break;
- }
- }
- } else {
- $instance->_flashMessanger->addError(Locale_Manager::translate('Incorrect login details'));
- Access_ClientManager::logout();
- }
- }
- $instance->view->passlink = $router->assemble(array(), 'passremind');
- $instance->view->body_class = 'shop_login';
- $instance->_handleFlashMessages();
- }
- public function Login_logoutAction($instance) {
- Access_ClientManager::logout();
- Zend_Session::regenerateId();
- Logic_UserOnline::recreate();
- $instance->_flashMessanger->addSuccess(Locale_Manager::translate('You have been successfully logged out.'));
- $instance->_redirect(Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER)->assemble(array(), 'index'));
- }
- public function Login_passremindAction($instance) {
- $instance->_breadCrumbs->add(Locale_Manager::translate('Password change'), '');
- $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
- if ($instance->getRequest()->isPost()) {
- $form = new Form_Shop_Passremind();
- if ($form->isValid($_POST)) {
- $val = $form->getValues();
- $ui = new Entity_UserInfo();
- $select = $ui->select()->from($ui, 'user_id');
- $select->where('email = ?', $val['remindmail']);
- $list = new Logic_UserList();
- $list->fillFromSelect($select);
- if (1 == $list->count()) {
- $user = $list[0];
- $url = $router->assemble(array(
- 'userId' => (int) $user->getIdentifier(),
- 'code' => self::Login_passCode($user),
- ), 'passremindStep2', System_Router::ROUTE_TYPE_CORE, true, array(), false, Zend_Registry::get(System_Bootstrap::REGISTRY_ROUTER_BASEURL));
- $template = Mail_Manager::getMailTemplate(Mail_Manager::MAIL_PASSWORD_REMINDER);
- $message = new Mail_Message($template);
- $message->setVarArray(array(
- 'email' => $user->userinfo->email,
- 'link' => $url,
- ));
- $message->addRecipient($user->userinfo->email, false);
- $metafields = new Metafield_Manager();
- foreach ($metafields->getMetafieldObjectList() as $m) {
- $key = "metafield.system." . $m->metafield->metafield->namespace . "." . $m->metafield->metafield->key;
- $message->setVar($key, Zend_Controller_Action_HelperBroker::getExistingHelper('ViewRenderer')->view->escape($m->value->value));
- }
- $metafields = $user->metafields;
- foreach ($metafields->getMetafieldObjectList() as $m) {
- $key = "metafield.user." . $m->metafield->metafield->namespace . "." . $m->metafield->metafield->key;
- $message->setVar($key, Zend_Controller_Action_HelperBroker::getExistingHelper('ViewRenderer')->view->escape($m->value->value));
- }
- try {
- Mail_Manager::send($message, true);
- Access_ClientManager::logout();
- $instance->_flashMessanger->addSuccess(Locale_Manager::translate('E-mail message has been sent.'));
- $instance->_redirect($router->assemble(array(), 'index'));
- return;
- } catch (Exception $e) {
- $instance->_errorLog->err($e);
- $instance->_flashMessanger->addWarning(Locale_Manager::translate('Error while sending e-mail.'));
- }
- } else
- $instance->_flashMessanger->addWarning(Locale_Manager::translate('Error while sending e-mail.'));
- } else {
- $uv = $form->getUnfilteredValues();
- $instance->view->remindmail = $uv['remindmail'];
- $instance->view->data_error = $form->getMessages();
- $instance->_flashMessanger->addError(Locale_Manager::translate('There is no such e-mail address in the database.'));
- }
- }
- $instance->view->body_class = 'shop_login_passremind';
- $instance->_handleFlashMessages();
- }
- public function Login_passremind2Action($instance) {
- $session = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_SESSION);
- $instance->_breadCrumbs->add(Locale_Manager::translate('Password change'), '');
- if ($instance->_hasParam('userId') && $instance->_hasParam('code')) {
- $uid = (int) $instance->_getParam('userId');
- $code = $instance->_getParam('code');
- if ($uid > 0 && 40 == strlen($code)) {
- try {
- $user = new Logic_User($uid);
- if (self::Login_passCode($user) === $code) {
- $session->passchange_uid = $uid;
- return;
- }
- } catch (Exception $e) {
- }
- }
- } elseif ($instance->getRequest()->isPost() && is_int($session->passchange_uid)) {
- $form = new Form_Shop_Passchange();
- if ($form->isValid($_POST)) {
- $val = $form->getValues();
- $pass = $val['pass1'];
- try {
- $user = new Logic_User($session->passchange_uid);
- $user->setPassword($pass);
- $instance->_flashMessanger->addSuccess(Locale_Manager::translate('Password has been changed. You can now sign in.'));
- $instance->_redirect(Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER)->assemble(array(), 'login'));
- } catch (Exception $e) {
- }
- } else {
- $instance->view->data_error = $form->getMessages();
- $instance->_flashMessanger->addError(Locale_Manager::translate('Form contains errors.'));
- }
- return;
- }
- $instance->_flashMessanger->addError(Locale_Manager::translate('Invalid authorization code.'));
- $instance->_forward('passremind');
- }
- public function Login_registerAction($instance) {
- if (Access_ClientManager::isLoggedIn()) {
- $instance->_redirect(Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER)->assemble(array(), 'index'));
- return;
- }
- if (!Zend_Registry::get('enable_register')) {
- $instance->_flashMessanger->addWarning(Locale_Manager::translate('Registration is temporarily unavailable'));
- $instance->_redirect(Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER)->assemble(array(), 'index'));
- return;
- }
- $instance->_breadCrumbs->add(Locale_Manager::translate('Registration'), '');
- if (Config_Manager::hasConfigValue('registration', 'REQUIRE_ADDRESS') &&
- 1 == (int) Config_Manager::getConfigValue('registration', 'REQUIRE_ADDRESS')) {
- $mode = 'full';
- } else {
- $mode = 'simple';
- }
- $fields = Logic_AdditionalField::getByLocate(
- Logic_AdditionalField::LOCATE_USER_REGISTRATION, Locale_Manager::getLanguageId()
- );
- $instance->view->additional_fields = $fields;
- if ('full' == $mode)
- $table1 = array(
- 'name' => array(
- 'name' => 'name',
- 'obligatory' => true,
- 'label' => Locale_Manager::translate('First name'),
- 'type' => 'text',
- 'hint' => '',
- 'value' => '',
- 'rowspan' => 1,
- ),
- 'surname' => array(
- 'name' => 'surname',
- 'obligatory' => true,
- 'label' => Locale_Manager::translate('Last name'),
- 'type' => 'text',
- 'rowspan' => 1,
- ),
- 'phone' => array(
- 'name' => 'phone',
- 'obligatory' => true,
- 'label' => Locale_Manager::translate('Phone'),
- 'type' => 'text',
- 'hint' => Locale_Manager::translate('Number format, e.g.: 123456789'),
- 'rowspan' => 1,
- ),
- );
- else
- $table1 = array();
- $table1['mail'] = array(
- 'name' => 'mail',
- 'obligatory' => true,
- 'label' => Locale_Manager::translate('E-mail'),
- 'type' => 'text',
- 'rowspan' => 1,
- );
- $table1['pass1'] = array(
- 'name' => 'pass1',
- 'obligatory' => true,
- 'label' => Locale_Manager::translate('Password'),
- 'type' => 'password',
- 'hint' => Locale_Manager::translate('Minimum of 6 characters'),
- 'rowspan' => 1,
- );
- $table1['pass2'] = array(
- 'name' => 'pass2',
- 'obligatory' => true,
- 'label' => Locale_Manager::translate('Repeat password'),
- 'type' => 'password',
- 'rowspan' => 1,
- );
- if ('simple' == $mode)
- $table2 = array();
- else
- $table2 = array(
- 'coname' => array(
- 'name' => 'coname',
- 'obligatory' => true,
- 'label' => Locale_Manager::translate('Company name'),
- 'type' => 'text',
- 'rowspan' => 1,
- ),
- 'nip' => array(
- 'name' => 'nip',
- 'obligatory' => true,
- 'label' => Locale_Manager::translate('Tax ID'),
- 'type' => 'text',
- 'rowspan' => 1,
- ),
- 'pesel' => array(
- 'name' => 'pesel',
- 'label' => Locale_Manager::translate('Personal Identification Number'),
- 'type' => 'text',
- 'rowspan' => 1,
- ),
- 'other_address' => array(
- 'name' => 'other_address',
- 'obligatory' => true,
- 'label' => Locale_Manager::translate('Street and house no.'),
- 'type' => 'text',
- 'hint' => Locale_Manager::translate('For example: 115 Oxford Street'),
- 'rowspan' => 1,
- ),
- 'zip' => array(
- 'name' => 'zip',
- 'obligatory' => true,
- 'label' => Locale_Manager::translate('Postal code'),
- 'type' => 'text',
- 'hint' => Locale_Manager::translate('Postal code format'),
- 'rowspan' => 1,
- ),
- 'city' => array(
- 'name' => 'city',
- 'obligatory' => true,
- 'label' => Locale_Manager::translate('City'),
- 'type' => 'text',
- 'rowspan' => 1,
- ),
- 'country' => array(
- 'name' => 'country',
- 'obligatory' => false,
- 'label' => Locale_Manager::translate('Country'),
- 'type' => 'select',
- 'list' => Locale_Manager::getCountries(),
- 'rowspan' => 1,
- ),
- );
- if (Zend_Registry::isRegistered(System_Bootstrap::REGISTRY_MOBILE)) {
- $f = Zend_Registry::get(System_Bootstrap::REGISTRY_MOBILE);
- if ($f) {
- unset($table2['coname']['obligatory']);
- unset($table2['nip']['obligatory']);
- }
- }
- $pesel = (1 == (int) Config_Manager::getConfigValue('shopping', 'SUPPORT_PESEL'));
- if (false === $pesel && isset($table2['pesel'])) {
- unset($table2['pesel']);
- }
- if ($instance->getRequest()->isPost()) {
- $form = new Form_Shop_Register(array($table1, $table2, $fields));
- if (isset($_POST['phone'][0])) {
- if ('+' == $_POST['phone'][0])
- $_POST['phone'] = '00' . substr($_POST['phone'], 1);
- $_POST['phone'] = preg_replace('/[\.\s\(\)]/', '', $_POST['phone']);
- }
- if ($form->isValid($_POST)) {
- $val = $form->getValues();
- $user = new Logic_User();
- $user->create();
- $user->user->date_add = date('Y-m-d H:i:s');
- $user->save();
- $autoGroup = 0;
- if (Config_Manager::hasConfigValue("registration", "auto_add_to_group")) {
- $group = Config_Manager::getConfigValue("registration", "auto_add_to_group");
- $uList = new Logic_UserGroupList();
- $uSelect = $uList->select();
- $uSelect->where("group_id = ?", $group);
- $uSelect->limit(1);
- $uList->fillFromSelect($uSelect);
- if (count($uList)) {
- $autoGroup = $group;
- }
- }
- if ($autoGroup > 0) {
- $table = new Entity_UserGroupsUsers();
- $table->insert(array(
- 'group_id' => $autoGroup,
- 'user_id' => $user->getIdentifier(),
- ));
- $grp = Logic_UserGroup::loadInstance($autoGroup);
- $grp->removeCachedObject();
- }
- $user->createInfo();
- $user->createSearch();
- $user->setPassword($val['pass1']);
- $user->userinfo->email = $val['mail'];
- if ('full' == $mode) {
- $user->userinfo->firstname = $val['name'];
- $user->userinfo->lastname = $val['surname'];
- }
- $user->userinfo->lang_id = Locale_Manager::getLanguageId();
- $user->userinfo->active = 1;
- $user->user->verify_email = 0;
- $confirm = ( 1 == (int) Config_Manager::getConfigValue('registration', 'CONFIRM_REGISTER') );
- if ($confirm) {
- $user->user->verify_code = md5($val['mail'] . microtime(true));
- }
- foreach ($val as $k => $v)
- if ('additional_' == substr($k, 0, 11) && strlen($v))
- $user->createAdditionalField(substr($k, 11), $v);
- $user->save();
- if ('full' == $mode) {
- $clist = Locale_Manager::getCountries();
- $address = array(
- 'company_name' => $val['coname'],
- 'tax_id' => $val['nip'],
- 'firstname' => $val['name'],
- 'lastname' => $val['surname'],
- 'street_1' => $val['other_address'],
- 'street_2' => '',
- 'city' => $val['city'],
- 'zip_code' => $val['zip'],
- 'state' => '',
- 'country' => $clist[$val['country']],
- 'country_code' => $val['country'],
- 'phone' => $val['phone'],
- 'default' => 1,
- 'shipping_default' => 1,
- );
- if (true === $pesel) {
- $address['pesel'] = $val['pesel'];
- }
- $user->processAddress($address);
- }
- $user->updateSearch();
- if (Zend_Registry::isRegistered(System_Bootstrap::REGISTRY_FACEBOOK)) {
- $f = Zend_Registry::get(System_Bootstrap::REGISTRY_FACEBOOK);
- if ($f) {
- $user->user->origin = Origin_Manager::ORIGIN_FACEBOOK;
- $user->user->save();
- }
- }
- if (Zend_Registry::isRegistered(System_Bootstrap::REGISTRY_MOBILE)) {
- $f = Zend_Registry::get(System_Bootstrap::REGISTRY_MOBILE);
- if ($f) {
- $user->user->origin = Origin_Manager::ORIGIN_MOBILE;
- $user->user->save();
- }
- }
- $fields = array();
- $additional_fields = array();
- foreach ($user->fields as $field) {
- $fid = (int) $field->field_id;
- if ($fid > 0) {
- $fields[$fid] = $field->value;
- }
- }
- foreach ($fields as $fid => $value) {
- $f = new Logic_AdditionalField($fid);
- if ($f->existsInDB() && 1 == (int) $f->field->active) {
- $additional_fields['additional_' . $fid . '_desc'] = $f->translation->description;
- switch ((int) $f->field->type) {
- case Logic_AdditionalField::TYPE_TEXT:
- case Logic_AdditionalField::TYPE_SELECT:
- $additional_fields['additional_' . $fid . '_value'] = $value;
- break;
- case Logic_AdditionalField::TYPE_CHECKBOX:
- $additional_fields['additional_' . $fid . '_value'] = Locale_Manager::translate(1 == (int) $value ? 'yes' : 'no');
- break;
- }
- }
- }
- if (1 == (int) Config_Manager::getConfigValue('mail', 'NOTIFY_EMAIL_NEW_CLIENT')) {
- try {
- $message = new Mail_Message(Mail_Manager::getMailTemplate(Mail_Manager::MAIL_ADMIN_REGISTER));
- $message->setVar('email', $val['mail']);
- $message->setVar('origin', Origin_Manager::getOriginNameForKey($user->user->origin));
- $message->setVarArray($additional_fields);
- $message->addRecipient(Config_Manager::getConfigValue('company', 'COMPANY_EMAIL'), false);
- $message->setReplyTo($val['mail'], $val['name'] . ' ' . $val['surname']);
- $metafields = new Metafield_Manager();
- foreach ($metafields->getMetafieldObjectList() as $m) {
- $key = "metafield.system." . $m->metafield->metafield->namespace . "." . $m->metafield->metafield->key;
- $message->setVar($key, Zend_Controller_Action_HelperBroker::getExistingHelper('ViewRenderer')->view->escape($m->value->value));
- }
- Mail_Manager::send($message, true);
- } catch (Exception $e) {
- $instance->_errorLog->err($e);
- }
- unset($message);
- }
- Plugin_Manager::callShopEvent('userRegisterSuccess', array($user));
- try {
- $template = Mail_Manager::getMailTemplate(Mail_Manager::MAIL_REGISTER);
- } catch (Exception $e) {
- $template = false;
- $instance->_errorLog->err($e);
- if ($confirm) {
- $instance->_flashMessanger->addWarning(Locale_Manager::translate('Error while sending e-mail message with an activation code.'));
- } else {
- $instance->_flashMessanger->addWarning(Locale_Manager::translate('Error while sending a welcome e-mail message.'));
- }
- }
- if ($template) {
- $message = new Mail_Message($template);
- $message->setVarArray(array(
- 'email' => $val['mail'],
- 'password' => $val['pass1'],
- 'link' => '',
- 'confirmation' => $confirm,
- 'origin' => Origin_Manager::getOriginNameForKey($user->user->origin),
- ));
- $message->setVarArray($additional_fields);
- $message->addRecipient($val['mail'], false);
- $metafields = new Metafield_Manager();
- foreach ($metafields->getMetafieldObjectList() as $m) {
- $key = "metafield.system." . $m->metafield->metafield->namespace . "." . $m->metafield->metafield->key;
- $message->setVar($key, Zend_Controller_Action_HelperBroker::getExistingHelper('ViewRenderer')->view->escape($m->value->value));
- }
- if ($confirm) {
- $url = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER)->assemble(array(
- 'userId' => (int) $user->getIdentifier(),
- 'code' => $user->user->verify_code,
- ), 'registerStep2', System_Router::ROUTE_TYPE_CORE, true, array(), false, Zend_Registry::get(System_Bootstrap::REGISTRY_ROUTER_BASEURL));
- $message->setVar('link', $url);
- try {
- Mail_Manager::send($message, true);
- $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.'));
- $instance->_redirect(Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER)->assemble(array(), 'index'));
- return;
- } catch (Exception $e) {
- $instance->_errorLog->err($e);
- $instance->_flashMessanger->addWarning(Locale_Manager::translate('Error while sending e-mail message with an activation code.'));
- }
- } else {
- try {
- Mail_Manager::send($message, true);
- } catch (Exception $e) {
- $instance->_errorLog->err($e);
- $instance->_flashMessanger->addWarning(Locale_Manager::translate('Error while sending a welcome e-mail message.'));
- }
- $instance->_flashMessanger->addSuccess(Locale_Manager::translate('Thank you for creating an account.'));
- $result = Access_ClientManager::authenticate($val['mail'], $val['pass1']);
- if ($result->isValid()) {
- $instance->_redirect(Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER)->assemble(array(), 'index'));
- return;
- }
- }
- }
- } else {
- $val = $form->getUnfilteredValues();
- $instance->_flashMessanger->addError(Locale_Manager::translate('The registration form contains errors.'));
- }
- foreach ($val as $k => $v) {
- if (isset($table1[$k]))
- $table1[$k]['value'] = $v;
- elseif (isset($table2[$k]))
- $table2[$k]['value'] = $v;
- elseif (preg_match('/^additional/', $k))
- $additional[$k] = $v;
- elseif ('address_type' == $k)
- $instance->view->address_type = $v;
- }
- $additional_error = array();
- foreach ($form->getMessages() as $k => $v) {
- if (isset($table1[$k]))
- $table1[$k]['error'] = $v;
- elseif (isset($table2[$k]))
- $table2[$k]['error'] = $v;
- elseif (preg_match('/^additional/', $k))
- $additional_error[$k] = $v;
- }
- $instance->view->additional_error = $additional_error;
- } else {
- $instance->view->address_type = 1;
- $table2['country']['value'] = Locale_Manager::getRegion(); //Config_Manager::getConfigValue('company', 'COUNTRY');
- foreach ($fields as $field) {
- if (Logic_AdditionalField::TYPE_CHECKBOX == (int) $field->field->type && 1 == (int) $field->checkbox->checked) {
- $additional['additional_' . (int) $field->getIdentifier()] = 1;
- }
- }
- }
- $table1['pass1']['value'] = $table1['pass2']['value'] = '';
- $instance->view->mode = $mode;
- $instance->view->table1 = $table1;
- $instance->view->table2 = $table2;
- $instance->view->additional_value = $additional;
- $instance->view->body_class = 'shop_login_register';
- $instance->_handleFlashMessages();
- }
- /**
- * IndexController::register2Action()
- *
- * @return void
- */
- public function Login_register2Action($instance) {
- if (Access_ClientManager::isLoggedIn()) {
- $instance->_redirect(Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER)->assemble(array(), 'index'));
- return;
- }
- if ($instance->_hasParam('userId') && $instance->_hasParam('code')) {
- $uid = (int) $instance->_getParam('userId');
- $code = $instance->_getParam('code');
- if ($uid > 0 && 32 == strlen($code)) {
- try {
- $user = new Logic_User($uid);
- if (0 == (int) $user->user->verify_email && $user->user->verify_code === $code) {
- $user->user->verify_email = 1;
- $user->save();
- $instance->_flashMessanger->addSuccess(Locale_Manager::translate('E-mail address has been confirmed.'));
- $result = Access_ClientManager::authenticate($user->userinfo->email, '', true);
- if ($result->isValid()) {
- $instance->_redirect(Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER)->assemble(array(), 'index'));
- } else
- $instance->_forward('login');
- return;
- }
- } catch (Exception $e) {
- }
- }
- }
- $instance->_flashMessanger->addError(Locale_Manager::translate('Invalid authorization code.'));
- $instance->_forward('login');
- }
- private static function Login_passCode($user) {
- return sha1('passremind' . $user->user->date_add . $user->user->salt);
- }
- public function Panel_indexAction($instance) {
- $instance->_breadCrumbs->add(Locale_Manager::translate('Customer panel'), '');
- View_Smarty::setCacheTag(array(
- ));
- $user = Logic_UserOnline::getUser();
- $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
- if (!$user->user instanceof Logic_User) {
- $instance->_redirect($router->assemble(array(), 'login'));
- return;
- }
- //Orders
- $list = new Logic_OrderList();
- $select = $list->select();
- $select->where('user_id = ?', $user->user->getIdentifier())
- ->where('parent_order_id is null')
- ->order('date DESC')
- ->limit(self::ORDERS_LIMIT);
- $list->fillFromSelect($select);
- $instance->view->orders = $list;
- $links = array();
- foreach ($list as $order)
- $links[$order->getIdentifier()] = $router->assemble(array('orderId' => $order->getIdentifier()), 'panelOrder');
- $instance->view->orders_links = $links;
- $instance->view->orders_alllink = ( count($user->user->orders) > self::ORDERS_LIMIT );
- $instance->view->orders_count = count($user->user->orders);
- //Addresses
- if ($user->user->address instanceof Logic_UserAddress)
- $instance->view->billing_address = $user->user->address;
- if ($user->user->shippingAddress instanceof Logic_UserAddress)
- $instance->view->shipping_address = $user->user->shippingAddress;
- //Comments
- $instance->view->comments_count = count($user->user->comments);
- //Favourites
- $instance->view->favourites_count = count($user->user->favourites);
- if ($user->user && Loyalty_Program::isEnabled()) {
- $sum = $user->user->loyalty->sum();
- $this->view->loyalty = true;
- $this->view->loyalty_points = View_Smarty_Helper_Float::float(array('value' => $sum, 'precision' => 0), null);
- ;
- $this->view->loyalty_discount = $ld = Loyalty_Program::exchangeModeDiscounts();
- if ($ld) {
- $next = false;
- $this->view->loyalty_level = $ll = Loyalty_Program::getDiscountFromPoints($sum, true);
- if (is_array($ll) && $ll['level']) {
- $next = Loyalty_Program::getNextDiscountFromPoints($sum);
- } else {
- $next = Loyalty_Program::getNextDiscountFromPoints(0);
- }
- if (is_array($next) && $next['level'] && $next['level'] > $sum) {
- $this->view->loyalty_next_level = View_Smarty_Helper_Float::float(array('value' => ($next['level'] - $sum), 'precision' => 0), null);
- } else {
- $this->view->loyalty_next_level = false;
- }
- }
- $this->view->loyalty_exchange = $le = Loyalty_Program::exchangeModeProducts();
- } else {
- $this->view->loyalty = false;
- }
- $this->view->QUANTITY_PRECISION = Logic_UserBasketList::QUANTITY_PRECISION;
- $instance->view->body_class = 'shop_panel';
- $instance->_handleFlashMessages();
- }
- public function Panel_ordersAction($instance) {
- View_Smarty::setCacheTag(array(
- ));
- $user = Logic_UserOnline::getUser();
- $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
- if (!$user->user instanceof Logic_User) {
- $instance->_redirect($router->assemble(array(), 'login'));
- return;
- }
- if (0 == count($user->user->orders)) {
- $instance->_redirect($router->assemble(array(), 'panel'));
- return;
- }
- $instance->_breadCrumbs->add(Locale_Manager::translate('Customer panel'), $router->assemble(array(), 'panel'));
- $instance->_breadCrumbs->add(Locale_Manager::translate('Order history'), '');
- $instance->view->orders = $user->user->orders;
- //Config confirm
- $instance->view->config_confirm = (1 == (int) Config_Manager::getConfigValue('shopping', 'CONFIRM_ORDER'));
- $instance->view->show_invoice = (1 == (int) Config_Manager::getConfigValue('invoice', 'INVOICE_ON'));
- $instance->view->body_class = 'shop_panel_orders';
- $instance->_handleFlashMessages();
- }
- public function Panel_orderAction($instance) {
- View_Smarty::setCacheTag(array(
- ));
- $user = Logic_UserOnline::getUser();
- $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
- $id = (int) $instance->_getParam('orderId');
- $token = (string) $instance->_getParam('token');
- $order = new Logic_Order($id);
- if (strlen($token)) {
- if (false === Config_Manager::hasConfigValue('shopping', 'ORDER_VIA_TOKEN') || 1 !== (int) Config_Manager::getConfigValue('shopping', 'ORDER_VIA_TOKEN')) {
- $instance->_redirect($router->assemble(array(), 'index'));
- return;
- }
- if (true !== $order->existsInDB() || 0 !== (int) $order->order->user_order || null !== $order->order->user_id || strlen($order->order->code) < 32 || $token !== $order->getAccessToken()) {
- $instance->_redirect($router->assemble(array(), 'index'));
- return;
- }
- } else {
- if (!$user->user instanceof Logic_User || $id < 1) {
- $instance->_redirect($router->assemble(array(), 'login'));
- }
- if (!$order->existsInDB() || $order->order->user_id !== $user->user->getIdentifier()) {
- $instance->_redirect($router->assemble(array(), 'index'));
- }
- $instance->_breadCrumbs->add(Locale_Manager::translate('Customer panel'), $router->assemble(array(), 'panel'));
- if (count($user->user->orders) > self::ORDERS_LIMIT) {
- $instance->_breadCrumbs->add(Locale_Manager::translate('Order history'), $router->assemble(array(), 'panelOrders'));
- }
- $token = false;
- }
- if ($order->hasParentOrder()) {
- $instance->_flashMessanger->addError(Locale_Manager::translate('The order has been combined with another'));
- $instance->_redirect($router->assemble(array(), 'index'));
- }
- $shippingHandler = $order->shipping->handler;
- $shippingHandler->setOrder($order);
- $instance->view->shippingHandler = $shippingHandler;
- $instance->view->order = $order;
- $instance->view->token = $token;
- $instance->_breadCrumbs->add(Locale_Manager::translate('Order no. %d', $id), '');
- //Config confirm
- $instance->view->config_confirm = (1 == (int) Config_Manager::getConfigValue('shopping', 'CONFIRM_ORDER'));
- $instance->view->show_invoice = (1 == (int) Config_Manager::getConfigValue('invoice', 'INVOICE_ON'));
- $instance->view->body_class = 'shop_panel_order';
- $instance->view->body_id = 'shop_panel_order' . $id;
- $instance->_handleFlashMessages();
- }
- public function Panel_digitalAction($instance) {
- $user = Logic_UserOnline::getUser();
- $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
- $did = (int) $instance->_getParam('digitalId');
- $pid = (int) $instance->_getParam('prodId');
- if ($instance->_hasParam('hash')) {
- $hash = preg_replace('/[^a-z0-9]/i', '', $instance->_getParam('hash'));
- } else {
- $hash = '';
- }
- if ($pid < 1 || $did < 1) {
- $instance->_redirect($router->assemble(array(), 'index'));
- return;
- }
- $ok = false;
- $hashok = false;
- $p = Logic_OrderProduct::loadInstance($pid);
- $o = $p->order;
- if ($p instanceof Logic_OrderProduct && $p->productObject) {
- $type = (int) $o->order->user_order;
- if ($type > 0) {
- if (!$user->user instanceof Logic_User) {
- $instance->_redirect($router->assemble(array(), 'login'));
- return;
- }
- $hashok = ($user->user->getIdentifier() === $o->order->user_id); //user logged, don't need to check hash, we have authentication
- } else {
- $hashok = $p->verifyDigitalHash($hash, $did);
- }
- if ($hashok && $o->isDigital() && $o->isDownloadReady()) {
- $d = Logic_ProductDigital::loadInstance($did);
- if ($d->existsInDB() && (int) $p->productObject->getIdentifier() === (int) $d->product->getIdentifier()) {
- $ok = true;
- }
- }
- }
- if (false == $ok) {
- $instance->_redirect($router->assemble(array(), 'index'));
- return;
- }
- $dl = (int) Config_Manager::getConfigValue('digitalProducts', 'LINK_EXPIRATION_TIME');
- if ($dl > 0) {
- $time = strtotime($o->order->status_date) + $dl * 86400;
- if (time() > $time) {
- $instance->_flashMessanger->addError(Locale_Manager::translate('Time limit to download this file has been exceeded.'));
- $instance->_redirect($router->assemble(array(
- 'orderId' => (int) $o->getIdentifier(),
- ), 'panelOrder'));
- return;
- }
- }
- $ul = (int) Config_Manager::getConfigValue('digitalProducts', 'NUMBER_OF_DOWNLOADS');
- $ul *= (int) $p->product->quantity;
- if ($ul > 0) {
- if ($user->user instanceof Logic_User && $type > 0) {
- $count = $d->countDownloads($user->user->getIdentifier(), $o->getIdentifier());
- if ($count >= $ul) {
- $instance->_flashMessanger->addError(Locale_Manager::translate('The limit of downloads for this file has been reached.'));
- $instance->_redirect($router->assemble(array(
- 'orderId' => (int) $o->getIdentifier(),
- ), 'panelOrder'));
- return;
- }
- } else {
- $count = $d->countDownloads(null, $o->getIdentifier());
- if ($count >= $ul) {
- $instance->_flashMessanger->addError(Locale_Manager::translate('The limit of downloads for this file has been reached.'));
- $instance->_redirect($router->assemble(array(), 'index'));
- return;
- }
- }
- }
- $path = $d->getPath(true);
- if ($path) {
- if ($user->user instanceof Logic_User && $type > 0) {
- $d->logDownload($user->user->getIdentifier(), $o->getIdentifier());
- } else {
- $d->logDownload(null, $o->getIdentifier());
- }
- Download_Manager::handle($path);
- } else {
- $instance->_redirect($router->assemble(array(), 'index'));
- return;
- }
- }
- public function Panel_paymentAction($instance) {
- View_Smarty::setCacheTag(array(
- ));
- $user = Logic_UserOnline::getUser();
- $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
- $id = (int) $instance->_getParam('orderId');
- $token = (string) $instance->_getParam('token');
- if (strlen($token)) {
- $order = new Logic_Order($id);
- if (true !== $order->existsInDB() || 0 !== (int) $order->order->user_order || null !== $order->order->user_id || strlen($order->order->code) < 32 || $token !== $order->getAccessToken()) {
- $instance->_redirect($router->assemble(array(), 'index'));
- return;
- }
- } else {
- if (!$user->user instanceof Logic_User || $id < 1) {
- $instance->_redirect($router->assemble(array(), 'login'));
- return;
- }
- $instance->_breadCrumbs->add(Locale_Manager::translate('Customer panel'), $router->assemble(array(), 'panel'));
- if (count($user->user->orders) > self::ORDERS_LIMIT)
- $instance->_breadCrumbs->add(Locale_Manager::translate('Order history'), $router->assemble(array(), 'panelOrders'));
- $order = null;
- foreach ($user->user->orders as $o) {
- if ($id == (int) $o->getIdentifier()) {
- $order = $o;
- break;
- }
- }
- if (is_null($order)) {
- $instance->_redirect($router->assemble(array(), 'login'));
- return;
- }
- $token = false;
- }
- if ($order->sumOrder() * 100 > $order->order->paid * 100 && $order->hasOnlinePayment()) {
- /** @var Plugin_Payment_Online_Abstract $onlinePayment */
- $onlinePayment = $order->getOnlinePayment();
- if ($onlinePayment->isFinished() && $onlinePayment->isStarted()) {
- $instance->_flashMessanger->addWarning(Locale_Manager::translate('Order has been already paid'));
- $instance->_redirect($router->assemble(array(), 'index'));
- return;
- }
- }
- $instance->_breadCrumbs->add(Locale_Manager::translate('Order no. %d', $id), $router->assemble(array('orderId' => $id, 'token' => $token), 'panelOrder'));
- $instance->_breadCrumbs->add(Locale_Manager::translate('Payment'), '');
- $instance->view->order = $order;
- $instance->view->token = $token;
- $handler = $order->payment->createHandler();
- $handler->setOrder($order);
- if ($handler instanceof Plugin_Payment_Online_Abstract) {
- $instance->view->payment_form = $handler->getForm();
- } else {
- $instance->view->payment_message = $order->payment->translation->notify;
- }
- $instance->view->body_class = 'shop_panel_payment';
- $instance->view->body_id = 'shop_panel_payment' . $id;
- $instance->_handleFlashMessages();
- }
- public function Panel_commentsAction($instance) {
- View_Smarty::setCacheTag(array(
- ));
- $user = Logic_UserOnline::getUser();
- $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
- if (!$user->user instanceof Logic_User) {
- $instance->_redirect($router->assemble(array(), 'login'));
- return;
- }
- if (0 == count($user->user->comments)) {
- $instance->_redirect($router->assemble(array(), 'panel'));
- return;
- }
- $instance->_breadCrumbs->add(Locale_Manager::translate('Customer panel'), $router->assemble(array(), 'panel'));
- $instance->_breadCrumbs->add(Locale_Manager::translate('Products reviews'), '');
- $instance->view->body_class = 'shop_panel_comments';
- $instance->_handleFlashMessages();
- }
- public function Panel_favouritesAction($instance) {
- View_Smarty::setCacheTag(array(
- ));
- $user = Logic_UserOnline::getUser();
- $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
- if (!$user->user instanceof Logic_User) {
- $instance->_redirect($router->assemble(array(), 'login'));
- return;
- }
- if (0 == count($user->user->favourites)) {
- $instance->_redirect($router->assemble(array(), 'panel'));
- return;
- }
- $instance->_breadCrumbs->add(Locale_Manager::translate('Customer panel'), $router->assemble(array(), 'panel'));
- $instance->_breadCrumbs->add(Locale_Manager::translate('Products on wishlist'), '');
- $instance->view->body_class = 'shop_panel_favourites';
- $instance->_handleFlashMessages();
- }
- public function Panel_removefavAction($instance) {
- $user = Logic_UserOnline::getUser();
- $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
- $id = (int) $instance->_getParam('stockId');
- if (!$user->user instanceof Logic_User || 0 == count($user->user->favourites) || $id < 1) {
- $instance->_redirect($router->assemble(array(), 'login'));
- return;
- }
- $ent = new Entity_UserFavourites();
- $ret = $ent->delete(array(
- 'stock_id = ?' => $id,
- 'user_id = ?' => (int) $user->user->getIdentifier(),
- ));
- if (1 == $ret)
- $instance->_flashMessanger->addSuccess(Locale_Manager::translate('Product removed from wish list.'));
- $instance->_redirect($router->assemble(array(), 'panelFavourites'));
- }
- public function Panel_addressAction($instance) {
- View_Smarty::setCacheTag(array(
- ));
- $user = Logic_UserOnline::getUser();
- $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
- if (!$user->user instanceof Logic_User) {
- $instance->_redirect($router->assemble(array(), 'login'));
- return;
- }
- $instance->_breadCrumbs->add(Locale_Manager::translate('Customer panel'), $router->assemble(array(), 'panel'));
- $instance->_breadCrumbs->add(Locale_Manager::translate('List of addresses'), '');
- $instance->view->body_class = 'shop_panel_addresses';
- $instance->_handleFlashMessages();
- }
- public function Panel_addressdefaultAction($instance) {
- $user = Logic_UserOnline::getUser();
- $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
- $id = (int) $instance->_getParam('addressId');
- if (!$user->user instanceof Logic_User || 0 == count($user->user->addresses) || $id < 1) {
- $instance->_redirect($router->assemble(array(), 'panelAddressList'));
- return;
- }
- foreach ($user->user->addresses as $address) {
- $d = (int) ($id == (int) $address->getIdentifier());
- if ($d != (int) $address->address->default) {
- $address->address->default = $d;
- $address->save();
- }
- }
- $instance->_flashMessanger->addSuccess(Locale_Manager::translate('Address has been set as default.'));
- $instance->_redirect($router->assemble(array(), 'panelAddressList'));
- }
- public function Panel_addressshippingAction($instance) {
- $user = Logic_UserOnline::getUser();
- $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
- $id = (int) $instance->_getParam('addressId');
- if (!$user->user instanceof Logic_User || 0 == count($user->user->addresses) || $id < 1) {
- $instance->_redirect($router->assemble(array(), 'panelAddressList'));
- return;
- }
- foreach ($user->user->addresses as $address) {
- $d = (int) ($id == (int) $address->getIdentifier());
- if ($d != (int) $address->address->shipping_default) {
- $address->address->shipping_default = $d;
- $address->save();
- }
- }
- $instance->_flashMessanger->addSuccess(Locale_Manager::translate('Address has been set as default.'));
- $instance->_redirect($router->assemble(array(), 'panelAddressList'));
- }
- public function Panel_addressremoveAction($instance) {
- $user = Logic_UserOnline::getUser();
- $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
- $id = (int) $instance->_getParam('addressId');
- if (!$user->user instanceof Logic_User || 0 == count($user->user->addresses) || $id < 1) {
- $instance->_redirect($router->assemble(array(), 'panelAddressList'));
- return;
- }
- foreach ($user->user->addresses as $address) {
- if ($id == (int) $address->getIdentifier()) {
- $def = (1 == (int) $address->address->default);
- $ship = (1 == (int) $address->address->shipping_default);
- $address->delete();
- $user->user->forgetAddresses();
- if (count($user->user->addresses) && ($def || $ship)) {
- if ($def)
- $user->user->addresses[0]->address->default = 1;
- if ($ship)
- $user->user->addresses[0]->address->shipping_default = 1;
- $user->user->addresses[0]->save();
- }
- $instance->_flashMessanger->addSuccess(Locale_Manager::translate('Address has been removed.'));
- }
- }
- $user->user->updateSearch();
- $instance->_redirect($router->assemble(array(), 'panelAddressList'));
- }
- public function Panel_addresseditAction($instance) {
- $user = Logic_UserOnline::getUser();
- $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
- $id = (int) $instance->_getParam('addressId');
- if (!$user->user instanceof Logic_User || $id < 0) {
- $instance->_redirect($router->assemble(array(), 'panelAddressList'));
- return;
- }
- $address = null;
- if ($id > 0)
- foreach ($user->user->addresses as $a)
- if ($id == (int) $a->getIdentifier()) {
- $address = $a;
- break;
- }
- if (($id > 0 && is_null($address)) || ($instance->getRequest()->isPost() && isset($_POST['button1'][0]))) {
- $instance->_redirect($router->assemble(array(), 'panelAddressList'));
- return;
- }
- $instance->_breadCrumbs->add(Locale_Manager::translate('Customer panel'), $router->assemble(array(), 'panel'));
- $instance->_breadCrumbs->add(Locale_Manager::translate('List of addresses'), $router->assemble(array(), 'panelAddressList'));
- $instance->_breadCrumbs->add($id > 0 ? Locale_Manager::translate('Edycja adresu') : Locale_Manager::translate('New address'), '');
- $instance->view->address_id = $id;
- $table = array(
- 'name' => array(
- 'name' => 'name',
- 'obligatory' => true,
- 'label' => Locale_Manager::translate('First name'),
- 'type' => 'text',
- 'rowspan' => 1,
- ),
- 'surname' => array(
- 'name' => 'surname',
- 'obligatory' => true,
- 'label' => Locale_Manager::translate('Last name'),
- 'type' => 'text',
- 'rowspan' => 1,
- ),
- 'phone' => array(
- 'name' => 'phone',
- 'obligatory' => true,
- 'label' => Locale_Manager::translate('Phone'),
- 'type' => 'text',
- 'hint' => Locale_Manager::translate('Number format, e.g.: 123456789'),
- 'rowspan' => 1,
- ),
- 'coname' => array(
- 'name' => 'coname',
- 'label' => Locale_Manager::translate('Company name'),
- 'type' => 'text',
- 'rowspan' => 1,
- ),
- 'nip' => array(
- 'name' => 'nip',
- 'label' => Locale_Manager::translate('Tax ID'),
- 'type' => 'text',
- 'rowspan' => 1,
- ),
- 'pesel' => array(
- 'name' => 'pesel',
- 'label' => Locale_Manager::translate('Personal Identification Number'),
- 'type' => 'text',
- 'rowspan' => 1,
- ),
- 'other_address' => array(
- 'name' => 'other_address',
- 'obligatory' => true,
- 'label' => Locale_Manager::translate('Street and house no.'),
- 'type' => 'text',
- 'hint' => Locale_Manager::translate('For example: 115 Oxford Street'),
- 'rowspan' => 1,
- ),
- 'zip' => array(
- 'name' => 'zip',
- 'obligatory' => true,
- 'label' => Locale_Manager::translate('Postal code'),
- 'type' => 'text',
- 'hint' => Locale_Manager::translate('Postal code format'),
- 'rowspan' => 1,
- ),
- 'city' => array(
- 'name' => 'city',
- 'obligatory' => true,
- 'label' => Locale_Manager::translate('City'),
- 'type' => 'text',
- 'rowspan' => 1,
- ),
- 'country' => array(
- 'name' => 'country',
- 'obligatory' => false,
- 'label' => Locale_Manager::translate('Country'),
- 'type' => 'select',
- 'list' => Locale_Manager::getCountries(),
- 'rowspan' => 1,
- 'value' => Locale_Manager::getRegion(),
- ),
- );
- $address_assign = array(
- 'name' => 'firstname',
- 'surname' => 'lastname',
- 'phone' => 'phone',
- 'coname' => 'company_name',
- 'nip' => 'tax_id',
- 'pesel' => 'pesel',
- 'other_address' => 'street_1',
- 'zip' => 'zip_code',
- 'city' => 'city',
- 'country' => 'country_code',
- );
- $pesel = (1 == (int) Config_Manager::getConfigValue('shopping', 'SUPPORT_PESEL'));
- if (false === $pesel) {
- unset($table['pesel']);
- unset($address_assign['pesel']);
- }
- if ($instance->getRequest()->isPost() && isset($_POST['addressform'][0])) {
- if (isset($_POST['phone'][0])) {
- if ('+' == $_POST['phone'][0])
- $_POST['phone'] = '00' . substr($_POST['phone'], 1);
- $_POST['phone'] = preg_replace('/[\.\s\(\)]/', '', $_POST['phone']);
- }
- $form = new Form_Shop_Singleaddress($table);
- if ($form->isValid($_POST)) {
- $val = $form->getValues();
- if (is_null($address)) {
- $address = new Logic_UserAddress();
- $address->create();
- $address->address->user_id = (int) $user->user->getIdentifier();
- }
- foreach ($address_assign as $k => $v)
- if (isset($val[$k]))
- $address->address->$v = $val[$k];
- $clist = Locale_Manager::getCountries();
- $address->address->country = $clist[$val['country']];
- if (strlen($address->address->company_name) > 0)
- $name = $address->address->company_name;
- else
- $name = $address->address->firstname . ' ' . $address->address->lastname;
- $name .= ', ' . $address->address->street_1 . ', ' . $address->address->city;
- $address->address->address_name = trim($name);
- $address->address->sortkey = trim($address->address->company_name . ' ' . $address->address->lastname . ' ' . $address->address->firstname);
- if (is_object($user->user->address)) {
- if (1 == $val['default1'] && 0 == (int) $address->address->default) {
- $address->address->default = 1;
- foreach ($user->user->addresses as $a) {
- if ($id != (int) $a->getIdentifier()) {
- $a->address->default = 0;
- $a->save();
- }
- }
- }
- } else
- $address->address->default = 1;
- if (is_object($user->user->shippingAddress)) {
- if (1 == $val['default2'] && 0 == (int) $address->address->shipping_default) {
- $address->address->shipping_default = 1;
- foreach ($user->user->addresses as $a) {
- if ($id != (int) $a->getIdentifier()) {
- $a->address->shipping_default = 0;
- $a->save();
- }
- }
- }
- } else
- $address->address->shipping_default = 1;
- $address->save();
- if (is_object($user->user)) {
- $user->user->updateSearch();
- }
- if ($id > 0)
- $instance->_flashMessanger->addSuccess(Locale_Manager::translate('Address has been saved.'));
- else
- $instance->_flashMessanger->addSuccess(Locale_Manager::translate('Address has been added.'));
- $instance->_redirect($router->assemble(array(), 'panelAddressList'));
- return;
- } else {
- $instance->_flashMessanger->addError(Locale_Manager::translate('Form contains errors.'));
- $val = $form->getUnfilteredValues();
- foreach ($val as $k => $v)
- if (isset($table[$k]))
- $table[$k]['value'] = $v;
- foreach ($form->getMessages() as $k => $v)
- if (isset($table[$k]))
- $table[$k]['error'] = $v;
- $instance->view->default1 = $val['default1'];
- $instance->view->default2 = $val['default2'];
- }
- } elseif ($id > 0) {
- foreach ($address_assign as $k => $v)
- if (isset($table[$k]))
- $table[$k]['value'] = $address->address->$v;
- }
- if ($id > 0) {
- $instance->view->show_default1 = (0 == (int) $address->address->default);
- $instance->view->show_default2 = (0 == (int) $address->address->shipping_default);
- } else {
- $instance->view->show_default1 = is_object($user->user->address);
- $instance->view->show_default2 = is_object($user->user->shippingAddress);
- }
- $instance->view->table = $table;
- $instance->view->body_class = 'shop_panel_address';
- $instance->view->body_id = 'shop_panel_address' . $id;
- $instance->_handleFlashMessages();
- }
- public function Panel_passwordAction($instance) {
- View_Smarty::setCacheTag(array(
- ));
- $user = Logic_UserOnline::getUser();
- $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
- if (!$user->user instanceof Logic_User) {
- $instance->_redirect($router->assemble(array(), 'login'));
- return;
- }
- $instance->_breadCrumbs->add(Locale_Manager::translate('Customer panel'), $router->assemble(array(), 'panel'));
- $instance->_breadCrumbs->add(Locale_Manager::translate('Password change'), '');
- if ($instance->getRequest()->isPost()) {
- $form = new Form_Shop_Passchange(true);
- if ($form->isValid($_POST)) {
- $val = $form->getValues();
- $oldpass = $val['pass'];
- $newpass = $val['pass1'];
- $adapter = new Access_Auth_Test_Hash(Access_ClientManager::getInstance()); // todo: move it to Access_CLientManager
- if ($adapter->test($user->user->user->login, $user->user->user->pass, $user->user->user->salt, $oldpass)) {
- Access_ClientManager::logout();
- Zend_Session::regenerateId();
- $user->user->setPassword($newpass);
- $instance->_flashMessanger->addSuccess(Locale_Manager::translate('Password has been changed. Please sign in again.'));
- $instance->_redirect($router->assemble(array(), 'login'));
- return;
- } else {
- $de = (array) $form->getMessages();
- if (!isset($de['pass']))
- $de['pass'] = array();
- $de['pass']['wrong'] = Locale_Manager::translate('Incorrect password.');
- $instance->view->data_error = $de;
- $instance->_flashMessanger->addError(Locale_Manager::translate('Form contains errors.'));
- }
- } else {
- $instance->view->data_error = $form->getMessages();
- $instance->_flashMessanger->addError(Locale_Manager::translate('Form contains errors.'));
- }
- }
- $instance->view->body_class = 'shop_panel_password';
- $instance->_handleFlashMessages();
- }
- public function Panel_editAction($instance) {
- View_Smarty::setCacheTag(array(
- ));
- $user = Logic_UserOnline::getUser();
- $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
- if (!$user->user instanceof Logic_User) {
- $instance->_redirect($router->assemble(array(), 'login'));
- return;
- }
- $instance->_breadCrumbs->add(Locale_Manager::translate('Customer panel'), $router->assemble(array(), 'panel'));
- $instance->_breadCrumbs->add(Locale_Manager::translate('Edit your profile'), '');
- $fields = Logic_AdditionalField::getByLocate(
- Logic_AdditionalField::LOCATE_USER_ACCOUNT, Locale_Manager::getLanguageId()
- );
- $instance->view->additional_fields = $fields;
- if ($instance->getRequest()->isPost()) {
- $form = new Form_Shop_UserEdit($user->user->getIdentifier());
- if ($form->isValid($_POST)) {
- $vals = $form->getValues();
- $data = array(
- 'firstname' => $vals['name'],
- 'lastname' => $vals['surname'],
- 'email' => $vals['mail']
- );
- $data['additional_fields'] = array();
- foreach ($fields as $field) {
- $id = (int) $field->getIdentifier();
- $x = 'additional_' . $id;
- if (isset($vals[$x])) {
- $data['additional_fields'][$id] = $vals[$x];
- }
- }
- Logic_User::createOrSaveUser($user->user, $data, $fields);
- $instance->_flashMessanger->addSuccess(Locale_Manager::translate('Profile changes have been saved.'));
- $instance->_redirect($router->assemble(array(), 'panel'));
- return;
- } else {
- $instance->view->data = $form->getUnfilteredValues();
- $instance->view->data_error = $form->getMessages();
- $instance->_flashMessanger->addError(Locale_Manager::translate('The registration form contains errors.'));
- }
- } else {
- $data = array(
- 'name' => $user->user->userinfo->firstname,
- 'surname' => $user->user->userinfo->lastname,
- 'mail' => $user->user->userinfo->email,
- );
- foreach ($user->user->fields as $field) {
- $data['additional_' . $field->field_id] = $field->value;
- }
- $instance->view->data = $data;
- }
- $instance->view->body_class = 'shop_panel_edit';
- $instance->_handleFlashMessages();
- }
- public function Panel_getaddressAction($instance) {
- header('Content-type: application/json');
- try {
- Access_ClientManager::reValidate();
- if (!Access_ClientManager::isLoggedIn()) {
- echo 0;
- return;
- }
- $id = (int) $instance->_getParam('id');
- if ($id <= 0) {
- echo 0;
- return;
- }
- $user = Logic_UserOnline::getUser();
- if (!is_object($user->user)) {
- echo 0;
- return;
- }
- $address = null;
- foreach ($user->user->addresses as $a)
- if ($id == (int) $a->getIdentifier())
- $address = $a;
- if (!is_object($address)) {
- echo 0;
- return;
- }
- $ret = array(
- 'name' => (string) $address->address->firstname,
- 'surname' => (string) $address->address->lastname,
- 'phone' => (string) $address->address->phone,
- 'coname' => (string) $address->address->company_name,
- 'nip' => (string) $address->address->tax_id,
- 'pesel' => (string) $address->address->pesel,
- 'other_address' => (string) $address->address->street_1,
- 'zip' => (string) $address->address->zip_code,
- 'city' => (string) $address->address->city,
- 'country' => (string) $address->address->country_code,
- );
- $pesel = (1 == (int) Config_Manager::getConfigValue('shopping', 'SUPPORT_PESEL'));
- if (false === $pesel) {
- unset($ret['pesel']);
- }
- echo Zend_Json::encode($ret);
- } catch (Exception $e) {
- $instance->_errorLog->debug('Error while downloading user address (' . date('Y-m-d H:i:s') . '): ' . $e->getMessage());
- echo 0;
- }
- }
- /**
- * ProductController
- */
- public function Product_listAction($instance) {
- //elo
- View_Smarty::setCacheTag(array(
- 'Logic_ProductList', 'Logic_Product', 'Logic_ProductStockList', 'Logic_ProductStock', 'Logic_Category', 'Logic_CategoryList',
- 'productImages', 'productFiles', 'productAttributes', 'productVote', 'productTranslation',
- 'Logic_ProductDelivery', 'Logic_ProductDeliveryList', 'Logic_ProductAvailability', 'Logic_ProductAvailabilityList',
- 'Logic_ProductStock', 'Logic_ProductStockList',
- ));
- View_Smarty::skipCache();
- $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
- $page = $instance->_hasParam('page') ? (int) $instance->_getParam('page') : 1;
- if ($page < 1)
- $page = 1;
- $view = $instance->_hasParam('view') ? $instance->_getParam('view') : null;
- if (!in_array($view, System_Router::$view_modes) || 'default' == $view) {
- $view = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_LAYOUT_MANAGER)->getSkin()->getSettings()->productlist->mode;
- }
- if ('default' == $view) {
- $view = 'full';
- }
- $sort = $instance->_hasParam('sort') ? (int) $instance->_getParam('sort') : 1;
- if ($sort > 5 || $sort < 1) {
- $sort = 1;
- }
- $session = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_SESSION);
- $instance->view->settingsgroup = 'productlist';
- $instance->view->loyalty_exchange = false;
- $groups = null;
- $has_filer_box = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_LAYOUT_MANAGER)->hasBox('Filter');
- if (Zend_Registry::isRegistered('products') && Zend_Registry::isRegistered('list_type') && !isset($_SESSION['poicvbgh'])) {
- $products = Zend_Registry::get('products');
- $list_type = Zend_Registry::get('list_type');
- switch ($list_type) {
- case 'promo':
- $instance->_breadCrumbs->add(Locale_Manager::translate('Only On Sale products'), '');
- $instance->view->router_name = 'promotions';
- $instance->handleSeo(array('promo' => true));
- break;
- case 'new':
- $instance->_breadCrumbs->add(Locale_Manager::translate('New products'), '');
- $instance->view->router_name = 'productNew';
- $instance->handleSeo(array('new' => true));
- break;
- case 'day':
- $instance->_breadCrumbs->add(Locale_Manager::translate('Products of the day'), '');
- $instance->view->router_name = 'productDay';
- $instance->handleSeo(array('day' => true));
- break;
- case 'producer':
- $manuf = new Logic_Manufacturer((int) $instance->_getParam('producerId'));
- if (false == $manuf->existsInDB()) {
- $instance->_redirect($router->assemble(array(), 'index'));
- return;
- }
- $manuf->setStats();
- $instance->_breadCrumbs->add(str_replace('%s', $manuf->manufacturer->name, Locale_Manager::translate('"%s" products')), '');
- $instance->view->router_name = 'producer';
- $instance->handleSEO($manuf);
- break;
- case 'loyalty':
- $instance->_breadCrumbs->add(Locale_Manager::translate('Exchangeable products in the loyalty program'), '');
- $instance->view->router_name = 'loyaltyList';
- $instance->view->loyalty_exchange = true;
- $instance->view->basketAddRoute = 'loyaltyExchange';
- $instance->view->productRoute = 'productExchange';
- break;
- }
- } else {
- $id = $instance->_hasParam('categoryId') ? (int) $instance->_getParam('categoryId') : 0;
- Zend_Registry::set('categoryId', $id);
- $instance->view->sort_links = true;
- $list_type = 'category';
- if ($instance->_hasParam('searchquery')) {
- if ($id <= 0) {
- $instance->view->router_name = 'searchQuery';
- }
- $instance->view->google = '';
- }
- $products = new Logic_ProductList();
- $cm_ent = new Entity_CategoriesMap();
- $pc_ent = new Entity_ProductsCategories();
- if ($id > 0) {
- $cat = new Logic_Category($id);
- if (!isset($_SESSION['poicvbgh']) && !$cat->translation->active && !($instance->_hasParam('preview') && Zend_Controller_Front::getInstance()->getParam(Access_Manager::ADMIN_IS_LOGGED_IN))) {
- $instance->_redirect($router->assemble(array(), 'index'));
- return;
- }
- if (true == $cat->missedLanguage()) {
- $instance->_redirect($router->assemble(array(), 'index'));
- return;
- }
- $cat->setStats();
- if (strlen($cat->translation->description))
- $instance->view->category_description = $cat->translation->description;
- $category_links = array();
- foreach ($cat->getCategoryPath(false) as $c)
- $category_links[$c->translation->name] = $router->assembleCategory(array(
- 'categoryName' => $c->translation->name,
- 'categoryId' => $c->category->category_id,
- 'page' => 1,
- 'view' => $view,
- 'sort' => 1,
- ), $c->category->category_id);
- foreach ($category_links as $k => $v)
- $instance->_breadCrumbs->add($k, $v);
- $instance->_breadCrumbs->add($cat->translation->name, '');
- if (Zend_Controller_Front::getInstance()->getParam(Access_Manager::ADMIN_IS_LOGGED_IN) && $this->_getParam('preview') || isset($_SESSION['poicvbgh'])) {
- View_Smarty::skipCache();
- $select = Search_Filter_Products::getProductsSearchSelect($cat->getIdentifier(), false);
- } else {
- $select = Search_Filter_Products::getProductsSearchSelect($cat->getIdentifier());
- }
- $request = Zend_Controller_Front::getInstance()->getRequest();
- if (Access_ClientManager::isLoggedIn() && $_SESSION['only_my_products'] == true || $request->getParam('only_my_products') == 1) {
- if ($request->getParam('only_my_products') != 2) {
- // Entity_UserMyproducts::cleanFlyweight();
- // Entity_ProductsCategories::cleanFlyweight();
- $user = Logic_UserOnline::getUser();
- $user = $user->toArray();
- $select->setUseCache(false);
- $user_id = $user['__userOnline']['data']['user_id'];
- $select->joinRight('user_myproducts', 'user_myproducts.stock_id = products_categories.product_id', null);
- $select->where('user_myproducts.user_id = ?', $user_id);
- // Entity_UserMyproducts::cleanFlyweight();
- }
- }
- if (1 == $sort or 5 == $sort)
- $select->order(array('products_translations.order DESC', Locale_Manager::collatedOrder('products_translations.name ASC')));
- elseif (2 == $sort)
- $select->order(Locale_Manager::collatedOrder('products_translations.name DESC'));
- elseif ($sort == 3 or $sort == 4) {
- $select->join(array('priceorder' => 'products_stock'), 'products.product_id = priceorder.product_id and priceorder.default = 1', null);
- $select->order('priceorder.comp_promo_price ' . (3 == $sort ? 'ASC' : 'DESC'));
- }
- $filter = Zend_Registry::get('Search_Filter_Products');
- if ($filter->hasData()) {
- View_Smarty::skipCache();
- $products = $filter->search(array($id), $select);
- } else {
- $products->fillFromSelect($select);
- }
- if ($instance->_hasParam('searchquery')) {
- $instance->_breadCrumbs->add(Locale_Manager::translate('Products found: %d', $products->count()), '');
- }
- if ($has_filer_box) {
- $groups = $filter->buildFilter(array($id), null, array(), false, Config_Manager::getConfigValue('filters', 'counter'));
- //$instance->view->filter_groups = $groups;
- $instance->view->filter_type = Config_Manager::getConfigValue('filters', 'type');
- $instance->view->filter_counter = (int) Config_Manager::getConfigValue('filters', 'counter');
- }
- $instance->view->sort_links = true;
- $instance->view->category_name = $cat->translation->name;
- $instance->view->category_id = (int) $cat->getIdentifier();
- $instance->handleSeo($cat);
- } else {
- if ($instance->_hasParam('searchquery')) {
- $s = preg_replace('/\s+/', ' ', (string) $instance->_getParam('searchquery'));
- $s = explode(' ', $s);
- $instance->handleSeo(array('search' => implode(', ', $s)));
- }
- if (Zend_Registry::isRegistered('Search_Filter_Products')) {
- $filter = Zend_Registry::get('Search_Filter_Products');
- if ($filter->hasData()) {
- View_Smarty::skipCache();
- $list = new Logic_CategoryList();
- $select2 = $list->select();
- $select2->where('root = ?', 1);
- $select2->join('categories_translations', 'categories_translations.category_id = categories.category_id', null);
- $select2->where('categories_translations.lang_id = ?', Locale_Manager::getLanguageId());
- if (!isset($_SESSION['poicvbgh'])) {
- $select2->where('categories_translations.active = ?', 1);
- }
- $select2->order('order ASC');
- $list->fillFromSelect($select2);
- if ($list->count() == 0) {
- $list->fillAll();
- }
- if ($list->count() == 0) {
- $products = new Logic_ProductList();
- } else {
- $select = Search_Filter_Products::getProductsSearchSelect($list->getIdentifiers());
- if (1 == $sort or 5 == $sort)
- $select->order(array('products_translations.order DESC', Locale_Manager::collatedOrder('products_translations.name ASC')));
- elseif (2 == $sort)
- $select->order(Locale_Manager::collatedOrder('products_translations.name DESC'));
- elseif ($sort == 3 or $sort == 4) {
- $select->join(array('priceorder' => 'products_stock'), 'products.product_id = priceorder.product_id and priceorder.default = 1', null);
- $select->order('priceorder.comp_promo_price ' . (3 == $sort ? 'ASC' : 'DESC'));
- }
- $products = $filter->search($list->getIdentifiers(), $select);
- if ($instance->_hasParam('searchquery')) {
- $instance->_breadCrumbs->add(Locale_Manager::translate('Products found: %d', $products->count()), '');
- }
- if ($has_filer_box) {
- $providers = array();
- if (Config_Manager::getConfigValue('filters', 'category_search')) {
- if (!$filter->hasProvider('Search_Filter_Products_Provider_Category')) {
- $filter->addProvider('Search_Filter_Products_Provider_Category');
- }
- $provider = $filter->getProvider('Search_Filter_Products_Provider_Category');
- $provider->setDepth(0);
- $providers[] = $provider;
- } else {
- if ($filter->hasProvider('Search_Filter_Products_Provider_Category')) {
- $filter->removeProvider('Search_Filter_Products_Provider_Category');
- }
- }
- if ($filter->hasProvider('Search_Filter_Products_Provider_Producer')) {
- $provider = $filter->getProvider('Search_Filter_Products_Provider_Producer');
- $providers[] = $provider;
- }
- if ($filter->hasProvider('Search_Filter_Products_Provider_Price')) {
- $provider = $filter->getProvider('Search_Filter_Products_Provider_Price');
- $provider->createRanges(false);
- $providers[] = $provider;
- }
- if (count($providers)) {
- $groups = $filter->buildFilter($list->getIdentifiers(), null, array(), false, Config_Manager::getConfigValue('filters', 'counter'), $providers);
- //$instance->view->filter_groups = $groups;
- $instance->view->filter_type = Config_Manager::getConfigValue('filters', 'type');
- $instance->view->filter_counter = (int) Config_Manager::getConfigValue('filters', 'counter');
- }
- }
- }
- }
- }
- }
- }
- if (!is_null($groups) and $has_filer_box) {
- $cgid = null;
- foreach ($groups as $k => &$g) {
- switch ($g['provider']) {
- case 'Search_Filter_Products_Provider_Category':
- $cgid = $k;
- break;
- case 'Search_Filter_Products_Provider_Price':
- if (0 == count($products) && 0 == count($g['items'])) {
- unset($groups[$k]);
- }
- if ((0 == (int) Config_Manager::getConfigValue('filters', 'price'))) {
- $groups[$k]['items'] = array();
- }
- break;
- }
- }
- if (Config_Manager::getConfigValue('filters', 'category') && $id > 0 && $cat instanceof Logic_Category) {
- $url = null;
- if ($instance->_hasParam('searchquery')) {
- $url = $router->assemble(array(), 'searchQuery');
- } elseif ($cat->getParent() > 0) {
- $pcat = $cat->getParentCategory();
- $url = $router->assembleCategory(array(
- 'categoryId' => (int) $pcat->getIdentifier(),
- 'categoryName' => $pcat->translation->name,
- ), $pcat->getIdentifier());
- }
- if (null === $cgid) {
- array_unshift($groups, array(
- 'name' => Locale_Manager::translate('Categories'),
- 'items' => array(
- array(
- 'name' => $cat->translation->name,
- 'active' => true,
- 'link_add' => null,
- 'link_remove' => $url,
- 'link_solo' => null,
- 'counter' => $products->count(),
- ),
- ),
- 'provider' => 'Search_Filter_Products_Provider_Category',
- ));
- } elseif (null !== $url) {
- foreach ($groups[$cgid]['items'] as &$i) {
- $i['indent'] = true;
- }
- array_unshift($groups[$cgid]['items'], array(
- 'name' => $cat->translation->name,
- 'active' => true,
- 'link_add' => null,
- 'link_remove' => $url,
- 'link_solo' => null,
- 'counter' => $products->count(),
- ));
- }
- }
- SEO_Handler::setFilterGroups($groups);
- $instance->view->filter_groups = $groups;
- }
- //my query
- $modelAdapter = Entity_Abstract::getDefaultAdapter();
- $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 ');
- $instance->view->view = $view;
- $instance->view->sort = $sort;
- $instance->view->list_type = $list_type;
- $router->routeParams($instance->getRequest()->getParams());
- $paginator = Zend_Paginator::factory($products);
- $paginator->setCurrentPageNumber($page);
- $paginator->setItemCountPerPage((int) Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_LAYOUT_MANAGER)->getSkin()->getSettings()->productlist->productspersite);
- $paginator->setPageRange(5);
- $instance->view->products = $paginator;
- $instance->view->pages = $paginator->getPages();
- $instance->handleSEO($paginator, 'paginator');
- if (!View_Smarty::isCached()) {
- $snippet = Logic_Snippet::getCode(Logic_Snippet::TYPE_PRODUCT_LIST);
- if ($snippet) {
- $vars = array(
- 'products' => array()
- );
- foreach ($paginator as $p) {
- $vars['products'][] = $p->getVariables();
- }
- $instance->view->snippet_product_list = Parser_Processor::onetimeCompile($snippet, $vars, array(
- 'ignore_non_breaking_space' => true,
- 'is_html_template' => true
- ));
- } else {
- $instance->view->snippet_product_list = "";
- }
- }
- $instance->view->description = $getDescription;
- if (is_null($instance->view->body_class)) {
- $instance->view->body_class = 'shop_product_list';
- $instance->view->body_id = 'shop_category' . $id;
- }
- $instance->_handleFlashMessages();
- }
- public function Product_positionAction($instance) {
- if ($_SESSION['auth']['mode']) {
- $product_id = $_POST['product_id'];
- $category_id=$_POST['category_id'];
- $content = $_POST['text'];
- if(!empty($product_id) && !empty($category_id) && !empty($content)) {
- $modelAdapter = Entity_Abstract::getDefaultAdapter();
- $getDescription = $modelAdapter->fetchAssoc('SELECT product_id, category_id, description FROM `product_description` WHERE `product_id` = '.$product_id.' and `category_id` = '.$category_id);
- if($getDescription){
- $data = 'isset';
- }else{
- $data = 'empty';
- $modelAdapter->query('INSERT INTO `product_description` VALUES(null,'.$product_id.','.$category_id.',"'.$content.'") ');
- }
- }else{
- $data = 'empty data';
- }
- }else{
- $data = 'permission';
- }
- echo Zend_Json::encode(array('status' => $data));
- }
- public function Product_mailfriendAction($instance) {
- View_Smarty::skipCache();
- $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
- if ($instance->_hasParam('productId') && $id = (int) $instance->_getParam('productId')) {
- $instance->view->prod_id = $id;
- if ($instance->getRequest()->isPost()) {
- $form = new Form_Shop_MailFriend();
- if ($form->isValid($_POST)) {
- $val = $form->getValues();
- foreach ($val as $k => $v)
- $val[$k] = Purifier_HTML::strip_tags($v);
- $template = Mail_Manager::getMailTemplate(Mail_Manager::MAIL_FRIEND);
- $prod = new Logic_Product($id);
- if (false == $prod->existsInDB()) {
- $instance->_redirect($router->assemble(array(), 'index'));
- return;
- }
- $template->mail->from_name = $val['from'];
- $url = $router->assembleProduct(array(
- 'productName' => $prod->translation->name,
- 'productId' => $id,
- ), $id, true);
- $message = new Mail_Message($template, true);
- $message->setVarArray(array(
- 'product_name' => $prod->translation->name,
- 'product_link' => $url,
- 'from' => $val['from'],
- ));
- $message->addRecipient($val['email'], false);
- try {
- $metafields = new Metafield_Manager();
- foreach ($metafields->getMetafieldObjectList() as $m) {
- $key = "metafield.system." . $m->metafield->metafield->namespace . "." . $m->metafield->metafield->key;
- $message->setVar($key, Zend_Controller_Action_HelperBroker::getExistingHelper('ViewRenderer')->view->escape($m->value->value));
- }
- $metafields = $prod->metafields;
- foreach ($metafields->getMetafieldObjectList() as $m) {
- $key = "metafield.product." . $m->metafield->metafield->namespace . "." . $m->metafield->metafield->key;
- $message->setVar($key, Zend_Controller_Action_HelperBroker::getExistingHelper('ViewRenderer')->view->escape($m->value->value));
- }
- Mail_Manager::send($message, true);
- $instance->_flashMessanger->addSuccess(Locale_Manager::translate('E-mail message has been sent.'));
- $instance->_redirect($url);
- return;
- } catch (Exception $e) {
- $instance->_errorLog->err($e);
- $instance->_flashMessanger->addError(Locale_Manager::translate('Error while sending e-mail.'));
- $instance->view->data = $val;
- }
- } else {
- $instance->_flashMessanger->addError(Locale_Manager::translate('Filled form contains errors.'));
- $instance->view->data = $form->getUnfilteredValues();
- $instance->view->data_error = $form->getMessages();
- }
- }
- $instance->view->body_class = 'shop_product_mailfriend';
- $instance->_handleFlashMessages();
- } else {
- $instance->_redirect($router->assemble(array(), 'index'));
- }
- }
- public function Product_indexAction($instance) {
- View_Smarty::skipCache();
- $instance->addCachedVariables();
- $session = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_SESSION);
- $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
- $view = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_LAYOUT_MANAGER)->getSkin()->getSettings()->productlist->mode;
- $user = Logic_UserOnline::getUser();
- $id = (int) $instance->_getParam('productId');
- $p = Logic_Product::loadInstance($id);
- if (false == $p->existsInDB() || true == $p->missedLanguage()) {
- $instance->_redirect($router->assemble(array(), 'index'));
- return;
- }
- $p->setStats();
- $options = Zend_Session::getOptions();
- if (is_array($options) && isset($options['name'][0])) {
- $cn = 'lastProducts-' . Locale_Manager::getLocale();
- } else {
- $cn = '';
- }
- if (isset($cn[0]) && isset($_COOKIE[$cn][0])) {
- $lp = explode(',', $_COOKIE[$cn]);
- } else {
- $lp = array();
- }
- $cp = '/' . trim(Config_Manager::getConfigValue('core', 'SITE_PATH'), '/');
- array_unshift($lp, $id);
- $lp = array_unique($lp);
- if (count($lp) > 30) {
- $lp = array_slice($lp, 0, 30);
- }
- try {
- $skin = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_LAYOUT_MANAGER)->getSkin();
- if ($skin->hasRecentBox() && !Zend_Registry::isRegistered(System_Bootstrap::REGISTRY_INDEX_MEMCACHED_NGINX)) {
- setcookie($cn, implode(',', $lp), mktime(0, 0, 0, 1, 1, 2 + date('Y')), $cp);
- }
- } catch (Exception $e) {
- $instance->_errorLog->err($e);
- }
- $cat_id = (int) $p->defaultCategory->getIdentifier();
- Zend_Registry::set('categoryId', $cat_id);
- $category_links = array();
- foreach ($p->defaultCategory->getCategoryPath() as $c) {
- if (strlen($c->translation->name)) {
- $category_links[$c->translation->name] = $router->assembleCategory(array(
- 'categoryName' => $c->translation->name,
- 'categoryId' => $c->category->category_id,
- 'page' => 1,
- 'view' => $view,
- 'sort' => 1,
- ), $c->category->category_id);
- }
- }
- /* $instance->_breadCrumbs->add(Locale_Manager::translate('All products'), Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER)->assemble(array(
- 'categoryName' => Locale_Manager::translate('All products'),
- 'categoryId' => 0,
- 'page' => 1,
- 'view' => 1,
- 'sort' => 1,
- ), 'category')); */
- foreach ($category_links as $k => $v)
- $instance->_breadCrumbs->add($k, $v);
- $instance->_breadCrumbs->add($p->translation->name, '');
- Entity_UserMyproducts::cleanFlyweight();
- $instance->view->id = $id;
- $instance->view->product = $p;
- $instance->view->category_link = $v;
- $instance->view->stock_id = $p->defaultStock->stock->stock_id;
- $precats = $p->defaultCategory->getCategoryPath(false)->toArray();
- $this->view->precategories = array_reverse($precats);
- if (!isset($_SESSION['poicvbgh']) && 0 == (int) $p->translation->active && !(Zend_Controller_Front::getInstance()->getParam(Access_Manager::ADMIN_IS_LOGGED_IN) && $this->_getParam('preview'))) {
- return;
- }
- $attrs = array();
- $names = array();
- if (count($p->attributes) > 0) {
- foreach ($p->attributes as $attrib) {
- $presid = (int) $attrib['pres_id'];
- $pres = Logic_Presentation::loadInstance($presid);
- if (1 == (int) $pres->presentation->active) {
- $x = (int) $attrib['attribute_id'];
- if (!isset($names[$x])) {
- $names[$x] = Logic_Attribute::loadInstance($x);
- }
- if (1 == (int) $names[$x]->attribute->active) {
- $value = '';
- switch ((int) $names[$x]->attribute->type) {
- case 2:
- foreach ($names[$x]->options as $o)
- if ($attrib['value'] == (int) $o->option_id)
- $value = $o->value;
- break;
- case 1:
- $value = (int) $attrib['value'];
- break;
- case 0:
- $value = $attrib['value'];
- break;
- }
- $attrs[] = array(
- 'name' => $names[$x]->attribute->name,
- 'type' => (int) $names[$x]->attribute->type,
- 'value' => $value,
- );
- }
- }
- }
- }
- $instance->view->attrs = $attrs;
- $instance->view->gallery = $p->galleryImages;
- $instance->view->jsgallery = true;
- $instance->view->view = $view;
- $instance->view->can_vote = !isset($_COOKIE['product_vote_' . $id]);
- $instance->view->vote_stars = $p->getVoteStars();
- if (1 == (int) Config_Manager::getConfigValue('comments', 'COMMENTS_ON')) {
- $comments = new Logic_ProductCommentList();
- $select = $comments->select();
- $select->where('product_id = ?', (int) $p->getIdentifier());
- $select->where('lang_id = ?', Locale_Manager::getLanguageId());
- if (1 == (int) Config_Manager::getConfigValue('comments', 'COMMENTS_MODERATION'))
- $select->where('validated = ?', 1);
- $comments->fillFromSelect($select, false);
- $instance->view->product_comments = $comments;
- $instance->view->can_comment = ( 0 == (int) Config_Manager::getConfigValue('comments', 'COMMENTS_FOR_USERS') || Access_ClientManager::isLoggedIn() );
- } else {
- $instance->view->product_comments = null;
- $instance->view->can_comment = false;
- }
- $related_products = new Logic_ProductList();
- $ent = new Entity_ProductsRelated();
- $select = $ent->select()->from($ent, 'product2');
- $select->join('products_translations', 'products_translations.product_id = products_related.product2', null);
- if (!isset($_SESSION['poicvbgh'])) {
- $select->where('products_translations.active = ?', 1);
- }
- $select->where('products_translations.lang_id = ?', Locale_Manager::getLanguageId());
- $select->where('products_related.product1 = ?', $p->getIdentifier());
- $select->order('products_related.order ASC');
- $related_products->fillFromSelect($select, false);
- $instance->view->related_products = $related_products;
- //chuj
- $modelSpare = new Entity_SpareProduct();
- $select = $modelSpare->select();
- $select->where('product_id = ?', (int) $id);
- $productSpare = $modelSpare->fetchAll($select);
- $instance->view->spare = $productSpare;
- if (count($p->optionsStock)) {
- $options = array();
- $default = array();
- foreach ($p->optionsStock as $stock) {
- if (1 == (int) $stock->stock->active || isset($_SESSION['poicvbgh'])) {
- $x = array();
- foreach ($stock->values as $value) {
- $x[] = $value->ovalue->value->ovalue_id;
- }
- $options['stock_' . (int) $stock->stock->stock_id] = $x;
- if (1 == (int) $stock->stock->default) {
- $default = $x;
- }
- }
- }
- $instance->view->options_configuration = base64_encode(Zend_Json::encode($options));
- $instance->view->options_default = base64_encode(Zend_Json::encode($default));
- }
- $body_class = 'shop_product';
- if ($cat_id > 0) {
- $body_class .= ' shop_product_from_cat_' . $cat_id;
- }
- $instance->view->body_class = $body_class;
- $instance->view->body_id = 'shop_product' . $id;
- $instance->_handleFlashMessages();
- $instance->handleSeo($p);
- $og = array();
- $host = $instance->getRequest()->getServer();
- $host = 'http' . ($instance->getRequest()->isSecure() ? 's' : '') . '://' . $host['HTTP_HOST'];
- $url = $host . $instance->getRequest()->getRequestUri();
- $og['type'] = 'product';
- $og['url'] = $url;
- $og['site_name'] = Config_Manager::getConfigValue('network', 'SHOP_NAME');
- $og['title'] = $p->translation->name;
- $photo = $p->mainImageName();
- if (false != $photo) {
- $og['image'] = $host . View_Smarty_Helper_ImageUrl::imageUrl(array(
- 'type' => 'productGfx',
- 'width' => 300,
- 'height' => 300,
- 'image' => $photo,
- 'noupscale' => true,
- ), null);
- }
- if (strlen($p->translation->short_description)) {
- $og['description'] = strip_tags($p->translation->short_description);
- } elseif (strlen($p->translation->description)) {
- $og['description'] = strip_tags($p->translation->description);
- } else {
- $og['description'] = $p->translation->name;
- }
- if (strlen($og['description']) > 100) {
- $w = explode("\n", wordwrap($og['description'], 100, "\n"));
- $og['description'] = $w[0];
- }
- $cp = '';
- if (Config_Manager::hasConfigValue('company', 'COMPANY_PHONE')) {
- $cp = Config_Manager::getConfigValue('company', 'COMPANY_PHONE');
- $cp = preg_replace('/[^0-9\+]/', '', $cp);
- }
- $instance->view->company_phone = $cp;
- $instance->view->opengraph_header = $og;
- $skinset = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_LAYOUT_MANAGER)->getSkin()->getSettings()->productdetails;
- if (1 == (int) $skinset->fb_like || 1 == (int) $skinset->fb_chat || 1 == (int) $skinset->fb_send) {
- $instance->view->xfbml = true;
- }
- if (Zend_Controller_Front::getInstance()->getParam(Access_Manager::ADMIN_IS_LOGGED_IN) && $instance->_getParam('preview')) {
- $instance->view->adminPreview = true;
- }
- if (1 == (int) $instance->_getParam('exchange', 0)) {
- if (!$user->user instanceof Logic_User || !Loyalty_Program::isEnabled() || !Loyalty_Program::exchangeModeProducts()) {
- $instance->_redirect($router->assembleProduct(array(
- 'productId' => $p->getIdentifier(),
- 'productName' => $p->translation->name,
- ), $p->getIdentifier()));
- return;
- }
- $instance->view->basketAddRoute = 'loyaltyExchange';
- $instance->view->productRoute = 'productExchange';
- $instance->view->loyalty_points = false;
- $instance->view->loyalty_exchange = true;
- } else {
- if (Loyalty_Program::orderGivesPoints()) {
- $points = $p->defaultStock->loyaltyPointsForOrder();
- if (false !== $points) {
- $instance->view->loyalty_points = View_Smarty_Helper_Float::float(array('value' => $points, 'precision' => 0), null);
- $instance->view->loyalty_msg_title = Locale_Manager::translate('Loyalty program points');
- $loyalty_msgs = array(
- 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.'),
- );
- if (!$user->user) {
- $loyalty_msgs[] = Locale_Manager::translate('Only available to registered customers.');
- }
- $instance->view->loyalty_msgs = $loyalty_msgs;
- } else {
- $instance->view->loyalty_points = false;
- }
- } else {
- $instance->view->loyalty_points = false;
- }
- $instance->view->loyalty_exchange = false;
- }
- $comparisonField = Logic_ProductAdditionalFieldList::getComparisonField();
- $productCode = null;
- if ($comparisonField != 'code') {
- $productCode = $p->stock->getAdditionalField($comparisonField);
- }
- if ($productCode === null) {
- $productCode = $p->stock->stock->code;
- }
- $instance->view->product_code = $productCode;
- if (!View_Smarty::isCached()) {
- $snippet = Logic_Snippet::getCode(Logic_Snippet::TYPE_PRODUCT);
- if ($snippet) {
- $instance->view->snippet_product = Parser_Processor::onetimeCompile($snippet, $p->getVariables(), array(
- 'ignore_non_breaking_space' => true,
- 'is_html_template' => true
- ));
- } else {
- $instance->view->snippet_product = "";
- }
- }
- }
- public function Product_questionAction($instance) {
- $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
- $id = (int) $instance->_getParam('productId');
- $product = new Logic_Product($id);
- if (false == $product->existsInDB()) {
- $instance->_redirect($router->assemble(array(), 'index'));
- return;
- }
- $instance->view->productId = $id;
- if ($instance->getRequest()->isPost()) {
- $form = new Form_Shop_Question();
- if ($form->isValid($_POST)) {
- $val = $form->getValues();
- $val['question'] = Purifier_HTML::strip_tags($val['question'], ENT_NOQUOTES);
- $val['from'] = Purifier_HTML::strip_tags($val['name'], ENT_NOQUOTES);
- $val['reply'] = $val['mail'];
- $val['ip'] = $_SERVER['REMOTE_ADDR'];
- $val['product_id'] = $id;
- $val['product_name'] = $product->translation->name;
- $val['product_link'] = $router->assembleProduct(array(
- 'productName' => $product->translation->name,
- 'productId' => $id,
- ), $id, true);
- $template = Mail_Manager::getMailTemplate(Mail_Manager::MAIL_PRODUCT_QUESTION);
- $template->mail->from_name = $val['from'];
- $message = new Mail_Message($template, true);
- $message->setReplyTo($val['reply']);
- $message->setVarArray($val);
- $message->addRecipient(Config_Manager::getConfigValue('company', 'COMPANY_EMAIL'), false);
- $metafields = new Metafield_Manager();
- foreach ($metafields->getMetafieldObjectList() as $m) {
- $key = "metafield.system." . $m->metafield->metafield->namespace . "." . $m->metafield->metafield->key;
- $message->setVar($key, Zend_Controller_Action_HelperBroker::getExistingHelper('ViewRenderer')->view->escape($m->value->value));
- }
- $metafields = $product->metafields;
- foreach ($metafields->getMetafieldObjectList() as $m) {
- $key = "metafield.product." . $m->metafield->metafield->namespace . "." . $m->metafield->metafield->key;
- $message->setVar($key, Zend_Controller_Action_HelperBroker::getExistingHelper('ViewRenderer')->view->escape($m->value->value));
- }
- try {
- Mail_Manager::send($message, true);
- $instance->_flashMessanger->addSuccess(Locale_Manager::translate('Thank you for your inquiry, we will contact you as soon as possible.'));
- $instance->view->mail_send = true;
- } catch (Exception $e) {
- $instance->_errorLog->err($e);
- $instance->_flashMessanger->addError(Locale_Manager::translate('Error while sending e-mail.'));
- $instance->view->data = $val;
- }
- } else {
- $instance->_flashMessanger->addError(Locale_Manager::translate('Filled form contains errors.'));
- $instance->view->data = $form->getUnfilteredValues();
- $instance->view->data_error = $form->getMessages();
- }
- }
- $instance->_handleFlashMessages();
- }
- public function Product_getrecommendedAction($instance) {
- if ($instance->getRequest()->isOptions()) {
- header('Access-Control-Allow-Headers: origin, content-type, accept, x-requested-with');
- header('Access-Control-Allow-Method: GET');
- header('Access-Control-Allow-Origin: *');
- return;
- }
- header('Access-Control-Allow-Origin: *');
- header('Content-type: application/json');
- //$settings = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_LAYOUT_MANAGER)->getSkin()->getSettings();
- //$random = (1 == (int) $settings->main->random);
- $random = false; /* ToDo: ----^ */
- $entity = new Entity_ProductsTranslations();
- $select = $entity->select()->from($entity, 'product_id');
- $select->where('lang_id = ?', Locale_Manager::getLanguageId());
- $select->where('active = ?', 1);
- $select->where('main_page = ?', 1);
- if (!$random) {
- $select->order(array('main_page_order DESC', 'name ASC'));
- $products = new Logic_ProductList();
- $products->fillFromSelect($select);
- } else {
- $query = $select->query();
- $identifiers = array();
- while ($identifier = $query->fetch(PDO::FETCH_NUM)) {
- $identifiers[] = $identifier[0];
- }
- shuffle($identifiers);
- $products = new Logic_ProductList($identifiers);
- }
- $page = $this->_hasParam('page') ? (int) $this->_getParam('page') : 1;
- if ($page < 1) {
- $page = 1;
- }
- $paginator = Zend_Paginator::factory($products);
- $paginator->setCurrentPageNumber($page);
- //$paginator->setItemCountPerPage( (int) $settings->main->productspersite ); /* ToDo */
- $paginator->setItemCountPerPage(30);
- $paginator->setPageRange(5);
- foreach ($paginator as $prod) {
- $prods[] = $prod->toArrayForJSON();
- }
- echo Zend_Json::encode($prods);
- }
- public function Product_getproductAction($instance) {
- header('Content-type: application/json');
- try {
- Access_ClientManager::reValidate();
- if (!Access_ClientManager::isLoggedIn()) {
- //echo 0;
- //return;
- }
- $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
- if ($this->_hasParam('id')) {
- $id = (int) $this->_getParam('id');
- if ($id <= 0) {
- echo 0;
- return;
- }
- } else {
- echo 0;
- return;
- }
- $product = Logic_Product::loadInstance($id);
- if (false === $product->existsInDb() || 0 === (int) $product->translation->active || isset($_SESSION['poicvbgh'])) {
- echo 0;
- return;
- }
- $json = array(
- 'id' => (int) $product->getIdentifier(),
- 'name' => $product->translation->name,
- 'code' => $product->getDefaultCode(),
- 'active' => (int) $product->translation->active,
- 'unit' => $product->unit->translation->name,
- 'rate' => (float) $product->vote->rate,
- 'votes' => (float) $product->vote->votes,
- 'stockId' => (int) $product->defaultStock->getIdentifier(),
- 'url' => $router->assembleProduct(array(
- 'productName' => $product->translation->name,
- 'productId' => $product->getIdentifier(),
- ), $product->getIdentifier(), System_Router::ROUTE_TYPE_DEFAULT, true, null, true),
- );
- if ($product->defaultStockOnly()) {
- $json['basket'] = $router->assemble(array(
- 'stockId' => 'post',
- ), 'basketAdd', System_Router::ROUTE_TYPE_DEFAULT, false, null, true);
- } else {
- $json['basket'] = $router->assemble(array(
- 'stockId' => (int) $product->defaultStock->getIdentifier(),
- ), 'basketAdd', System_Router::ROUTE_TYPE_DEFAULT, false, null, true);
- }
- $json['availability']['name'] = $product->defaultStock->availability->translation->name;
- if ($product->defaultStock->availability->availability->photo) {
- $json['availability']['img'] = $product->defaultStock->availability->getUrl();
- }
- if ($product->defaultStock->delivery) {
- $json['delivery'] = $product->defaultStock->delivery->translation->name;
- }
- $json['price'] = array(
- 'gross' => array(
- 'base' => View_Smarty_Helper_Currency::currency(array('value' => $product->defaultStock->getPrice(false)), null),
- 'base_float' => (float) $product->defaultStock->getPrice(false),
- ),
- 'net' => array(
- 'base' => View_Smarty_Helper_Currency::currency(array('value' => $product->defaultStock->getPrice(true)), null),
- 'base_float' => (float) $product->defaultStock->getPrice(true),
- ),
- );
- if ($product->specialOffer) {
- $json['price']['gross']['promo'] = View_Smarty_Helper_Currency::currency(array('value' => $product->defaultStock->getSpecialOfferPrice(false)), null);
- $json['price']['gross']['promo_float'] = (float) $product->defaultStock->getSpecialOfferPrice(false);
- $json['price']['gross']['final'] = $json['price']['gross']['promo'];
- $json['price']['gross']['final_float'] = $json['price']['gross']['promo_float'];
- $json['price']['net']['promo'] = View_Smarty_Helper_Currency::currency(array('value' => $product->defaultStock->getSpecialOfferPrice(true)), null);
- $json['price']['gross']['promo_float'] = (float) $product->defaultStock->getSpecialOfferPrice(true);
- $json['price']['net']['final'] = $json['price']['net']['promo'];
- $json['price']['net']['final_float'] = $json['price']['net']['promo_float'];
- } else {
- $json['price']['gross']['final'] = $json['price']['gross']['base'];
- $json['price']['gross']['final_float'] = $json['price']['gross']['base_float'];
- $json['price']['net']['final'] = $json['price']['net']['base'];
- $json['price']['net']['final_float'] = $json['price']['net']['base_float'];
- }
- if ($product->product->other_price > 0) {
- $json['price']['other'] = View_Smarty_Helper_Currency::currency(array('value' => $product->product->other_price), null);
- $json['price']['other_float'] = (float) $product->product->other_price;
- }
- if ($product->product->producer_id) {
- $json['producer'] = array(
- 'name' => $product->producer->manufacturer->name,
- );
- if ($product->producer->manufacturer->web) {
- $json['producer']['url'] = $product->producer->manufacturer->web;
- } else {
- $json['producer']['url'] = $router->assembleProducer(array(
- 'producerName' => $product->producer->manufacturer->name,
- 'producerId' => $product->producer->getIdentifier(),
- ), $product->producer->getIdentifier(), System_Router::ROUTE_TYPE_DEFAULT, true, null, true);
- }
- if ($product->producer->manufacturer->gfx) {
- $sp = trim(Config_Manager::getConfigValue('core', 'SITE_PATH'), '/');
- if (strlen($sp)) {
- $sp = '/' . $sp;
- }
- $json['producer']['img'] = $sp . '/' . $product->producer->getUrl();
- }
- }
- $json['newProduct'] = $product->isNew();
- $json['description'] = $product->translation->description;
- $json['short_description'] = $product->translation->short_description;
- $json['additional_description'] = $product->translation->additional_description;
- //$json['options'] = $product->getOptionsConfigurationStruct();
- echo Zend_Json::encode($json);
- } catch (Exception $e) {
- $instance->_errorLog->debug('Error while downloading product (' . $id . '): ' . $e->getMessage());
- echo 0;
- }
- }
- public function Product_getstockAction($instance) {
- header('Content-type: application/json');
- try {
- Access_ClientManager::reValidate();
- if (!Access_ClientManager::isLoggedIn()) {
- //echo 0;
- //return;
- }
- $id = (int) $instance->_getParam('stock');
- if ($id <= 0) {
- echo 0;
- return;
- }
- $options = array();
- $currentOv = $currentOid = null;
- if ($instance->_hasParam('currentVirt')) {
- $virt = explode('=', $instance->_getParam('currentVirt'));
- if (count($virt) === 2) {
- $currentOid = (int) $virt[0];
- $currentOv = (int) $virt[1];
- }
- }
- if ($instance->_hasParam('virt')) {
- $virt = explode('&', $instance->_getParam('virt'));
- foreach ($virt as $v) {
- $v = explode('=', $v);
- if (2 == count($v)) {
- $oid = (int) $v[0];
- $ov = (int) $v[1];
- if ($oid && $ov) {
- $options[$oid] = $ov;
- }
- }
- }
- $virt = array(); //stack up again for return to JSON
- foreach ($options as $k => $v) {
- $virt[] = $k . '=' . $v;
- }
- $virt = implode('&', $virt);
- } else {
- $virt = 'default';
- }
- $p = new Logic_ProductStock($id);
- if (!$p->existsInDB()) {
- echo 0;
- return;
- }
- $photo = $p->mainImageName($currentOid, $currentOv);
- $photoOrig = $photo;
- if (false != $photo) {
- $photoOrig = View_Smarty_Helper_ImageUrl::imageUrl(array(
- 'type' => 'productGfx',
- 'image' => $photo
- ), null);
- $photo = View_Smarty_Helper_ImageUrl::imageUrl(array(
- 'type' => 'productGfx',
- 'width' => (int) $instance->_getParam('imgwidth'),
- 'height' => (int) $instance->_getParam('imgheight'),
- 'image' => $photo,
- 'overlay' => 1,
- ), null);
- }
- $buying = (1 !== (int) Config_Manager::getConfigValue('shopping', 'OFF_SHOPPING'));
- $ret = array(
- 'sid' => (int) $p->getIdentifier(),
- 'photo' => $photo,
- 'photo_orig' => $photoOrig,
- 'photo_id' => $p->mainImageId(),
- 'availability_photo' => $p->availability->getUrl(true),
- 'availability' => $p->availability->translation->name,
- 'delivery' => ( $p->delivery ? $p->delivery->translation->name : false ),
- 'price' => View_Smarty_Helper_Currency::currency(
- array('value' => $p->getPrice(false, $options)), null),
- 'net_price' => View_Smarty_Helper_Currency::currency(
- array('value' => $p->getPrice(true, $options)), null),
- 'special_offer' => ( $p->product->specialOffer ?
- View_Smarty_Helper_Currency::currency(
- array('value' => $p->getSpecialOfferPrice(false, $options), 'ceil' => 2), null) : false ),
- 'net_special_offer' => ( $p->product->specialOffer ?
- View_Smarty_Helper_Currency::currency(
- array('value' => $p->getSpecialOfferPrice(true, $options), 'ceil' => 2), null) : false ),
- 'can_buy' => ($buying && 1 == (int) $p->availability->availability->can_buy),
- 'unit' => $p->product->unit->translation->name,
- 'code' => ( strlen($p->stock->code) ? $p->stock->code : $p->product->stock->stock->code ),
- 'ean' => ( strlen($p->stock->ean) ? $p->stock->ean : $p->product->stock->stock->ean ),
- 'loyaltypts_float' => $p->loyaltyPointsForOrder(false, $options),
- 'loyaltypts' => $p->loyaltyPointsForOrder(true, $options),
- 'loyaltyprice' => $p->loyaltyPointsPrice(true, $options),
- 'stock' => (float) $p->stock->stock,
- 'virt' => $virt,
- );
- if (Access_ClientManager::isLoggedIn()) {
- $ret['is_subscribed'] = ($p->getAvailabilityNotifyByUser() !== null);
- } else {
- $ret['is_subscribed'] = false;
- }
- echo Zend_Json::encode($ret);
- } catch (Exception $e) {
- $instance->_errorLog->debug('Error while downloading product stock (' . $id . '): ' . $e->getMessage());
- echo 0;
- }
- }
- public function Product_voteAction($instance) {
- header('Content-type: application/json');
- try {
- Access_ClientManager::reValidate();
- if (!Access_ClientManager::isLoggedIn()) {
- //echo 0;
- //return;
- }
- $id = (int) $instance->_getParam('prod');
- if ($id <= 0) {
- echo 0;
- return;
- }
- if (isset($_COOKIE['product_vote_' . $id])) {
- echo 0;
- return;
- }
- $vote = (int) $instance->_getParam('vote');
- if ($vote <= 0 || $vote > 5) {
- echo 0;
- return;
- }
- $p = new Logic_Product($id);
- $p->vote->rate = ( ( floatval($p->vote->rate) * intval($p->vote->votes) ) + $vote ) / ( intval($p->vote->votes) + 1 );
- $p->vote->votes = intval($p->vote->votes) + 1;
- $p->vote->save();
- $p->removeCachedObject();
- $path = Config_Manager::getConfigValue('core', 'SITE_PATH');
- if (!isset($path[0]))
- $path = '/';
- setcookie('product_vote_' . $id, $vote, time() + 86400 * 365, $path);
- echo 1;
- } catch (Exception $e) {
- $instance->_errorLog->debug('Error while voting (' . date('Y-m-d H:i:s') . '): ' . $e->getMessage());
- echo 0;
- }
- }
- public function Product_commentAction($instance) {
- $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
- if (1 == (int) Config_Manager::getConfigValue('comments', 'COMMENTS_ON') &&
- ( 0 == (int) Config_Manager::getConfigValue('comments', 'COMMENTS_FOR_USERS') || Access_ClientManager::isLoggedIn() ) &&
- 1 == (int) Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_LAYOUT_MANAGER)->getSkin()->getSettings()->productdetails->comments &&
- $instance->getRequest()->isPost() && $instance->_hasParam('productId')) {
- $id = (int) $instance->_getParam('productId');
- $product = new Logic_Product($id);
- if (false == $product->existsInDB()) {
- $instance->_redirect($router->assemble(array(), 'index'));
- return;
- }
- $form = new Form_Shop_Comment();
- if ($form->isValid($_POST)) {
- $val = $form->getValues();
- $comm = new Logic_ProductComment();
- $comm->create();
- $comm->comment->product_id = $id;
- $comm->comment->user_name = Purifier_HTML::strip_tags($val['user']);
- $comm->comment->date = date('Y-m-d H:i:s');
- $comm->comment->content = Purifier_HTML::strip_tags($val['comment']);
- $comm->comment->lang_id = Locale_Manager::getLanguageId();
- $comm->comment->user_id = Access_ClientManager::isLoggedIn() ? Logic_UserOnline::getUser()->user->user->user_id : NULL;
- $comm->comment->validated = 0; //intval(1 != (int) Config_Manager::getConfigValue('comments', 'COMMENTS_MODERATION'));
- $comm->save();
- $commid = '#comment' . (int) $comm->getIdentifier();
- if (1 == (int) Config_Manager::getConfigValue('comments', 'COMMENTS_MODERATION'))
- $instance->_flashMessanger->addSuccess(Locale_Manager::translate('Your comment has been added. To display it in the store, it must be approved by the administrator.'));
- else
- $instance->_flashMessanger->addSuccess(Locale_Manager::translate('Your comment has been added. Thank you.'));
- } else {
- $instance->_flashMessanger->addError(Locale_Manager::translate('The content of your review cannot be blank.'));
- $this->storeForRedirect('data', $form->getValues());
- $this->storeForRedirect('data_error', $form->getMessages());
- $commid = '#commentform';
- }
- $instance->_redirect($router->assembleProduct(array(
- 'productName' => $product->translation->name,
- 'productId' => $id,
- ), 'product') . $commid);
- return;
- }
- $instance->_redirect($router->assemble(array(), 'index'));
- }
- public function Product_searchAction($instance) {
- View_Smarty::setCacheTag(array(
- 'Logic_ProductList', 'Logic_Product', 'Logic_ProductStockList', 'Logic_ProductStock', 'Logic_Category', 'Logic_CategoryList',
- 'productImages', 'productFiles', 'productAttributes', 'productVote', 'productTranslation',
- 'Logic_ProductDelivery', 'Logic_ProductDeliveryList', 'Logic_ProductAvailability', 'Logic_ProductAvailabilityList',
- 'Logic_ProductStock', 'Logic_ProductStockList',
- ));
- View_Smarty::skipCache();
- if ($instance->getRequest()->isPost()) {
- $form = new Form_Shop_Search();
- if ($form->isValid($_POST)) {
- $val = $form->getValues();
- if (!isset($val['search'][0])) {
- $instance->_flashMessanger->addError(Locale_Manager::translate('Search field cannot be blank'));
- } else {
- $val['search'] = trim($val['search'], "%");
- $val['search'] = str_replace("/", "%2f", $val['search']);
- $val['search'] = str_replace(":", " ", $val['search']);
- $val['search'] = str_replace("#", "%23", $val['search']);
- $val['search'] = str_replace("\\", "%5c", $val['search']);
- $view = isset($_POST['view'][0]) ? $_POST['view'] : Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_LAYOUT_MANAGER)->getSkin()->getSettings()->productlist->mode;
- $params = array(
- 'page' => 1,
- 'view' => $view,
- 'sort' => 5,
- 'searchquery' => (string) $val['search'],
- );
- $route = 'searchQuery';
- if (isset($val['category'][0])) {
- $id = (int) $val['category'];
- $c = new Logic_Category($id);
- if ($c->existsInDB()) {
- $route = 'category';
- $params['categoryId'] = $id;
- $params['categoryName'] = $c->translation->name;
- }
- }
- if (isset($val['priceto'][0])) {
- $p = (float) Locale_Manager::getFloat($val['priceto']);
- $params['priceto'] = (string) $p;
- }
- if (isset($val['pricefrom'][0])) {
- $p = (float) Locale_Manager::getFloat($val['pricefrom']);
- $params['pricefrom'] = (string) $p;
- }
- if (isset($val['promotion']) && 1 == (int) $val['promotion']) {
- $params['promotion'] = 1;
- }
- if (isset($val['producer'][0])) {
- $params['f_producer_' . $val['producer']] = 1;
- }
- $url = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER)->assemble($params, $route) . '?' . self::googleString($val['search']);
- $instance->_redirect($url);
- return;
- }
- } else {
- $instance->view->data = $form->getUnfilteredValues();
- $instance->view->data_error = $form->getMessages();
- $instance->_flashMessanger->addError(Locale_Manager::translate('Incorrect search criteria.'));
- }
- }
- $producers = new Logic_ManufacturerList();
- $select = $producers->select();
- $select->order('name ASC');
- $producers->fillFromSelect($select);
- $instance->view->producers = $producers;
- $categories = new Logic_CategoryList();
- $ent = new Entity_CategoriesTranslations();
- $select = $ent->select()->from($ent, 'category_id');
- $select->join('categories', 'categories.category_id = categories_translations.category_id', null);
- if (!isset($_SESSION['poicvbgh'])) {
- $select->where('active = ?', 1);
- }
- $select->where('root = ?', 1);
- $select->where('lang_id = ?', Locale_Manager::getLanguageId());
- $select->order('categories.order ASC');
- $instance->view->categories = $categories->fillFromSelect($select);
- $instance->view->filter_price = Config_Manager::getConfigValue('filters', 'PRICE') == 1;
- $instance->view->filter_producer = Config_Manager::getConfigValue('filters', 'PRODUCER') == 1;
- $instance->view->filter_promotion = Config_Manager::getConfigValue('filters', 'PROMOTION') == 1;
- $instance->_breadCrumbs->add(Locale_Manager::translate('Product search'), '');
- $instance->view->body_class = 'shop_product_search';
- $instance->_handleFlashMessages();
- }
- public function Product_exchangeAction($instance) {
- $user = Logic_UserOnline::getUser();
- $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
- if (!$user->user instanceof Logic_User || !Loyalty_Program::isEnabled() || !Loyalty_Program::exchangeModeProducts()) {
- $instance->_redirect($router->assemble(array(), 'index'));
- return;
- }
- $ret = $this->Basket_add($instance, true);
- foreach ($ret['messages'] as $f => $msgs) {
- $f = 'add' . ucfirst($f);
- foreach ($msgs as $msg) {
- $instance->_flashMessanger->$f($msg);
- }
- }
- if (!is_string($ret['redirect'])) {
- $ret['redirect'] = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER)->assemble(array(), 'loyaltyList');
- }
- $instance->_redirect($ret['redirect']);
- }
- public function Product_availabilitysubAction(Zend_Controller_Action $instance) {
- if (!$instance->getRequest()->isXmlHttpRequest()) {
- return;
- }
- if ($instance->getRequest()->isPost()) {
- $form = new Form_Shop_ProductAvailabilitySub();
- if ($form->isValid($_POST)) {
- $data = $form->getValues();
- $data['user_id'] = null;
- $lObject = null;
- if (Access_ClientManager::isLoggedIn()) {
- $lUser = Logic_UserOnline::getUser()->user;
- $data['user_id'] = $lUser->getIdentifier();
- $data['email'] = $lUser->userinfo->email;
- $lObject = Logic_ProductAvailabilityNotify::getNotifyByStockIdAndUserId($data['stock_id'], $data['user_id']);
- }
- if ($lObject === null) {
- $lObject = Logic_ProductAvailabilityNotify::getNotifyByStockIdAndEmail($data['stock_id'], $data['email']);
- if ($lObject === null || Access_ClientManager::isLoggedIn()) {
- Logic_ProductAvailabilityNotify::createOrUpdateNotify($lObject, $data);
- $ret = 1;
- } else {
- $ret = 2;
- }
- } else {
- $ret = 2;
- }
- } else {
- $ret = $form->getMessages();
- }
- }
- header('Content-type: application/json');
- echo json_encode($ret);
- }
- public function Product_availabilityunsubAction(Zend_Controller_Action $instance) {
- if (!$instance->getRequest()->isXmlHttpRequest()) {
- return;
- }
- if (Access_ClientManager::isLoggedIn()) {
- if ($instance->getRequest()->isPost()) {
- $form = new Form_Shop_ProductAvailabilityUnsub();
- if ($form->isValid($_POST)) {
- $data = $form->getValues();
- $lObject = Logic_ProductAvailabilityNotify::getNotifyByStockIdAndUserId(
- $data['stock_id'], Logic_UserOnline::getUser()->user->getIdentifier()
- );
- if ($lObject === null) {
- $ret = 0;
- } else {
- $lObject->delete();
- $ret = 1;
- }
- } else {
- $ret = $form->getMessages();
- }
- }
- } else {
- $ret = -1;
- }
- header('Content-type: application/json');
- echo json_encode($ret);
- }
- public function loyaltyProducts($instance) {
- $user = Logic_UserOnline::getUser();
- $products = new Logic_ProductList();
- $select = $products->select();
- $select->join('products_translations', 'products_translations.product_id = products.product_id', null);
- $select->where('products_translations.lang_id = ?', Locale_Manager::getLocaleId());
- $select->where('products_translations.active = ?', 1);
- $select->join('products_stock', 'products_stock.product_id = products.product_id', null);
- $select->where('products_stock.extended = ?', 0);
- $select->where('products_stock.price > 0 OR products.loyalty_price IS NOT NULL');
- if (Loyalty_Program::exchangeModeProductsExplicit()) {
- $select->where('in_loyalty = ?', 1);
- } elseif (Loyalty_Program::exchangeModeProductsProducers()) {
- $select->join('producers', 'producers.producer_id = products.producer_id', null);
- $select->where('producers.in_loyalty = ?', 1);
- } elseif (Loyalty_Program::exchangeModeProductsCategories()) {
- $select->join('products_categories', 'products_categories.product_id = products.product_id', null);
- $select->join('categories', 'categories.category_id = products_categories.category_id', null);
- $select->where('categories.in_loyalty = ?', 1);
- }
- $sort = $instance->_hasParam('sort') ? (int) $instance->_getParam('sort') : 1;
- if ($sort > 5 || $sort < 1) {
- $sort = 5;
- }
- $filter = $instance->_hasParam('filter') ? (int) $instance->_getParam('filter') : 0;
- $sum = (float) $user->user->loyalty->sum();
- $ratio = Loyalty_Program::getExchangeRatio();
- if ($ratio['amount'] > 0 && $ratio['points'] > 0) {
- $ratio['ratio'] = (float) $ratio['points'] / (float) $ratio['amount'];
- } else {
- $ratio = false;
- }
- if (1 == $filter && $ratio) {
- if ($sum < $ratio['points']) {
- return $products; //now enough points for first exchange level
- }
- $select->where('((loyalty_price IS NULL) * price * ' . $ratio['ratio'] . ' + IFNULL(loyalty_price, 0)) <= ?', $sum);
- }
- if (5 == $sort) {
- if ($ratio) {
- $select->order('((loyalty_price IS NULL) * price * ' . $ratio['ratio'] . ' + IFNULL(loyalty_price, 0)) ASC');
- } else {
- $select->order(Locale_Manager::collatedOrder('products_translations.name ASC'));
- }
- } elseif ($sort > 2) {
- $select->order('products_stock.price ' . (3 == $sort ? 'ASC' : 'DESC'));
- } else {
- $select->order(Locale_Manager::collatedOrder('products_translations.name ' . (1 == $sort ? 'ASC' : 'DESC')));
- }
- $products->fillFromSelect($select);
- return $products;
- }
- public function Product_loyaltyAction($instance) {
- $user = Logic_UserOnline::getUser();
- $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
- if (!$user->user instanceof Logic_User || !Loyalty_Program::isEnabled() || !Loyalty_Program::exchangeModeProducts()) {
- $instance->_redirect($router->assemble(array(), 'index'));
- return;
- }
- $instance->view->user_points = View_Smarty_Helper_Float::float(array('value' => $user->user->loyalty->sum(), 'precision' => 0), null);
- $instance->view->loyalty_filter = $instance->_hasParam('filter') ? (int) $instance->_getParam('filter') : 0;
- $loyalty_msgs = array();
- // 'text' is not put through |escape in .tpl !
- if (Loyalty_Program::orderGivesPoints()) {
- $loyalty_msgs[] = array(
- 'title' => Locale_Manager::translate('Placing orders'),
- 'text' => htmlspecialchars(Loyalty_Program::exchangeModeDiscounts() ?
- 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.') :
- Locale_Manager::translate('for the purchase of every product available in the loyalty program you gain points, which you can exchange for other products.')
- ),
- );
- }
- if (Loyalty_Program::commentGivesPoints()) {
- $loyalty_msgs[] = array(
- 'title' => Locale_Manager::translate('Reviewing a product'),
- 'text' => sprintf(
- htmlspecialchars(
- Locale_Manager::translate('select a product and write a review about it. You will gain %s %s points. %s')
- ), '<b>', Loyalty_Program::commentHowManyPoints(true), '</b>'
- ),
- );
- }
- if (Loyalty_Program::newsletterGivesPoints()) {
- $url = $router->assemble(array(), 'newsletterSign');
- $loyalty_msgs[] = array(
- 'title' => Locale_Manager::translate('Subscribing to our newsletter'),
- 'text' => sprintf(
- htmlspecialchars(
- Locale_Manager::translate('%s subscribe%s, and you will gain %s %s points. %s')
- ), '<a href="' . $url . '">', '</a>', '<b>', Loyalty_Program::newsletterHowManyPoints(true), '</b>'
- ),
- );
- }
- $instance->view->loyalty_msgs = $loyalty_msgs;
- Zend_Registry::set('products', $this->loyaltyProducts($instance));
- Zend_Registry::set('list_type', 'loyalty');
- $instance->view->sort_links = true;
- $instance->view->body_class = 'shop_product_list shop_product_loyaltylist';
- $instance->view->body_id = 'shop_product_loyaltylist';
- $instance->_forward('list');
- }
- public function Product_producerAction($instance) {
- $router = Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER);
- if ($instance->_hasParam('producerId') && $id = (int) $instance->_getParam('producerId')) {
- $p = new Logic_Manufacturer($id);
- if (false == $p->existsInDB()) {
- $instance->_redirect($router->assemble(array(), 'index'));
- return;
- }
- $products = new Logic_ProductList();
- $select = $products->select();
- $select->where('products.producer_id = ?', $id);
- $select->join('products_translations', 'products_translations.product_id = products.product_id', null);
- $select->where('products_translations.lang_id = ?', Locale_Manager::getLocaleId());
- $select->where('products_translations.active = ?', 1);
- $sort = $instance->_hasParam('sort') ? (int) $instance->_getParam('sort') : 1;
- if ($sort > 4 || $sort < 1)
- $sort = 1;
- if (1 == $sort)
- $select->order('products_translations.order DESC');
- if ($sort > 2) {
- $select->join('products_stock', 'products_stock.product_id = products.product_id', null);
- $select->where('products_stock.extended = ?', 0);
- $select->order('products_stock.price ' . (3 == $sort ? 'ASC' : 'DESC'));
- } else
- $select->order(Locale_Manager::collatedOrder('products_translations.name ' . (1 == $sort ? 'ASC' : 'DESC')));
- $products->fillFromSelect($select);
- Zend_Registry::set('products', $products);
- Zend_Registry::set('list_type', 'producer');
- $instance->view->sort_links = true;
- $instance->view->body_class = 'shop_product_list shop_product_producer';
- $instance->view->body_id = 'shop_product_producer' . $id;
- $instance->_forward('list');
- } else {
- $instance->_redirect($router->assemble(array(), 'index'));
- }
- }
- public function Product_promotionsAction($instance) {
- $products = new Logic_ProductList();
- $select = $products->select();
- $select->join('products_translations', 'products_translations.product_id = products.product_id', null);
- $select->where('products_translations.lang_id = ?', Locale_Manager::getLocaleId());
- $select->where('products_translations.active = ?', 1);
- $select->join('special_offers_conditions', 'special_offers_conditions.object_id = products.product_id', null);
- $select->join('special_offers', 'special_offers_conditions.promo_id = special_offers.promo_id', null);
- $select->where('special_offers_conditions.condition_type = ?', 3);
- $select->where('special_offers.date_to >= ?', date('Y-m-d H:i') . ':00');
- $select->where('special_offers.date_from <= ?', date('Y-m-d H:i') . ':59');
- $sort = $instance->_hasParam('sort') ? (int) $instance->_getParam('sort') : 1;
- if ($sort > 4 || $sort < 1)
- $sort = 1;
- if ($sort > 2) {
- $select->join(array('priceorder' => 'products_stock'), 'products.product_id = priceorder.product_id and priceorder.default = 1', null);
- $select->order('priceorder.comp_promo_price ' . (3 == $sort ? 'ASC' : 'DESC'));
- } else
- $select->order(Locale_Manager::collatedOrder('products_translations.name ' . (1 == $sort ? 'ASC' : 'DESC')));
- $products->fillFromSelect($select, true, array('Logic_SpecialOfferList'));
- Zend_Registry::set('products', $products);
- Zend_Registry::set('list_type', 'promo');
- $instance->view->sort_links = true;
- $instance->view->body_class = 'shop_product_list shop_product_promo';
- $instance->_forward('list');
- }
- public function Product_newAction($instance) {
- $products = new Logic_ProductList();
- $select = $products->select();
- $select->join('products_translations', 'products_translations.product_id = products.product_id', null);
- $select->where('products_translations.lang_id = ?', Locale_Manager::getLocaleId());
- if (!isset($_SESSION['poicvbgh'])) {
- $select->where('products_translations.active = ?', 1);
- }
- $mode = (bool) Config_Manager::getConfigValue('shopping', 'NEWPRODUCTS_MODE');
- if ($mode == 0) {
- $select->where('products.newproduct = ?', 1);
- } else {
- if (Config_Manager::hasConfigValue('shopping', 'NEWPRODUCTS_DAYS')) {
- $days = (int) Config_Manager::getConfigValue('shopping', 'NEWPRODUCTS_DAYS');
- } else {
- $days = 0;
- }
- $limit = mktime(0, 0, 0) - 86400 * $days;
- $select->where('add_date >= ?', date('Y-m-d', $limit));
- }
- $sort = $instance->_hasParam('sort') ? (int) $instance->_getParam('sort') : 5;
- if ($sort > 5 || $sort < 1)
- $sort = 5;
- if (5 == $sort) {
- $select->order('products.add_date DESC');
- } elseif ($sort > 2) {
- $select->join(array('priceorder' => 'products_stock'), 'products.product_id = priceorder.product_id and priceorder.default = 1', null);
- $select->order('priceorder.comp_promo_price ' . (3 == $sort ? 'ASC' : 'DESC'));
- } else {
- $select->order(Locale_Manager::collatedOrder('products_translations.name ' . (1 == $sort ? 'ASC' : 'DESC')));
- }
- $products->fillFromSelect($select);
- Zend_Registry::set('products', $products);
- Zend_Registry::set('list_type', 'new');
- $instance->view->sort_links = true;
- $instance->view->body_class = 'shop_product_list shop_product_new';
- $instance->_forward('list');
- }
- public function Product_dayAction($instance) {
- $products = new Logic_ProductList();
- $ent = new Entity_ProductsPotd();
- $select = $ent->select()->from($ent, 'product_id');
- $select->join('products_translations', 'products_translations.product_id = products_potd.product_id', null);
- $select->where('products_translations.lang_id = ?', Locale_Manager::getLocaleId());
- $select->where('products_translations.active = ?', 1);
- $sort = $instance->_hasParam('sort') ? (int) $instance->_getParam('sort') : 5;
- if ($sort > 4 || $sort < 1)
- $sort = 1;
- if ($sort > 2) {
- $select->join(array('priceorder' => 'products_stock'), 'products.product_id = priceorder.product_id and priceorder.default = 1', null);
- $select->order('priceorder.comp_promo_price ' . (3 == $sort ? 'ASC' : 'DESC'));
- } else {
- $select->order(Locale_Manager::collatedOrder('products_translations.name ' . (1 == $sort ? 'ASC' : 'DESC')));
- }
- $products->fillFromSelect($select);
- Zend_Registry::set('products', $products);
- Zend_Registry::set('list_type', 'day');
- $instance->view->sort_links = true;
- $instance->view->body_class = 'shop_product_list shop_product_day';
- $instance->_forward('list');
- }
- public function Info_indexAction($instance) {
- View_Smarty::setCacheTag(array(
- 'Logic_AboutPageList', 'Logic_AboutPage'
- ));
- $ok = false;
- if ($id = (int) $instance->_getParam('pageId')) {
- $page = new Logic_AboutPage($id);
- if (false == $page->existsInDB()) {
- $instance->_redirect(Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER)->assemble(array(), 'index'));
- return;
- }
- $page->setStats();
- if (isset($_SESSION['poicvbgh']) || 1 == (int) $page->page->active || (Zend_Controller_Front::getInstance()->getParam(Access_Manager::ADMIN_IS_LOGGED_IN) && $this->_getParam('preview'))) {
- $instance->_breadCrumbs->add($page->page->name, '');
- $instance->view->page = $page;
- $ok = true;
- }
- }
- if (!$ok) {
- $instance->_redirect(Zend_Registry::get(System_Bootstrap::REGISTRY_INDEX_ROUTER)->assemble(array(), 'index'));
- return;
- }
- $instance->view->body_class = 'shop_infopage';
- $instance->view->body_id = 'shop_infopage' . $id;
- $instance->handleSeo($page);
- $instance->_handleFlashMessages();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement