public function execute()
 {
     if (!$this->getRights('settings')) {
         throw new waAPIException('access_denied', 403);
     }
     $code = $this->post('code', true);
     $type = $this->post('type', true);
     $this->post('name', true);
     $feature_model = new shopFeatureModel();
     if ($feature_model->getByCode($code)) {
         throw new waAPIException('invalid_param', 'Code ' . $code . ' already exists');
     }
     $types = array(shopFeatureModel::TYPE_BOOLEAN, shopFeatureModel::TYPE_DOUBLE, shopFeatureModel::TYPE_TEXT, shopFeatureModel::TYPE_VARCHAR, shopFeatureModel::TYPE_COLOR);
     if (!in_array($type, $types)) {
         throw new waAPIException('invalid_param', 'Invalid type: ' . $type);
     }
     $data = waRequest::post();
     $feature_id = $feature_model->insert($data);
     if ($feature_id) {
         $_GET['id'] = $feature_id;
         $method = new shopFeatureGetInfoMethod();
         $this->response = $method->getResponse(true);
     } else {
         throw new waAPIException('server_error', 500);
     }
 }
 public function execute()
 {
     $app_settings_model = new waAppSettingsModel();
     $settings = $app_settings_model->get(array('shop', 'yoss'));
     if ($settings['status'] === 'on') {
         $query = waRequest::post('query', '', waRequest::TYPE_STRING_TRIM);
         $page = waRequest::post('page', 1, 'int');
         $result = array();
         $result['products'] = array();
         $result['product_count'] = 0;
         $collection = new shopProductsCollection('search/query=' . $query);
         $product_limit = $settings['product_limit'];
         if (!$product_limit) {
             $product_limit = $this->getConfig()->getOption('products_per_page');
         }
         $products = $collection->getProducts('*', ($page - 1) * $product_limit, $product_limit);
         if ($products) {
             $brands = array();
             $categories = array();
             $feature_model = new shopFeatureModel();
             $result['searh_all_url'] = wa()->getRouteUrl('/frontend/search/query=') . '?query=' . $query;
             foreach ($products as $p) {
                 $brand_feature = $feature_model->getByCode('brand');
                 $brand = '';
                 if ($brand_feature) {
                     $feature_value_model = $feature_model->getValuesModel($brand_feature['type']);
                     $product_brands = $feature_value_model->getProductValues($p['id'], $brand_feature['id']);
                     $brands = array();
                     foreach ($product_brands as $k => $v) {
                         $brand_id = $feature_value_model->getValueId($brand_feature['id'], $v);
                         $brands[] = array('id' => $brand_id, 'brand' => '<a href="' . wa()->getRouteUrl('shop/frontend/brand', array('brand' => str_replace('%2F', '/', urlencode($v)))) . '">' . $v . '</a>');
                     }
                 }
                 $category_model = new shopCategoryModel();
                 $category = $category_model->getById($p['category_id']);
                 $res_category = '';
                 if ($category) {
                     $res_category = '<a href="' . wa()->getRouteUrl('/frontend/category', array('category_url' => $category['full_url'])) . '">' . $category['name'] . '</a>';
                 }
                 $result['products'][] = array("name" => $p['name'], "url" => $p['frontend_url'], "image" => $p['image_id'] ? "<img src='" . shopImage::getUrl(array("product_id" => $p['id'], "id" => $p['image_id'], "ext" => $p['ext']), "48x48") . "' />" : "", "price" => shop_currency_html($p['price'], true), "brands" => $brands, "category" => $res_category);
             }
             $product_model = new shopProductModel();
             $product_count = $collection->count();
             $result['product_count'] = $product_count;
             if ($product_count > ($page - 1) * $product_limit + $product_limit) {
                 $result['next_page'] = $page + 1;
             } else {
                 $result['next_page'] = false;
             }
         }
         $this->response = $result;
     } else {
         $this->response = false;
     }
 }
 public function execute()
 {
     if (!$this->getUser()->getRights('shop', 'settings')) {
         throw new waRightsException(_w('Access denied'));
     }
     $model = new shopPluginModel();
     $this->view->assign('instances', $model->listPlugins(shopPluginModel::TYPE_SHIPPING, array('all' => true)));
     $this->view->assign('plugins', shopShipping::getList());
     $feature_model = new shopFeatureModel();
     $this->view->assign('no_weight', $feature_model->getByCode('weight') ? false : true);
     $this->view->assign('installer', $this->getUser()->getRights('installer', 'backend'));
 }
 public function execute()
 {
     $items = waRequest::post('items');
     $product_ids = array();
     foreach ($items as $i) {
         $product_ids[] = $i['product_id'];
     }
     $product_ids = array_unique($product_ids);
     $feature_model = new shopFeatureModel();
     $f = $feature_model->getByCode('weight');
     if (!$f) {
         $values = array();
     } else {
         $values_model = $feature_model->getValuesModel($f['type']);
         $values = $values_model->getProductValues($product_ids, $f['id']);
     }
     $contact = $this->getContact();
     $shipping_address = $contact->getFirst('address.shipping');
     if ($shipping_address) {
         $shipping_address = $shipping_address['data'];
     }
     $shipping_items = array();
     foreach ($items as $i) {
         if (isset($values['skus'][$i['sku_id']])) {
             $w = $values['skus'][$i['sku_id']];
         } else {
             $w = isset($values[$i['product_id']]) ? $values[$i['product_id']] : 0;
         }
         $shipping_items[] = array('name' => '', 'price' => $i['price'], 'quantity' => $i['quantity'], 'weight' => $w);
     }
     $order_id = waRequest::post('order_id');
     if ($order_id) {
         $order_model = new shopOrderModel();
         $order_info = $order_model->getById($order_id);
         $currency = $order_info['currency'];
     } else {
         $currency = $this->getConfig()->getCurrency();
     }
     $total = waRequest::post('subtotal') - waRequest::post('discount');
     $order = array('currency' => $currency, 'contact' => $contact, 'items' => $items, 'total' => waRequest::post('subtotal'));
     if ($order_id) {
         $order['id'] = $order_info['id'];
     }
     $this->response['discount'] = shopDiscounts::calculate($order_info);
     $this->response['shipping_methods'] = shopHelper::getShippingMethods($shipping_address, $shipping_items, array('currency' => $currency, 'total_price' => $total));
     // for saving order in js
     $this->response['shipping_method_ids'] = array_keys($this->response['shipping_methods']);
 }
 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;
 }
示例#6
0
 private function getOrder($order_id)
 {
     $order = $this->order_model->getOrder($order_id, true, true);
     if (!$order) {
         throw new waException("Unknow order", 404);
     }
     $order['shipping_id'] = ifset($order['params']['shipping_id'], '') . '.' . ifset($order['params']['shipping_rate_id'], '');
     $sku_ids = array();
     foreach ($order['items'] as $item) {
         foreach ($item['skus'] as $sku) {
             if (empty($sku['fake'])) {
                 $sku_ids[] = $sku['id'];
             }
         }
     }
     $sku_stocks = $this->getSkuStocks(array_unique($sku_ids));
     $subtotal = 0;
     $product_ids = array();
     foreach ($order['items'] as $i) {
         $product_ids[] = $i['id'];
         $subtotal += $i['item']['price'] * $i['item']['quantity'];
     }
     $order['subtotal'] = $subtotal;
     $product_ids = array_unique($product_ids);
     $feature_model = new shopFeatureModel();
     $f = $feature_model->getByCode('weight');
     if (!$f) {
         $values = array();
     } else {
         $values_model = $feature_model->getValuesModel($f['type']);
         $values = $values_model->getProductValues($product_ids, $f['id']);
     }
     foreach ($order['items'] as &$item) {
         if (isset($values['skus'][$item['item']['sku_id']])) {
             $w = $values['skus'][$item['item']['sku_id']];
         } else {
             $w = isset($values[$item['id']]) ? $values[$item['id']] : 0;
         }
         $this->workupItems($item, $sku_stocks);
         $item['quantity'] = $item['item']['quantity'];
         $item['weight'] = $w;
     }
     unset($item);
     return $order;
 }
 public function execute()
 {
     if (!$this->getRights('settings')) {
         throw new waAPIException('access_denied', 403);
     }
     $feature_model = new shopFeatureModel();
     if ($id = $this->post('id')) {
         $feature = $feature_model->getById($id);
     } elseif ($code = $this->post('code')) {
         $feature = $feature_model->getByCode($code);
     } else {
         throw new waAPIException('invalid_param', 'Required parameter is missing: id or code', 400);
     }
     if (!$feature) {
         throw new waAPIException('invalid_param', 'Feature not found', 404);
     }
     $this->response = (bool) $feature_model->delete($feature['id']);
 }
 public function execute()
 {
     $feature_model = new shopFeatureModel();
     if ($id = $this->get('id')) {
         $feature = $feature_model->getById($id);
     } elseif ($code = $this->get('code')) {
         $feature = $feature_model->getByCode($code);
     } else {
         throw new waAPIException('invalid_param', 'Required parameter is missing: id or code', 400);
     }
     if (!$feature) {
         throw new waAPIException('invalid_param', 'Feature not found', 404);
     }
     if ($feature['selectable']) {
         $feature['values'] = array_values($feature_model->getFeatureValues($feature));
         $feature['values']['_element'] = 'value';
     }
     $this->response = $feature;
 }
    protected function init()
    {
        try {
            $backend = wa()->getEnv() == 'backend';
            $profiles = new shopImportexportHelper('yandexmarket');
            switch ($this->encoding) {
                case 'windows-1251':
                    setlocale(LC_CTYPE, 'ru_RU.CP-1251', 'ru_RU.CP1251', 'ru_RU.win');
                    break;
            }
            $this->data['offset'] = array('offers' => 0);
            $this->data['timestamp'] = time();
            $default_export_config = array('zero_stock' => 0, 'compare_price' => 0, 'sku' => 0, 'sku_group' => '', 'hidden_categories' => 0);
            if ($backend) {
                $hash = shopImportexportHelper::getCollectionHash();
                $profile_config = array('hash' => $hash['hash'], 'domain' => waRequest::post('domain'), 'map' => array(), 'types' => array_filter((array) waRequest::post('types')), 'export' => (array) waRequest::post('export', array()) + $default_export_config, 'company' => waRequest::post('company'), 'company_name' => waRequest::post('company_name'), 'shop' => waRequest::post('shop'), 'lifetime' => waRequest::post('lifetime', 0, waRequest::TYPE_INT), 'utm_source' => waRequest::post('utm_source'), 'utm_medium' => waRequest::post('utm_medium'), 'utm_campaign' => waRequest::post('utm_campaign'));
                $this->data['map'] = $this->plugin()->map(waRequest::post('map', array()), $profile_config['types']);
                foreach ($this->data['map'] as $type => $offer_map) {
                    foreach ($offer_map['fields'] as $field => $info) {
                        if (!empty($info['source']) && preg_match('@^\\w+:(.+)$@', $info['source'], $matches) && $matches[1] != '%s') {
                            $profile_config['map'][$type][$field] = $info['source'];
                        }
                    }
                    if (empty($profile_config['map'][$type])) {
                        unset($profile_config['map'][$type]);
                    }
                }
                $profile_id = $profiles->setConfig($profile_config);
                $this->plugin()->getHash($profile_id);
            } else {
                $profile_id = waRequest::param('profile_id');
                if (!$profile_id || !($profile = $profiles->getConfig($profile_id))) {
                    throw new waException('Profile not found', 404);
                }
                $profile_config = $profile['config'];
                $profile_config['export'] += $default_export_config;
                $this->data['map'] = $this->plugin()->map($profile_config['map'], $profile_config['types']);
                foreach ($this->data['map'] as $type => &$offer_map) {
                    foreach ($offer_map['fields'] as $field => &$info) {
                        $info['source'] = ifempty($profile_config['map'][$type][$field], 'skip:');
                    }
                    unset($offer_map);
                }
            }
            foreach ($this->data['map'] as $type => &$offer_map) {
                if ($type != 'simple') {
                    $offer_map['fields']['type'] = array('source' => 'value:' . $type, 'attribute' => true);
                }
                unset($offer_map);
            }
            $feature_model = new shopFeatureModel();
            foreach ($this->data['map'] as $type => &$offer_map) {
                foreach ($offer_map['fields'] as $field => &$info) {
                    if (strpos($field, 'param.') === 0 && isset($info['source'])) {
                        switch (preg_replace('@:.+$@', '', $info['source'])) {
                            case 'feature':
                                if ($feature = $feature_model->getByCode(preg_replace('@^[^:]+:@', '', $info['source']))) {
                                    $info['source_name'] = $feature['name'];
                                }
                                break;
                        }
                    }
                }
                unset($info);
                unset($offer_map);
            }
            $this->data['hash'] = $profile_config['hash'];
            if (!isset($this->data['categories'])) {
                $this->data['categories'] = array();
            }
            $this->data['export'] = $profile_config['export'];
            $this->data['domain'] = $profile_config['domain'];
            $this->data['utm'] = array();
            foreach (array('utm_source', 'utm_medium', 'utm_campaign') as $field) {
                if (!empty($profile_config[$field])) {
                    $this->data['utm'][$field] = $profile_config[$field];
                }
            }
            if ($this->data['utm']) {
                $this->data['utm'] = http_build_query(array_map('rawurlencode', $this->data['utm']));
            }
            $this->data['types'] = array();
            foreach ($profile_config['types'] as $type => $type_map) {
                $this->data['types'] += array_fill_keys(array_filter(array_map('intval', $type_map)), $type);
            }
            $this->initRouting();
            $model = new shopCategoryModel();
            if (empty($this->data['export']['hidden_categories'])) {
                $sql = <<<SQL
SELECT COUNT(1) as `cnt`
FROM shop_category c
LEFT JOIN shop_category_routes cr ON (c.id = cr.category_id)
WHERE
  ((cr.route IS NULL) OR (cr.route = s:route))
   AND
  (`c`.`type`=i:type)
  AND
  (`c`.`status`=1)

SQL;
            } else {
                $sql = <<<SQL
SELECT COUNT(1) as `cnt`
FROM shop_category c
LEFT JOIN shop_category_routes cr ON (c.id = cr.category_id)
WHERE
  ((cr.route IS NULL) OR (cr.route = s:route))
   AND
  (`c`.`type`=i:type)

SQL;
            }
            $params = array('route' => $this->data['domain'], 'type' => shopCategoryModel::TYPE_STATIC);
            $this->data['count'] = array('category' => (int) $model->query($sql, $params)->fetchField('cnt'), 'product' => $this->getCollection()->count());
            $stages = array_keys($this->data['count']);
            $this->data['current'] = array_fill_keys($stages, 0);
            $this->data['processed_count'] = array_fill_keys($stages, 0);
            $this->data['stage'] = reset($stages);
            $this->data['stage_name'] = $this->getStageName($this->data['stage']);
            $this->data['memory'] = memory_get_peak_usage();
            $this->data['memory_avg'] = memory_get_usage();
            if (!class_exists('DOMDocument')) {
                throw new waException('PHP extension DOM required');
            }
            $this->dom = new DOMDocument("1.0", $this->encoding);
            $this->dom->encoding = $this->encoding;
            $this->dom->preserveWhiteSpace = false;
            $this->dom->formatOutput = true;
            /**
             * @var shopConfig $config
             */
            $config = wa('shop')->getConfig();
            $xml = <<<XML
<?xml version="1.0" encoding="{$this->encoding}"?>
<!DOCTYPE yml_catalog SYSTEM "shops.dtd">
<yml_catalog  date="%s">
</yml_catalog>
XML;
            $original = shopYandexmarketPlugin::path('shops.dtd');
            $target = $this->getTempPath('shops.dtd');
            $ft = filesize($target);
            $fo = filesize($original);
            if (!file_exists($target) || filesize($target) != filesize($original) && waFiles::delete($target)) {
                waFiles::copy($original, $target);
            }
            $this->dom->loadXML(sprintf($xml, date("Y-m-d H:i")));
            $this->dom->lastChild->appendChild($shop = $this->dom->createElement("shop"));
            $name = ifempty($profile_config['company_name'], $config->getGeneralSettings('name'));
            $name = str_replace('&', '&amp;', $name);
            $name = str_replace("'", '&apos;', $name);
            $this->addDomValue($shop, 'name', $name);
            $company = str_replace('&', '&amp;', $profile_config['company']);
            $company = str_replace("'", '&apos;', $company);
            $this->addDomValue($shop, 'company', $company);
            $this->addDomValue($shop, 'url', preg_replace('@^https@', 'http', wa()->getRouteUrl('shop/frontend', array(), true)));
            if ($phone = $config->getGeneralSettings('phone')) {
                $shop->appendChild($this->dom->createElement('phone', $phone));
            }
            $this->addDomValue($shop, 'platform', 'Shop-Script');
            $this->addDomValue($shop, 'version', wa()->getVersion('shop'));
            $currencies = $this->dom->createElement('currencies');
            $model = new shopCurrencyModel();
            $this->data['currency'] = array();
            $available_currencies = shopYandexmarketPlugin::settingsPrimaryCurrencies();
            if (empty($available_currencies)) {
                throw new waException('Экспорт не может быть выполнен: не задано ни одной валюты, которая могла бы использоваться в качестве основной.');
            }
            unset($available_currencies['auto']);
            $primary_currency = $this->plugin()->getSettings('primary_currency');
            $this->data['default_currency'] = $config->getCurrency();
            if (!isset($available_currencies[$primary_currency])) {
                $primary_currency = $this->data['default_currency'];
                if (!isset($available_currencies[$primary_currency])) {
                    reset($available_currencies);
                    $primary_currency = key($available_currencies);
                }
            }
            $this->data['primary_currency'] = $primary_currency;
            $rate = $available_currencies[$primary_currency]['rate'];
            $available_currencies = $model->getCurrencies(shopYandexmarketPlugin::getConfigParam('currency'));
            foreach ($available_currencies as $info) {
                if ($info['rate'] > 0) {
                    $info['rate'] = $info['rate'] / $rate;
                    $this->data['currency'][] = $info['code'];
                    if (abs(round($info['rate'], 4) - $info['rate']) / $info['rate'] > 0.01) {
                        $info['rate'] = 'CB';
                    }
                    $value = array('id' => $info['code'], 'rate' => $this->format('rate', $info['rate']));
                    $this->addDomValue($currencies, 'currency', $value);
                }
            }
            $shop->appendChild($currencies);
            $shop->appendChild($this->dom->createElement('categories'));
            $fields = array('store' => true, 'pickup' => true, 'delivery' => true, 'deliveryIncluded' => false, 'local_delivery_cost' => '%0.2f', 'adult' => true);
            foreach ($fields as $field => $include_value) {
                $value = ifset($profile_config['shop'][$field], '');
                if ($value || $value !== '') {
                    if ($include_value) {
                        $value = $include_value === true ? $value : $this->format($field, $value, array('format', $include_value));
                        $this->addDomValue($shop, $field, $value);
                    } else {
                        $shop->appendChild($this->dom->createElement($field));
                    }
                }
            }
            $shop->appendChild($this->dom->createElement('offers'));
            if (!$this->data['currency']) {
                throw new waException('Не задано ни одной поддерживаемой валюты');
            }
            if (!in_array($this->data['primary_currency'], $this->data['currency'])) {
                $this->data['primary_currency'] = reset($this->data['currency']);
            }
            $this->data['path'] = array('offers' => shopYandexmarketPlugin::path($profile_id . '.xml'));
            $this->save();
            $this->dom = null;
            $this->loadDom();
        } catch (waException $ex) {
            $this->error($ex->getMessage());
            echo json_encode(array('error' => $ex->getMessage()));
            exit;
        }
    }
 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');
 }
 /**
  * @see shopProductStorageInterface::setData()
  * @param shopProduct $product current product object
  * @param array [string] mixed $data new product feature values
  */
 public function setData(shopProduct $product, $data)
 {
     $product_id = $product->getId();
     $feature_model = new shopFeatureModel();
     $codes = array_keys($data);
     $features = $feature_model->getByCode($codes);
     /**
      * composite fields workaround
      */
     $composite_codes = array();
     foreach ($data as $code => $value) {
         if (!preg_match('/\\.[0-3]$/', $code) && isset($features[$code]) && preg_match('/^([23])d\\./', $features[$code]['type'], $matches)) {
             $n = $matches[1];
             $pattern = '/^' . implode('\\s*[×xX\\*]?\\s*', array_fill(0, $n, '([^\\s]+)')) . '(\\s+.+)?$/u';
             if (preg_match($pattern, trim($value), $matches)) {
                 $unit = ifset($matches[$n + 1]);
                 for ($i = 0; $i < $n; $i++) {
                     $c_code = $code . '.' . $i;
                     $data[$c_code] = $matches[$i + 1] . $unit;
                     $composite_codes[] = $c_code;
                 }
                 unset($features[$code]);
             } else {
                 /**
                  * invalid complex feature format
                  */
             }
             unset($data[$code]);
         }
     }
     if ($composite_codes) {
         $features += $feature_model->getByCode($composite_codes);
     }
     $features_map = array();
     foreach ($features as $code => $f) {
         $features_map[$f['id']] =& $features[$code];
     }
     $current = array();
     $rows = $this->getByField(array('product_id' => $product_id, 'sku_id' => null), true);
     foreach ($rows as $row) {
         $id = $row['feature_id'];
         if (isset($features_map[$id])) {
             $f = $features_map[$id];
             $code = $f['code'];
             if (empty($f['multiple'])) {
                 $current[$code] = intval($row['feature_value_id']);
             } else {
                 if (!isset($current[$code])) {
                     $current[$code] = array();
                 }
                 $current[$code][] = intval($row['feature_value_id']);
             }
         } else {
             //obsolete data
         }
     }
     $add = $delete = array();
     foreach ($data as $code => $value) {
         if (isset($features[$code])) {
             $f =& $features[$code];
             if (is_array($value)) {
                 $empty = isset($value['value']) && $value['value'] === '';
                 if (!$empty && isset($value['value']) && is_array($value['value'])) {
                     foreach ($value['value'] as $key => $v) {
                         if ($v === '') {
                             unset($value['value'][$key]);
                         }
                     }
                     $empty = count($value['value']) == 0;
                 }
                 if (!$empty && !isset($value['value'])) {
                     foreach ($value as $key => $v) {
                         if ($v === '') {
                             unset($value[$key]);
                         }
                     }
                     $empty = count($value) == 0;
                 }
             } else {
                 $empty = $value === '';
             }
             if ($empty) {
                 //delete it
                 if (isset($current[$code])) {
                     $delete[$f['id']] = $current[$code];
                 }
             } else {
                 if (is_array($value) && preg_match('/^(.+\\.)[12]$/', $code, $matches) && isset($data[$matches[1] . '0'])) {
                     $value = array_merge($data[$matches[1] . '0'], $value);
                 }
                 $id = $feature_model->getValueId($f, $value, true);
                 if (isset($current[$code])) {
                     if (empty($f['multiple'])) {
                         if ($current[$code] != $id) {
                             $delete[$f['id']] = $current[$code];
                             $add[$f['id']] = $id;
                         }
                     } else {
                         $delete[$f['id']] = array_diff($current[$code], (array) $id);
                         if (empty($delete[$f['id']])) {
                             unset($delete[$f['id']]);
                         }
                         $add[$f['id']] = array_diff((array) $id, $current[$code]);
                         if (empty($add[$f['id']])) {
                             unset($add[$f['id']]);
                         }
                     }
                 } else {
                     $add[$f['id']] = $id;
                 }
             }
         } elseif (!empty($value) && is_array($value)) {
             //it's a new feature
             if (!empty($value) && (ifset($value['type']) == shopFeatureModel::TYPE_BOOLEAN || !empty($value['value']))) {
                 $f = array('name' => $value['name'], 'type' => $value['type'], 'types' => $value['types']);
                 $f['id'] = $feature_model->save($f);
                 $type_features_model = new shopTypeFeaturesModel();
                 $type_features_model->updateByFeature($f['id'], $f['types']);
                 if ($value['value'] !== '') {
                     $add[$f['id']] = $feature_model->getValueId($f, $value['value'], true);
                 }
             }
         }
     }
     foreach ($features as $code => $f) {
         if (empty($data[$code]) && !empty($current[$code])) {
             $delete[$f['id']] = $current[$code];
         }
     }
     foreach ($delete as $feature_id => $value_id) {
         $this->deleteByField(array('product_id' => $product_id, 'sku_id' => null, 'feature_id' => $feature_id, 'feature_value_id' => $value_id));
     }
     foreach ($add as $feature_id => $value_id) {
         $this->multipleInsert(array('product_id' => $product_id, 'feature_id' => $feature_id, 'feature_value_id' => $value_id));
     }
 }
    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');
    }
 /**
  * Verify input data and get selected base features
  * @param array &$data
  * @return int[int][int] value_id[value_id][feature_id]
  */
 private function getSelectedData(&$data)
 {
     $selected = array();
     $features = array();
     if ($feature_codes = array_keys($data)) {
         $feature_model = new shopFeatureModel();
         $features = $feature_model->getByCode($feature_codes);
     }
     foreach ($data as $code => &$feature) {
         if (!isset($features[$code])) {
             unset($data[$code]);
         } else {
             $feature_id = intval($features[$code]['id']);
             $selected[$feature_id] = array();
             if (!isset($feature['values'])) {
                 $feature = array('values' => $feature);
             }
             $feature['feature_id'] = $feature_id;
             $values = $feature['values'];
             $feature['values'] = array();
             foreach ($values as $value) {
                 if (is_array($value)) {
                     if (isset($value['value']) && empty($value['id'])) {
                         $value['id'] = $feature_model->getValueId($features[$code], $value['value'], true);
                     }
                 } else {
                     $value = array('id' => $value);
                 }
                 $id = $value['id'];
                 if (!isset($value['value'])) {
                     $value['value'] = (string) $feature_model->getValuesModel($features[$code]['type'])->getFeatureValue($id);
                 }
                 $feature['values'][$id] = $value;
                 $selected[$feature_id][$id] = $id;
                 unset($value);
             }
         }
         unset($values);
     }
     ksort($selected, SORT_NUMERIC);
     return $selected;
 }
 private function getOrderItems($items, $weight_unit)
 {
     $product_ids = array();
     foreach ($items as $item) {
         $product_ids[] = $item['product_id'];
     }
     $product_ids = array_unique($product_ids);
     $feature_model = new shopFeatureModel();
     $f = $feature_model->getByCode('weight');
     if (!$f) {
         $values = array();
     } else {
         $values_model = $feature_model->getValuesModel($f['type']);
         $values = $values_model->getProductValues($product_ids, $f['id']);
     }
     $m = null;
     if ($weight_unit) {
         $dimension = shopDimension::getInstance()->getDimension('weight');
         if ($weight_unit != $dimension['base_unit']) {
             $m = $dimension['units'][$weight_unit]['multiplier'];
         }
     }
     foreach ($items as &$item) {
         if ($item['type'] == 'product') {
             if (isset($values['skus'][$item['sku_id']])) {
                 $w = $values['skus'][$item['sku_id']];
             } else {
                 $w = isset($values[$item['product_id']]) ? $values[$item['product_id']] : 0;
             }
             if ($m !== null) {
                 $w = $w / $m;
             }
             $item['weight'] = $w;
         } else {
             $item['weight'] = 0;
         }
     }
     unset($item);
     return $items;
 }
 public function execute()
 {
     $id = waRequest::get('order_id');
     if (!$id) {
         throw new waException("Unknown order", 404);
     }
     $order = $this->getOrder($id);
     if (!$order) {
         $id = shopHelper::decodeOrderId($id);
         $order = $this->getOrder($id);
         if (!$order) {
             throw new waException("Unkown order", 404);
         }
     }
     $product_ids = array();
     foreach ($order['items'] as $item) {
         if ($item['type'] == 'product') {
             $product_ids[] = $item['product_id'];
         }
     }
     $product_ids = array_unique($product_ids);
     $form_id = waRequest::get('form_id');
     if (strpos($form_id, '.')) {
         list($type, $form) = explode('.', $form_id, 2);
     } else {
         $form = null;
         $type = $form_id;
     }
     $order_params_model = new shopOrderParamsModel();
     $params = $order_params_model->get($order['id']);
     $plugin = self::getPlugin($type, ifempty($params[$type . '_id']));
     if ($type == 'shipping') {
         /* add weight info only for shipping modules */
         $feature_model = new shopFeatureModel();
         $f = $feature_model->getByCode('weight');
         if (!$f) {
             $weights = array();
         } else {
             $values_model = $feature_model->getValuesModel($f['type']);
             $weights = $values_model->getProductValues($product_ids, $f['id']);
         }
         if ($weights) {
             $dimension = shopDimension::getInstance()->getDimension('weight');
             $weight_unit = $plugin->allowedWeightUnit();
             $m = null;
             if ($weight_unit != $dimension['base_unit']) {
                 $m = $dimension['units'][$weight_unit]['multiplier'];
             }
             foreach ($order['items'] as &$item) {
                 if ($item['type'] == 'product') {
                     if (isset($weights['skus'][$item['sku_id']])) {
                         $w = $weights['skus'][$item['sku_id']];
                     } else {
                         $w = isset($weights[$item['product_id']]) ? $weights[$item['product_id']] : 0;
                     }
                     if ($m !== null) {
                         $w = $w / $m;
                     }
                     $item['weight'] = $w;
                 }
             }
             unset($item);
         }
     }
     if (!$plugin) {
         throw new waException(_w('Printform not found'), 404);
     }
     print $plugin->displayPrintForm(ifempty($form, $plugin->getId()), shopPayment::getOrderData($order, $plugin));
     exit;
 }
 public function getItems($weight_unit = null)
 {
     $items = array();
     $cart = new shopCart();
     $cart_items = $cart->items();
     $product_ids = $sku_ids = array();
     foreach ($cart_items as $item) {
         $product_ids[] = $item['product_id'];
         $sku_ids[] = $item['sku_id'];
     }
     $feature_model = new shopFeatureModel();
     $f = $feature_model->getByCode('weight');
     if (!$f) {
         $values = array();
     } else {
         $values_model = $feature_model->getValuesModel($f['type']);
         $values = $values_model->getProductValues($product_ids, $f['id']);
     }
     $m = null;
     if ($weight_unit) {
         $dimension = shopDimension::getInstance()->getDimension('weight');
         if ($weight_unit != $dimension['base_unit']) {
             $m = $dimension['units'][$weight_unit]['multiplier'];
         }
     }
     foreach ($cart_items as $item) {
         if (isset($values['skus'][$item['sku_id']])) {
             $w = $values['skus'][$item['sku_id']];
         } else {
             $w = isset($values[$item['product_id']]) ? $values[$item['product_id']] : 0;
         }
         if ($m !== null) {
             $w = $w / $m;
         }
         $items[] = array('name' => $item['name'], 'price' => $item['price'], 'quantity' => $item['quantity'], 'weight' => $w);
     }
     return $items;
 }