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_ps_get_customer_offers(&$cart, &$products, $_user_info = array())
{
    global $tables, $domain_attributes, $addons, $smarty;
    static $offers_hash;
    if (empty($cart) || empty($products)) {
        return array();
    }
    global $customer_id, $user_info;
    $customer_zone = null;
    if (isset($customer_id) && !empty($customer_id)) {
        if (!isset($user_info) || empty($user_info)) {
            $user_info = cw_user_get_info($customer_id, 1);
        }
    } else {
        $user_info = $_user_info;
        if (empty($_user_info)) {
            $user_info = $cart['userinfo'];
        }
    }
    $customer_zone = cw_func_call('cw_cart_get_zone_ship', array('address' => $user_info['current_address'], 'type' => 'D'));
    list($_products, $_categories, $_manufacturers) = cw_ps_normalize_products($products);
    if (empty($_products) || empty($_categories)) {
        return array();
    }
    //$hash_key = md5(serialize($_products) . serialize($user_info));
    $shipping_address = array();
    $shipping_address_fields = array('country', 'state', 'zipcode', 'city', 'address');
    if (!isset($user_info) || empty($user_info)) {
        foreach ($shipping_address_fields as $field) {
            if (isset($user_info['current_address'][$field])) {
                $shipping_address[] = $user_info['current_address'][$field];
            }
        }
    }
    $hash_key = md5(serialize($_products) . serialize($shipping_address));
    if (!isset($offers_hash[$hash_key])) {
        $offers_hash[$hash_key] = array();
    } else {
        return $offers_hash[$hash_key];
    }
    $fields = $from_tbls = $query_joins = $where = $groupbys = $having = $orderbys = array();
    $fields = array("{$tables['ps_offers']}.offer_id");
    $offers = array();
    $from_tbls[] = 'ps_offers';
    if (isset($addons['multi_domains'])) {
        $conditions = cw_md_get_available_domains();
        if ($conditions !== false) {
            $query_joins['attributes_values'] = array('on' => "{$tables['ps_offers']}.offer_id = {$tables['attributes_values']}.item_id and {$tables['attributes_values']}.item_type = '" . PS_ATTR_ITEM_TYPE . "' and {$tables['attributes_values']}.attribute_id='" . $domain_attributes[PS_ATTR_ITEM_TYPE] . "' and {$tables['attributes_values']}.value in " . $conditions, 'is_inner' => 1);
        }
    }
    $query_joins['ps_bonuses'] = array('on' => "{$tables['ps_offers']}.offer_id = {$tables['ps_bonuses']}.offer_id", 'is_inner' => 1);
    $query_joins['ps_conditions'] = array('on' => "{$tables['ps_offers']}.offer_id = {$tables['ps_conditions']}.offer_id", 'is_inner' => 1);
    $where[] = "{$tables['ps_offers']}.enddate >= '" . cw_core_get_time() . "'";
    $where[] = "{$tables['ps_offers']}.active = '1'";
    $having[] = "COUNT({$tables['ps_bonuses']}.bonus_id) > 0";
    $having[] = "COUNT({$tables['ps_conditions']}.cond_id) > 0";
    $groupbys[] = "{$tables['ps_offers']}.offer_id";
    $orderbys[] = 'priority DESC';
    $orderbys[] = 'position';
    $_query_joins = $query_joins;
    $_where = $where;
    $_having = $having;
    $_groupbys = $groupbys;
    $_fields = $fields;
    // let's take offers suitable by date and domain
    $search_query = cw_db_generate_query($fields, $from_tbls, $query_joins, $where, $groupbys, $having, $orderbys);
    $offers = cw_query_hash($search_query, 'offer_id', false);
    if (empty($offers) || !is_array($offers)) {
        return array();
    }
    // let's take offers with the subtotal condition defined
    $offers_condition = "{$tables['ps_cond_details']}.offer_id IN ('" . implode("', '", array_keys($offers)) . "')";
    $fields = $from_tbls = $query_joins = $where = $groupbys = $having = $orderbys = array();
    $fields = array('offer_id');
    $from_tbls[] = 'ps_conditions';
    //TODO: update the code below
    //echo '<pre>', print_r($tmp_cart), '</pre>';
    $discounted_subtotal = 0;
    //if (!isset($cart['info']['discounted_subtotal'])) {
    //$cart['discounted_subtotal'] = 10;
    $tmp_cart = array();
    $products_warehouses = cw_cart_get_products_warehouses($products);
    if (!empty($products_warehouses) && is_array($products_warehouses)) {
        foreach ($products_warehouses as $warehouse_id) {
            $tmp_products = cw_get_products_by_warehouse($products, $warehouse_id);
            $result = cw_func_call('cw_cart_calc_single', array('cart' => $cart, 'products' => $tmp_products, 'userinfo' => $user_info, 'warehouse_id' => $warehouse_id));
            //echo '<pre>result: ', print_r($result), '</pre>';
            $tmp_cart = cw_func_call('cw_cart_summarize', array('res' => $result, 'warehouse_id' => $warehouse_id), $tmp_cart);
        }
        unset($tmp_products);
    } else {
        $warehouse_id = 0;
        $result = cw_func_call('cw_cart_calc_single', array('cart' => $cart, 'products' => $products, 'userinfo' => $user_info, 'warehouse_id' => $warehouse_id));
        $tmp_cart = cw_func_call('cw_cart_summarize', array('res' => $result, 'warehouse_id' => $warehouse_id), $tmp_cart);
    }
    if (!empty($tmp_cart) && is_array($tmp_cart)) {
        if (isset($tmp_cart['info']['discounted_subtotal'])) {
            $discounted_subtotal = $tmp_cart['info']['discounted_subtotal'];
            if ($tmp_cart['info']['discounted_subtotal'] > $tmp_cart['info']['subtotal']) {
                $discounted_subtotal = $tmp_cart['info']['subtotal'];
            }
        }
    }
    unset($tmp_cart);
    //}
    //echo '<pre>', "discounted_subtotal: $discounted_subtotal", '</pre>';
    //echo '<pre>tmp_cart: ', print_r($tmp_cart), '</pre>';
    //die;
    $where[] = "type = '" . PS_TOTAL . "'";
    $where[] = "total > {$discounted_subtotal}";
    $where[] = "offer_id IN ('" . implode("', '", array_keys($offers)) . "')";
    $search_query = cw_db_generate_query($fields, $from_tbls, $query_joins, $where, $groupbys, $having, $orderbys);
    $not_allowed_offers = cw_query_hash($search_query, 'offer_id', false);
    //echo '<pre>1 ', print_r($offers), '</pre>';
    //echo '<pre>2 ', print_r($not_allowed_offers), '</pre>';
    if (!empty($not_allowed_offers) && is_array($not_allowed_offers)) {
        $offers = array_diff_key($offers, $not_allowed_offers);
    }
    //echo '<pre>3 ', print_r($offers), '</pre>';
    //die;
    if (empty($offers) || !is_array($offers)) {
        return array();
    }
    // let's take offers with the destination zone defined
    $fields = $from_tbls = $query_joins = $where = $groupbys = $having = $orderbys = array();
    $fields = array('offer_id');
    $from_tbls[] = 'ps_cond_details';
    if (!empty($customer_zone)) {
        $where[] = "object_type = '" . PS_OBJ_TYPE_ZONES . "'";
        $where[] = "object_id != '" . $customer_zone . "'";
        $where[] = "offer_id IN ('" . implode("', '", array_keys($offers)) . "')";
        $search_query = cw_db_generate_query($fields, $from_tbls, $query_joins, $where, $groupbys, $having, $orderbys);
        $not_allowed_offers = cw_query_hash($search_query, 'offer_id', false);
        //die(var_dump($offers, $customer_zone, $not_allowed_offers));
        if (!empty($not_allowed_offers) && is_array($not_allowed_offers)) {
            $offers = array_diff_key($offers, $not_allowed_offers);
        }
    } else {
        $where[] = "object_type = '" . PS_OBJ_TYPE_ZONES . "'";
        $where[] = "offer_id IN ('" . implode("', '", array_keys($offers)) . "')";
        $search_query = cw_db_generate_query($fields, $from_tbls, $query_joins, $where, $groupbys, $having, $orderbys);
        $not_allowed_offers = cw_query_hash($search_query, 'offer_id', false);
        if (!empty($not_allowed_offers) && is_array($not_allowed_offers)) {
            $offers = array_diff_key($offers, $not_allowed_offers);
        }
    }
    if (empty($offers) || !is_array($offers)) {
        return array();
    }
    //let's take offers with suitable products
    //list($_products, $_categories, $_manufacturers) = cw_ps_normalize_products($products);
    foreach ($offers as $offer_id => $trash) {
        $checking_result = cw_ps_check_offer($offer_id, $_products);
        if ($checking_result == false) {
            unset($offers[$offer_id]);
        }
    }
    //let's delete offers which cannot be applied after the application of the first ones by priority
    //die(var_dump($offers, $customer_zone));
    $first_offer = null;
    foreach ($offers as $offer_id => $trash) {
        if (empty($first_offer)) {
            $first_offer = $offer_id;
            cw_ps_update_conditions($offer_id, $_products, $_categories, $_manufacturers);
            continue;
        }
        $checking_result = false;
        if (!empty($_products)) {
            $checking_result = cw_ps_check_offer($offer_id, $_products);
        }
        if ($checking_result == false) {
            unset($offers[$offer_id]);
        } else {
            cw_ps_update_conditions($offer_id, $_products, $_categories, $_manufacturers);
        }
    }
    //var_dump($offers, $_categories, $_manufacturers, $_products);
    //die('end');
    $offers_hash[$hash_key] = $offers;
    unset($offers);
    return $offers_hash[$hash_key];
}
function cw_md_taxes_search($params, $return)
{
    global $tables, $domain_attributes;
    $conditions = cw_md_get_available_domains();
    if ($conditions === false) {
        return $return;
    }
    $return['query_joins']['attributes_values'] = array('on' => "{$tables['taxes']}.tax_id={$tables['attributes_values']}.item_id  and {$tables['attributes_values']}.item_type = 'T' and {$tables['attributes_values']}.attribute_id='{$domain_attributes['T']}' and {$tables['attributes_values']}.value in " . $conditions, 'is_inner' => 1);
    return $return;
}