public function execute()
 {
     // Creating a model instance for retriving data from the database
     // Создаем экземпляр модели для получения данных из БД
     $model = new guestbookModel();
     // If a POST request is received then a new record is added to the database
     // Если пришёл POST-запрос, то нужно записать в БД новую запись
     if (waRequest::method() == 'post') {
         // Retrieving data from the POST request
         // Получаем данные из POST
         $name = waRequest::post('name');
         $text = waRequest::post('text');
         if ($name && $text) {
             // Inserting a new record into the table
             // Вставляем новую запись в таблицу
             $model->insert(array('name' => $name, 'text' => $text, 'datetime' => date('Y-m-d H:i:s')));
         }
         $this->redirect();
     }
     // Retrieving guestbook records from the database
     // Получаем записи гостевой книги из БД
     $records = $model->order('datetime DESC')->fetchAll();
     // Passing records to the template
     // Передаем записи в шаблон
     $this->view->assign('records', $records);
 }
 public function execute()
 {
     if (wa()->getAuth()->isAuth()) {
         $this->redirect(wa()->getAppUrl());
     }
     // check auth config
     $auth = wa()->getAuthConfig();
     if (!isset($auth['auth']) || !$auth['auth']) {
         throw new waException(_ws('Page not found'), 404);
     }
     // check auth app and url
     $signup_url = wa()->getRouteUrl((isset($auth['app']) ? $auth['app'] : '') . '/signup');
     if (wa()->getConfig()->getRequestUrl(false) != $signup_url) {
         $this->redirect($signup_url);
     }
     $errors = array();
     if (waRequest::method() == 'post') {
         // try sign up
         if ($contact = $this->signup(waRequest::post('data'), $errors)) {
             // assign new contact to view
             $this->view->assign('contact', $contact);
         }
     }
     $this->view->assign('errors', $errors);
     wa()->getResponse()->setTitle(_ws('Sign up'));
 }
 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 execute()
 {
     // Setting the frontend layout
     // Задаём лайаут для фронтенда
     $this->setLayout(new guestbook2FrontendLayout());
     // Setting the theme template
     // Задаём шаблон темы
     $this->setThemeTemplate('guestbook.html');
     // if a POST request has been received then write a new record to the database
     // Если пришёл POST-запрос, то нужно записать в БД новую запись
     if (waRequest::method() == 'post') {
         $this->add();
     }
     // Creating a model instance for retrieving data from the database
     // Создаем экземпляр модели для получения данных из БД
     $model = new guestbook2Model();
     // Retrieving the record count per page from the app's settings
     // Получаем количество записей на одной странице из настроек приложения
     $limit = $this->getConfig()->getOption('records_per_page');
     // Current page
     // Текущая страница
     $page = waRequest::param('page');
     if (!$page) {
         $page = 1;
     }
     $this->view->assign('page', $page);
     // Calculating offset
     // Вычисляем смещение
     $offset = ($page - 1) * $limit;
     // Retrieving all records from the database
     // Получаем записи гостевой книги из БД
     $records = $model->getRecords($offset, $limit);
     // Total record count
     // Всего записей
     $records_count = $model->countAll();
     $pages_count = ceil($records_count / $limit);
     $this->view->assign('pages_count', $pages_count);
     // Preparing records for being passed to the theme template
     // Подготавливаем записи для передачи в шаблон темы
     foreach ($records as &$r) {
         if ($r['contact_id']) {
             $r['name'] = htmlspecialchars($r['contact_name']);
             // getting contact photo URL
             // получаем URL на фотографию контакта
             $r['photo_url'] = waContact::getPhotoUrl($r['contact_id'], $r['photo'], 20);
         } else {
             $r['name'] = htmlspecialchars($r['name']);
         }
         $r['text'] = nl2br(htmlspecialchars($r['text']));
     }
     unset($r);
     // Passing records to the template
     // Передаем записи в шаблон
     $this->view->assign('records', $records);
     // URL portion for links to pages
     // Часть урла для ссылок на страницы
     $this->view->assign('url', wa()->getRouteUrl('/frontend'));
 }
 public function updateLastPage()
 {
     if (waRequest::isXMLHttpRequest() || !$this->id || wa()->getEnv() !== 'backend' || waRequest::method() == 'post') {
         return;
     }
     $page = wa()->getRequest()->server('REQUEST_URI');
     $backend = wa()->getConfig()->getBackendUrl(true);
     if ($page === $backend || substr($page, 0, strlen($backend) + 1) === $backend . '?') {
         return;
     }
     wa()->getResponse()->setCookie('last_page', $this->getId() . '^^^' . $page, null, null, '', false, true);
 }
Example #6
0
 public function getResponse($internal = false)
 {
     if (!$internal) {
         // check request method
         $request_method = strtoupper(waRequest::method());
         if (is_array($this->method) && !in_array($request_method, $this->method) || !is_array($this->method) && $request_method != $this->method) {
             throw new waAPIException('invalid_request', 'Method ' . $request_method . ' not allowed', 405);
         }
     }
     $this->execute();
     return $this->response;
 }
 public function execute()
 {
     $cart = new shopCart();
     $total = $cart->total();
     $shipping = new shopCheckoutShipping();
     $items = $shipping->getItems();
     if (waRequest::method() == 'post') {
         wa()->getStorage()->close();
         $shipping_id = waRequest::post('shipping_id');
         $customer = waRequest::post('customer_' . $shipping_id);
         if (isset($customer['address.shipping'])) {
             $address = $customer['address.shipping'];
         } else {
             $address = array();
         }
         if ($shipping_id) {
             $this->response = $this->getRates($shipping_id, $items, $address, $total);
         } else {
             $this->errors = _w('Shipping is required');
         }
     } elseif ($shipping_ids = waRequest::get('shipping_id', array(), waRequest::TYPE_ARRAY_INT)) {
         $address = $shipping->getAddress();
         wa()->getStorage()->close();
         $empty = true;
         foreach ($address as $v) {
             if ($v) {
                 $empty = false;
                 break;
             }
         }
         if ($empty) {
             $address = array();
         }
         if (!$address) {
             $settings = wa('shop')->getConfig()->getCheckoutSettings();
             if ($settings['contactinfo']['fields']['address']) {
                 foreach ($settings['contactinfo']['fields']['address']['fields'] as $k => $f) {
                     if (!empty($f['value'])) {
                         $address[$k] = $f['value'];
                     }
                 }
             }
         }
         foreach ($shipping_ids as $shipping_id) {
             $this->response[$shipping_id] = $this->getRates($shipping_id, $items, $address, $total);
         }
     }
 }
 public function execute()
 {
     // Задаём лайаут для фронтенда
     $this->setLayout(new guestbook2FrontendLayout());
     // Задаём шаблон темы
     $this->setThemeTemplate('guestbook.html');
     // Если пришёл POST-запрос, то нужно записать в БД новую запись
     if (waRequest::method() == 'post') {
         $this->add();
     }
     // Создаем экземпляр модели для получения данных из БД
     $model = new guestbook2Model();
     // Получаем количество записей на одной странице из настроек приложения
     $limit = $this->getConfig()->getOption('records_per_page');
     // Текущая страница
     $page = waRequest::param('page');
     if (!$page) {
         $page = 1;
     }
     $this->view->assign('page', $page);
     // Вычисляем смещение
     $offset = ($page - 1) * $limit;
     // Получаем записи гостевой книги из БД
     $records = $model->getRecords($offset, $limit);
     // Всего записей
     $records_count = $model->countAll();
     $pages_count = ceil($records_count / $limit);
     $this->view->assign('pages_count', $pages_count);
     // Подготавливаем записи для передачи в шаблон темы
     foreach ($records as &$r) {
         if ($r['contact_id']) {
             $r['name'] = htmlspecialchars($r['contact_name']);
             // получаем URL на фотографию контакта
             $r['photo_url'] = waContact::getPhotoUrl($r['contact_id'], $r['photo'], 20);
         } else {
             $r['name'] = htmlspecialchars($r['name']);
         }
         $r['text'] = nl2br(htmlspecialchars($r['text']));
     }
     unset($r);
     // Передаем записи в шаблон
     $this->view->assign('records', $records);
     // Часть урла для ссылок на страницы
     $this->view->assign('url', wa()->getRouteUrl('/frontend'));
 }
 public function execute()
 {
     // Создаем экземпляр модели для получения данных из БД
     $model = new guestbookModel();
     // Если пришёл POST-запрос, то нужно записать в БД новую запись
     if (waRequest::method() == 'post') {
         // Получаем данные из POST
         $name = waRequest::post('name');
         $text = waRequest::post('text');
         if ($name && $text) {
             // Вставляем новую запись в таблицу
             $model->insert(array('name' => $name, 'text' => $text, 'datetime' => date('Y-m-d H:i:s')));
         }
         $this->redirect();
     }
     // Получаем записи гостевой книги из БД
     $records = $model->order('datetime DESC')->fetchAll();
     // Передаем записи в шаблон
     $this->view->assign('records', $records);
 }
 public function execute()
 {
     if (!waRequest::isMobile()) {
         $this->setLayout(new webasystLoginLayout());
     }
     $this->response_type = waRequest::get('response_type');
     $this->client_id = waRequest::get('client_id');
     $this->client_name = waRequest::get('client_name');
     if ($this->response_type === 'token') {
         $this->required_fields['redirect_uri'] = true;
     }
     if (!$this->checkRequest()) {
         $this->template = 'ApiError';
         return;
     }
     $this->contact_id = $this->getUser()->getId();
     if (waRequest::method() == 'post') {
         if (waRequest::post('approve')) {
             $this->approve();
         } else {
             $this->deny();
         }
     } else {
         $tokens_model = new waApiTokensModel();
         $token = $tokens_model->getByField(array('contact_id' => $this->contact_id, 'client_id' => $this->client_id));
         // if token exists then create auth code and redirect to redirect_uri
         if ($token) {
             $this->approve();
         }
     }
     $this->view->assign('client_name', $this->client_name, true);
     $scope = explode(',', waRequest::get('scope'));
     $apps = array();
     foreach ($scope as $app_id) {
         if (wa()->appExists($app_id)) {
             $apps[] = wa()->getAppInfo($app_id);
         }
     }
     $this->view->assign('scope', $apps);
 }
Example #11
0
 public function execute()
 {
     $confirm_hash = waRequest::get('confirm', false);
     if (wa()->getAuth()->isAuth() && !$confirm_hash) {
         $this->redirect(wa()->getAppUrl());
     }
     // check auth config
     $auth = wa()->getAuthConfig();
     if (!isset($auth['auth']) || !$auth['auth']) {
         throw new waException(_ws('Page not found'), 404);
     }
     // check auth app and url
     $signup_url = wa()->getRouteUrl((isset($auth['app']) ? $auth['app'] : '') . '/signup');
     if (urldecode(wa()->getConfig()->getRequestUrl(false, true)) != $signup_url) {
         $this->redirect($signup_url);
     }
     $errors = array();
     if (waRequest::method() == 'post') {
         // try sign up
         if ($contact = $this->signup(waRequest::post('data'), $errors)) {
             // assign new contact to view
             $this->view->assign('contact', $contact);
         }
     } elseif ($confirm_hash) {
         if ($contact = $this->confirmEmail($confirm_hash, $errors)) {
             // if we successfully confirmed email
             // assign contact with confirmed email to view
             $this->view->assign('contact', $contact);
             $this->view->assign('confirmed_email', true);
         } else {
             // else email is already confirmed or smth else happend
             if (wa()->getAuth()->isAuth()) {
                 // redirect to main page
                 $this->redirect(wa()->getAppUrl());
             }
         }
     }
     $this->view->assign('errors', $errors);
     wa()->getResponse()->setTitle(_ws('Sign up'));
 }
 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 themeUpdateAction()
 {
     $theme_id = waRequest::get('theme');
     $theme = new waTheme($theme_id);
     if (waRequest::method() == 'post') {
         if (!waRequest::post("parent_only")) {
             if (waRequest::post('reset')) {
                 foreach (waRequest::post('reset') as $f) {
                     $theme->revertFile($f);
                 }
             }
             $theme->update(false);
         }
         if ($theme->parent_theme && $theme->parent_theme->type == waTheme::OVERRIDDEN) {
             if (waRequest::post('parent_reset')) {
                 foreach (waRequest::post('parent_reset') as $f) {
                     $theme->parent_theme->revertFile($f);
                 }
             }
             $theme->parent_theme->update(false);
         }
         $this->displayJson(array());
     } else {
         $theme_original = new waTheme($theme_id, true, 'original');
         $data = array('theme' => $theme, 'theme_original_version' => $theme_original->version);
         if ($theme->parent_theme && $theme->version == $theme_original->version && $theme->parent_theme->type == waTheme::OVERRIDDEN) {
             $parent_theme_original = new waTheme($theme->parent_theme->id, $theme->parent_theme->app, 'original');
             $data['theme_original_version'] = $parent_theme_original->version;
             $data['parent_only'] = true;
         }
         $this->display($data, $this->getConfig()->getRootPath() . '/wa-system/design/templates/ThemeUpdate.html');
     }
 }
 protected function forgotPassword()
 {
     $error = '';
     $auth = wa()->getAuth();
     if (waRequest::method() == 'post' && !waRequest::post('ignore')) {
         if ($contact = $this->findContact(waRequest::post('login'), $auth)) {
             if ($contact->get('is_banned')) {
                 $error = _ws('Password recovery for this email has been banned.');
             } elseif ($email = $contact->get('email', 'default')) {
                 if ($contact['locale']) {
                     wa()->setLocale($contact['locale']);
                     waLocale::loadByDomain('webasyst', wa()->getLocale());
                 }
                 $hash = $this->getHash($contact['id'], true);
                 if ($this->send($email, $this->getResetPasswordUrl($hash))) {
                     $this->view->assign('sent', 1);
                 } else {
                     $error = _ws('Sorry, we can not recover password for this login name or email. Please refer to your system administrator.');
                 }
             }
         } else {
             if ($auth->getOption('login') == 'email') {
                 $error = _ws('No user with this email has been found.');
             } else {
                 $error = _ws('No user with this login name or email has been found.');
             }
         }
     }
     $this->view->assign('options', $auth->getOptions());
     $this->view->assign('error', $error);
     if ($this->layout) {
         $this->layout->assign('error', $error);
     }
     wa()->getResponse()->setTitle(_ws('Password recovery'));
 }
 public function checkout($templates)
 {
     $view = wa()->getView();
     $steps = wa()->getConfig()->getCheckoutSettings();
     $cart = new shopCart();
     if (!$cart->count()) {
         return false;
     }
     if (waRequest::method() == 'post') {
         if (waRequest::post('wa_auth_login')) {
             $login_action = new shopLoginAction();
             $login_action->run();
         } else {
             $error = false;
             foreach ($steps as $step_id => $step) {
                 $step_instance = self::getStep($step_id);
                 if (!$step_instance->execute()) {
                     $error = true;
                 }
             }
             if (waRequest::post('confirmation') && !$error && !self::checkCart()) {
                 if (self::createOrder()) {
                     wa()->getResponse()->redirect(wa()->getRouteUrl('/frontend/checkout', array('step' => 'success')));
                 }
             }
         }
     }
     $checkout_tpls = array();
     foreach ($steps as $step_id => $step) {
         $step = self::getStep($step_id);
         $step->initDefault();
         $steps[$step_id]['content'] = $step->display();
         /**
          * @event frontend_checkout
          * @return array[string]string $return[%plugin_id%] html output
          */
         $event_params = array('step' => $step_id);
         $view->assign('frontend_checkout', wa()->event('frontend_checkout', $event_params));
         $step_tpl_path = $templates['checkout.' . $step_id]['template_path'];
         $step_tpl = $view->fetch($step_tpl_path);
         $checkout_tpls[$step_id] = $step_tpl;
     }
     $view->assign('checkout_tpls', $checkout_tpls);
     $view->assign('checkout_steps', $steps);
 }
 public function execute()
 {
     $this->getResponse()->addHeader("Cache-Control", "no-store, no-cache, must-revalidate");
     $this->getResponse()->addHeader("Expires", date("r"));
     if (waRequest::method() == 'post') {
         $data = wa()->getStorage()->get('shop/checkout', array());
         if ($coupon_code = waRequest::post('coupon_code')) {
             $data['coupon_code'] = $coupon_code;
         } elseif (isset($data['coupon_code'])) {
             unset($data['coupon_code']);
         }
         if (($use = waRequest::post('use_affiliate')) !== null) {
             if ($use) {
                 $data['use_affiliate'] = 1;
             } elseif (isset($data['use_affiliate'])) {
                 unset($data['use_affiliate']);
             }
         }
         if ($coupon_code || $use) {
             wa()->getStorage()->set('shop/checkout', $data);
             wa()->getStorage()->remove('shop/cart');
         }
     }
     $cart_model = new shopCartItemsModel();
     $cart = new shopCart();
     $code = $cart->getCode();
     $errors = array();
     if (waRequest::post('checkout')) {
         $saved_quantity = $cart_model->select('id,quantity')->where("type='product' AND code = s:code", array('code' => $code))->fetchAll('id');
         $quantity = waRequest::post('quantity');
         foreach ($quantity as $id => $q) {
             if ($q != $saved_quantity[$id]) {
                 $cart->setQuantity($id, $q);
             }
         }
         $not_available_items = $cart_model->getNotAvailableProducts($code, !wa()->getSetting('ignore_stock_count'));
         foreach ($not_available_items as $row) {
             if ($row['sku_name']) {
                 $row['name'] .= ' (' . $row['sku_name'] . ')';
             }
             if ($row['available']) {
                 $errors[$row['id']] = sprintf(_w('Only %d pcs of %s are available, and you already have all of them in your shopping cart.'), $row['count'], $row['name']);
             } else {
                 $errors[$row['id']] = _w('Oops! %s is not available for purchase at the moment. Please remove this product from your shopping cart to proceed.');
             }
         }
         if (!$errors) {
             $this->redirect(wa()->getRouteUrl('/frontend/checkout'));
         }
     }
     $this->setThemeTemplate('cart.html');
     $items = $cart_model->where('code= ?', $code)->order('parent_id')->fetchAll('id');
     $product_ids = $sku_ids = $service_ids = $type_ids = array();
     foreach ($items as $item) {
         $product_ids[] = $item['product_id'];
         $sku_ids[] = $item['sku_id'];
     }
     $product_ids = array_unique($product_ids);
     $sku_ids = array_unique($sku_ids);
     $product_model = new shopProductModel();
     if (waRequest::param('url_type') == 2) {
         $products = $product_model->getWithCategoryUrl($product_ids);
     } else {
         $products = $product_model->getById($product_ids);
     }
     $sku_model = new shopProductSkusModel();
     $skus = $sku_model->getByField('id', $sku_ids, 'id');
     $image_model = new shopProductImagesModel();
     $delete_items = array();
     foreach ($items as $item_id => &$item) {
         if (!isset($skus[$item['sku_id']])) {
             unset($items[$item_id]);
             $delete_items[] = $item_id;
             continue;
         }
         if ($item['type'] == 'product') {
             $item['product'] = $products[$item['product_id']];
             $sku = $skus[$item['sku_id']];
             if ($sku['image_id'] && $sku['image_id'] != $item['product']['image_id']) {
                 $img = $image_model->getById($sku['image_id']);
                 if ($img) {
                     $item['product']['image_id'] = $sku['image_id'];
                     $item['product']['ext'] = $img['ext'];
                 }
             }
             $item['sku_name'] = $sku['name'];
             $item['sku_code'] = $sku['sku'];
             $item['price'] = $sku['price'];
             $item['compare_price'] = $sku['compare_price'];
             $item['currency'] = $item['product']['currency'];
             $type_ids[] = $item['product']['type_id'];
             if (isset($errors[$item_id])) {
                 $item['error'] = $errors[$item_id];
                 if (strpos($item['error'], '%s') !== false) {
                     $item['error'] = sprintf($item['error'], $item['product']['name'] . ($item['sku_name'] ? ' (' . $item['sku_name'] . ')' : ''));
                 }
             }
         }
     }
     unset($item);
     if ($delete_items) {
         $cart_model->deleteByField(array('code' => $code, 'id' => $delete_items));
     }
     $type_ids = array_unique($type_ids);
     // get available services for all types of products
     $type_services_model = new shopTypeServicesModel();
     $rows = $type_services_model->getByField('type_id', $type_ids, true);
     $type_services = array();
     foreach ($rows as $row) {
         $service_ids[] = $row['service_id'];
         $type_services[$row['type_id']][$row['service_id']] = true;
     }
     // get services for all products
     $product_services_model = new shopProductServicesModel();
     $rows = $product_services_model->getByProducts($product_ids);
     $product_services = $sku_services = array();
     foreach ($rows as $row) {
         if ($row['sku_id'] && !in_array($row['sku_id'], $sku_ids)) {
             continue;
         }
         $service_ids[] = $row['service_id'];
         if (!$row['sku_id']) {
             $product_services[$row['product_id']][$row['service_id']]['variants'][$row['service_variant_id']] = $row;
         }
         if ($row['sku_id']) {
             $sku_services[$row['sku_id']][$row['service_id']]['variants'][$row['service_variant_id']] = $row;
         }
     }
     $service_ids = array_unique($service_ids);
     $service_model = new shopServiceModel();
     $variant_model = new shopServiceVariantsModel();
     $services = $service_model->getByField('id', $service_ids, 'id');
     foreach ($services as &$s) {
         unset($s['id']);
     }
     unset($s);
     $rows = $variant_model->getByField('service_id', $service_ids, true);
     foreach ($rows as $row) {
         $services[$row['service_id']]['variants'][$row['id']] = $row;
         unset($services[$row['service_id']]['variants'][$row['id']]['id']);
     }
     foreach ($items as $item_id => $item) {
         if ($item['type'] == 'product') {
             $p = $item['product'];
             $item_services = array();
             // services from type settings
             if (isset($type_services[$p['type_id']])) {
                 foreach ($type_services[$p['type_id']] as $service_id => &$s) {
                     $item_services[$service_id] = $services[$service_id];
                 }
             }
             // services from product settings
             if (isset($product_services[$item['product_id']])) {
                 foreach ($product_services[$item['product_id']] as $service_id => $s) {
                     if (!isset($s['status']) || $s['status']) {
                         if (!isset($item_services[$service_id])) {
                             $item_services[$service_id] = $services[$service_id];
                         }
                         // update variants
                         foreach ($s['variants'] as $variant_id => $v) {
                             if ($v['status']) {
                                 if ($v['price'] !== null) {
                                     $item_services[$service_id]['variants'][$variant_id]['price'] = $v['price'];
                                 }
                             } else {
                                 unset($item_services[$service_id]['variants'][$variant_id]);
                             }
                         }
                     } elseif (isset($item_services[$service_id])) {
                         // remove disabled service
                         unset($item_services[$service_id]);
                     }
                 }
             }
             // services from sku settings
             if (isset($sku_services[$item['sku_id']])) {
                 foreach ($sku_services[$item['sku_id']] as $service_id => $s) {
                     if (!isset($s['status']) || $s['status']) {
                         // update variants
                         foreach ($s['variants'] as $variant_id => $v) {
                             if ($v['status']) {
                                 if ($v['price'] !== null) {
                                     $item_services[$service_id]['variants'][$variant_id]['price'] = $v['price'];
                                 }
                             } else {
                                 unset($item_services[$service_id]['variants'][$variant_id]);
                             }
                         }
                     } elseif (isset($item_services[$service_id])) {
                         // remove disabled service
                         unset($item_services[$service_id]);
                     }
                 }
             }
             foreach ($item_services as $s_id => &$s) {
                 if (!$s['variants']) {
                     unset($item_services[$s_id]);
                     continue;
                 }
                 if ($s['currency'] == '%') {
                     foreach ($s['variants'] as $v_id => $v) {
                         $s['variants'][$v_id]['price'] = $v['price'] * $item['price'] / 100;
                     }
                     $s['currency'] = $item['currency'];
                 }
                 if (count($s['variants']) == 1) {
                     $v = reset($s['variants']);
                     $s['price'] = $v['price'];
                     unset($s['variants']);
                 }
             }
             unset($s);
             uasort($item_services, array('shopServiceModel', 'sortServices'));
             $items[$item_id]['services'] = $item_services;
         } else {
             $items[$item['parent_id']]['services'][$item['service_id']]['id'] = $item['id'];
             if (isset($item['service_variant_id'])) {
                 $items[$item['parent_id']]['services'][$item['service_id']]['variant_id'] = $item['service_variant_id'];
             }
             unset($items[$item_id]);
         }
     }
     foreach ($items as $item_id => $item) {
         $price = shop_currency($item['price'] * $item['quantity'], $item['currency'], null, false);
         if (isset($item['services'])) {
             foreach ($item['services'] as $s) {
                 if (!empty($s['id'])) {
                     if (isset($s['variants'])) {
                         $price += shop_currency($s['variants'][$s['variant_id']]['price'] * $item['quantity'], $s['currency'], null, false);
                     } else {
                         $price += shop_currency($s['price'] * $item['quantity'], $s['currency'], null, false);
                     }
                 }
             }
         }
         $items[$item_id]['full_price'] = $price;
     }
     $total = $cart->total(false);
     $order = array('total' => $total, 'items' => $items);
     $order['discount'] = $discount = shopDiscounts::calculate($order);
     $order['total'] = $total = $total - $order['discount'];
     $data = wa()->getStorage()->get('shop/checkout');
     $this->view->assign('cart', array('items' => $items, 'total' => $total, 'count' => $cart->count()));
     $this->view->assign('coupon_code', isset($data['coupon_code']) ? $data['coupon_code'] : '');
     if (shopAffiliate::isEnabled()) {
         $affiliate_bonus = 0;
         if ($this->getUser()->isAuth()) {
             $customer_model = new shopCustomerModel();
             $customer = $customer_model->getById($this->getUser()->getId());
             $affiliate_bonus = $customer ? round($customer['affiliate_bonus'], 2) : 0;
         }
         $this->view->assign('affiliate_bonus', $affiliate_bonus);
         $use = !empty($data['use_affiliate']);
         $this->view->assign('use_affiliate', $use);
         if ($use) {
             $discount -= shop_currency(shopAffiliate::convertBonus($order['params']['affiliate_bonus']), $this->getConfig()->getCurrency(true), null, false);
             $this->view->assign('used_affiliate_bonus', $order['params']['affiliate_bonus']);
         }
         $order['currency'] = $this->getConfig()->getCurrency(false);
         $add_affiliate_bonus = shopAffiliate::calculateBonus($order);
         $this->view->assign('add_affiliate_bonus', round($add_affiliate_bonus, 2));
     }
     $this->view->assign('discount', $discount);
     /**
      * @event frontend_cart
      * @return array[string]string $return[%plugin_id%] html output
      */
     $this->view->assign('frontend_cart', wa()->event('frontend_cart'));
     $this->getResponse()->setTitle(_w('Cart'));
     $checkout_flow = new shopCheckoutFlowModel();
     $checkout_flow->add(array('code' => $code, 'step' => 0, 'description' => null));
 }
Example #17
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;
         }
     }
 }
 public function execute()
 {
     $steps = $this->getConfig()->getCheckoutSettings();
     $current_step = waRequest::param('step', waRequest::request('step'));
     if (!$current_step) {
         $current_step = key($steps);
     }
     $title = _w('Checkout');
     if ($current_step == 'success') {
         $order_id = waRequest::get('order_id');
         if (!$order_id) {
             $order_id = wa()->getStorage()->get('shop/order_id');
             $payment_success = false;
         } else {
             $payment_success = true;
             $this->view->assign('payment_success', true);
         }
         if (!$order_id) {
             wa()->getResponse()->redirect(wa()->getRouteUrl('shop/frontend'));
         }
         $order_model = new shopOrderModel();
         $order = $order_model->getById($order_id);
         if ($order) {
             $order['_id'] = $order['id'];
         }
         if (!$payment_success) {
             $order_params_model = new shopOrderParamsModel();
             $order['params'] = $order_params_model->get($order_id);
             $order_items_model = new shopOrderItemsModel();
             $order['items'] = $order_items_model->getByField('order_id', $order_id, true);
             $payment = '';
             if (!empty($order['params']['payment_id'])) {
                 try {
                     /**
                      * @var waPayment $plugin
                      */
                     $plugin = shopPayment::getPlugin(null, $order['params']['payment_id']);
                     $payment = $plugin->payment(waRequest::post(), shopPayment::getOrderData($order, $plugin), true);
                 } catch (waException $ex) {
                     $payment = $ex->getMessage();
                 }
             }
             $order['id'] = shopHelper::encodeOrderId($order_id);
             $this->getResponse()->addGoogleAnalytics($this->getGoogleAnalytics($order));
         } else {
             $order['id'] = shopHelper::encodeOrderId($order_id);
         }
         $this->view->assign('order', $order);
         if (isset($payment)) {
             $this->view->assign('payment', $payment);
         }
     } else {
         $cart = new shopCart();
         if (!$cart->count() && $current_step != 'error') {
             $current_step = 'error';
             $this->view->assign('error', _w('Your shopping cart is empty. Please add some products to cart, and then proceed to checkout.'));
         }
         if ($current_step != 'error') {
             if (waRequest::method() == 'post') {
                 if (waRequest::post('wa_auth_login')) {
                     $login_action = new shopLoginAction();
                     $login_action->run();
                 } else {
                     $redirect = false;
                     foreach ($steps as $step_id => $step) {
                         if ($step_id == $current_step) {
                             $step_instance = $this->getStep($step_id);
                             if ($step_instance->execute()) {
                                 $redirect = true;
                             }
                         } elseif ($redirect) {
                             $this->redirect(wa()->getRouteUrl('/frontend/checkout', array('step' => $step_id)));
                         }
                     }
                     // last step
                     if ($redirect) {
                         if ($this->createOrder()) {
                             $this->redirect(wa()->getRouteUrl('/frontend/checkout', array('step' => 'success')));
                         }
                     }
                 }
             } else {
                 $this->view->assign('error', '');
             }
             $title .= ' - ' . $steps[$current_step]['name'];
             $steps[$current_step]['content'] = $this->getStep($current_step)->display();
             $this->view->assign('checkout_steps', $steps);
         }
     }
     $this->getResponse()->setTitle($title);
     $this->view->assign('checkout_current_step', $current_step);
     /**
      * @event frontend_checkout
      * @return array[string]string $return[%plugin_id%] html output
      */
     $event_params = array('step' => $current_step);
     $this->view->assign('frontend_checkout', wa()->event('frontend_checkout', $event_params));
     if (waRequest::isXMLHttpRequest()) {
         $this->setThemeTemplate('checkout.' . $current_step . '.html');
     } else {
         $this->setLayout(new shopFrontendLayout());
         $this->setThemeTemplate('checkout.html');
     }
 }
 public function display()
 {
     $plugin_model = new shopPluginModel();
     if (waRequest::param('shipping_id') && is_array(waRequest::param('shipping_id'))) {
         $methods = $plugin_model->getById(waRequest::param('shipping_id'));
     } else {
         $methods = $plugin_model->listPlugins('shipping');
     }
     $address = $this->getAddress();
     $empty = true;
     foreach ($address as $v) {
         if ($v) {
             $empty = false;
             break;
         }
     }
     if ($empty) {
         $address = array();
     }
     $items = $this->getItems();
     $cart = new shopCart();
     $total = $cart->total();
     $settings = wa('shop')->getConfig()->getCheckoutSettings();
     $address_form = !isset($settings['contactinfo']) || !isset($settings['contactinfo']['fields']['address.shipping']);
     if (!isset($settings['contactinfo']) || !isset($settings['contactinfo']['fields']['address.shipping']) && !isset($settings['contactinfo']['fields']['address'])) {
         $settings = wa('shop')->getConfig()->getCheckoutSettings(true);
     }
     if (!$address) {
         $shipping_address = array();
         $address_form = true;
         if ($settings['contactinfo']['fields']['address']) {
             foreach ($settings['contactinfo']['fields']['address']['fields'] as $k => $f) {
                 if (!empty($f['value'])) {
                     $shipping_address[$k] = $f['value'];
                 }
             }
         }
     } else {
         $shipping_address = $address;
     }
     if (waRequest::method() == 'post') {
         $shipping_id = waRequest::post('shipping_id');
         $rate_id = waRequest::post('rate_id');
         $selected_shipping = array('id' => $shipping_id, 'rate_id' => !empty($rate_id[$shipping_id]) ? $rate_id[$shipping_id] : '');
     } else {
         $selected_shipping = $this->getSessionData('shipping', array());
     }
     $dimension = shopDimension::getInstance()->getDimension('weight');
     $currencies = wa('shop')->getConfig()->getCurrencies();
     foreach ($methods as $method_id => $m) {
         $plugin = shopShipping::getPlugin($m['plugin'], $m['id']);
         $plugin_info = $plugin->info($m['plugin']);
         $m['icon'] = $plugin_info['icon'];
         $m['img'] = $plugin_info['img'];
         $m['currency'] = $plugin->allowedCurrency();
         $weight_unit = $plugin->allowedWeightUnit();
         if ($weight_unit != $dimension['base_unit']) {
             $shipping_items = array();
             foreach ($items as $item_id => $item) {
                 if ($item['weight']) {
                     $item['weight'] = $item['weight'] / $dimension['units'][$weight_unit]['multiplier'];
                 }
                 $shipping_items[$item_id] = $item;
             }
         } else {
             $shipping_items = $items;
         }
         $m['external'] = $selected_shipping && $selected_shipping['id'] == $m['id'] ? 0 : $plugin->getProperties('external');
         if ($m['external']) {
             $m['rates'] = array();
         } else {
             $m['rates'] = $plugin->getRates($shipping_items, $shipping_address, array('total_price' => $total));
         }
         if (is_array($m['rates'])) {
             if (!isset($currencies[$m['currency']])) {
                 $m['rate'] = 0;
                 $m['error'] = sprintf(_w('Shipping rate was not calculated because required currency %s is not defined in your store settings.'), $m['currency']);
                 $methods[$method_id] = $m;
                 continue;
             }
             foreach ($m['rates'] as &$r) {
                 if (is_array($r['rate'])) {
                     $r['rate'] = max($r['rate']);
                 }
             }
             if ($m['rates']) {
                 if (!empty($selected_shipping['rate_id']) && isset($m['rates'][$selected_shipping['rate_id']])) {
                     $rate = $m['rates'][$selected_shipping['rate_id']];
                 } else {
                     $rate = reset($m['rates']);
                 }
                 $m['rate'] = $rate['rate'];
                 $m['est_delivery'] = isset($rate['est_delivery']) ? $rate['est_delivery'] : '';
                 if (!empty($rate['comment'])) {
                     $m['comment'] = $rate['comment'];
                 }
             } else {
                 $m['rates'] = array();
                 $m['rate'] = null;
             }
         } elseif (is_string($m['rates'])) {
             if ($address) {
                 $m['error'] = $m['rates'];
             } else {
                 $m['rates'] = array();
                 $m['rate'] = null;
             }
         } else {
             unset($methods[$method_id]);
             continue;
         }
         $custom_fields = $this->getCustomFields($method_id, $plugin);
         $custom_html = '';
         foreach ($custom_fields as $c) {
             $custom_html .= '<div class="wa-field">' . $c . '</div>';
         }
         if ($custom_html) {
             $m['custom_html'] = $custom_html;
         }
         $f = $this->getAddressForm($m['id'], $plugin, $settings, $address, $address_form);
         if ($f) {
             $m['form'] = $f;
             $m['form']->setValue($this->getContact());
         }
         $methods[$method_id] = $m;
     }
     $view = wa()->getView();
     $view->assign('checkout_shipping_methods', $methods);
     $default_method = '';
     foreach ($methods as $m) {
         if (empty($m['error'])) {
             $default_method = $m['id'];
             break;
         }
     }
     $view->assign('shipping', $selected_shipping ? $selected_shipping : array('id' => $default_method, 'rate_id' => ''));
     $checkout_flow = new shopCheckoutFlowModel();
     $step_number = shopOnestepCheckout::getStepNumber('shipping');
     // IF no errors
     $checkout_flow->add(array('step' => $step_number));
     // ELSE
     //        $checkout_flow->add(array(
     //            'step' => $step_number,
     //            'description' => ERROR MESSAGE HERE
     //        ));
 }