public function init()
 {
     parent::init();
     $this->storage = waSystem::getInstance()->getStorage();
     if (!isset(self::$options['session_timeout'])) {
         self::$options['session_timeout'] = 1800;
     }
     if (ini_get('session.gc_maxlifetime') < self::$options['session_timeout']) {
         ini_set('session.gc_maxlifetime', self::$options['session_timeout']);
     }
     $auth = waSystem::getInstance()->getAuth();
     $info = $auth->isAuth();
     if ($info && isset($info['id']) && $info['id']) {
         $this->auth = true;
         $this->id = $info['id'];
         // update last_datetime for contact
         if (!waRequest::request('background_process')) {
             $this->updateLastTime();
         }
         // check CSRF cookie
         if (!waRequest::cookie('_csrf')) {
             waSystem::getInstance()->getResponse()->setCookie('_csrf', uniqid('', true));
         }
     }
 }
Exemple #2
0
 public function __construct()
 {
     $this->view = waSystem::getInstance()->getView();
     if (wa()->getEnv() == 'frontend') {
         // save utm to cookie
         $utm = array();
         foreach (waRequest::get() as $k => $v) {
             if (substr($k, 0, 4) == 'utm_') {
                 $utm[substr($k, 4)] = $v;
             }
         }
         if ($utm) {
             // save utm to cookie
             wa()->getResponse()->setCookie('utm', json_encode($utm), time() + 30 * 86400, null, '', false, true);
         }
         // save referer
         if ($ref = waRequest::server('HTTP_REFERER')) {
             $ref_host = @parse_url($ref, PHP_URL_HOST);
             if ($ref_host != waRequest::server('HTTP_HOST')) {
                 wa()->getResponse()->setCookie('referer', waRequest::server('HTTP_REFERER'), time() + 30 * 86400, null, '', false, true);
             }
         }
         // save landing page
         if (!waRequest::cookie('landing')) {
             wa()->getResponse()->setCookie('landing', waRequest::server('REQUEST_URI'), 0, null, '', false, true);
         }
     }
 }
 private function cartSync($contact = null)
 {
     if (!$this->getSettings('enabled')) {
         return null;
     }
     if (!$contact) {
         $id = wa()->getUser()->getId();
     } else {
         $id = $contact->getId;
     }
     $cart = waRequest::cookie('shop_cart');
     $model = new shopCartItemsModel();
     $carts = $model->query('SELECT code FROM shop_cart_items WHERE contact_id=' . $id)->fetchAssoc();
     if (count($carts) == 0) {
         return null;
     }
     $values = array('contact_id' => $id);
     if (count($carts) == 1) {
         if ($cart != $carts['code']) {
             $data = array('code' => $cart);
             $model->updateByField($data, $values);
             $data = array('code' => $carts['code']);
             $model->updateByField($values, $data);
             $model->updateByField($data, $values);
             wa()->getResponse()->setCookie('shop_cart', $carts['code'], time() + 30 * 86400, null, '', false, true);
             return true;
         }
     }
 }
 public function execute()
 {
     if (wa()->getAuth()->isAuth()) {
         $this->afterAuth();
     }
     // check XMLHttpRequest (ajax)
     $this->checkXMLHttpRequest();
     if (wa()->getEnv() == 'frontend') {
         $this->checkAuthConfig();
     }
     $auth = wa()->getAuth();
     // check remember enabled
     if (waRequest::method() == 'get') {
         $this->view->assign('remember', waRequest::cookie('remember', 1));
     }
     $this->saveReferer();
     $error = '';
     // try auth
     try {
         if ($auth->auth()) {
             $this->afterAuth();
         }
     } catch (waException $e) {
         $error = $e->getMessage();
     }
     $this->view->assign('error', $error);
     // assign auth options
     $this->view->assign('options', $auth->getOptions());
     wa()->getResponse()->setTitle(_ws('Log in'));
 }
    public function frontend_head()
    {
        if (!$this->getSettings('enabled')) {
            return false;
        }
        if (waRequest::cookie('agecheck') == 1) {
            return false;
        } else {
            $enter = !empty($this->getSettings('enter')) ? $this->getSettings('enter') : _wp('Enter');
            $leave = !empty($this->getSettings('leave')) ? $this->getSettings('leave') : _wp('Leave');
            $header = !empty($this->getSettings('header')) ? $this->getSettings('header') : _wp('Adults only');
            $style = !empty($this->getSettings('css')) ? $this->getSettings('css') : '';
            $logo = !empty($this->getSettings('logo_url')) ? $this->getSettings('logo_url') : $this->getPluginStaticUrl(true) . 'img/' . $this->getSettings('logo') . '.png';
            $html = '<div id="agecheck" class="agecheck-fade">';
            $html .= '<script type="text/javascript">
			$(document).on("click","#s-agecheck-enter",function(){var e=new Date;e.setTime(e.getTime()+31536e7),document.cookie="agecheck=1;path=/;expires="+e.toUTCString(),$("#agecheck").hide()}),$(document).on("click","#s-agecheck-leave",function(){""==document.referrer?window.close():window.location.href=document.referrer});
</script>';
            $html .= '<style>.agecheck-fade{height:100%;width:100%;background-color:rgba(0,0,0,.9);position:fixed;overflow:hidden;left:0;top:0;display:block;z-index:10000}.agecheck-cont{padding:20px;margin:10% auto 0;width:350px;background-color:#FFF!important;-moz-box-shadow:0 0 100px 1px #444;-webkit-box-shadow:0 0 100px 1px #444;font-size:20px}.agecheck-button{font-family:inherit;font-size:100%;padding:.5em 1em;color:#444;border:1px solid #999;background-color:#E6E6E6;text-decoration:none;border-radius:2px}</style>';
            if (!empty($style)) {
                $html .= '<style>' . $style . '</style>';
            }
            $html .= '
		<div class="agecheck-cont" align="center">
			<img align="middle" class="agecheck-logo" style="clear:both" src="' . $logo . '"></img><br><br>
			<h3>' . $header . '</h3>
			<button class="agecheck-button" id="s-agecheck-enter">' . $enter . '</button>&nbsp;&nbsp;<button class="agecheck-button" id="s-agecheck-leave">' . $leave . '</button>
		</div></div>';
            return $html;
        }
    }
 public function execute()
 {
     $id = (int) waRequest::get('id');
     $html = '';
     $app_settings_model = new waAppSettingsModel();
     $settings = $app_settings_model->get(array('shop', 'fprview'));
     $product = new shopProduct($id);
     $route_params = array('product_url' => $product['url']);
     if (isset($product['category_url'])) {
         $route_params['category_url'] = $product['category_url'];
     }
     $product['frontend_url'] = wa()->getRouteUrl('shop/frontend/product', $route_params);
     $feature_codes = array_keys($product->features);
     $feature_model = new shopFeatureModel();
     $features = $feature_model->getByCode($feature_codes);
     $theme = waRequest::param('theme', 'default');
     $theme_path = wa()->getDataPath('themes', true) . '/' . $theme;
     if (!file_exists($theme_path) || !file_exists($theme_path . '/theme.xml')) {
         $theme_path = wa()->getAppPath() . '/themes/' . $theme;
     }
     switch ($settings['template_type']) {
         case 'plugin':
             $view = wa()->getView();
             $view->assign('features', $features);
             $view->assign('product', $product);
             $view->assign('fprview_settings', $settings);
             $html = $view->fetch(realpath(dirname(__FILE__) . "/../../") . '/templates/Frontend.html');
             break;
         case 'theme':
             if ($settings['template_theme_file'] && file_exists($theme_path . '/' . $settings['template_theme_file'])) {
                 $view = wa()->getView(array('template_dir' => $theme_path));
                 list($services, $skus_services) = $this->getServiceVars($product);
                 $compare = waRequest::cookie('shop_compare', array(), waRequest::TYPE_ARRAY_INT);
                 $stock_model = new shopStockModel();
                 $view->assign(array('sku_services' => $skus_services, 'services' => $services, 'compare' => in_array($product['id'], $compare) ? $compare : array(), 'currency_info' => $this->getCurrencyInfo(), 'stocks' => $stock_model->getAll('id'), 'reviews' => $this->getTopReviews($product['id']), 'rates' => $this->reviews_model->getProductRates($product['id']), 'reviews_total_count' => $this->getReviewsTotalCount($product['id']), 'features' => $features, 'product' => $product));
                 $view->assign('frontend_product', wa()->event('frontend_product', $product, array('menu', 'cart', 'block_aux', 'block')));
                 $template = $this->setThemeTemplate($settings['template_theme_file']);
                 $html = $view->fetch($this->getTemplate());
             }
             break;
         default:
             $html = '';
             break;
     }
     echo $html;
     exit;
 }
 protected function setCollection(shopProductsCollection $collection)
 {
     $collection->filters(waRequest::get());
     $limit = (int) waRequest::cookie('products_per_page');
     if (!$limit || $limit < 0 || $limit > 500) {
         $limit = $this->getConfig()->getOption('products_per_page');
     }
     $page = waRequest::get('page', 1, 'int');
     if ($page < 1) {
         $page = 1;
     }
     $offset = ($page - 1) * $limit;
     $products = $collection->getProducts('*', $offset, $limit);
     $count = $collection->count();
     $pages_count = ceil((double) $count / $limit);
     $this->view->assign('pages_count', $pages_count);
     $this->view->assign('products', $products);
     $this->view->assign('products_count', $count);
 }
 public function orderActionCreate($params)
 {
     if ($this->getSettings('status') && waRequest::cookie('uuid')) {
         $customer_model = new shopCustomerModel();
         $is_spamer = $customer_model->getByField(array('uuid' => waRequest::cookie('uuid'), 'is_spamer' => 1));
         $update = array();
         if ($is_spamer && $this->getSettings('action_id')) {
             $update['is_spamer'] = 1;
             $action_id = $this->getSettings('action_id');
             $workflow = new shopWorkflow();
             $action = $workflow->getActionById($action_id);
             $action->run($params['order_id']);
         }
         $customer = $customer_model->getById($params['contact_id']);
         if (!$customer['uuid']) {
             $update['uuid'] = waRequest::cookie('uuid');
             $customer_model->updateById($params['contact_id'], $update);
         }
     }
 }
 /** Default action when no other action is specified. */
 public function defaultAction()
 {
     $lm = new checklistsListModel();
     $lists = $lm->getAllowed();
     if (!$lists) {
         if ($this->getRights('add_list')) {
             $this->execute('editor');
             return;
         }
         // No available lists and cannot create new one: show default template
         return;
     }
     // is there a cookie with last list user opened?
     $id = waRequest::cookie('last_list_id', 0, 'int');
     if ($id && isset($lists[$id])) {
         $this->execute('list', $lists[$id]);
         return;
     }
     // simply show the first list
     $lists = array_values($lists);
     $this->execute('list', $lists[0]);
 }
 public function updateAuth($data)
 {
     wa()->getStorage()->set('auth_user', $this->getAuthData($data));
     if (waRequest::cookie('auth_token')) {
         $cookie_domain = ifset($this->options['cookie_domain'], '');
         wa()->getResponse()->setCookie('auth_token', $this->getToken($data), time() + 2592000, null, $cookie_domain, false, true);
     }
 }
 public function execute()
 {
     $ids = waRequest::param('id', array(), waRequest::TYPE_ARRAY_INT);
     if (!$ids) {
         $ids = waRequest::cookie('shop_compare', array(), waRequest::TYPE_ARRAY_INT);
     }
     $collection = new shopProductsCollection('id/' . implode(',', $ids));
     $products = $collection->getProducts();
     $features = array();
     $i = 0;
     $compare_link = wa()->getRouteUrl('/frontend/compare', array('id' => '%ID%'));
     foreach ($products as &$p) {
         $p = new shopProduct($p);
         $temp_ids = $ids;
         unset($temp_ids[array_search($p['id'], $temp_ids)]);
         $p['delete_url'] = str_replace('%ID%', implode(',', $temp_ids), $compare_link);
         if (!$temp_ids) {
             $p['delete_url'] = substr($p['delete_url'], 0, -1);
         }
         foreach ($p->features as $code => $v) {
             if (is_object($v)) {
                 $v = trim(isset($v['compare']) ? $v['compare'] : $v['value']);
             } elseif (is_array($v)) {
                 foreach ($v as &$_v) {
                     if (is_object($_v)) {
                         $_v = trim(isset($_v['compare']) ? $_v['compare'] : $_v['value']);
                     } else {
                         $_v = trim($_v);
                     }
                     unset($_v);
                 }
                 sort($v, SORT_STRING);
                 $v = serialize($v);
             } else {
                 $v = trim($v);
             }
             if (isset($features[$code]) && $features[$code]['same']) {
                 if ($v !== $features[$code]['value']) {
                     $features[$code]['same'] = false;
                 }
             } else {
                 if (!isset($features[$code])) {
                     $features[$code] = array();
                 }
                 if (!$i) {
                     $features[$code]['same'] = true;
                     $features[$code]['value'] = $v;
                 } else {
                     $features[$code]['same'] = false;
                 }
             }
         }
         foreach ($features as $code => $v) {
             if (!isset($p->features[$code])) {
                 $features[$code]['same'] = false;
             }
         }
         $i++;
         unset($p);
     }
     if ($features) {
         $feature_model = new shopFeatureModel();
         foreach ($all_features = $feature_model->getByCode(array_keys($features)) as $code => $f) {
             $features[$code] += $f;
         }
     }
     $this->view->assign('features', $features);
     $this->view->assign('products', $products);
     $this->setLayout(new shopFrontendLayout());
     $this->setThemeTemplate('compare.html');
 }
 protected function createOrder()
 {
     $checkout_data = wa()->getStorage()->get('shop/checkout');
     if (wa()->getUser()->isAuth()) {
         $contact = wa()->getUser();
     } else {
         if (!empty($checkout_data['contact']) && $checkout_data['contact'] instanceof waContact) {
             $contact = $checkout_data['contact'];
         } else {
             $contact = new waContact();
         }
     }
     $cart = new shopCart();
     $items = $cart->items(false);
     // remove id from item
     foreach ($items as &$item) {
         unset($item['id']);
         unset($item['parent_id']);
     }
     unset($item);
     $order = array('contact' => $contact, 'items' => $items, 'total' => $cart->total(false), 'params' => isset($checkout_data['params']) ? $checkout_data['params'] : array());
     $order['discount_description'] = null;
     $order['discount'] = shopDiscounts::apply($order, $order['discount_description']);
     if (isset($checkout_data['shipping'])) {
         $order['params']['shipping_id'] = $checkout_data['shipping']['id'];
         $order['params']['shipping_rate_id'] = $checkout_data['shipping']['rate_id'];
         $shipping_step = new shopOnestepCheckoutShipping();
         $rate = $shipping_step->getRate($order['params']['shipping_id'], $order['params']['shipping_rate_id']);
         $order['params']['shipping_plugin'] = $rate['plugin'];
         $order['params']['shipping_name'] = $rate['name'];
         if (isset($rate['est_delivery'])) {
             $order['params']['shipping_est_delivery'] = $rate['est_delivery'];
         }
         if (!isset($order['shipping'])) {
             $order['shipping'] = $rate['rate'];
         }
         if (!empty($order['params']['shipping'])) {
             foreach ($order['params']['shipping'] as $k => $v) {
                 $order['params']['shipping_params_' . $k] = $v;
             }
             unset($order['params']['shipping']);
         }
     } else {
         $order['shipping'] = 0;
     }
     if (isset($checkout_data['payment'])) {
         $order['params']['payment_id'] = $checkout_data['payment'];
         $plugin_model = new shopPluginModel();
         $plugin_info = $plugin_model->getById($checkout_data['payment']);
         $order['params']['payment_name'] = $plugin_info['name'];
         $order['params']['payment_plugin'] = $plugin_info['plugin'];
         if (!empty($order['params']['payment'])) {
             foreach ($order['params']['payment'] as $k => $v) {
                 $order['params']['payment_params_' . $k] = $v;
             }
             unset($order['params']['payment']);
         }
     }
     if ($skock_id = waRequest::post('stock_id')) {
         $order['params']['stock_id'] = $skock_id;
     }
     $routing_url = wa()->getRouting()->getRootUrl();
     $order['params']['storefront'] = wa()->getConfig()->getDomain() . ($routing_url ? '/' . $routing_url : '');
     if ($ref = waRequest::cookie('referer')) {
         $order['params']['referer'] = $ref;
         $ref_parts = @parse_url($ref);
         $order['params']['referer_host'] = $ref_parts['host'];
         // try get search keywords
         if (!empty($ref_parts['query'])) {
             $search_engines = array('text' => 'yandex\\.|rambler\\.', 'q' => 'bing\\.com|mail\\.|google\\.', 's' => 'nigma\\.ru', 'p' => 'yahoo\\.com');
             $q_var = false;
             foreach ($search_engines as $q => $pattern) {
                 if (preg_match('/(' . $pattern . ')/si', $ref_parts['host'])) {
                     $q_var = $q;
                     break;
                 }
             }
             // default query var name
             if (!$q_var) {
                 $q_var = 'q';
             }
             parse_str($ref_parts['query'], $query);
             if (!empty($query[$q_var])) {
                 $order['params']['keyword'] = $query[$q_var];
             }
         }
     }
     if ($utm = waRequest::cookie('utm')) {
         $utm = json_decode($utm, true);
         if ($utm && is_array($utm)) {
             foreach ($utm as $k => $v) {
                 $order['params']['utm_' . $k] = $v;
             }
         }
     }
     if (($landing = waRequest::cookie('landing')) && ($landing = @parse_url($landing))) {
         if (!empty($landing['query'])) {
             @parse_str($landing['query'], $arr);
             if (!empty($arr['gclid']) && !empty($order['params']['referer_host']) && strpos($order['params']['referer_host'], 'google') !== false) {
                 $order['params']['referer_host'] .= ' (cpc)';
                 $order['params']['cpc'] = 1;
             } else {
                 if (!empty($arr['_openstat']) && !empty($order['params']['referer_host']) && strpos($order['params']['referer_host'], 'yandex') !== false) {
                     $order['params']['referer_host'] .= ' (cpc)';
                     $order['params']['openstat'] = $arr['_openstat'];
                     $order['params']['cpc'] = 1;
                 }
             }
         }
         $order['params']['landing'] = $landing['path'];
     }
     // A/B tests
     /*
             $abtest_variants_model = new shopAbtestVariantsModel();
             foreach (waRequest::cookie() as $k => $v) {
                 if (substr($k, 0, 5) == 'waabt') {
                     $variant_id = $v;
                     $abtest_id = substr($k, 5);
                     if (wa_is_int($abtest_id) && wa_is_int($variant_id)) {
                         $row = $abtest_variants_model->getById($variant_id);
                         if ($row && $row['abtest_id'] == $abtest_id) {
                             $order['params']['abt' . $abtest_id] = $variant_id;
                         }
                     }
                 }
             }
     */
     $order['params']['ip'] = waRequest::getIp();
     $order['params']['user_agent'] = waRequest::getUserAgent();
     foreach (array('shipping', 'billing') as $ext) {
         $address = $contact->getFirst('address.' . $ext);
         if ($address) {
             foreach ($address['data'] as $k => $v) {
                 $order['params'][$ext . '_address.' . $k] = $v;
             }
         }
     }
     if (isset($checkout_data['comment'])) {
         $order['comment'] = $checkout_data['comment'];
     }
     $workflow = new shopWorkflow();
     if ($order_id = $workflow->getActionById('create')->run($order)) {
         $step_number = shopOnestepCheckout::getStepNumber();
         $checkout_flow = new shopCheckoutFlowModel();
         $checkout_flow->add(array('step' => $step_number));
         $cart->clear();
         wa()->getStorage()->remove('shop/checkout');
         wa()->getStorage()->set('shop/order_id', $order_id);
         return $order_id;
     } else {
         return false;
     }
 }
 public function csrf()
 {
     return '<input type="hidden" name="_csrf" value="' . waRequest::cookie('_csrf', '') . '" />';
 }
Exemple #14
0
 public function dispatch()
 {
     try {
         if (preg_match('/^sitemap-?([a-z0-9_]+)?(-([0-9]+))?.xml$/i', $this->config->getRequestUrl(true), $m)) {
             $app_id = isset($m[1]) ? $m[1] : 'webasyst';
             if ($this->appExists($app_id)) {
                 self::getInstance($app_id);
                 $class = $app_id . 'SitemapConfig';
                 if (class_exists($class)) {
                     /**
                      * @var $sitemap waSitemapConfig
                      */
                     $sitemap = new $class();
                     $n = ifempty($m[3]);
                     if (!$n) {
                         $n = 1;
                     }
                     $sitemap->display($n);
                 }
             } else {
                 throw new waException("Page not found", 404);
             }
         } elseif (preg_match('/^([a-z0-9_]+)?\\/?captcha\\.php$/i', $this->config->getRequestUrl(true, true), $m)) {
             $app_id = isset($m[1]) ? $m[1] : 'webasyst';
             if ($this->appExists($app_id)) {
                 $wa = self::getInstance($app_id, null, true);
                 $captcha = $wa->getCaptcha(array('app_id' => $app_id));
                 $captcha->display();
             } else {
                 throw new waException("Page not found", 404);
             }
         } elseif (!strncmp($this->config->getRequestUrl(true), 'oauth.php', 9)) {
             $app_id = $this->getStorage()->get('auth_app');
             if ($app_id && !$this->appExists($app_id)) {
                 throw new waException("Page not found", 404);
             }
             $app_system = self::getInstance($app_id);
             if (class_exists($app_id . 'OAuthController')) {
                 $app_system->getFrontController()->execute(null, 'OAuth');
             } else {
                 wa('webasyst')->getFrontController()->execute(null, 'OAuth');
             }
         } elseif (!strncmp($this->config->getRequestUrl(true), 'payments.php/', 13)) {
             $url = substr($this->config->getRequestUrl(true), 13);
             waRequest::setParam('module_id', strtok($url, '/?'));
             $webasyst_system = self::getInstance('webasyst');
             $webasyst_system->getFrontController()->execute(null, 'payments', null, true);
         } elseif ($this->getEnv() == 'backend' && !$this->getUser()->isAuth()) {
             $webasyst_system = self::getInstance('webasyst', null, true);
             $webasyst_system->getFrontController()->execute(null, 'login', waRequest::get('action'), true);
         } elseif ($this->config instanceof waAppConfig) {
             if ($this->getEnv() == 'backend' && !$this->getUser()->getRights($this->getConfig()->getApplication(), 'backend')) {
                 header("Location: " . $this->getConfig()->getBackendUrl(true));
                 exit;
             }
             $this->getFrontController()->dispatch();
         } else {
             $app = null;
             $route = null;
             if ($this->getEnv() == 'frontend') {
                 // logout
                 if (null !== ($logout_url = waRequest::get('logout'))) {
                     // for getting app
                     $this->getRouting()->dispatch();
                     $app = waRequest::param('app');
                     // For logging logout action
                     $data = array('app_id' => $app, 'contact_id' => $this->getUser()->getId(), 'datetime' => date("Y-m-d H:i:s"), 'action' => 'logout', 'params' => $this->getEnv());
                     // logout itself
                     $this->getUser()->logout();
                     if (!$logout_url) {
                         $logout_url = $this->config->getRequestUrl(false, true);
                     }
                     // logging logout
                     if (!class_exists('waLogModel')) {
                         wa('webasyst');
                     }
                     $log_model = new waLogModel();
                     $log_model->insert($data);
                     // make redirect after logout
                     $this->getResponse()->redirect($logout_url);
                 }
                 if (!$this->getRouting()->dispatch()) {
                     $this->getResponse()->redirect($this->getConfig()->getBackendUrl(true), 302);
                 }
                 $app = waRequest::param('app');
             } else {
                 self::getInstance('webasyst');
                 $path = $this->getConfig()->getRequestUrl(true);
                 if (($i = strpos($path, '?')) !== false) {
                     $path = substr($path, 0, $i);
                 }
                 $url = explode("/", $path);
                 $app = isset($url[1]) && $url[1] != 'index.php' ? $url[1] : 'webasyst';
             }
             if (!$app) {
                 $app = 'webasyst';
             }
             $app_system = self::getInstance($app, null, true);
             if ($app != 'webasyst' && $this->getEnv() == 'backend' && !$this->getUser()->getRights($app_system->getConfig()->getApplication(), 'backend')) {
                 //$this->getResponse()->redirect($this->getConfig()->getBackendUrl(true), 302);
                 throw new waRightsException('Access to this app denied', 403);
             }
             if ((waRequest::param('secure') || waRequest::param('auth')) && !$this->getUser()->isAuth()) {
                 $auth = $this->getAuthConfig();
                 if (!empty($auth['app'])) {
                     $app_system = self::getInstance($auth['app'], null, true);
                 }
                 $app_system->login();
             } else {
                 if (waRequest::param('secure') && $app_system->getConfig()->getInfo('csrf') && waRequest::method() == 'post' && waRequest::post('_csrf') != waRequest::cookie('_csrf')) {
                     throw new waException('CSRF Protection', 403);
                 }
                 $app_system->getFrontController()->dispatch();
             }
         }
     } catch (waApiException $e) {
         print $e;
     } catch (waException $e) {
         print $e;
     } catch (Exception $e) {
         if (waSystemConfig::isDebug()) {
             print $e;
         } else {
             $e = new waException($e->getMessage(), $e->getCode());
             print $e;
         }
     }
 }
Exemple #15
0
 /**
  * Saves contact's data to database.
  *
  * @param array $data Associative array of contact property values.
  * @param bool $validate Flag requiring to validate property values. Defaults to false.
  * @return int|array Zero, if saved successfully, or array of error messages otherwise
  */
 public function save($data = array(), $validate = false)
 {
     $is_user = $this->get('is_user');
     $add = array();
     foreach ($data as $key => $value) {
         if (strpos($key, '.')) {
             $key_parts = explode('.', $key);
             $f = waContactFields::get($key_parts[0]);
             if ($f) {
                 $key = $key_parts[0];
                 if ($key_parts[1] && $f->isExt()) {
                     // add next field
                     $add[$key] = true;
                     if (is_array($value)) {
                         if (!isset($value['value'])) {
                             $value = array('ext' => $key_parts[1], 'value' => $value);
                         }
                     } else {
                         $value = array('ext' => $key_parts[1], 'value' => $value);
                     }
                 }
             }
         } else {
             $f = waContactFields::get($key);
         }
         if ($f) {
             $this->data[$key] = $f->set($this, $value, array(), isset($add[$key]) ? true : false);
         } else {
             if ($key == 'password') {
                 $value = self::getPasswordHash($value);
             }
             $this->data[$key] = $value;
         }
     }
     $this->data['name'] = $this->get('name');
     $this->data['firstname'] = $this->get('firstname');
     $this->data['is_company'] = $this->get('is_company');
     if ($this->id && isset($this->data['is_user'])) {
         $log_model = new waLogModel();
         if ($this->data['is_user'] == '-1' && $is_user != '-1') {
             $log_model->add('access_disable', null, $this->id, wa()->getUser()->getId());
         } else {
             if ($this->data['is_user'] != '-1' && $is_user == '-1') {
                 $log_model->add('access_enable', null, $this->id, wa()->getUser()->getId());
             }
         }
     }
     $save = array();
     $errors = array();
     $contact_model = new waContactModel();
     foreach ($this->data as $field => $value) {
         if ($field == 'login') {
             $f = new waContactStringField('login', _ws('Login'), array('unique' => true, 'storage' => 'info'));
         } else {
             $f = waContactFields::get($field, $this['is_company'] ? 'company' : 'person');
         }
         if ($f) {
             if ($f->isMulti() && !is_array($value)) {
                 $value = array($value);
             }
             if ($f->isMulti()) {
                 foreach ($value as &$val) {
                     if (is_string($val)) {
                         $val = trim($val);
                     } else {
                         if (isset($val['value']) && is_string($val['value'])) {
                             $val['value'] = trim($val['value']);
                         } else {
                             if ($f instanceof waContactCompositeField && isset($val['data']) && is_array($val['data'])) {
                                 foreach ($val['data'] as &$v) {
                                     if (is_string($v)) {
                                         $v = trim($v);
                                     }
                                 }
                                 unset($v);
                             }
                         }
                     }
                 }
                 unset($val);
             } else {
                 if (is_string($value)) {
                     $value = trim($value);
                 } else {
                     if (isset($value['value']) && is_string($value['value'])) {
                         $value['value'] = trim($value['value']);
                     } else {
                         if ($f instanceof waContactCompositeField && isset($value['data']) && is_array($value['data'])) {
                             foreach ($value['data'] as &$v) {
                                 if (is_string($v)) {
                                     $v = trim($v);
                                 }
                             }
                             unset($v);
                         }
                     }
                 }
             }
             if ($validate !== 42) {
                 // this deep dark magic is used when merging contacts
                 if ($validate) {
                     if ($e = $f->validate($value, $this->id)) {
                         $errors[$f->getId()] = $e;
                     }
                 } elseif ($f->isUnique()) {
                     // validate unique
                     if ($e = $f->validateUnique($value, $this->id)) {
                         $errors[$f->getId()] = $e;
                     }
                 }
             }
             if (!$errors && $f->getStorage()) {
                 $save[$f->getStorage()->getType()][$field] = $f->prepareSave($value, $this);
             }
         } elseif ($contact_model->fieldExists($field)) {
             $save['waContactInfoStorage'][$field] = $value;
         } else {
             $save['waContactDataStorage'][$field] = $value;
         }
     }
     // Returns errors
     if ($errors) {
         return $errors;
     }
     $is_add = false;
     // Saving to all storages
     try {
         if (!$this->id) {
             $is_add = true;
             $storage = 'waContactInfoStorage';
             if (wa()->getEnv() == 'frontend') {
                 if ($ref = waRequest::cookie('referer')) {
                     $save['waContactDataStorage']['referer'] = $ref;
                     $save['waContactDataStorage']['referer_host'] = parse_url($ref, PHP_URL_HOST);
                 }
                 if ($utm = waRequest::cookie('utm')) {
                     $utm = json_decode($utm, true);
                     if ($utm && is_array($utm)) {
                         foreach ($utm as $k => $v) {
                             $save['waContactDataStorage']['utm_' . $k] = $v;
                         }
                     }
                 }
             }
             $this->id = waContactFields::getStorage($storage)->set($this, $save[$storage]);
             unset($save[$storage]);
         }
         foreach ($save as $storage => $storage_data) {
             waContactFields::getStorage($storage)->set($this, $storage_data);
         }
         $this->data = array();
         wa()->event(array('contacts', 'save'), $this);
         $this->removeCache();
         $this->clearDisabledFields();
     } catch (Exception $e) {
         // remove created contact
         if ($is_add && $this->id) {
             $this->delete();
             $this->id = null;
         }
         $errors['name'][] = $e->getMessage();
     }
     return $errors ? $errors : 0;
 }
Exemple #16
0
 public static function getFile($params)
 {
     $mode = isset($params['direction']) ? 'line' : 'page';
     $check = isset($params['check']) ? $params['check'] : true;
     $path = self::getRootLogsDirPath() . DIRECTORY_SEPARATOR . self::normalizePath($params['path'], true);
     $lines_per_page = waRequest::cookie('lines_per_page', self::LINES_PER_PAGE, 'int');
     $error = '';
     if ($check) {
         self::checkPath($path);
     } elseif (!self::checkPath($path, false)) {
         $error = _w('File cannot be accessed.');
     }
     if (!strlen($error)) {
         $first_line = null;
         $last_line = null;
         $contents = '';
         if ($file = @fopen($path, 'r')) {
             if ($mode == 'page') {
                 $line_count = 0;
                 $current_page = 1;
                 while (!feof($file)) {
                     $current_line = $line_count;
                     $line = fgets($file, 4096);
                     $current_page_updated = floor($line_count++ / $lines_per_page) + 1;
                     if (isset($params['page'])) {
                         if ($current_page_updated == $params['page']) {
                             //continue reading specified page
                             $contents .= $line;
                             if ($first_line === null) {
                                 $first_line = $current_line;
                             }
                             $last_line = $current_line;
                         }
                     } else {
                         if ($current_page == $current_page_updated) {
                             //continue reading current page
                             $contents .= $line;
                             if ($first_line === null) {
                                 //if first file page
                                 $first_line = $current_line;
                             }
                             $last_line = $current_line;
                         } else {
                             //start reading next (2+) page
                             $contents = $line;
                             $first_line = $current_line;
                         }
                     }
                     $current_page = $current_page_updated;
                 }
             } else {
                 //mode 'line'
                 if ($params['direction'] == 'previous') {
                     $first_line = $params['first_line'] - $lines_per_page;
                     $last_line = $params['first_line'] - 1;
                 } else {
                     $first_line = $params['last_line'] + 1;
                     $last_line = $params['last_line'] + $lines_per_page;
                 }
                 $line_count = -1;
                 while (!feof($file)) {
                     $line_count++;
                     $line = fgets($file, 4096);
                     if ($line_count >= $first_line && $line_count <= $last_line) {
                         $contents .= $line;
                     } elseif ($line_count > $last_line) {
                         break;
                     }
                 }
                 $last_line = $line_count;
             }
             fclose($file);
         } else {
             $error = _w('File cannot be accessed.');
         }
     }
     return array('contents' => isset($contents) ? $contents : null, 'page_count' => $mode == 'page' ? ceil($line_count / $lines_per_page) : null, 'path' => $params['path'], 'return_url' => strpos($params['path'], '/') === false ? wa()->getAppUrl() : '?path=' . dirname($params['path']), 'error' => isset($error) ? $error : '', 'first_line' => isset($first_line) ? $first_line : null, 'last_line' => isset($last_line) ? $last_line : null);
 }
    public function execute()
    {
        $this->setLayout(new shopFrontendLayout());
        if ($this->params) {
            $product = $this->params;
        } else {
            $product_model = new shopProductModel();
            $product = $product_model->getByField('url', waRequest::param('product_url'));
        }
        if (!$product) {
            throw new waException(_w('Product not found'), 404);
        }
        if ($types = waRequest::param('type_id')) {
            if (!in_array($product['type_id'], (array) $types)) {
                throw new waException(_w('Product not found'), 404);
            }
        }
        $is_cart = waRequest::get('cart');
        if ($is_cart) {
            $this->setLayout(null);
        }
        $product = new shopProduct($product);
        if (!$is_cart) {
            $this->getBreadcrumbs($product);
        }
        // check url
        $product['num'] = 141;
        if ($product['url'] !== urldecode(waRequest::param('product_url'))) {
            $url_params = array('product_url' => $product['url']);
            if ($product['category_id']) {
                $url_params['category_url'] = $product['category_url'];
            }
            $q = waRequest::server('QUERY_STRING');
            $this->redirect(wa()->getRouteUrl('/frontend/product', $url_params) . ($q ? '?' . $q : ''), 301);
        }
        $this->prepareProduct($product);
        $this->addCanonical();
        // get services
        $type_services_model = new shopTypeServicesModel();
        $services = $type_services_model->getServiceIds($product['type_id']);
        $service_model = new shopServiceModel();
        $product_services_model = new shopProductServicesModel();
        $services = array_merge($services, $product_services_model->getServiceIds($product['id']));
        $services = array_unique($services);
        $services = $service_model->getById($services);
        $variants_model = new shopServiceVariantsModel();
        $rows = $variants_model->getByField('service_id', array_keys($services), true);
        foreach ($rows as $row) {
            if (!$row['price']) {
                $row['price'] = $services[$row['service_id']]['price'];
            }
            $services[$row['service_id']]['variants'][$row['id']] = $row;
        }
        $rows = $product_services_model->getByField('product_id', $product['id'], true);
        $skus_services = array();
        foreach ($product['skus'] as $sku) {
            $skus_services[$sku['id']] = array();
        }
        foreach ($rows as $row) {
            if (!$row['sku_id']) {
                // remove disabled services and variantsimg
                if (!$row['status']) {
                    unset($services[$row['service_id']]['variants'][$row['service_variant_id']]);
                } elseif ($row['price'] !== null) {
                    // update price
                    $services[$row['service_id']]['variants'][$row['service_variant_id']]['price'] = $row['price'];
                }
                if ($row['status'] == shopProductServicesModel::STATUS_DEFAULT) {
                    // update default
                    $services[$row['service_id']]['variant_id'] = $row['service_variant_id'];
                }
            } else {
                if (!$row['status']) {
                    $skus_services[$row['sku_id']][$row['service_id']][$row['service_variant_id']] = false;
                } else {
                    $skus_services[$row['sku_id']][$row['service_id']][$row['service_variant_id']] = $row['price'];
                }
            }
        }
        foreach ($skus_services as $sku_id => &$sku_services) {
            $sku_price = $product['skus'][$sku_id]['price'];
            foreach ($services as $service_id => $service) {
                if (isset($sku_services[$service_id])) {
                    if ($sku_services[$service_id]) {
                        foreach ($service['variants'] as $v) {
                            if (!isset($sku_services[$service_id][$v['id']]) || $sku_services[$service_id][$v['id']] === null) {
                                $sku_services[$service_id][$v['id']] = array($v['name'], $this->getPrice($v['price'], $service['currency'], $sku_price, $product['currency']));
                            } elseif ($sku_services[$service_id][$v['id']]) {
                                $sku_services[$service_id][$v['id']] = array($v['name'], $this->getPrice($sku_services[$service_id][$v['id']], $service['currency'], $sku_price, $product['currency']));
                            }
                        }
                    }
                } else {
                    foreach ($service['variants'] as $v) {
                        $sku_services[$service_id][$v['id']] = array($v['name'], $this->getPrice($v['price'], $service['currency'], $sku_price, $product['currency']));
                    }
                }
            }
        }
        unset($sku_services);
        // disable service if all variants disabled
        foreach ($skus_services as $sku_id => $sku_services) {
            foreach ($sku_services as $service_id => $service) {
                if (is_array($service)) {
                    $disabled = true;
                    foreach ($service as $v) {
                        if ($v !== false) {
                            $disabled = false;
                            break;
                        }
                    }
                    if ($disabled) {
                        $skus_services[$sku_id][$service_id] = false;
                    }
                }
            }
        }
        foreach ($services as $s_id => &$s) {
            if (!$s['variants']) {
                unset($services[$s_id]);
                continue;
            }
            if ($s['currency'] == '%') {
                foreach ($s['variants'] as $v_id => $v) {
                    $s['variants'][$v_id]['price'] = $v['price'] * $product['skus'][$product['sku_id']]['price'] / 100;
                }
                $s['currency'] = $product['currency'];
            }
            if (count($s['variants']) == 1) {
                $v = reset($s['variants']);
                if ($v['name']) {
                    $s['name'] .= ' ' . $v['name'];
                }
                $s['variant_id'] = $v['id'];
                $s['price'] = $v['price'];
                unset($s['variants']);
                foreach ($skus_services as $sku_id => $sku_services) {
                    if (isset($sku_services[$s_id]) && isset($sku_services[$s_id][$v['id']])) {
                        $skus_services[$sku_id][$s_id] = $sku_services[$s_id][$v['id']][1];
                    }
                }
            }
        }
        unset($s);
        uasort($services, array('shopServiceModel', 'sortServices'));
        $this->view->assign('sku_services', $skus_services);
        $this->view->assign('services', $services);
        $compare = waRequest::cookie('shop_compare', array(), waRequest::TYPE_ARRAY_INT);
        $this->view->assign('compare', in_array($product['id'], $compare) ? $compare : array());
        if (!$is_cart) {
            $this->view->assign('reviews', $this->getTopReviews($product['id']));
            $this->view->assign('rates', $this->reviews_model->getProductRates($product['id']));
            $this->view->assign('reviews_total_count', $this->getReviewsTotalCount($product['id']));
            $meta_fields = $this->getMetafields($product);
            $title = $meta_fields['meta_title'] ? $meta_fields['meta_title'] : $product['name'];
            wa()->getResponse()->setTitle($title);
            wa()->getResponse()->setMeta('keywords', $meta_fields['meta_keywords']);
            wa()->getResponse()->setMeta('description', $meta_fields['meta_description']);
            $feature_codes = array_keys($product->features);
            $feature_model = new shopFeatureModel();
            $features = $feature_model->getByCode($feature_codes);
            $this->view->assign('features', $features);
        }
        $this->view->assign('currency_info', $this->getCurrencyInfo());
        /**
         * @event frontend_product
         * @param shopProduct $product
         * @return array[string][string]string $return[%plugin_id%]['menu'] html output
         * @return array[string][string]string $return[%plugin_id%]['cart'] html output
         * @return array[string][string]string $return[%plugin_id%]['block_aux'] html output
         * @return array[string][string]string $return[%plugin_id%]['block'] html output
         */
        $this->view->assign('frontend_product', wa()->event('frontend_product', $product, array('menu', 'cart', 'block_aux', 'block')));
        $sku_stocks = array();
        foreach ($product->skus as $sku) {
            $sku_stocks[$sku_id] = array($sku['count'], $sku['stock']);
        }
        $stock_model = new shopStockModel();
        $this->view->assign('stocks', $stock_model->getAll('id'));
        $duble = db_query("SELECT * FROM shop_product where id=" . $product['id']);
        $dubles = mysql_fetch_assoc($duble);
        $dubles_sku = db_query("SELECT * FROM shop_product_skus where product_id=" . $product['id'] . " and  id=" . $dubles['sku_id']);
        $dubl_sku = mysql_fetch_assoc($dubles_sku);
        $dubles_prod = db_query("SELECT * FROM shop_product_skus where product_id!=" . $product['id'] . " and  sku='" . $dubl_sku['sku'] . "' Group by product_id");
        while ($dubl_product = mysql_fetch_array($dubles_prod)) {
            $dubles_img_pr = db_query("SELECT * FROM shop_product p, shop_product_images img where p.id=" . $dubl_product['product_id'] . " and img.product_id=" . $dubl_product['product_id'] . "");
            $dubles_img = mysql_fetch_assoc($dubles_img_pr);
            if ($dubles_img['status'] != 0) {
                $koldz = substr($dubles_img['product_id'], -2, 2);
                $kolds = str_replace($koldz, '', $dubles_img['product_id']);
                if (preg_match_all("#\\d#", $kolds) < 2) {
                    $kolds = '0' . $kolds;
                }
                if ($kolds == 0) {
                    $kolds = '00';
                }
                $alt_test = db_query("SELECT * FROM shop_product_features_selectable where feature_id=12 and  product_id=" . $dubles_img['product_id'] . "");
                $alt_t = mysql_fetch_assoc($alt_test);
                $alt_value = db_query("SELECT * FROM shop_feature_values_color where id=" . $alt_t['value_id'] . "");
                $alt = mysql_fetch_assoc($alt_value);
                $dubl_p = $dubl_p . ' <a  class="duble_prod"  href="http://' . $_SERVER['HTTP_HOST'] . '/index.php/' . $dubles_img['url'] . '" >
		 
		 
		 <img alt="' . $alt['value'] . '" title="' . $alt['value'] . '"  style="width:50px" src="/wa-data/public/shop/products/' . $koldz . '/' . $kolds . '/' . $dubles_img['product_id'] . '/images/' . $dubles_img['id'] . '/' . $dubles_img['id'] . '.96x96.jpg"/></a>';
                $dubl_p2 = $dubl_p2 . '<a onclick="doubl(' . $dubles_img['product_id'] . ')" class="duble_prod" >
		 
		 
		 <img alt="' . $alt['value'] . '" title="' . $alt['value'] . '" style="width:50px" src="/wa-data/public/shop/products/' . $koldz . '/' . $kolds . '/' . $dubles_img['product_id'] . '/images/' . $dubles_img['id'] . '/' . $dubles_img['id'] . '.96x96.jpg"/></a>';
            }
            $dubl_p = $dubl_p;
            $dubl_p2 = $dubl_p2;
        }
        $this->view->assign('duble', $dubl_p);
        $this->view->assign('duble2', $dubl_p2);
        $this->view->assign('duble_list', $dubl_p);
        $product['num'] = $_GET['num'];
        $this->view->assign('numis', $_GET['num']);
        $this->setThemeTemplate($is_cart ? 'product.cart.html' : 'product.html');
    }
 /**
  * @param $product_id
  * @return array - return array ids in comparison or array()
  */
 public function inComparison($product_id = null)
 {
     $ids = waRequest::cookie('shop_compare', array(), waRequest::TYPE_ARRAY_INT);
     if (!$product_id) {
         return $ids;
     }
     return in_array($product_id, $ids) ? $ids : array();
 }
 /**
  * HTML for the whole form or single form field.
  * @param string $field_id
  * @param boolean $with_errors whether to add class="error" and error text next to form fields
  */
 public function html($field_id = null, $with_errors = true, $placeholders = false)
 {
     $this->validateFields();
     // Single field?
     if ($field_id) {
         if (empty($this->fields[$field_id])) {
             return '';
         }
         $opts = $this->options;
         $opts['id'] = $field_id;
         $opts['my_profile'] = $this->fields[$field_id]->getParameter('my_profile');
         if (empty($this->contact)) {
             $this->contact = new waContact();
         }
         if ($this->post() !== null) {
             $opts['value'] = $this->fields[$field_id]->set($this->contact, $this->post($field_id), array());
         } else {
             if (isset($this->values[$field_id]) && (is_array($this->values[$field_id]) && count($this->values[$field_id]) > 0 || !is_array($this->values[$field_id]) && strlen((string) $this->values[$field_id]))) {
                 $opts['value'] = $this->fields[$field_id]->set($this->contact, $this->values[$field_id], array());
             } else {
                 $default_value = $this->fields[$field_id]->getParameter('value');
                 if ($default_value) {
                     $opts['value'] = $this->fields[$field_id]->set($this->contact, $default_value, array());
                 }
             }
         }
         // HTML with no errors?
         if ($with_errors && !empty($this->errors[$field_id]) && !empty($this->errors[$field_id])) {
             $opts['validation_errors'] = $this->errors[$field_id];
         }
         // output password field with 'confirm password' field like composite fields
         if ($field_id === 'password') {
             $this->fields[$field_id]->setParameter('localized_names', _ws('New password'));
             $opts['add_password_confirm'] = true;
         }
         if ($placeholders) {
             $opts['placeholder'] = true;
         }
         return $this->fields[$field_id]->getHTML($opts);
     }
     // Whole form
     $class_field = $this->opt('css_class_field', wa()->getEnv() == 'frontend' ? 'wa-field' : 'field');
     $class_value = $this->opt('css_class_value', wa()->getEnv() == 'frontend' ? 'wa-value' : 'value');
     $class_name = $this->opt('css_class_name', wa()->getEnv() == 'frontend' ? 'wa-name' : 'name');
     $result = '';
     foreach ($this->fields() as $fid => $f) {
         if ($fid === 'password_confirm') {
             continue;
         }
         if ($fid === 'photo') {
             $fake_user = new waContact();
             $result .= '<div class="' . $class_field . ' ' . ($class_field . '-' . $f->getId()) . '"><div class="' . $class_name . '">' . _ws('Photo') . '</div><div class="' . $class_value . '">';
             if (wa()->getUser()->get($fid)) {
                 $result .= "\n" . '<img src="' . wa()->getUser()->getPhoto() . '">';
             }
             $result .= "\n" . '<img src="' . $fake_user->getPhoto() . '">';
             $result .= "\n" . '<p><input type="file" name="' . $fid . '_file"></p>';
             $result .= $this->html($fid, true);
             $result .= "\n</div></div>";
             continue;
         }
         if ($f instanceof waContactHiddenField) {
             $result .= $this->html($fid, true);
             continue;
         }
         $field_class = $class_field . '-' . $f->getId();
         if (strpos($fid, '.') !== false) {
             $field_class .= ' ' . $class_field . '-' . str_replace('.', '-', $fid);
         }
         if ($f->isRequired()) {
             $field_class .= ' ' . (wa()->getEnv() == 'frontend' ? 'wa-required' : 'required');
         }
         $result .= '<div class="' . $class_field . ' ' . $field_class . '"><div class="' . $class_name . '">' . $f->getName(null, true) . '</div><div class="' . $class_value . '">';
         $result .= "\n" . $this->html($fid, $with_errors, $placeholders);
         $result .= "\n</div></div>";
     }
     $result .= '<input type="hidden" name="_csrf" value="' . waRequest::cookie('_csrf', '') . '" />';
     return $result;
 }
Exemple #20
0
 /**
  * Constructor
  * @param string $code Cart unique ID
  */
 public function __construct($code = '')
 {
     $this->code = waRequest::cookie(self::COOKIE_KEY, $code);
     $this->model = new shopCartItemsModel();
 }
 private function _include_tracker()
 {
     if (!($api_key = self::_get_app_key())) {
         return false;
     }
     include_once 'vendors/ConveadTracker.php';
     $auth = new waAuth();
     if (isset($_REQUEST['customer_id'])) {
         // create purchase from admin panel without customer
         $guest_uid = $_REQUEST['customer_id'] == 0 ? uniqid() : false;
         $uid = $_REQUEST['customer_id'] == 0 ? false : $_REQUEST['customer_id'];
     } else {
         $guest_uid = waRequest::cookie('convead_guest_uid');
         $uid = ($auth_info = $auth->isAuth()) ? $auth_info['id'] : false;
     }
     $tracker = new ConveadTracker($api_key, waRequest::server('SERVER_NAME'), $guest_uid, $uid, isset($this->visitor_info) ? $this->visitor_info : false);
     return $tracker;
 }
 protected function createOrder()
 {
     $checkout_data = $this->getStorage()->get('shop/checkout');
     $contact = $this->getUser()->isAuth() ? $this->getUser() : $checkout_data['contact'];
     $cart = new shopCart();
     $items = $cart->items(false);
     // remove id from item
     foreach ($items as &$item) {
         unset($item['id']);
         unset($item['parent_id']);
     }
     unset($item);
     $order = array('contact' => $contact, 'items' => $items, 'total' => $cart->total(false), 'params' => isset($checkout_data['params']) ? $checkout_data['params'] : array());
     $order['discount'] = shopDiscounts::apply($order);
     if (isset($checkout_data['shipping'])) {
         $order['params']['shipping_id'] = $checkout_data['shipping']['id'];
         $order['params']['shipping_rate_id'] = $checkout_data['shipping']['rate_id'];
         $shipping_step = new shopCheckoutShipping();
         $rate = $shipping_step->getRate($order['params']['shipping_id'], $order['params']['shipping_rate_id']);
         $order['params']['shipping_plugin'] = $rate['plugin'];
         $order['params']['shipping_name'] = $rate['name'];
         if (isset($rate['est_delivery'])) {
             $order['params']['shipping_est_delivery'] = $rate['est_delivery'];
         }
         if (!isset($order['shipping'])) {
             $order['shipping'] = $rate['rate'];
         }
         if (!empty($order['params']['shipping'])) {
             foreach ($order['params']['shipping'] as $k => $v) {
                 $order['params']['shipping_params_' . $k] = $v;
             }
             unset($order['params']['shipping']);
         }
     } else {
         $order['shipping'] = 0;
     }
     if (isset($checkout_data['payment'])) {
         $order['params']['payment_id'] = $checkout_data['payment'];
         $plugin_model = new shopPluginModel();
         $plugin_info = $plugin_model->getById($checkout_data['payment']);
         $order['params']['payment_name'] = $plugin_info['name'];
         $order['params']['payment_plugin'] = $plugin_info['plugin'];
         if (!empty($order['params']['payment'])) {
             foreach ($order['params']['payment'] as $k => $v) {
                 $order['params']['payment_params_' . $k] = $v;
             }
             unset($order['params']['payment']);
         }
     }
     if ($skock_id = waRequest::post('stock_id')) {
         $order['params']['stock_id'] = $skock_id;
     }
     $routing_url = wa()->getRouting()->getRootUrl();
     $order['params']['storefront'] = wa()->getConfig()->getDomain() . ($routing_url ? '/' . $routing_url : '');
     if (($ref = wa()->getStorage()->get('shop/referer')) || ($ref = waRequest::cookie('referer'))) {
         $order['params']['referer'] = $ref;
         $ref_parts = parse_url($ref);
         $order['params']['referer_host'] = $ref_parts['host'];
         // try get search keywords
         if (!empty($ref_parts['query'])) {
             $search_engines = array('text' => 'yandex\\.|rambler\\.', 'q' => 'bing\\.com|mail\\.|google\\.', 's' => 'nigma\\.ru', 'p' => 'yahoo\\.com');
             $q_var = false;
             foreach ($search_engines as $q => $pattern) {
                 if (preg_match('/(' . $pattern . ')/si', $ref_parts['host'])) {
                     $q_var = $q;
                     break;
                 }
             }
             // default query var name
             if (!$q_var) {
                 $q_var = 'q';
             }
             parse_str($ref_parts['query'], $query);
             if (!empty($query[$q_var])) {
                 $order['params']['keyword'] = $query[$q_var];
             }
         }
     }
     if ($utm = waRequest::cookie('utm')) {
         $utm = json_decode($utm, true);
         if ($utm && is_array($utm)) {
             foreach ($utm as $k => $v) {
                 $order['params']['utm_' . $k] = $v;
             }
         }
     }
     $order['params']['ip'] = waRequest::getIp();
     $order['params']['user_agent'] = waRequest::getUserAgent();
     foreach (array('shipping', 'billing') as $ext) {
         $address = $contact->getFirst('address.' . $ext);
         if ($address) {
             foreach ($address['data'] as $k => $v) {
                 $order['params'][$ext . '_address.' . $k] = $v;
             }
         }
     }
     if (isset($checkout_data['comment'])) {
         $order['comment'] = $checkout_data['comment'];
     }
     $workflow = new shopWorkflow();
     if ($order_id = $workflow->getActionById('create')->run($order)) {
         $step_number = shopCheckout::getStepNumber();
         $checkout_flow = new shopCheckoutFlowModel();
         $checkout_flow->add(array('step' => $step_number));
         $cart->clear();
         wa()->getStorage()->remove('shop/checkout');
         wa()->getStorage()->set('shop/order_id', $order_id);
         return true;
     }
 }
 public function init()
 {
     $files = array($this->getAppPath() . '/lib/config/config.php', $this->getPath('config') . '/apps/' . $this->application . '/config.php');
     foreach ($files as $file_path) {
         if (file_exists($file_path)) {
             $config = (include $file_path);
             if ($config && is_array($config)) {
                 foreach ($config as $name => $value) {
                     $this->options[$name] = $value;
                 }
             }
         }
     }
     $this->info = (include $this->getAppPath() . '/lib/config/app.php');
     if ($this->environment == 'backend' && !empty($this->info['csrf']) && waRequest::method() == 'post') {
         if (waRequest::post('_csrf') != waRequest::cookie('_csrf')) {
             throw new waException('CSRF Protection', 403);
         }
     }
     waAutoload::getInstance()->add($this->getClasses());
     if (file_exists($this->getAppPath() . '/lib/config/factories.php')) {
         $this->factories = (include $this->getAppPath() . '/lib/config/factories.php');
     }
     if (!empty($this->options['factories']) && is_array($this->options['factories'])) {
         foreach ($this->options['factories'] as $k => $v) {
             $this->factories[$k] = $v;
         }
     }
 }
 public function execute()
 {
     $code = waRequest::cookie('shop_cart');
     if (!$code) {
         $code = md5(uniqid(time(), true));
         // header for IE
         wa()->getResponse()->addHeader('P3P', 'CP="NOI ADM DEV COM NAV OUR STP"');
         // set cart cookie
         wa()->getResponse()->setCookie('shop_cart', $code, time() + 30 * 86400, null, '', false, true);
     }
     $this->cart = new shopCart($code);
     $this->cart_model = new shopCartItemsModel();
     $data = waRequest::post();
     $this->is_html = waRequest::request('html');
     // add service
     if (isset($data['parent_id'])) {
         $this->addService($data);
         return;
     }
     // add sku
     $sku_model = new shopProductSkusModel();
     $product_model = new shopProductModel();
     if (!isset($data['product_id'])) {
         $sku = $sku_model->getById($data['sku_id']);
         $product = $product_model->getById($sku['product_id']);
     } else {
         $product = $product_model->getById($data['product_id']);
         if (isset($data['sku_id'])) {
             $sku = $sku_model->getById($data['sku_id']);
         } else {
             if (isset($data['features'])) {
                 $product_features_model = new shopProductFeaturesModel();
                 $sku_id = $product_features_model->getSkuByFeatures($product['id'], $data['features']);
                 if ($sku_id) {
                     $sku = $sku_model->getById($sku_id);
                 } else {
                     $sku = null;
                 }
             } else {
                 $sku = $sku_model->getById($product['sku_id']);
                 if (!$sku['available']) {
                     $sku = $sku_model->getByField(array('product_id' => $product['id'], 'available' => 1));
                 }
                 if (!$sku) {
                     $this->errors = _w('This product is not available for purchase');
                     return;
                 }
             }
         }
     }
     $quantity = waRequest::post('quantity', 1);
     if ($product && $sku) {
         // check quantity
         if (!wa()->getSetting('ignore_stock_count')) {
             $c = $this->cart_model->countSku($code, $sku['id']);
             if ($sku['count'] !== null && $c + $quantity > $sku['count']) {
                 $quantity = $sku['count'] - $c;
                 $name = $product['name'] . ($sku['name'] ? ' (' . $sku['name'] . ')' : '');
                 if (!$quantity) {
                     $this->errors = sprintf(_w('Only %d pcs of %s are available, and you already have all of them in your shopping cart.'), $sku['count'], $name);
                     return;
                 } else {
                     $this->response['error'] = sprintf(_w('Only %d pcs of %s are available, and you already have all of them in your shopping cart.'), $sku['count'], $name);
                 }
             }
         }
         $services = waRequest::post('services', array());
         if ($services) {
             $variants = waRequest::post('service_variant');
             $temp = array();
             $service_ids = array();
             foreach ($services as $service_id) {
                 if (isset($variants[$service_id])) {
                     $temp[$service_id] = $variants[$service_id];
                 } else {
                     $service_ids[] = $service_id;
                 }
             }
             if ($service_ids) {
                 $service_model = new shopServiceModel();
                 $temp_services = $service_model->getById($service_ids);
                 foreach ($temp_services as $row) {
                     $temp[$row['id']] = $row['variant_id'];
                 }
             }
             $services = $temp;
         }
         $item_id = null;
         $item = $this->cart_model->getItemByProductAndServices($code, $product['id'], $sku['id'], $services);
         if ($item) {
             $item_id = $item['id'];
             $this->cart->setQuantity($item_id, $item['quantity'] + $quantity);
         }
         if (!$item_id) {
             $data = array('create_datetime' => date('Y-m-d H:i:s'), 'product_id' => $product['id'], 'sku_id' => $sku['id'], 'quantity' => $quantity, 'type' => 'product');
             if ($services) {
                 $data_services = array();
                 foreach ($services as $service_id => $variant_id) {
                     $data_services[] = array('service_id' => $service_id, 'service_variant_id' => $variant_id);
                 }
             } else {
                 $data_services = array();
             }
             $item_id = $this->cart->addItem($data, $data_services);
         }
         if (waRequest::isXMLHttpRequest()) {
             $this->response['item_id'] = $item_id;
             $this->response['total'] = $this->currencyFormat($this->cart->total());
             $this->response['discount'] = $this->currencyFormat($this->cart->discount());
             $this->response['count'] = $this->cart->count();
         } else {
             $this->redirect(waRequest::server('HTTP_REFERER'));
         }
     } else {
         throw new waException('product not found');
     }
 }