function cw_ab_get_contentsection($contentsection_id)
{
    global $tables, $current_language;
    $query = "SELECT * FROM {$tables['cms']} WHERE contentsection_id = '" . intval($contentsection_id) . "'";
    $contentsection = cw_query_first($query);
    if (!empty($contentsection) && is_array($contentsection)) {
        $contentsection_alt_languages = cw_query_first("SELECT name, alt, url, content FROM {$tables['cms_alt_languages']} WHERE contentsection_id = '" . intval($contentsection_id) . "' AND code = '" . $current_language . "'");
        if (!empty($contentsection_alt_languages) && is_array($contentsection_alt_languages)) {
            $contentsection['name'] = $contentsection_alt_languages['name'];
            $contentsection['url'] = $contentsection_alt_languages['url'];
            $contentsection['content'] = $contentsection_alt_languages['content'];
        }
    }
    if ($contentsection['type'] == 'image') {
        $contentsection['image'] = cw_image_get('cms_images', $contentsection_id);
    }
    $attributes = cw_func_call('cw_attributes_get', array('item_id' => $contentsection_id, 'item_type' => 'AB'));
}
function smarty_function_select_categories($params, &$smarty)
{
    extract($params);
    if (empty($assign)) {
        $smarty->trigger_error("assign: missing 'assign' parameter");
        return;
    }
    if ($remove_root && !$current_category_id) {
        return false;
    }
    cw_load('category', 'image');
    if ($remove_root) {
        $path = cw_category_get_path($current_category_id);
        $category_id = array_shift($path);
    }
    $categories = cw_category_get_subcategories($category_id, $current_category_id);
    if ($params['images']) {
        foreach ($categories as $k => $v) {
            $categories[$k]['image'] = cw_image_get('categories_images_thumb', $v['category_id']);
        }
    }
    $smarty->assign($assign, $categories);
}
        $result = cw_query_first("\n\t\t\tSELECT *\n\t\t\tFROM {$tables['clean_urls_custom_facet_urls']}\n\t\t\tWHERE url_id = '{$custom_facet_url_id}'\n\t\t");
        $custom_facet_url = $result['custom_facet_url'];
        $description = $result['description'];
        $title = $result['title'];
        $attribute_value_ids_list = cw_query("select attribute_value_ids from {$tables['clean_urls_custom_facet_urls_options']} where url_id='{$custom_facet_url_id}'");
        $attribute_value_ids_data = array();
        foreach ($attribute_value_ids_list as $avi_v) {
            $attribute_value_ids_data = array_merge($attribute_value_ids_data, explode(',', $avi_v['attribute_value_ids']));
        }
    } else {
        $attribute_value_ids_data = explode(',', str_replace('###', ',', $custom_facet_url_data['attribute_value_ids']));
        $custom_facet_url = $custom_facet_url_data['custom_facet_url'];
        $description = $result['description'];
        $title = $result['title'];
    }
    $custom_facet_image = cw_image_get('facet_categories_images', $custom_facet_url_id);
    $custom_facet_url_data = array();
    $smarty->assign('attributes_options', cw_clean_url_get_attributes_options($attribute_value_ids_data));
    $smarty->assign('custom_facet_url_id', $custom_facet_url_id);
    $smarty->assign('custom_facet_url', $custom_facet_url);
    $smarty->assign('description', $description);
    $smarty->assign('title', $title);
    $smarty->assign('custom_facet_image', $custom_facet_image);
    $smarty->assign('mode', $mode);
    $smarty->assign('main', 'custom_facet_url');
} else {
    if ($action == 'delete' && !empty($to_delete)) {
        foreach ($to_delete as $url_id => $v) {
            cw_clean_url_custom_facet_url_delete($url_id);
        }
        $top_message = array('content' => cw_get_langvar_by_name("txt_selected_custom_facet_urls_deleted", null, false, true), 'type' => 'I');
function smarty_function_product_image($params, &$smarty)
{
    global $config;
    require_once $smarty->_get_plugin_filepath('function', 'xcm_thumb');
    cw_load('image');
    if (!empty($params['image'])) {
        $params['image_type'] = $params['image']['in_type'];
    }
    if (!in_array($params['image_type'], array('products_images_det', 'products_images_thumb'), true)) {
        $params['image_type'] = 'products_images_det';
    }
    // Get image by product ID only
    if (empty($params['src_url']) && empty($params['image']) && !empty($params['product_id'])) {
        if (empty($params['image_type'])) {
            $params['image_type'] = 'products_images_thumb';
        }
        $params['image'] = cw_image_get($params['image_type'], $params['product_id']);
    }
    // Try to find main image instead of empty thumbnail
    if ($params['image_type'] == 'products_images_thumb' && (empty($params['image']) || $params['image']['is_default']) && !empty($params['product_id'])) {
        $image = cw_image_get('products_images_det', $params['product_id']);
        if (!empty($image) && empty($image['is_default'])) {
            $params['image'] = $image;
        }
    }
    if (!empty($params['image'])) {
        $params['src_url'] = $params['image']['image_path'];
    }
    if (empty($params['width'])) {
        $params['width'] = $config['Appearance'][$params['image_type'] . '_width'];
    }
    $params['keep_file_h2w'] = 'Y';
    if (empty($params['alt']) && !empty($params['image']['alt'])) {
        $params['alt'] = $params['image']['alt'];
    }
    $orig_params = $params;
    $params['assign_x'] = "result_thumb_width";
    $params['assign_y'] = "result_thumb_height";
    $params['assign_url'] = "result_thumb_url";
    $params['just_url'] = "Y";
    smarty_function_xcm_thumb($params, $smarty);
    $thumb_image_url = $smarty->get_template_vars($params['assign_url']);
    $result_thumb_width = $smarty->get_template_vars($params['assign_x']);
    $result_thumb_height = $smarty->get_template_vars($params['assign_y']);
    $extra_img_code = "";
    if (!empty($params['extra'])) {
        $extra_img_code = $params['extra'];
    }
    $extra_html_params = array("title", "class", "style", "id", "alt");
    foreach ($extra_html_params as $p_name) {
        if (!empty($params[$p_name])) {
            $extra_img_code .= " {$p_name}=\"" . $params[$p_name] . "\"";
        }
    }
    $html_width = !empty($params['html_width']) ? $params['html_width'] : $result_thumb_width;
    if (!empty($params['html_height'])) {
        $html_heigth = $params['html_heigth'];
    } elseif (!empty($params['html_width'])) {
        $html_heigth = '';
    } else {
        $html_heigth = $result_thumb_height;
    }
    if ($orig_params['just_url'] != 'Y') {
        $img_tag_code = '<img src="' . $thumb_image_url . '" width="' . $html_width . '" ' . (!empty($html_heigth) ? 'height="' . $html_heigth . '" ' : ' ') . $extra_img_code . ' />';
    } else {
        $img_tag_code = $thumb_image_url;
    }
    return $img_tag_code;
}
function ps_details($offer_id)
{
    global $tables, $top_message, $smarty, $available_fields;
    if (empty($offer_id)) {
        ps_redirect();
    }
    $offer_id = (int) $offer_id;
    if ($_SERVER['REQUEST_METHOD'] != 'GET') {
        ps_redirect($offer_id);
    }
    $offer_data = cw_query_first('SELECT `' . implode('`, `', array_keys($available_fields)) . '` FROM ' . $tables['ps_offers'] . ' WHERE offer_id = \'' . $offer_id . '\'');
    if (empty($offer_data) || !is_array($offer_data)) {
        ps_redirect();
    }
    $offer_data['image'] = cw_image_get(PS_IMG_TYPE, $offer_id);
    $smarty->assign('offer_data', cw_stripslashes($offer_data));
    // bonuses
    $sess_bonuses =& cw_session_register('_ps_bonus');
    $bonuses = ps_get_offer_bonuses($offer_id);
    if (!is_array($bonuses) || empty($bonuses)) {
        $bonuses = array();
    }
    if (!empty($sess_bonuses)) {
        if (is_array($sess_bonuses)) {
            $bonuses = array_merge($bonuses, $sess_bonuses);
            $smarty->assign('not_sav_bons', $sess_bonuses);
        }
        cw_session_unregister('_ps_bonus');
    }
    $smarty->assign('ps_bonus', $bonuses);
    $bonus_types = array_flip(array_keys($bonuses));
    $bonus_types = array_map(create_function('$elm', 'return 1;'), $bonus_types);
    if (empty($bonus_types)) {
        $bonus_types = array();
    }
    $sess_bonus_types =& cw_session_register('_ps_bonuses');
    $sess_cond_types =& cw_session_register('_ps_conditions');
    if (!empty($sess_bonus_types)) {
        if (is_array($sess_bonus_types)) {
            $bonus_types = array_merge($bonus_types, $sess_bonus_types);
        }
        cw_session_unregister('_ps_bonuses');
    }
    $smarty->assign('ps_bonuses', $bonus_types);
    // conditions
    $sess_conditions =& cw_session_register('_ps_conds');
    $conditions = ps_get_offer_conditions($offer_id);
    if (!is_array($conditions) || empty($conditions)) {
        $conditions = array();
    }
    if (!empty($sess_conditions)) {
        if (is_array($sess_conditions)) {
            $conditions = array_merge($conditions, $sess_conditions);
            $smarty->assign('not_sav_conds', $sess_conditions);
        }
        cw_session_unregister('_ps_conds');
    }
    $smarty->assign('ps_conds', $conditions);
    $cond_types = array_flip(array_keys($conditions));
    $cond_types = array_map(create_function('$elm', 'return 1;'), $cond_types);
    if (empty($cond_types)) {
        $cond_types = array();
    }
    if (!empty($sess_cond_types)) {
        if (is_array($sess_cond_types)) {
            $cond_types = array_merge($cond_types, $sess_cond_types);
        }
        cw_session_unregister('_ps_conditions');
    }
    $smarty->assign('ps_conditions', $cond_types);
    cw_load('attributes');
    $ps_attr = cw_call('cw_attributes_filter', array(array('addon' => '', 'item_type' => 'P')));
    $smarty->assign('ps_attr', $ps_attr);
    $smarty->assign('ps_coupons', ps_get_coupons());
    $smarty->assign('ps_mans', ps_get_manufacturers());
    $smarty->assign('ps_zones', ps_get_zones());
    $smarty->assign('ps_memberships', cw_get_memberships());
    global $js_tab;
    if (isset($js_tab)) {
        $smarty->assign('js_tab', (string) $js_tab);
    }
    global $app_catalogs, $target, $mode;
    $smarty->assign('ps_url_get_coupons', "{$app_catalogs['admin']}/index.php?target={$target}&mode={$mode}&action=coupons&offer_id={$offer_id}&js_tab=ps_offer_bonuses");
    $smarty->assign('ps_url_add_coupon', "{$app_catalogs['admin']}/index.php?target=coupons");
    $smarty->assign('ps_url_get_zones', "{$app_catalogs['admin']}/index.php?target={$target}&mode={$mode}&action=zones&offer_id={$offer_id}&js_tab=ps_offer_conditions");
    $smarty->assign('ps_url_add_zone', "{$app_catalogs['admin']}/index.php?target=shipping_zones&mode=add");
    //attributes
    global $attributes;
    global $edited_language;
    $attributes = cw_func_call('cw_attributes_get', array('item_id' => $offer_id, 'item_type' => PS_ATTR_ITEM_TYPE, 'prefilled' => $attributes));
    $smarty->assign('attributes', $attributes);
}
function cw_product_get($params, $return = null)
{
    extract($params);
    global $customer_id, $customer_id_type, $current_area, $cart, $current_location;
    global $current_language, $tables, $config, $addons;
    cw_load('files', 'taxes', 'tags');
    $lang = $lang ? $lang : $current_language;
    $variant_id = $variant_id ? $variant_id : 0;
    $amount = intval($amount > 0 ? $amount : 1);
    $fields = $from_tbls = $query_joins = $where = array();
    # kornev, merge standart and additional variables
    if ($return) {
        foreach ($return as $saname => $sadata) {
            if (isset(${$saname}) && is_array(${$saname}) && empty(${$saname})) {
                ${$saname} = $sadata;
            }
        }
    }
    $from_tbls[] = 'products';
    $where[] = "{$tables['products']}.product_id='{$id}'";
    # kornev
    # customer area - all of the checkings
    # pos area - not check for membership, just available for sale property
    if (in_array($current_area, array('C'))) {
        $memberships = array(0);
        if ($user_account['membership_id'] > 0) {
            $memberships[] = intval($user_account['membership_id']);
        }
        $where[] = "{$tables['products_memberships']}.membership_id IN (" . join(',', $memberships) . ")";
        $where[] = "{$tables['products_prices']}.quantity <= {$amount} and {$tables['products_prices']}.membership_id in (" . join(',', $memberships) . ")";
        if ($config['Appearance']['categories_in_products'] == '1') {
            $where[] = "{$tables['categories_memberships']}.membership_id IN (" . join(',', $memberships) . ")";
            $query_joins['products_categories'] = array('on' => "{$tables['products_categories']}.product_id = {$tables['products']}.product_id", 'pos' => '0', 'is_straight' => 1);
            $query_joins['categories'] = array('on' => "{$tables['products_categories']}.category_id = {$tables['categories']}.category_id", 'parent' => 'products_categories');
            $query_joins['categories_memberships'] = array('on' => "{$tables['categories_memberships']}.category_id = {$tables['categories']}.category_id", 'parent' => 'categories', 'is_straight' => 1);
        }
        $where[] = "{$tables['products']}.status in ('" . implode("', '", cw_core_get_required_status($current_area)) . "')";
    } elseif (in_array($current_area, array('G'))) {
        $where[] = "{$tables['products']}.product_id = {$tables['products_prices']}.product_id AND {$tables['products_prices']}.quantity <= {$amount} and {$tables['products_prices']}.membership_id in (" . join(',', $memberships) . ")";
    }
    $fields[] = "{$tables['products']}.*";
    $query_joins['products_warehouses_amount'] = array('on' => "{$tables['products']}.product_id = {$tables['products_warehouses_amount']}.product_id and {$tables['products_warehouses_amount']}.warehouse_customer_id=0 and {$tables['products_warehouses_amount']}.variant_id='{$variant_id}'");
    $in_cart = 0;
    if ($current_area == 'C' && !empty($cart) && !empty($cart['products'])) {
        foreach ($cart['products'] as $cart_item) {
            if ($cart_item['product_id'] == $id) {
                $in_cart += $cart_item['amount'];
            }
        }
    }
    $fields[] = "{$tables['products_warehouses_amount']}.avail-{$in_cart} AS avail";
    # kornev, TOFIX
    if ($addons['product_options'] && in_array($current_area, array('A', 'P'))) {
        $query_joins['product_variants'] = array('on' => "{$tables['products']}.product_id = {$tables['product_variants']}.product_id");
        $fields[] = "IF({$tables['product_variants']}.product_id IS NULL, '', 'Y') as is_variants";
    }
    /*
        if ($addons['manufacturers']) {
            $query_joins['manufacturers'] = array(
                'on' => "$tables[manufacturers].manufacturer_id = $tables[products].manufacturer_id",
            );
            $fields[] = "$tables[manufacturers].manufacturer";
        }
    */
    // statistic
    $fields[] = "{$tables['products_stats']}.views_stats";
    $fields[] = "{$tables['products_stats']}.sales_stats";
    $fields[] = "{$tables['products_stats']}.del_stats";
    $fields[] = "{$tables['products_stats']}.add_to_cart";
    $query_joins['products_stats'] = array('on' => "{$tables['products_stats']}.product_id = {$tables['products']}.product_id");
    if ($current_area == 'A' || $current_area == 'P') {
        $fields[] = "{$tables['products_prices']}.price";
        $fields[] = "{$tables['products_prices']}.list_price";
        $query_joins['products_prices'] = array('on' => "{$tables['products_prices']}.product_id={$tables['products']}.product_id AND {$tables['products_prices']}.variant_id = '{$variant_id}' and {$tables['products_prices']}.quantity <= {$amount}");
    } else {
        $query_joins['products_prices'] = array('on' => "{$tables['products_prices']}.product_id={$tables['products']}.product_id", 'is_inner' => 1);
        # kornev, find the min price and select only this record.
        $fields[] = "min({$tables['products_prices']}.price) as price";
        $fields[] = "{$tables['products_prices']}.variant_id";
        $fields[] = "min({$tables['products_prices']}.list_price) as list_price";
    }
    $fields[] = "IF({$tables['products_lng']}.product_id != '', {$tables['products_lng']}.product, {$tables['products']}.product) as product";
    $fields[] = "IF({$tables['products_lng']}.product_id != '', {$tables['products_lng']}.descr, {$tables['products']}.descr) as descr";
    $fields[] = "IF({$tables['products_lng']}.product_id != '', {$tables['products_lng']}.fulldescr, {$tables['products']}.fulldescr) as fulldescr";
    $fields[] = "IF({$tables['products_lng']}.product_id != '', {$tables['products_lng']}.features_text, {$tables['products']}.features_text) as features_text";
    $fields[] = "IF({$tables['products_lng']}.product_id != '', {$tables['products_lng']}.specifications, {$tables['products']}.specifications) as specifications";
    $query_joins['products_lng'] = array('on' => "{$tables['products_lng']}.code='{$lang}' AND {$tables['products_lng']}.product_id = {$tables['products']}.product_id");
    if (in_array($current_area, array('C', 'G', 'S'))) {
        $fields[] = "{$tables['products_flat']}.*";
        $query_joins['products_flat'] = array('on' => "{$tables['products']}.product_id = {$tables['products_flat']}.product_id");
        if ($current_area == 'C') {
            $query_joins['products_memberships'] = array('on' => "{$tables['products_memberships']}.product_id = {$tables['products']}.product_id", 'is_inner' => 1);
        }
    }
    if ($config['Appearance']['categories_in_products'] == '1') {
        $fields[] = "{$tables['products_categories']}.category_id";
        $query_joins['categories'] = array('parent' => 'products_categories', 'on' => "{$tables['categories']}.category_id = {$tables['products_categories']}.category_id");
        $query_joins['products_categories'] = array('on' => "{$tables['products_categories']}.product_id = {$tables['products']}.product_id and {$tables['products_categories']}.main=1", 'pos' => '0', 'is_straight' => 1);
    }
    $fields[] = "{$tables['products']}.product_id";
    $query = cw_db_generate_query($fields, $from_tbls, $query_joins, $where, array("{$tables['products']}.product_id"), array(), array());
    $product = cw_query_first($query);
    # Error handling
    if (!$product || $current_area == 'C' && !$product['category_id'] && $config['Appearance']['categories_in_products'] == '1') {
        return false;
    }
    $product['system'] = cw_call('cw_product_get_system_info', array($product['product_id']));
    $product['attribute_class_ids'] = cw_func_call('cw_items_attribute_classes_get', array('item_id' => $product['product_id'], 'item_type' => 'P', 'for_product_modify' => $for_product_modify));
    if ($info_type & 1) {
        $product['membership_ids'] = cw_query_key("select membership_id from {$tables['products_memberships']} where product_id = '{$product['product_id']}'");
    }
    # kornev, TOFIX
    if ($info_type & 64 && $product['variant_id'] && $addons['product_options']) {
        $tmp = cw_query_first("SELECT * FROM {$tables['product_variants']} WHERE variant_id = '{$product['variant_id']}'");
        if (!empty($tmp)) {
            cw_unset($tmp, "def");
            $product = cw_array_merge($product, $tmp);
        } else {
            cw_unset($product, 'variant_id');
        }
    }
    if ($info_type & 128) {
        cw_load('image');
        $product['image_thumb'] = cw_image_get('products_images_thumb', $id);
    }
    if ($info_type & 512) {
        $product['image_det'] = cw_image_get('products_images_det', $id);
        # kornev, TOFIX
        if (in_array($current_area, array('C', 'B')) && $product['variant_id'] && $addons['product_options']) {
            $var_image = cw_image_get('products_images_var', $id);
            if (!$var_image['is_default']) {
                $product['image_det'] = $var_image;
            }
        }
    }
    # TOFIX
    if (in_array($current_area, array('C', 'B', 'G'))) {
        if (!$addons['egoods']) {
            $product['distribution'] = '';
        }
        $product['display_price'] = $product['price'];
        if ($current_area == 'C' && $info_type & 8) {
            $_tmp_price = $product['price'];
            $product['price'] = $product['list_price'];
            cw_get_products_taxes($product, $user_account);
            $product['list_price_net'] = $product['list_price'];
            $product['list_price'] = $product['taxed_price'];
            $product['price'] = $_tmp_price;
        }
        $product['taxes'] = cw_get_products_taxes($product, $user_account, false, '', $current_area == 'G' && $user_account['usertype'] != 'R');
    }
    if (in_array($current_area, array('C', 'B'))) {
        $product['descr'] = cw_eol2br($product['descr']);
        $product['fulldescr'] = cw_eol2br($product['fulldescr']);
    }
    $product['uns_shippings'] = unserialize($product['shippings']);
    $product['tags'] = cw_tags_get_product_tags($id);
    if ($info_type & 4096 && $product['warranty_id']) {
        $wr = cw_get_warranty($product['warranty_id'], $lang);
        $product['warranties'] = $wr['body'];
    }
    // TODO: move to addon as on_product_get handler
    if ($info_type & 8192) {
        cw_load('warehouse');
        if ($addons['warehouse']) {
            if (AREA_TYPE == 'A') {
                $product['avail_ordered'] = cw_warehouse_get_avail($id, 0, 'avail_ordered');
                $product['avail_sold'] = cw_warehouse_get_avail($id, 0, 'avail_sold');
                $product['avail_reserved'] = cw_warehouse_get_avail($id, 0, 'avail_reserved');
            } elseif (AREA_TYPE == 'P') {
                $product['avail'] = cw_warehouse_get_warehouse_avail($customer_id, $id);
                $product['avail_ordered'] = cw_warehouse_get_warehouse_avail($customer_id, $id, 'avail_ordered');
            } else {
                // TOFIX:  $product['avail'] becomes different meanings when info_type & 8192 flag is raised or not
                // without flag - avail of all variants without products already in cart
                // with flag - total avail as set in admin per variant
                //                $product['avail'] = cw_warehouse_get_avail_for_customer($id, $product['variant_id']);
                //                $product['avails']= cw_warehouse_get_avails_customer($id);
                $product['avail'] = cw_warehouse_get_avail_for_customer($id, $product['variant_id']);
            }
        } else {
            $product['avails'] = cw_warehouse_get_avails_customer($id, $product['avail'] + $product['avail_ordered']);
        }
    }
    return $product;
}
<?php

if ($manufacturer_id) {
    $f_categories = cw_clean_url_manufacturers_categories($manufacturer_id);
    cw_load('image');
    foreach ($f_categories as $k => $v) {
        $f_categories[$k]['image'] = cw_image_get('facet_categories_images', $v['url_id']);
    }
    $smarty->assign('f_categories', $f_categories);
    if (APP_AREA == 'admin') {
        cw_include('addons/clean_urls/admin/custom_facet_urls.php');
        if ($REQUEST_METHOD == 'POST') {
            if ($action == 'delete_fcat') {
                foreach ($fcat as $url_id => $v) {
                    if (isset($v['delete']) && $v['delete'] == '1') {
                        $url_id = intval($url_id);
                        db_query("DELETE FROM {$tables['manufacturers_categories']} WHERE manufacturer_id='{$manufacturer_id}' AND url_id='{$url_id}'");
                    }
                }
            }
            if ($action == 'update_fcat') {
                foreach ($fcat as $url_id => $v) {
                    $url_id = intval($url_id);
                    cw_array2update('manufacturers_categories', array('pos' => $v['pos']), "manufacturer_id='{$manufacturer_id}' AND url_id='{$url_id}'");
                }
            }
            if ($action == 'add_fcat') {
                /* Do not worry about posted var name "to_delete", it is from re-used template. In this context used to adding of new entries */
                foreach ($to_delete as $url_id => $v) {
                    $url_id = intval($url_id);
                    $data = array('manufacturer_id' => $manufacturer_id, 'url_id' => $url_id, 'pos' => 0);
function cw_attributes_get($params, $return)
{
    global $tables, $current_language;
    extract($params);
    if (empty($attribute_class_ids) && !empty($attribute_class_id)) {
        $attribute_class_ids = array($attribute_class_id);
    }
    # kornev, TOFIX lng param
    $language = $language ? $language : $current_language;
    if ($attribute_fields) {
        # kornev, selecte only a few fields
        $att_ids = cw_query_column($sql = "select a.attribute_id from {$tables['attributes']} as a where field in ('" . implode("', '", $attribute_fields) . "') and a.item_type='{$item_type}'");
    } elseif ($item_type == 'P') {
        # kornev, try to find it
        $all_attribute_class_ids = cw_func_call('cw_items_attribute_classes_get', array('item_id' => $item_id, 'item_type' => 'P'));
        if (!empty($all_attribute_class_ids)) {
            $attribute_class_condition = " and aca.attribute_class_id in (" . implode(",", $all_attribute_class_ids) . ")";
        }
        if (empty($attribute_class_ids)) {
            $attribute_class_ids = $all_attribute_class_ids;
        }
        # kornev, for the products we should unset the not-assigned attributes;
        # kornev, also we should apply the default class on the new product
        if ($is_default || empty($attribute_class_ids)) {
            $att_ids = cw_query_column($sql = "select a.attribute_id from {$tables['attributes']} as a, {$tables['attributes_classes']} as ac, {$tables['attributes_classes_assignement']} as acm where ac.is_default = 1 and acm.attribute_class_id=ac.attribute_class_id and acm.attribute_id=a.attribute_id and a.item_type='{$item_type}'");
        } else {
            $att_ids = cw_query_column($sql = "select a.attribute_id from {$tables['attributes']} as a, {$tables['attributes_classes']} as ac, {$tables['attributes_classes_assignement']} as acm where ac.attribute_class_id in ('" . implode("', '", $attribute_class_ids) . "') and acm.attribute_class_id=ac.attribute_class_id and acm.attribute_id=a.attribute_id and a.item_type='{$item_type}'");
        }
        if (!$att_ids) {
            $att_ids = array();
        }
    }
    $where_is_show_addon = empty($attribute_fields) ? " or (a.addon != '' && a.is_show_addon=1)" : '';
    $attributes = cw_query($sql = "select a.*, ifnull(al.name, a.name) as name, IFNULL(lng1.value, a.addon) as addon_lng, IFNULL(aca.attribute_class_id, 0) as attr_class_id, ac.name as attr_class_name from {$tables['attributes']} as a left join  {$tables['attributes_lng']} as al on a.attribute_id=al.attribute_id and al.code='{$language}' left join {$tables['languages']} as lng1 ON lng1.code = '{$language}' and lng1.name = CONCAT('addon_name_', a.addon) left join {$tables['addons']} as m on m.addon=a.addon left join {$tables['attributes_classes_assignement']} as aca on a.attribute_id=aca.attribute_id {$attribute_class_condition} left join {$tables['attributes_classes']} as ac on ac.attribute_class_id=aca.attribute_class_id where (m.active or m.addon is null or a.addon='core') " . (isset($is_show) ? "and is_show='{$is_show}' and a.active='{$is_show}'" : '') . " and item_type='{$item_type}' " . ($item_type == 'P' ? " and (a.attribute_id in ('" . implode("', '", $att_ids) . "') {$where_is_show_addon})" : ($att_ids ? " and a.attribute_id in ('" . implode("', '", $att_ids) . "')" : '')) . " group by a.attribute_id order by addon, attr_class_id, orderby");
    # kornev, multi-lng, '' - because the selectboxes
    $values = cw_query_hash($sql = "select av.attribute_id, ifnull(lng.value, av.value) as value from {$tables['attributes_values']} as av left join {$tables['attributes_values']} as lng on lng.item_id=av.item_id and lng.attribute_id=av.attribute_id and lng.item_type=av.item_type and lng.code='{$language}' where av.item_id='{$item_id}' and av.item_type='{$item_type}' and av.code in ('', '{$language}')", 'attribute_id', true, true);
    # kornev, we need to receive the attributes by 'field' in key - it's more suitable in most of the cases for addons
    $return = array();
    if ($attributes) {
        foreach ($attributes as $k => $v) {
            # kornev, in the default values we are store the option for the selectbox and the default values
            $attributes[$k]['default_value'] = cw_call('cw_attributes_get_attribute_default_value', array('attribute_id' => $v['attribute_id'], 'language' => $language));
            if ($is_default) {
                # kornev, if the default should be used, but the prefilled is already set - use it
                # kornev, mostly it means that the fields was filled partially we have to fix the other
                if ($prefilled[$v['field']]) {
                    $return[$attributes[$k]['field']] = $attributes[$k];
                    continue;
                }
                if (in_array($v['type'], array('selectbox', 'multiple_selectbox')) && is_array($attributes[$k]['default_value'])) {
                    foreach ($attributes[$k]['default_value'] as $dfv) {
                        if ($dfv['is_default']) {
                            $prefilled[$v['field']][] = $dfv['value'];
                        }
                    }
                } else {
                    $prefilled[$v['field']] = $attributes[$k]['default_value'];
                }
            }
            # kornev, extract images for customer area
            # kornev, we need to extract it for the $values only
            if (in_array($v['type'], array('selectbox', 'multiple_selectbox')) && is_array($attributes[$k]['default_value']) && is_array($values[$v['attribute_id']])) {
                foreach ($attributes[$k]['default_value'] as $dfv) {
                    $select_values[$dfv['attribute_value_id']] = $value;
                    if ($dfv['image_id'] && in_array($dfv['value'], $values[$v['attribute_id']])) {
                        $image = cw_image_get('attributes_images', $dfv['image_id']);
                        $image['alt'] = $dfv['value'];
                        $attributes[$k]['images'][$dfv['value']] = $image;
                    }
                }
            }
            if (is_array($prefilled) && count($prefilled)) {
                //            $attributes[$k]['values'] = $prefilled[$v['field']];
                if ($attributes[$k]['type'] == 'date' && !empty($prefilled[$v['field']]['Date_Month'])) {
                    $prefilled[$v['field']] = mktime(0, 0, 0, $prefilled[$v['field']]['Date_Month'], $prefilled[$v['field']]['Date_Day'], $prefilled[$v['field']]['Date_Year']);
                }
                if (is_array($prefilled[$v['field']])) {
                    $attributes[$k]['values'] = $prefilled[$v['field']];
                    $attributes[$k]['value'] = array_pop($prefilled[$v['field']]);
                } else {
                    $attributes[$k]['value'] = $prefilled[$v['field']];
                    $attributes[$k]['values'] = array($prefilled[$v['field']]);
                }
            } elseif (is_array($values[$v['attribute_id']])) {
                $attributes[$k]['values'] = $values[$v['attribute_id']];
                $attributes[$k]['value'] = array_pop($values[$v['attribute_id']]);
            }
            if (!is_array($attributes[$k]['values'])) {
                $attributes[$k]['values'] = array();
            }
            if (empty($attributes[$k]['addon']) && in_array($v['type'], array('selectbox', 'multiple_selectbox')) && !empty($attributes[$k]['default_value'])) {
                //check if current values of extra fields are valid options
                $values_are_valid = true;
                if (is_array($attributes[$k]['values'])) {
                    foreach ($attributes[$k]['values'] as $atv_k => $atv) {
                        $atr_value_found = false;
                        foreach ($attributes[$k]['default_value'] as $dfv) {
                            if ($dfv['attribute_value_id'] == $atv) {
                                $atr_value_found = true;
                                break;
                            }
                        }
                        if (!$atr_value_found) {
                            $values_are_valid = false;
                        }
                    }
                } else {
                    $values_are_valid = false;
                }
                if (!$values_are_valid) {
                    $attributes[$k]['values'] = array();
                    foreach ($attributes[$k]['default_value'] as $dfv) {
                        if ($dfv['is_default'] == 1) {
                            $attributes[$k]['values'][] = $dfv['attribute_value_id'];
                            $attributes[$k]['default_values_selected'] = 'Y';
                        }
                    }
                }
            }
            # kornev, for the selectbox, multi-selectbox the text values are stored in the default_values (required by multi-lng) - need to find that
            $attributes[$k]['values_str'] = $attributes[$k]['values'];
            $select_values = array();
            if (in_array($v['type'], array('selectbox', 'multiple_selectbox'))) {
                foreach ($attributes[$k]['default_value'] as $dfv) {
                    $select_values[$dfv['attribute_value_id']] = $dfv['value'];
                }
                foreach ($attributes[$k]['values_str'] as $vid => $vv) {
                    $attributes[$k]['values_str'][$vid] = $select_values[$vv];
                }
            }
            $return[$attributes[$k]['field']] = $attributes[$k];
        }
    }
    return $return;
}
<?php

$file_upload_data =& cw_session_register('file_upload_data');
cw_image_clear(array('magnifier_images'));
if ($action == 'product_zoomer') {
    cw_load('magnifier');
    foreach ($file_upload_data['magnifier_images'] as $image) {
        $image_posted = cw_image_check_posted($image);
        if ($image_posted) {
            $image_id = cw_image_save($image, array('id' => $product_id));
            $image = cw_image_get('magnifier_images', $image_id);
            $dir_name = cw_magnifier_create($image['image_path'], $image_id);
            db_query("update {$tables['magnifier_images']} set image_path='{$dir_name}/TileGroup0/0-0-0.jpg' where image_id='{$image_id}'");
        }
    }
    $top_message['content'] = cw_get_langvar_by_name('msg_adm_images_added_4zoomer');
    cw_refresh($product_id, 'zoomer');
}
if ($action == "zoomer_update_availability" && !empty($zoomer_image)) {
    # Update images
    foreach ($zoomer_image as $key => $value) {
        db_query("UPDATE {$tables['magnifier_images']} SET orderby='" . $value['orderby'] . "', avail='" . $value['avail'] . "' WHERE image_id='{$key}'");
    }
    $top_message['content'] = cw_get_langvar_by_name("msg_adm_images_updated_4zoomer");
    cw_refresh($product_id, 'zoomer');
}
if ($action == "product_zoomer_delete") {
    if (!empty($iids)) {
        foreach ($iids as $image_id => $tmp) {
            cw_image_delete($image_id, 'magnifier_images');
        }
function cw_manufacturer_get($params, $return = null)
{
    extract($params);
    global $tables, $current_language;
    $fields = $from_tbls = $query_joins = $where = array();
    # kornev, merge standart and additional variables
    if ($return) {
        foreach ($return as $saname => $sadata) {
            if (isset(${$saname}) && is_array(${$saname}) && empty(${$saname})) {
                ${$saname} = $sadata;
            }
        }
    }
    $from_tbls[] = 'manufacturers';
    $fields[] = "{$tables['manufacturers']}.*";
    $lang = $lang ? $lang : $current_language;
    $query_joins['manufacturers_lng'] = array('on' => "{$tables['manufacturers_lng']}.manufacturer_id = {$tables['manufacturers']}.manufacturer_id AND {$tables['manufacturers_lng']}.code = '{$lang}'");
    $fields[] = "IFNULL({$tables['manufacturers_lng']}.manufacturer, {$tables['manufacturers']}.manufacturer) as manufacturer";
    $fields[] = "IFNULL({$tables['manufacturers_lng']}.descr, {$tables['manufacturers']}.descr) as descr";
    $query_joins['manufacturer_images'] = array('on' => "{$tables['manufacturer_images']}.id = {$tables['manufacturers']}.manufacturer_id");
    $fields[] = "IF({$tables['manufacturer_images']}.id IS NULL, '', 'Y') as is_image";
    $where[] = "{$tables['manufacturers']}.manufacturer_id = '{$manufacturer_id}'";
    if (isset($avail)) {
        $where[] = "{$tables['manufacturers']}.avail = '{$avail}'";
    }
    $search_query = cw_db_generate_query($fields, $from_tbls, $query_joins, $where, $groupbys, $having, $orderbys);
    $manuf = cw_query_first($search_query);
    if (!$manuf) {
        return false;
    }
    if (!empty($manuf['url']) && strpos($manuf['url'], 'www.') === 0) {
        $manuf['url'] = 'http://' . $manuf['url'];
    }
    $manuf['image'] = cw_image_get('manufacturer_images', $manufacturer_id);
    return $manuf;
}
function cw_featured_categories_get($current_language)
{
    global $tables;
    $featured_categories = cw_query("select {$tables['categories']}.category_id,\n    IF({$tables['categories_lng']}.category_id IS NOT NULL AND {$tables['categories_lng']}.category != '',\n        {$tables['categories_lng']}.category, {$tables['categories']}.category) as category\n    from {$tables['categories']}\n    LEFT JOIN {$tables['categories_lng']}\n    ON {$tables['categories_lng']}.code='{$current_language}' AND {$tables['categories_lng']}.category_id={$tables['categories']}.category_id\n    LEFT JOIN {$tables['categories_memberships']}\n    ON {$tables['categories_memberships']}.category_id = {$tables['categories']}.category_id\n    where {$tables['categories']}.status=1 and {$tables['categories']}.featured=1\n    and {$tables['categories_memberships']}.membership_id IN(0, '{$user_account['membership_id']}')\n    group by {$tables['categories']}.category_id order by {$tables['categories']}.order_by, {$tables['categories']}.category");
    if (!empty($featured_categories) && count($featured_categories)) {
        foreach ($featured_categories as $key => $category) {
            $featured_categories[$key]['image'] = cw_image_get('categories_images_thumb', $category['category_id']);
        }
    }
    return $featured_categories;
}
function smarty_function_cms($params, &$smarty)
{
    global $tables, $domain_attributes, $mobile_attributes;
    global $config, $identifiers, $current_area, $addons;
    global $current_language, $product_id, $code;
    global $attributes;
    if (empty($addons['cms'])) {
        return false;
    }
    if (!empty($params['bannercode'])) {
        $params['service_code'] = $params['bannercode'];
    }
    if (empty($params['service_code'])) {
        return '';
    }
    $current_date = time();
    $output = '<!-- {cms service_code="' . $params['service_code'] . '"} -->';
    // MDM
    $mysql_contentsection_domains_conditions = '';
    if (!empty($domain_attributes['AB']) && ($conditions = cw_md_get_available_domains()) !== false) {
        $mysql_contentsection_domains_conditions = "INNER JOIN {$tables['attributes_values']} av\n\t        ON ab.contentsection_id=av.item_id\n\t\t    AND av.attribute_id = '" . $domain_attributes['AB'] . "'\n\t\t    AND av.value in " . $conditions;
    }
    // Mobile
    if (isset($mobile_attributes['AB']) && !empty($mobile_attributes['AB']['attribute_id']) && !empty($mobile_attributes['AB']['values'])) {
        $mysql_contentsection_domains_conditions .= " INNER JOIN {$tables['attributes_values']} avm\n\t        ON ab.contentsection_id=avm.item_id\n\t\t    AND avm.attribute_id = '" . $mobile_attributes['AB']['attribute_id'] . "'\n\t\t    AND avm.value in (" . implode(",", $mobile_attributes['AB']['values']) . ")";
    }
    $query = "SELECT ab.contentsection_id, " . "ab.service_code, " . "ab.content, " . "ab.url, " . "ab.type, " . "ab.target, " . "ab.start_date, " . "ab.end_date, " . "ab.skin, " . "ab.parse_smarty_tags " . "FROM {$tables['cms']} AS ab {$mysql_contentsection_domains_conditions} " . "WHERE ab.service_code = '" . addslashes($params['service_code']) . "' " . "AND IF(ab.start_date > 0, ab.start_date <= '" . $current_date . "', 1) " . "AND IF(ab.end_date > 0, ab.end_date >= '" . $current_date . "', 1) " . "AND ab.active = 'Y' " . ($code == 404 ? "AND ab.display_on_404 = 'Y' " : "AND ab.display_on_404 = 'N' ") . "ORDER BY ab.orderby ASC";
    $contentsections = cw_query($query);
    $is_editable = !empty($identifiers['A']) && $config['cms']['allow_edit_from_customer_area'] == 'Y';
    if (!$is_editable && (empty($contentsections) || !is_array($contentsections))) {
        return $output . '<!-- NO cms with service_code="' . $params['service_code'] . '" -->';
    }
    $first_contentsection = $contentsections[0];
    if (!empty($params['skin'])) {
        $skin = $params['skin'];
    } else {
        $skin = $first_contentsection['skin'];
    }
    $allowed_contentsections = array();
    foreach ($contentsections as $contentsection_data) {
        // Check attributes restriction
        if (!empty($attributes) && !empty($product_id)) {
            $_allowed_attributes = cw_query("select object_id as attribute_id, value_id, operation, value from {$tables['cms_restrictions']} where contentsection_id='" . $contentsection_data['contentsection_id'] . "' AND object_type='A'");
            if (!empty($_allowed_attributes) && is_array($_allowed_attributes)) {
                $allowed_attributes = array();
                foreach ($_allowed_attributes as $_allowed_attribute) {
                    if (!isset($allowed_attributes[$_allowed_attribute['attribute_id']])) {
                        $allowed_attributes[$_allowed_attribute['attribute_id']] = array();
                    }
                    $allowed_attributes[$_allowed_attribute['attribute_id']][$_allowed_attribute['value_id']] = $_allowed_attribute;
                }
                $contentsection_attributes = array();
                $attributes_conflict = false;
                foreach ($attributes as $attribute_name => $attribute_data) {
                    if (!isset($allowed_attributes[$attribute_data['attribute_id']])) {
                        continue;
                    }
                    $_attributes_conflict = false;
                    if (isset($allowed_attributes[$attribute_data['attribute_id']][0])) {
                        if ($allowed_attributes[$attribute_data['attribute_id']][0]['operation'] == 'bt') {
                            $between_values = explode(",", $allowed_attributes[$attribute_data['attribute_id']][0]['value']);
                            if (count($between_values) != 2) {
                                continue;
                            }
                            $_attributes_conflict = $attribute_data['value'] < min($between_values) || $attribute_data['value'] > max($between_values);
                        } elseif ($allowed_attributes[$attribute_data['attribute_id']][0]['operation'] == 'in') {
                            $in_values = explode(",", $allowed_attributes[$attribute_data['attribute_id']][0]['value']);
                            if (!count($in_values)) {
                                continue;
                            }
                            $_attributes_conflict = !in_array($attribute_data['value'], $in_values);
                        } elseif ($allowed_attributes[$attribute_data['attribute_id']][0]['operation'] == 'eq') {
                            $_attributes_conflict = $attribute_data['value'] != $allowed_attributes[$attribute_data['attribute_id']][0]['value'];
                        } elseif ($allowed_attributes[$attribute_data['attribute_id']][0]['operation'] == 'lt') {
                            $_attributes_conflict = $attribute_data['value'] >= $allowed_attributes[$attribute_data['attribute_id']][0]['value'];
                        } elseif ($allowed_attributes[$attribute_data['attribute_id']][0]['operation'] == 'le') {
                            $_attributes_conflict = $attribute_data['value'] > $allowed_attributes[$attribute_data['attribute_id']][0]['value'];
                        } elseif ($allowed_attributes[$attribute_data['attribute_id']][0]['operation'] == 'gt') {
                            $_attributes_conflict = $attribute_data['value'] <= $allowed_attributes[$attribute_data['attribute_id']][0]['value'];
                        } elseif ($allowed_attributes[$attribute_data['attribute_id']][0]['operation'] == 'ge') {
                            $_attributes_conflict = $attribute_data['value'] < $allowed_attributes[$attribute_data['attribute_id']][0]['value'];
                        }
                        $values_intersection = array(0);
                    } else {
                        $values_intersection = array_intersect($attribute_data['values'], array_keys($allowed_attributes[$attribute_data['attribute_id']]));
                        $_attributes_conflict = empty($values_intersection);
                    }
                    if (!$_attributes_conflict) {
                        //prepare restricted attributes for display
                        $contentsection_attributes[$attribute_data['attribute_id']] = array('attribute_data' => $attribute_data, 'values' => array());
                        foreach ($values_intersection as $value) {
                            $contentsection_attributes[$attribute_data['attribute_id']]['values'][$value] = $allowed_attributes[$attribute_data['attribute_id']][$value];
                        }
                    }
                    if ($_attributes_conflict) {
                        $attributes_conflict = true;
                    }
                }
                if ($attributes_conflict || empty($contentsection_attributes)) {
                    continue;
                }
                $contentsection_data['attributes'] = $contentsection_attributes;
            }
        }
        // Collect all restrictions validation result. All must return (bool)true to show section.
        // Listen to on_cms_check_restrictions event with your handlers and return false or true.
        $cms_restrictions = cw_event('on_cms_check_restrictions', array($contentsection_data), array());
        $is_valid = true;
        foreach ($cms_restrictions as $rest) {
            $is_valid &= $rest;
        }
        if (!$is_valid) {
            continue;
        }
        // Load image
        if (true || $contentsection_data['type'] == 'image') {
            cw_load('image');
            $contentsection_data['image'] = cw_image_get('cms_images', $contentsection_data['contentsection_id']);
        }
        // Load alt lang
        $contentsection_alt_languages = cw_query_first("SELECT name, url, content FROM {$tables['cms_alt_languages']} WHERE contentsection_id = '" . $contentsection_data['contentsection_id'] . "' AND code = '" . $current_language . "'");
        if (!empty($contentsection_alt_languages) && is_array($contentsection_alt_languages)) {
            $contentsection_data['url'] = $contentsection_alt_languages['url'];
            $contentsection_data['name'] = $contentsection_alt_languages['name'];
            $contentsection_data['content'] = $contentsection_alt_languages['content'];
        }
        // Update counter
        $count = intval(cw_query_first_cell("SELECT abuc.count FROM {$tables['cms_user_counters']} AS abuc WHERE abuc.contentsection_id = '" . $contentsection_data['contentsection_id'] . "'"));
        $count++;
        $is_entry_exists = intval(cw_query_first_cell("SELECT COUNT(*) FROM {$tables['cms_user_counters']} WHERE contentsection_id = '" . $contentsection_data['contentsection_id'] . "'"));
        if ($is_entry_exists) {
            cw_array2update('cms_user_counters', array('count' => $count), "contentsection_id = '" . $contentsection_data['contentsection_id'] . "'");
        } else {
            cw_array2insert('cms_user_counters', array('count' => '1', 'contentsection_id' => $contentsection_data['contentsection_id']), true);
        }
        $allowed_contentsections[] = $contentsection_data;
    }
    if (intval($params['pick_random']) > 0 && count($allowed_contentsections) > 1) {
        $random_select_count = min(count($allowed_contentsections) - 1, intval($params['pick_random']));
        if ($random_select_count > 0) {
            shuffle($allowed_contentsections);
            $allowed_contentsections = array_slice($allowed_contentsections, 0, $random_select_count);
        }
    }
    $smarty->assign('contentsections', $allowed_contentsections);
    $smarty->assign('cs_skin', $skin);
    $smarty->assign('service_code', $params['service_code']);
    return $output . "\n" . $smarty->fetch('addons/cms/skins/content.tpl');
}
function cw_product_options_prepare_products_found(&$products, $data, $user_account, $info_type)
{
    global $tables;
    if (!empty($data['attributes']) && !empty($products)) {
        foreach ($products as $_key => $_product) {
            $attr_def_values = array();
            foreach ($data['attributes'] as $k => $v) {
                if (in_array($k, array('price', 'substring'))) {
                    continue;
                }
                if (!is_array($v)) {
                    $v = array($v);
                }
                if (!is_numeric($v[0])) {
                    continue;
                }
                $attr_def_values = array_merge($attr_def_values, $v);
            }
            $result = cw_query("SELECT pp.price, pp.variant_id, pv.productcode, pw.avail, pvi.option_id\n                FROM {$tables['attributes_default']} ad\n                JOIN {$tables['product_options_values']} pov ON pov.name = ad.value\n                JOIN {$tables['product_options']} po ON po.product_option_id = pov.product_option_id\n                JOIN {$tables['product_variant_items']} pvi ON pvi.option_id = pov.option_id\n                JOIN {$tables['product_variants']} pv ON pv.variant_id = pvi.variant_id\n                JOIN {$tables['products_prices']} pp ON pp.variant_id = pvi.variant_id\n                JOIN {$tables['products_warehouses_amount']} pw ON pw.product_id = pp.product_id\n                    AND pw.variant_id = pp.variant_id\n                    AND pw.warehouse_customer_id = '" . $user_account['warehouse_customer_id'] . "'\n                    WHERE ad.attribute_value_id in ('" . implode("','", $attr_def_values) . "')\n                        AND po.product_id = '" . $_product['product_id'] . "' AND po.avail=1 AND pov.avail=1");
            if (!empty($result)) {
                $products[$_key]['price'] = $result[0]['price'];
                $products[$_key]['avail'] = $result[0]['avail'];
                $products[$_key]['productcode'] = $result[0]['productcode'];
                $products[$_key]['variant_id'] = $result[0]['variant_id'];
                $first_option_ids = array();
                $option_ids = array();
                foreach ($result as $_v) {
                    $option_ids[] = $_v['option_id'];
                }
                $option_ids = array_unique($option_ids);
                // Product options
                $product_options = cw_call('cw_get_product_classes', array($_product['product_id']));
                if (!empty($product_options)) {
                    foreach ($product_options as $_k => $_v) {
                        foreach ($option_ids as $option_id) {
                            // Hide selected option
                            if (isset($product_options[$_k]['options'][$option_id])) {
                                if (count($product_options) == 1) {
                                    unset($product_options[$_k]);
                                } else {
                                    $product_options[$_k]['options'] = array($option_id => $product_options[$_k]['options'][$option_id]);
                                    $product_options[$_k]['hidden'] = 1;
                                }
                                break 1;
                            }
                        }
                        if (is_array($product_options[$_k]) && is_array($product_options[$_k]['options'])) {
                            reset($product_options[$_k]['options']);
                            $first_option_ids[] = key($product_options[$_k]['options']);
                        }
                    }
                }
                if (!empty($product_options)) {
                    $products[$_key]['options'] = array_values($product_options);
                    // Product options ex
                    $products_options_ex = cw_get_product_exceptions($_product['product_id']);
                    if (!empty($products_options_ex)) {
                        $products[$_key]['options_ex'] = $products_options_ex;
                    }
                    // Product variants
                    $variants = cw_get_product_variants($_product['product_id'], $user_account['membership_id']);
                    if (!empty($variants)) {
                        $products[$_key]['variants'] = $variants;
                        // Find the selected variant
                        $selected_variant_id = $result[0]['variant_id'];
                        if (!empty($first_option_ids)) {
                            foreach ($variants as $vk => $variant) {
                                $match = TRUE;
                                foreach ($variant['options'] as $_k => $_v) {
                                    if (!in_array($_k, $first_option_ids)) {
                                        $match = FALSE;
                                        break 1;
                                    }
                                }
                                if ($match) {
                                    $selected_variant_id = $vk;
                                    break 1;
                                }
                            }
                        }
                        // If find variant, then change start values
                        if ($selected_variant_id != $result[0]['variant_id']) {
                            $products[$_key]['price'] = $variants[$selected_variant_id]['price'];
                            $products[$_key]['avail'] = $variants[$selected_variant_id]['avail'];
                            $products[$_key]['productcode'] = $variants[$selected_variant_id]['productcode'];
                            $products[$_key]['variant_id'] = $selected_variant_id;
                        }
                        if ($info_type & 128 && !empty($variants[$selected_variant_id]['image'])) {
                            $products[$_key]['variants']['image_thumb'] = $variants[$selected_variant_id]['image'];
                        }
                        $products[$_key]['image_det'] = cw_image_get('products_images_det', $_product['product_id']);
                        $min_avail = cw_query_first_cell("SELECT min_amount FROM {$tables['products']} WHERE product_id = '{$_product['product_id']}'");
                        if (!$min_avail) {
                            $min_avail = 1;
                        }
                        $products[$_key]['min_avail'] = $min_avail;
                    }
                }
            }
        }
    }
}
//cw_image_get('cms_images', intval($presaved_content_section['contentsection_id']));
$attributes = cw_func_call('cw_attributes_get', array('item_id' => 0, 'item_type' => 'AB', 'language' => $edited_language));
if (!empty($contentsection_id)) {
    $query = "SELECT *, service_code as service_code FROM {$tables['cms']} WHERE contentsection_id = '" . intval($contentsection_id) . "'";
    $content_section = cw_query_first($query);
    if (!empty($content_section) && is_array($content_section) && $mode != 'add') {
        $content_section_alt_languages = cw_query_first("SELECT name, alt, url, content FROM {$tables['cms_alt_languages']} WHERE contentsection_id = '" . intval($contentsection_id) . "' AND code = '" . $current_language . "'");
        if (!empty($content_section_alt_languages) && is_array($content_section_alt_languages)) {
            $content_section['name'] = $content_section_alt_languages['name'];
            $content_section['alt'] = $content_section_alt_languages['alt'];
            $content_section['url'] = $content_section_alt_languages['url'];
            $content_section['content'] = $content_section_alt_languages['content'];
        }
    }
    $content_section['image_id'] = 0;
    $content_section['image'] = cw_image_get('cms_images', $contentsection_id);
    $attributes = cw_func_call('cw_attributes_get', array('item_id' => $contentsection_id, 'item_type' => 'AB', 'language' => $edited_language));
} else {
    $content_section['service_code'] = $service_code;
}
if ($edit == 'Y') {
    $content_section = $presaved_content_section;
}
$smarty->assign('skins', $skins);
$smarty->assign('attributes', $attributes);
$smarty->assign('clean_urls', $clean_urls);
$smarty->assign('categories', $categories);
$smarty->assign('products', $products);
$smarty->assign('manufacturers', $manufacturers);
$smarty->assign('restricted_attributes', $restricted_attributes);
$smarty->assign('presaved_content_section', $presaved_content_section);
     $search_data =& cw_session_register("search_data", array());
     $search_data['products']['customer_search']['redirected_to_facet'] = true;
     cw_header_location($current_location . '/' . $combination_url . '?' . $url['query']);
 }
 // Check custom facet url in urls
 // e.g. search/custom-url-for-A-B --[parse as]--> search/attribute-A/attribute-B
 $new_clean_urls = array();
 $converted_clean_urls = array();
 foreach ($clean_urls as $urk_key => $clean_url) {
     if ($custom_facet_url = cw_clean_url_get_custom_facet_url($clean_url)) {
         define('FACET_URL', $clean_url);
         $custom_facet_clean_url_parts = explode('/', $custom_facet_url['clean_urls']);
         $new_clean_urls = array_merge($new_clean_urls, $custom_facet_clean_url_parts);
         $converted_clean_urls = array_merge($converted_clean_urls, $custom_facet_clean_url_parts);
         cw_load('image');
         $smarty->assign('facet_category', array('image' => cw_image_get('facet_categories_images', $custom_facet_url['url_id'])));
     } else {
         $new_clean_urls[] = $clean_url;
     }
 }
 $clean_urls = $new_clean_urls;
 $clean_url_attrubute_ids = array_keys(cw_call('cw_attributes_filter', array(array('field' => 'clean_url'))));
 $clean_url_html_attribute_ids = cw_call('cw_clean_url_html_attribute_ids', array());
 foreach ($clean_urls as $urk_key => $clean_url) {
     // Detect data
     $clean_url_values = array();
     // values for range or select attributes
     $clean_url_parts = explode('-', $clean_url);
     // for substring use special code
     if ($clean_url_parts[0] == 'substring') {
         global $att;
function cw_products_from_scratch($scratch_products, $user_info, $persistent_products, $leave_info = false)
{
    global $addons, $tables, $config, $app_main_dir;
    global $current_area, $current_language, $customer_id;
    cw_load('image');
    $products = array();
    if (empty($scratch_products)) {
        return $products;
    }
    $pids = array();
    foreach ($scratch_products as $product_data) {
        $pids[] = $product_data['product_id'];
    }
    $int_res = cw_query_hash("SELECT * FROM {$tables['products_lng']} WHERE code = '{$current_language}' AND product_id IN ('" . implode("','", $pids) . "')", "product_id", false);
    unset($pids);
    cw_event('on_before_products_from_scratch', array(&$scratch_products));
    $hash = array();
    cw_load('warehouse');
    foreach ($scratch_products as $product_data) {
        $product_id = $product_data['product_id'];
        $cartid = $product_data['cartid'];
        $amount = $product_data['amount'];
        $variant_id = $product_data['variant_id'];
        $warehouse = $product_data['warehouse_customer_id'];
        if (!cw_warehouse_is_customer($customer_id, $warehouse)) {
            continue;
        }
        if (!is_numeric($amount)) {
            $amount = 0;
        }
        $options = $product_data['options'];
        $product_options = false;
        $variant = array();
        # kornev, TOFIX
        if ($addons['product_options'] && !empty($options) && is_array($options)) {
            if (!cw_check_product_options($product_id, $options)) {
                continue;
            }
            list($variant, $product_options) = cw_get_product_options_data($product_id, $options, $membership_id);
            if (empty($variant_id) && isset($variant['variant_id'])) {
                $variant_id = $variant['variant_id'];
            }
        }
        $fields[] = "p.*";
        # kornev, supplier has got it's own prices
        if ($current_area != 'S') {
            $fields[] = "min(pq.price) as price";
        }
        $fields[] = 'avail';
        $status = cw_core_get_required_status($current_area);
        $products_array = cw_func_call('cw_product_get', array('id' => $product_id, 'variant_id' => $variant_id, 'amount' => $amount, 'user_account' => $user_info, 'info_type' => 8192));
        //cw_query_first($sql="select ".implode(', ', $fields)." from $tables[products] as p, $tables[products_prices] as pq, $tables[products_enabled] as pe left join $tables[products_warehouses_amount] as pwa on pwa.product_id=pe.product_id and pwa.variant_id='$variant_id' and pwa.warehouse_customer_id='$warehouse' WHERE p.product_id= pe.product_id and pe.product_id=pq.product_id AND pe.status in (".implode(", ", $status).") AND pe.product_id='$product_id' AND pq.quantity<='$amount' AND pq.membership_id IN(0, '$user_info[membership_id]') AND pq.variant_id = '$variant_id' ORDER BY pq.quantity DESC");
        $unlimited_products = true;
        if ($products_array['avail'] < $amount && in_array($current_area, array('G', 'C'))) {
            $unlimited_products = cw_query_first_cell("select backorder & " . ($current_area == 'G' ? 2 : 1) . " from {$tables['warehouse_divisions']} where division_id = '{$warehouse}'");
            if (!$unlimited_products) {
                $amount = $products_array['avail'];
            }
        }
        if ($products_array) {
            $products_array = cw_array_merge($product_data, $products_array);
            if ($leave_info) {
                $products_array['price'] = abs($product_data['price']);
            }
            $products_array['warehouse_customer_id'] = $warehouse;
            $hash_key = $product_id . "|" . $warehouse;
            cw_event('on_product_from_scratch', array(&$products_array));
            #
            # If priduct's price is 0 then use customer-defined price
            #
            $free_price = false;
            if ($products_array['price'] == 0) {
                $free_price = true;
                $products_array['taxed_price'] = $products_array['price'] = price_format($product_data['free_price'] ? $product_data['free_price'] : 0);
            }
            # kornev, TOFIX
            if ($addons['product_options'] && $options) {
                if (!empty($variant)) {
                    # kornev, it's not allow to set the variant price.
                    //					unset($variant['price']);
                    if (is_null($variant['pimage_path'])) {
                        cw_unset($variant, "pimage_path", "pimage_x", "pimage_y");
                    } else {
                        $variant['is_pimage'] = 'W';
                    }
                    $products_array = cw_array_merge($products_array, $variant);
                }
                $hash_key .= "|" . $products_array['variant_id'];
                if ($product_options === false) {
                    unset($product_options);
                } else {
                    $variant['price'] = $products_array['price'];
                    $variant['cost'] = $products_array['cost'];
                    $products_array['options_surcharge'] = 0;
                    $products_array['cost_surcharge'] = 0;
                    if ($product_options) {
                        foreach ($product_options as $o) {
                            $products_array['options_surcharge'] += $o['modifier_type'] ? $products_array['price'] * $o['price_modifier'] / 100 : $o['price_modifier'];
                            $products_array['cost_surcharge'] += $o['cost_modifier_type'] ? $products_array['cost'] * $o['cost_modifier'] / 100 : $o['cost_modifier'];
                        }
                    }
                }
            }
            if (!$unlimited_products && !$persistent_products && $products_array['avail'] - $hash[$hash_key] < $amount) {
                continue;
            }
            # Get thumbnail's URL (uses only if images stored in FS)
            $products_array['image_thumb'] = cw_image_get('products_images_thumb', $product_id);
            $products_array['price'] += $products_array['options_surcharge'];
            $products_array['cost'] += $products_array['cost_surcharge'];
            if ($products_array['price'] < 0) {
                $products_array['price'] = 0;
            }
            if ($products_array['cost'] < 0) {
                $products_array['cost'] = 0;
            }
            if (in_array($current_area, array('C', 'G'))) {
                $products_array['taxes'] = cw_get_products_taxes($products_array, $user_info, false, '', $current_area == 'G' && $customer_info['usertype'] != 'R');
                if ($config['Taxes']['display_taxed_order_totals'] == 'Y') {
                    $products_array['display_price'] = $products_array['taxed_price'];
                    $products_array['display_net_price'] = $products_array['taxed_net_price'];
                } else {
                    $products_array['display_price'] = $products_array['price'];
                    $products_array['display_net_price'] = $products_array['net_price'];
                }
            }
            $products_array['total'] = $amount * $products_array['price'];
            $products_array['product_options'] = $product_options;
            $products_array['options'] = $options;
            $products_array['amount'] = $amount;
            $products_array['cartid'] = $cartid;
            $products_array['product_orig'] = $products_array['product'];
            if (isset($int_res[$product_id])) {
                $products_array['product'] = stripslashes($int_res[$product_id]['product']);
                $products_array['descr'] = stripslashes($int_res[$product_id]['descr']);
                $products_array['fulldescr'] = stripslashes($int_res[$product_id]['fulldescr']);
                cw_unset($int_res, $product_id);
            }
            if ($products_array['descr'] == strip_tags($products_array['descr'])) {
                $products_array['descr'] = str_replace("\n", "<br />", $products_array['descr']);
            }
            if ($products_array['fulldescr'] == strip_tags($products_array['fulldescr'])) {
                $products_array['fulldescr'] = str_replace("\n", "<br />", $products_array['fulldescr']);
            }
            // Order hash defines how all products in cart will be split by orders
            // Listen for the event and return own part of hash
            $order_hash = cw_event('on_build_order_hash', array($products_array), array());
            $order_hash[] = 'W' . $products_array['warehouse_customer_id'];
            $products_array['order_hash'] = join('-', $order_hash);
            $products[] = $products_array;
            $hash[$hash_key] += $amount;
        }
    }
    //cw_var_dump($products);
    return $products;
}
<?php

# [TOFIX]
# kornev, move to addon
if (!$addons['magnifier']) {
    cw_close_window();
}
cw_load('image');
if ($image_id) {
    $image = cw_image_get('magnifier_images', $image_id);
}
$product = cw_func_call('cw_product_get', array('id' => $product_id, 'user_account' => $user_account));
$zoomer_images = cw_image_get_list('magnifier_images', $product_id, $current_area == 'C' ? 1 : 0);
if (!$image_id) {
    $image = cw_image_get('magnifier_images', $zoomer_images[0]['image_id']);
}
if (!$product || !$image) {
    cw_close_window();
}
$location[] = array($product['product'], '');
$location[] = array(cw_get_langvar_by_name('lbl_magnifier_image'), '');
$smarty->assign('images_count', count($zoomer_images));
if (is_array($zoomer_images)) {
    foreach ($zoomer_images as $k => $v) {
        $zoomer_images[$k]['image_path'] = dirname(dirname($v['tmbn_url']));
    }
}
$smarty->assign('zoomer_images', $zoomer_images);
$smarty->assign('image_path', dirname(dirname($image['tmbn_url'])));
$smarty->assign('product_id', $product_id);
$smarty->assign('home_style', 'iframe');