function dod_show()
{
    global $available_fields, $optional_fields, $tables, $smarty, $top_message, $target;
    $generators = array();
    $fields = $from_tbls = $query_joins = $where = $groupbys = $having = $orderbys = array();
    $from_tbls[] = 'dod_generators';
    $fields = array_keys($available_fields);
    $where[] = 1;
    $orderbys[] = 'position';
    $orderbys[] = 'generator_id';
    $search_query_count = cw_db_generate_query('count(generator_id)', $from_tbls, $query_joins, $where, $groupbys, $having, array(), 0);
    $search_query = cw_db_generate_query($fields, $from_tbls, $query_joins, $where, $groupbys, $having, $orderbys);
    $total_items_res_id = db_query($search_query_count);
    $number_generators = db_num_rows($total_items_res_id);
    if (empty($number_generators)) {
        return null;
    }
    global $navigation, $page;
    $navigation = cw_core_get_navigation($target, $number_generators, $page);
    $limit_str = " LIMIT {$navigation['first_page']}, {$navigation['objects_per_page']}";
    $generators = cw_query($search_query . $limit_str);
    if (empty($generators)) {
        return null;
    }
    $generators = array_map(create_function('$elm', '$elm["description"] = strip_tags($elm["description"]); return $elm;'), $generators);
    $smarty->assign('dod_generators', cw_stripslashes($generators));
    $navigation['script'] = 'index.php?target=' . $target;
    $smarty->assign('navigation', $navigation);
}
function ppd_show($product_id)
{
    global $available_fields, $smarty, $tables, $config, $target;
    global $app_catalogs, $mode;
    $product_id = (int) $product_id;
    if (empty($product_id)) {
        return;
    }
    if ($_SERVER['REQUEST_METHOD'] != 'GET') {
        ppd_redirect($product_id);
    }
    global $page;
    if (!isset($page)) {
        $page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
    }
    $_new_files =& cw_session_register('_new_files');
    if (!empty($_new_files)) {
        $smarty->assign('_new_files', $_new_files);
        cw_session_unregister('_new_files');
    }
    $limit_files = null;
    $number_files = cw_query_first_cell('SELECT COUNT(file_id) FROM ' . $tables['ppd_files'] . ' WHERE product_id = \'' . $product_id . '\'');
    $navigation = cw_core_get_navigation($target, $number_files, $page);
    $navigation['script'] = "{$app_catalogs['admin']}/index.php?target={$target}&mode={$mode}&js_tab=ppd&product_id={$product_id}";
    $smarty->assign('navigation', $navigation);
    if (isset($navigation['first_page']) && isset($navigation['objects_per_page'])) {
        $limit_files = " LIMIT {$navigation['first_page']}, {$navigation['objects_per_page']}";
    }
    unset($available_fields['type_id']);
    $files = array();
    if (!empty($number_files)) {
        $files = cw_query('SELECT `' . implode('`, `', array_keys($available_fields)) . '`, `type`, `fileicon` FROM ' . $tables['ppd_files'] . ' AS files LEFT JOIN ' . $tables['ppd_types'] . ' AS types ON files.type_id = types.type_id WHERE product_id = \'' . $product_id . '\' ORDER BY number' . $limit_files);
    }
    if (empty($files) || !is_array($files)) {
        return;
    }
    foreach ($files as $key => $file) {
        $files[$key]['fileicon'] = ppd_get_url_fileicon($files[$key]['fileicon']);
        $_real_path = ppd_check_path($files[$key]['filename']);
        $files[$key]['is_deleted'] = empty($_real_path) ? true : false;
        $files[$key]['fileicon'] = empty($files[$key]['filename']) ? null : $files[$key]['fileicon'];
        $files[$key]['perms_owner'] = ppd_permissions($files[$key]['perms_owner']);
        $files[$key]['perms_all'] = ppd_permissions($files[$key]['perms_all']);
        $files[$key]['size'] = ppd_convertfrom_bytes($files[$key]['size']);
        $files[$key]['month_stats'] = ppd_get_stats($files[$key]['file_id'], $product_id, mktime(0, 0, 0, date('m'), 1, date('Y')), mktime(23, 59, 59, date('m') + 1, 0, date('Y')));
        $files[$key]['year_stats'] = ppd_get_stats($files[$key]['file_id'], $product_id, mktime(0, 0, 0, 1, 1, date('Y')), mktime(23, 59, 59, 12, 31, date('Y')));
    }
    $smarty->assign('ppd_files', $files);
}
function ppd_filetype_show()
{
    global $available_fields, $smarty, $tables, $config, $target;
    global $app_catalogs;
    global $page;
    if (!isset($page)) {
        $page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
    }
    $page = (int) $page;
    if ($_SERVER['REQUEST_METHOD'] != 'GET') {
        ppd_filetype_redirect();
    }
    $_new_types =& cw_session_register('_new_types');
    if (!empty($_new_types)) {
        $smarty->assign('_new_types', $_new_types);
        cw_session_unregister('_new_types');
    }
    $limit_types = null;
    $number_types = cw_query_first_cell('SELECT COUNT(type_id) FROM ' . $tables['ppd_types']);
    $navigation = cw_core_get_navigation($target, $number_types, $page);
    $navigation['script'] = "{$app_catalogs['admin']}/index.php?target={$target}";
    $smarty->assign('navigation', $navigation);
    if (isset($navigation['first_page']) && isset($navigation['objects_per_page'])) {
        $limit_types = " LIMIT {$navigation['first_page']}, {$navigation['objects_per_page']}";
    }
    $types = array();
    if (!empty($number_types)) {
        $types = cw_query('SELECT `' . implode('`, `', array_keys($available_fields)) . '` FROM ' . $tables['ppd_types'] . $limit_types);
    }
    if (empty($types) || !is_array($types)) {
        return;
    }
    foreach ($types as $key => $file) {
        $types[$key]['fileicon_exists'] = true;
        $types[$key]['fileicon_url'] = ppd_get_url_fileicon($types[$key]['fileicon']);
        if (empty($types[$key]['fileicon_url'])) {
            $types[$key]['fileicon_exists'] = false;
        }
    }
    $smarty->assign('ppd_types', $types);
}
    db_query("UPDATE {$tables['map_countries']} SET active=1");
    $top_message['content'] = cw_get_langvar_by_name("msg_adm_countries_enabled");
}
if ($action == 'update' && is_array($posted_data)) {
    foreach ($posted_data as $k => $v) {
        $to_update = array('active' => $v['active'], 'display_regions' => $v['display_regions'], 'display_states' => $v['display_states'], 'display_counties' => $v['display_counties'], 'display_cities' => $v['display_cities'], 'lang' => $v['lang']);
        cw_array2update('map_countries', $to_update, "code='{$k}'");
        db_query("UPDATE {$tables['languages']} SET value = '{$v['country']}' WHERE name = 'country_{$k}' AND code = '{$current_language}'");
    }
    $top_message['content'] = cw_get_langvar_by_name("msg_adm_countries_upd");
    cw_header_location("index.php?target=countries&zone={$zone}&page={$page}");
}
if ($action) {
    cw_header_location("index.php?target=countries&zone={$zone}&page={$page}");
}
$condition = "";
if (!empty($zone)) {
    if ($zone == "SU") {
        $condition = " WHERE {$tables['map_countries']}.code IN ('AM','AZ','BY','EE','GE','KZ','KG','LV','LT','MD','RU','TJ','TM','UA','UZ')";
    } else {
        $condition = " WHERE {$tables['map_countries']}.region='{$zone}'";
    }
}
$total_items_in_search = cw_query_first_cell("SELECT COUNT(*) FROM {$tables['map_countries']} {$condition}");
$navigation = cw_core_get_navigation($target, $total_items_in_search, $page);
$navigation['script'] = "index.php?target=countries&zone=" . (empty($zone) ? "ALL" : $zone);
$smarty->assign('navigation', $navigation);
$countries = cw_query("SELECT {$tables['map_countries']}.*, IFNULL(lng1c.value, lng2c.value) as country, IFNULL(lng1l.value, lng2l.value) as language FROM {$tables['map_countries']} LEFT JOIN {$tables['languages']} as lng1c ON lng1c.name = CONCAT('country_', {$tables['map_countries']}.code) AND lng1c.code = '{$current_language}' LEFT JOIN {$tables['languages']} as lng2c ON lng2c.name = CONCAT('country_', {$tables['map_countries']}.code) AND lng2c.code = '{$config['default_admin_language']}' LEFT JOIN {$tables['languages']} as lng1l ON lng1l.name = CONCAT('language_', {$tables['map_countries']}.code) AND lng1l.code = '{$current_language}' LEFT JOIN {$tables['languages']} as lng2l ON lng2l.name = CONCAT('language_', {$tables['map_countries']}.code) AND lng2l.code = '{$config['default_admin_language']}' {$condition} ORDER BY country LIMIT {$navigation['first_page']}, {$navigation['objects_per_page']}");
$smarty->assign('countries', $countries);
$smarty->assign('zones', $zones);
$smarty->assign('zone', $zone);
<?php

cw_load('files', 'image');
if (!isset($available_images[$type])) {
    cw_close_window();
}
$images = cw_query($sql = "SELECT " . ($available_images[$type] == "U" ? "id" : "image_id") . " as id, image_path, image_x, image_y, image_size, alt FROM " . $tables[$type] . " WHERE id = '{$id}' AND avail = 1 ORDER BY orderby");
if (empty($images)) {
    cw_close_window();
}
$navigation = cw_core_get_navigation($target, count($total_items), $page);
$navigation['script'] = "index.php?target=popup_image&type={$type}&id={$id}&title=" . urlencode($title);
$smarty->assign('navigation', $navigation);
$max_x = 0;
// get max height
foreach ($images as $k => $v) {
    $images[$k] = cw_image_info($type, $v);
    if ($images[$k]['image_x'] > $max_x) {
        $max_x = $images[$k]['image_x'];
    }
}
if (!empty($title)) {
    $smarty->assign('title', $title);
}
$smarty->assign('max_x', $max_x);
$smarty->assign('images_count', count($images));
$smarty->assign('images', $images);
$smarty->assign('id', $id);
$smarty->assign('type', $type);
$smarty->assign('area', $area);
$smarty->assign('body_onload', 'changeImg(0);');
function cw_pages_search($params, $return = null)
{
    extract($params);
    global $tables, $current_language, $target;
    $fields = $from_tbls = $query_joins = $where = $groupbys = $having = $orderbys = 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[] = 'pages';
    $fields[] = "{$tables['pages']}.*";
    $where[] = 1;
    if (!empty($data['sort_field'])) {
        $direction = $data['sort_direction'] ? 'DESC' : 'ASC';
        $orderbys[] = $data['sort_field'] . ' ' . $direction;
    } else {
        $orderbys[] = 'title';
    }
    $search_query_count = cw_db_generate_query('count(*)', $from_tbls, $query_joins, $where, $groupbys, $having, array(), 0);
    $search_query = cw_db_generate_query($fields, $from_tbls, $query_joins, $where, $groupbys, $having, $orderbys);
    $total_items_res_id = db_query($search_query_count);
    $total_items = db_num_rows($total_items_res_id);
    $page = $data['page'];
    if ($data['count']) {
        return $total_items;
    } elseif ($data['limit']) {
        $limit_str = " LIMIT {$data['limit']}";
    } elseif ($data['all']) {
        $limit_str = '';
    } else {
        $navigation = cw_core_get_navigation($target, $total_items, $page);
        $limit_str = " LIMIT {$navigation['first_page']}, {$navigation['objects_per_page']}";
    }
    $pages = cw_query($search_query . $limit_str);
    return array($pages, $navigation);
}
function cw_gift_get_giftreg_wishlist_database($customer_id, $event_id)
{
    global $tables;
    global $items_per_page, $page, $sort, $sort_direction, $items_per_page_targets;
    global $smarty, $target, $action, $mode;
    $wishlist_items_nav = array();
    if (isset($items_per_page)) {
        $wishlist_items_nav['items_per_page'] = $items_per_page;
    }
    if (isset($page)) {
        $wishlist_items_nav['page'] = $page;
    }
    $page = 1;
    if (isset($sort)) {
        $wishlist_items_nav['sort_field'] = $sort;
    }
    if (isset($sort_direction)) {
        $wishlist_items_nav['sort_direction'] = $sort_direction;
    }
    $items_per_page_targets['wishlist'] = PHP_INT_MAX;
    $items_fields = array("{$tables['wishlist']}.*");
    $items_from_tbls = array('wishlist');
    $items_where = array("{$tables['wishlist']}.customer_id='{$customer_id}' and {$tables['wishlist']}.event_id='{$event_id}'");
    $items_groupbys = array();
    $items_having = array();
    if ($wishlist_items_nav['sort_field'] == 'forsale') {
        $items_orderbys = array("{$tables['wishlist']}.product_id" . ($wishlist_items_nav['sort_direction'] ? ' DESC' : ' ASC'));
    }
    $items_count_query = cw_db_generate_query(array('count(*)'), $items_from_tbls, $items_query_joins, $items_where, $items_groupbys, $items_having, null);
    $items_total_items = cw_query_first_cell($items_count_query);
    $items_qry = cw_db_generate_query($items_fields, $items_from_tbls, $items_query_joins, $items_where, $items_groupbys, $items_having, $items_orderbys);
    $items_per_page_targets['wishlist'] = $wishlist_items_nav['items_per_page'];
    $navigation = cw_core_get_navigation($target, $items_total_items, $wishlist_items_nav['page']);
    $navigation['script'] = "index.php?target={$target}&action={$action}&mode={$mode}";
    $smarty->assign('navigation', $navigation);
    if ($items_total_items > 0) {
        $wishlist_items = cw_query($items_qry . " LIMIT {$navigation['first_page']}, {$navigation['objects_per_page']}");
    }
    if (!empty($wishlist_items)) {
        $smarty->assign('wishlist_items_nav', $wishlist_items_nav);
    }
    return $wishlist_items;
}
function cw_category_search($params, $return = null)
{
    extract($params);
    global $tables, $current_language;
    $fields = $from_tbls = $query_joins = $where = $groupbys = $having = $orderbys = array();
    $from_tbls[] = 'categories';
    # kornev, merge standart and additional variables
    if ($return) {
        foreach ($return as $saname => $sadata) {
            if (isset(${$saname}) && is_array(${$saname}) && empty(${$saname})) {
                ${$saname} = $sadata;
            }
        }
    }
    $query_joins['categories_lng'] = array('on' => "{$tables['categories_lng']}.category_id = {$tables['categories']}.category_id and {$tables['categories_lng']}.code='{$current_language}'\n");
    $query_joins['categories_subcount'] = array('on' => "{$tables['categories_subcount']}.category_id = {$tables['categories']}.category_id");
    $fields[] = "{$tables['categories_subcount']}.subcategory_count";
    $fields[] = "{$tables['categories_subcount']}.product_count";
    $query_joins['categories_subcount_1'] = array('tblname' => 'categories_subcount', 'on' => "categories_subcount_1.category_id = {$tables['categories']}.category_id and categories_subcount_1.status=1");
    $fields[] = "categories_subcount_1.subcategory_count as subcategory_count_web";
    $fields[] = "categories_subcount_1.product_count as product_count_web";
    $fields[] = "{$tables['categories']}.*";
    $fields[] = "IFNULL({$tables['categories_lng']}.category, {$tables['categories']}.category) as category";
    $fields[] = "IFNULL({$tables['categories_lng']}.description, {$tables['categories']}.description) as description";
    $where[] = 1;
    if ($data['substring']) {
        $where[] = "(IFNULL({$tables['categories_lng']}.category, {$tables['categories']}.category) like '%{$data['substring']}%' or IFNULL({$tables['categories_lng']}.description, {$tables['categories']}.description) like '%{$data['substring']}%')";
    }
    if (isset($data['parent_id'])) {
        $where[] = "{$tables['categories']}.parent_id='" . intval($data['parent_id']) . "'";
    }
    if (isset($data['active']) || isset($data['status'])) {
        $data['status'] = intval($data['status'] || $data['active']);
        $where[] = "{$tables['categories']}.status = '{$data['status']}'";
    }
    if (isset($data['membership_id'])) {
        $query_joins['categories_memberships'] = array('on' => "{$tables['categories_memberships']}.category_id = {$tables['categories']}.category_id");
        $where[] = "{$tables['categories_memberships']}.membership_id='{$data['membership_id']}'";
    }
    $groupbys[] = "{$tables['categories']}.category_id";
    $orderbys[] = "{$tables['categories']}.order_by";
    $search_query_count = cw_db_generate_query('count(*)', $from_tbls, $query_joins, $where, $groupbys, $having, array(), 0);
    $search_query = cw_db_generate_query($fields, $from_tbls, $query_joins, $where, $groupbys, $having, $orderbys);
    $_res = db_query($search_query_count);
    $total_items = db_num_rows($_res);
    db_free_result($_res);
    $page = $data['page'];
    if ($data['count']) {
        return $total_items;
    } elseif ($data['limit']) {
        $limit_str = " LIMIT {$data['limit']}";
    } elseif ($data['all']) {
        $limit_str = '';
    } else {
        $navigation = cw_core_get_navigation($target, $total_items, $page);
        $limit_str = " LIMIT {$navigation['first_page']}, {$navigation['objects_per_page']}";
    }
    $categories = cw_query($search_query . $limit_str);
    if ($data['all']) {
        $navigation = cw_core_get_navigation($target, count($categories), $page, count($categories));
    }
    if (is_array($categories)) {
        foreach ($categories as $k => $v) {
            $categories[$k]['subcounts'] = cw_query_hash("SELECT cs.status, sum(cs.subcategory_count) as subcategory_count, \n\t\t\tsum(cs.product_count) as product_count\n        FROM {$tables['categories_subcount']} cs, {$tables['categories_parents']} cp\n        WHERE cs.membership_id='{$data['membership_id']}' AND\n\t\t\tcs.category_id = cp.category_id AND cp.parent_id='{$v['category_id']}'\n\t\t\tGROUP BY status", 'status', false, false);
        }
    }
    return array($categories, $navigation);
}
                $load_data_tables_qry[] = "CREATE TABLE `{$table_name}` ({$table_key_name} int(11) NOT NULL AUTO_INCREMENT, " . implode(", ", $add_field_qry) . ", PRIMARY KEY `{$table_key_name}` (`{$table_key_name}`))ENGINE=MyISAM;";
                $load_data_tables_qry[] = "INSERT INTO `{$table_name}` (" . implode(", ", $field_names) . ") SELECT " . implode(", ", $tmp_fields) . " FROM {$parsed_file['tmp_table']}";
            }
            $load_data_tables_qry[] = "DROP TABLE IF EXISTS {$parsed_file['tmp_table']}";
            foreach ($load_data_tables_qry as $lqry) {
                cw_csvxc_logged_query($lqry);
            }
            cw_include('addons/flexible_import/include/tmp_tables_load.php');
            if ($parsed_file['err']) {
                cw_add_top_message($parsed_file['err'], 'E');
            } else {
                cw_add_top_message(cw_get_langvar_by_name('lbl_import_success'), 'I');
            }
        }
        cw_header_location("index.php?target={$target}&mode={$mode}");
    }
    $search_prefilled['files'] = cw_flexible_import_files_dir();
    $search_prefilled['sort_field'] = $sort && $sort != "" ? $sort : "id";
    $search_prefilled['sort_direction'] = $sort_direction && $sort_direction != 0 ? 0 : 1;
    $search_prefilled['items_per_page'] = $items_per_page ? $items_per_page : 20;
    $search_prefilled['page'] = $page ? $page : 1;
    $profiles = cw_call('cw_flexible_import_get_profiles', array('params' => $search_prefilled));
    $total_profiles = cw_query_first_cell("SELECT COUNT(*) from {$tables['flexible_import_profiles']}");
    $navigation = cw_core_get_navigation($target, $total_profiles, $page, $items_per_page);
    $navigation['script'] = "index.php?target=import&mode=flexible_import";
    $navigation['objects_per_page'] = $search_prefilled['items_per_page'];
    $smarty->assign('navigation', $navigation);
    $smarty->assign('search_prefilled', $search_prefilled);
    $smarty->assign('profiles', $profiles);
    $smarty->assign('main', 'flexible_import');
}
function cw_product_search($params, $return = null)
{
    extract($params);
    global $tables, $addons, $current_language, $config, $app_config_file;
    global $cart;
    global $smarty;
    global $target;
    $fields = $from_tbls = $query_joins = $where = $groupbys = $having = $orderbys = array();
    $from_tbls[] = 'products';
    # kornev, merge standart and additional variables
    if ($return) {
        foreach ($return as $saname => $sadata) {
            if (isset(${$saname}) && is_array(${$saname}) && empty(${$saname})) {
                ${$saname} = $sadata;
            }
        }
    }
    if ($data['where']) {
        $where[] = $data['where'];
    }
    $query_joins['products_stats'] = array('on' => "{$tables['products_stats']}.product_id = {$tables['products']}.product_id", 'only_select' => 1);
    # kornev, all of the inner joins are replaced by left join && not null
    # it works fastly because mylsq do not optimize the tables order is query and we are able to play with it.
    $memberships = array(0);
    if ($user_account['membership_id'] > 0) {
        $memberships[] = intval($user_account['membership_id']);
    }
    $query_joins['products_flat'] = array('on' => "{$tables['products_flat']}.product_id = {$tables['products']}.product_id", 'only_select' => 1);
    $fields[] = "{$tables['products_flat']}.*";
    $fields[] = "{$tables['products']}.*";
    if (!is_array($data['warehouse_customer_id'])) {
        $data['warehouse_customer_id'] = array($data['warehouse_customer_id'] => 1);
    }
    $query_joins['products_warehouses_amount'] = array('parent' => 'products', 'on' => "{$tables['products_warehouses_amount']}.product_id = {$tables['products']}.product_id and {$tables['products_warehouses_amount']}.warehouse_customer_id = 0 and {$tables['products_warehouses_amount']}.variant_id=0");
    $fields[] = "{$tables['products_warehouses_amount']}.avail";
    if ($current_area == 'A') {
        $fields[] = "{$tables['products_prices']}.variant_id";
        $fields[] = "{$tables['products_prices']}.price";
        # kornev, TOFIX
        if ($addons['product_options']) {
            $fields[] = "if({$tables['product_variants']}.product_id IS NULL, '', 'Y') as is_variants";
        }
        $query_joins['products_prices'] = array('on' => "{$tables['products_prices']}.product_id = {$tables['products']}.product_id", 'is_inner' => 1);
    } else {
        $fields[] = "min({$tables['products_prices']}.price) as price";
        $fields[] = "{$tables['products_prices']}.variant_id";
        $fields[] = "{$tables['products_prices']}.list_price";
        //        $fields[] = "min($tables[products_prices].list_price) as list_price";
        $query_joins['products_prices'] = array('parent' => 'products', 'on' => "{$tables['products_prices']}.product_id = {$tables['products']}.product_id and {$tables['products_prices']}.quantity=1 and {$tables['products_prices']}.membership_id in (" . join(',', $memberships) . ")", 'is_inner' => 1);
        if ($config['Appearance']['show_views_on_product_page'] == 'Y') {
            $fields[] = "{$tables['products_stats']}.views_stats";
        }
    }
    if ($config['Appearance']['categories_in_products'] == '1') {
        $query_joins['products_categories'] = array('on' => "{$tables['products_categories']}.product_id = {$tables['products']}.product_id", 'pos' => '0', 'is_inner' => 1);
    }
    # kornev, we should add filter by attributes names
    if ($data['attribute_names']) {
        $att_ids = cw_call('cw_attributes_get_attribute_by_field', array('field' => array_keys($data['attribute_names'])));
        if ($att_ids) {
            foreach ($att_ids as $k => $v) {
                $data['attributes'][$v] = $data['attribute_names'][$k];
            }
        }
    }
    # kornev, filter by attributes
    if ($data['attributes']) {
        if ($data['attributes'][PRICE_ATTRIBUTE_ID]) {
            $data['price_min'] = $data['attributes'][PRICE_ATTRIBUTE_ID]['min'];
            $data['price_max'] = $data['attributes'][PRICE_ATTRIBUTE_ID]['max'];
        }
        if ($data['attributes']['substring']) {
            $data['substring'] = $data['attributes']['substring'];
        }
        foreach ($data['attributes'] as $k => $v) {
            $a = cw_call('cw_attributes_filter', array(array('attribute_id' => $k), true));
            // If attr is number and presented in filter as predefined ranges,
            // then range attribute_value_id is passed as criteria, not real value or real range
            if (in_array($a['type'], array('decimal', 'integer'), true) && in_array($a['pf_display_type'], array('P', 'W', 'E', 'G')) && !isset($v['min'])) {
                $result = cw_product_filter_get_price_range_values($v[0]);
                if ($result) {
                    $v['min'] = $result[0];
                    $v['max'] = $result[1];
                }
                if ($k == PRICE_ATTRIBUTE_ID) {
                    $data['price_min'] = $v['min'];
                    $data['price_max'] = $v['max'];
                    $data['attributes']['price'] = $v;
                    continue;
                }
            }
            if (in_array($k, array('price', 'substring', PRICE_ATTRIBUTE_ID))) {
                continue;
            }
            if (!is_numeric($k)) {
                continue;
            }
            // Only real attributes must e converted into JOIN sql statement
            if (!is_array($v)) {
                $data['attributes'][$k] = $v = array($v);
            }
            $query_joins['atv_' . $k] = array('tblname' => 'attributes_values', 'on' => "{$tables['products']}.product_id=atv_{$k}.item_id and atv_{$k}.attribute_id = '{$k}' and atv_{$k}.code in ('{$current_language}', '') and " . (isset($v['min']) ? "atv_{$k}.value >= " . floatval($v['min']) . " and atv_{$k}.value <= " . floatval($v['max']) : "atv_{$k}.value in ('" . implode("', '", $v) . "')"), 'is_inner' => 1);
        }
    }
    if (!empty($data['by_pf_s_attr']) && !empty($data['substring'])) {
        $attr_pf_s_where = array();
        foreach ($data['by_pf_s_attr'] as $attr_id => $digit_flag) {
            $is_def_values = cw_query_first_cell("select count(*) from {$tables['attributes_default']} where attribute_id='{$attr_id}'");
            $attr_type = cw_query_first_cell("select type from {$tables['attributes']} where attribute_id='{$attr_id}'");
            if ($is_def_values && !in_array($attr_type, array('textarea', 'text'))) {
                if ($data['including'] == 'all' || $data['including'] == 'any') {
                    $search_words = array_filter(explode(" ", $data['substring']));
                    $search_words_arr = array();
                    foreach ($search_words as $word) {
                        $word = addslashes($word);
                        $search_words_arr[] = "atd_pf_s_{$attr_id}.value like '%{$word}%'";
                    }
                }
                if ($data['including'] == 'all') {
                    $value_eq_sql = " (" . implode(" and ", $search_words_arr) . ") ";
                } elseif ($data['including'] == 'any') {
                    $value_eq_sql = " (" . implode(" or ", $search_words_arr) . ") ";
                } else {
                    $value_eq_sql = "atd_pf_s_{$attr_id}.value like '%" . addslashes($data['substring']) . "%'";
                }
                $attr_value_ids = cw_query_column("select attribute_value_id from {$tables['attributes_default']} atd_pf_s_{$attr_id} where atd_pf_s_{$attr_id}.attribute_id='{$attr_id}' and {$value_eq_sql}");
                if (!empty($attr_value_ids)) {
                    $query_joins['atv_pf_s_' . $attr_id] = array('tblname' => 'attributes_values', 'on' => "{$tables['products']}.product_id=atv_pf_s_{$attr_id}.item_id and atv_pf_s_{$attr_id}.item_type='P' and atv_pf_s_{$attr_id}.attribute_id = '{$attr_id}' and atv_pf_s_{$attr_id}.code in ('{$current_language}', '') and cast(atv_pf_s_{$attr_id}.value as SIGNED) in ('" . implode("','", $attr_value_ids) . "')");
                    $attr_pf_s_where[] = "atv_pf_s_{$attr_id}.item_id is not null";
                }
            } else {
                if ($data['including'] == 'all' || $data['including'] == 'any') {
                    $search_words = array_filter(explode(" ", $data['substring']));
                    $search_words_arr = array();
                    foreach ($search_words as $word) {
                        $word = addslashes($word);
                        $search_words_arr[] = "atv_pf_s_{$attr_id}.value like '%{$word}%'";
                    }
                }
                if ($data['including'] == 'all') {
                    $value_eq_sql = " (" . implode(" and ", $search_words_arr) . ") ";
                } elseif ($data['including'] == 'any') {
                    $value_eq_sql = " (" . implode(" or ", $search_words_arr) . ") ";
                } else {
                    $value_eq_sql = "atv_pf_s_{$attr_id}.value like '%" . addslashes($data['substring']) . "%'";
                }
                $query_joins['atv_pf_s_' . $attr_id] = array('tblname' => 'attributes_values', 'on' => "{$tables['products']}.product_id=atv_pf_s_{$attr_id}.item_id and atv_pf_s_{$attr_id}.item_type='P' and atv_pf_s_{$attr_id}.attribute_id = '{$attr_id}' and atv_pf_s_{$attr_id}.code in ('{$current_language}', '') and {$value_eq_sql}");
                $attr_pf_s_where[] = "atv_pf_s_{$attr_id}.item_id is not null";
            }
            $return['substring_search_alternative'] = true;
        }
        if (!empty($attr_pf_s_where)) {
            $where[] = "(" . implode(" or ", $attr_pf_s_where) . ")";
        }
    }
    if (!empty($data['by_pf_attr_numeric'])) {
        $cast_types = array('decimal' => 'DECIMAL', 'integer' => 'SIGNED', 'yes_no' => 'SIGNED');
        foreach ($data['by_pf_attr_numeric'] as $attr_id => $attr_limits) {
            if (empty($attr_limits['min']) && empty($attr_limits['max'])) {
                continue;
            }
            $attr_type = cw_query_first_cell("select type from {$tables['attributes']} where attribute_id='{$attr_id}'");
            $_cast_type = $cast_types[$attr_type];
            if (empty($_cast_type)) {
                continue;
            }
            $ps_numeric_val_limits = array();
            $_min_limit = min($attr_limits['min'], $attr_limits['max']);
            $_max_limit = max($attr_limits['min'], $attr_limits['max']);
            $ps_num_table_alias = "ps_num_" . $attr_id;
            if (!empty($_min_limit)) {
                $ps_numeric_val_limits[] = "cast(" . $ps_num_table_alias . ".value as {$_cast_type}) >= '{$_min_limit}'";
            }
            if (!empty($_max_limit)) {
                $ps_numeric_val_limits[] = "cast(" . $ps_num_table_alias . ".value as {$_cast_type}) <= '{$_max_limit}'";
            }
            if (!empty($ps_numeric_val_limits)) {
                $query_joins[$ps_num_table_alias] = array('tblname' => 'attributes_values', 'on' => "{$tables['products']}.product_id={$ps_num_table_alias}.item_id and {$ps_num_table_alias}.item_type='P' and {$ps_num_table_alias}.attribute_id='{$attr_id}' and " . implode(" and ", $ps_numeric_val_limits), 'is_inner' => 1);
            }
        }
    }
    if (isset($data['by_pf_attr_multi'])) {
        foreach ($data['by_pf_attr_multi'] as $attr_id => $attr_value_ids) {
            if (empty($attr_value_ids)) {
                continue;
            }
            $ps_multi_table_alias = 'atv_pf_multi_' . $attr_id;
            $query_joins[$ps_multi_table_alias] = array('tblname' => 'attributes_values', 'on' => "{$tables['products']}.product_id={$ps_multi_table_alias}.item_id and {$ps_multi_table_alias}.item_type='P' and {$ps_multi_table_alias}.attribute_id = '{$attr_id}' and {$ps_multi_table_alias}.code in ('{$current_language}', '') and (cast({$ps_multi_table_alias}.value as SIGNED) in ('" . implode("','", $attr_value_ids) . "'))", 'is_inner' => 1);
        }
    }
    if (!$data['substring_exact']) {
        $data['substring'] = trim($data['substring']);
        $data['substring_prepared'] = '%' . $data['substring'] . '%';
    } else {
        $data['substring_prepared'] = $data['substring'];
    }
    $search_by_variants = false;
    if (($data['search_sections']['tab_basic_search'] || $data['flat_search'] || $data['attributes']['substring']) && $data['substring']) {
        $condition = array();
        $search_string_fields = array();
        if (empty($data['by_title']) && empty($data['by_shortdescr']) && empty($data['by_fulldescr']) && empty($data['by_sku']) && empty($return['substring_search_alternative'])) {
            $search_data['products'][$use_search_conditions]['by_title'] = $data['by_title'] = 1;
            // TOFIX: both $search_data and $use_search_conditions is undefinde
            $flag_save = true;
        }
        if ($data['by_title']) {
            $search_string_fields[] = "product";
        }
        if ($data['by_manufacturer']) {
            $search_string_fields[] = 'manufacturer_code';
        }
        if ($data['by_productcode']) {
            $search_string_fields[] = 'productcode';
        }
        if ($data['by_ean']) {
            $search_string_fields[] = 'eancode';
        }
        if ($data['by_shortdescr']) {
            $search_string_fields[] = "descr";
        }
        if ($data['by_fulldescr']) {
            $search_string_fields[] = "fulldescr";
        }
        if ($data['by_ean'] && !empty($addons['product_options'])) {
            $search_by_variants = true;
            $condition[] = "search_variants.eancode LIKE '" . $data['substring_prepared'] . "'";
        }
        if ($data['by_manufacturer'] && !empty($addons['product_options'])) {
            $search_by_variants = true;
            $condition[] = "search_variants.mpn LIKE '" . $data['substring_prepared'] . "'";
        }
        $search_words = array();
        if ($config['General']['allow_search_by_words'] == 'Y' && in_array($data['including'], array("all", "any"))) {
            $tmp = stripslashes(trim($data['substring']));
            if (preg_match_all('/"([^"]+)"/', $tmp, $match)) {
                $search_words = $match[1];
                $tmp = str_replace($match[0], '', $tmp);
            }
            $tmp = explode(' ', $tmp);
            $tmp = cw_array_map("trim", $tmp);
            $search_words = array_merge($search_words, $tmp);
            unset($tmp);
            # Check word length limit
            if ($search_word_length_limit > 0) {
                $search_words = preg_grep("/^..+\$/", $search_words);
            }
            $stopwords = cw_get_stopwords();
            if (!empty($stopwords) && is_array($stopwords)) {
                $tmp = preg_grep("/^(" . implode("|", $stopwords) . ")\$/i", $search_words);
                if (!empty($tmp) && is_array($tmp)) {
                    $search_words = array_diff($search_words, $tmp);
                    $search_words = array_values($search_words);
                }
                unset($tmp);
            }
            # Check word count limit
            if ($search_word_limit > 0 && count($search_words) > $search_word_limit) {
                $search_words = array_splice($search_words, $search_word_limit - 1);
            }
        }
        $search_words = array_filter($search_words);
        $search_words = cw_addslashes($search_words);
        foreach ($search_string_fields as $ssf) {
            if ($config['General']['allow_search_by_words'] == 'Y' && !empty($search_words) && in_array($data['including'], array("all", "any"))) {
                if ($data['including'] == 'all') {
                    $tmp = array();
                    foreach ($search_words as $sw) {
                        if ($current_area == 'C' || $current_area == 'B') {
                            if (in_array($ssf, array('productcode', 'manufacturer_code', 'eancode'))) {
                                $tmp[] = "{$tables['products']}.{$ssf} LIKE '%" . $sw . "%'";
                            } else {
                                $tmp[] = "IF({$tables['products_lng']}.product_id != '', {$tables['products_lng']}.{$ssf}, {$tables['products']}.{$ssf}) LIKE '%" . $sw . "%'";
                            }
                        } else {
                            $tmp[] = "{$tables['products']}.{$ssf} LIKE '%" . $sw . "%'";
                        }
                    }
                    if (!empty($tmp)) {
                        $condition[] = "(" . implode(" AND ", $tmp) . ")";
                    }
                    unset($tmp);
                } else {
                    if ($current_area == 'C' || $current_area == 'B') {
                        if (in_array($ssf, array('productcode', 'manufacturer_code', 'eancode'))) {
                            $condition[] = "{$tables['products']}.{$ssf} REGEXP '" . implode("|", $search_words) . "'";
                        } else {
                            $condition[] = "IF({$tables['products_lng']}.product_id != '', {$tables['products_lng']}.{$ssf}, {$tables['products']}.{$ssf}) REGEXP '" . implode("|", $search_words) . "'";
                        }
                    } else {
                        $condition[] = "{$tables['products']}.{$ssf} REGEXP '" . implode("|", $search_words) . "'";
                    }
                }
            } elseif ($current_area == 'C' || $current_area == 'B') {
                if (in_array($ssf, array('productcode', 'manufacturer_code', 'eancode'))) {
                    $condition[] = "{$tables['products']}.{$ssf} LIKE '" . $data['substring_prepared'] . "'";
                } else {
                    $condition[] = "IF({$tables['products_lng']}.product_id != '', {$tables['products_lng']}.{$ssf}, {$tables['products']}.{$ssf}) LIKE '" . $data['substring_prepared'] . "'";
                }
            } else {
                $condition[] = "{$tables['products']}.{$ssf} LIKE '" . $data['substring_prepared'] . "'";
            }
        }
        if ($data['by_sku']) {
            $search_by_variants = true;
            # kornev, TOFIX
            $condition[] = (empty($addons['product_options']) ? "({$tables['products']}.productcode)" : "(IFNULL(search_variants.productcode, {$tables['products']}.productcode)") . " LIKE '" . $data['substring_prepared'] . "' OR {$tables['products']}.eancode like '" . $data['substring_prepared'] . "')";
        }
        if ($data['by_tags'] || $data['by_shortdescr'] || $data['by_fulldescr']) {
            if (!empty($search_words) && in_array($data['including'], array("all", "any"))) {
                $tags_condition = "name REGEXP '" . implode("|", $search_words) . "'";
            } else {
                $tags_condition = "name LIKE '" . $data['substring_prepared'] . "'";
            }
            $tag_ids = cw_query_column("SELECT tag_id FROM {$tables['tags']} WHERE {$tags_condition}");
            $query_joins['tags_substr'] = array('tblname' => 'tags_products', 'on' => "tags_substr.product_id = {$tables['products']}.product_id", 'only_select' => 0);
            $condition[] = "tags_substr.tag_id IN ('" . join("','", $tag_ids) . "')";
            unset($tag_ids, $tags_condition);
        }
        if (!empty($condition)) {
            $where[] = "(" . implode(" OR ", $condition) . ")";
        }
        unset($condition);
    }
    if ($data['search_sections']['tab_add_search'] || $data['flat_search'] || $data['product_types']) {
        if (!$data['status']) {
            $data['status'] = cw_core_get_required_status($current_area);
        }
        if ($data['status']) {
            $where[] = "{$tables['products']}.status in (" . implode(", ", $data['status']) . ")";
        }
        if ($config['Appearance']['categories_in_products'] == '1') {
            if ($data['category_id']) {
                $data['categories'] = array($data['category_id'] => 1);
                $data['categories_orig'] = array($data['category_id']);
            }
            if ($data['category_ids']) {
                $_categories = array();
                $_categories_orig = array();
                foreach ($data['category_ids'] as $c_id) {
                    $_categories[$c_id] = 1;
                    $_categories_orig[] = $c_id;
                }
                $data['categories'] = $_categories;
                $data['categories_orig'] = $_categories_orig;
            }
            if ($data['categories'] && is_array($data['categories'])) {
                if ($data['search_in_subcategories']) {
                    $categories_to_search = cw_category_get_subcategory_ids($data['categories_orig']);
                    if (count($categories_to_search)) {
                        $where[] = "{$tables['products_categories']}.category_id IN (" . implode(",", $categories_to_search) . ")";
                    }
                } else {
                    $where[] = "{$tables['products_categories']}.category_id IN (" . implode(",", $data['categories_orig']) . ")";
                }
                $condition = array();
                if ($data['category_main']) {
                    $condition[] = "{$tables['products_categories']}.main = 1";
                }
                if ($data['category_extra']) {
                    $condition[] = "{$tables['products_categories']}.main = 0";
                }
                if (count($condition)) {
                    $where[] = "(" . implode(" OR ", $condition) . ")";
                }
            }
        }
        if ($data['productcode']) {
            $search_by_variants = true;
            # kornev, TOFIX
            $productcode_cond_string = empty($addons['product_options']) ? "{$tables['products']}.productcode" : "IFNULL(search_variants.productcode, {$tables['products']}.productcode)";
            $where[] = "({$productcode_cond_string} LIKE '%" . $data['productcode'] . "%')";
        }
        if ($data['manufacturer_code']) {
            $where[] = "({$tables['products']}.manufacturer_code like '%" . $data['manufacturer_code'] . "%')";
        }
        if ($data['eancode']) {
            $search_by_variants = true;
            # kornev, TOFIX
            $productcode_cond_string = empty($addons['product_options']) ? "{$tables['products']}.eancode" : "IFNULL(search_variants.eancode, {$tables['products']}.eancode)";
            $where[] = "({$productcode_cond_string} LIKE '%" . $data['eancode'] . "%')";
        }
        if ($data['product_id']) {
            $where[] = "{$tables['products']}.product_id " . (is_array($data['product_id']) ? " IN ('" . implode("','", $data['product_id']) . "')" : "= '" . $data['product_id'] . "'");
        }
        if (!empty($data['serial_number'])) {
            $warehouse_condition = AREA_TYPE == 'P' ? "and {$tables['serial_numbers']}.warehouse_customer_id='{$user_account['warehouse_customer_id']}'" : "";
            $where[] = "{$tables['serial_numbers']}.sn LIKE '%" . $data['serial_number'] . "%' {$warehouse_condition}";
            $query_joins['serial_numbers'] = array("on" => "{$tables['serial_numbers']}.product_id = {$tables['products']}.product_id", 'is_inner' => 1);
        }
        /* kornev, removed - the manufacturer is attribute now and search is going to be done in another way
                if ($addons['manufacturers']) {
        /*
        # kornev, attribute should be selected in another way
                    $fields[] = "$tables[manufacturers].manufacturer";
                    $query_joins['manufacturers'] = array(
                        'on' => "$tables[products].manufacturer_id = $tables[manufacturers].manufacturer_id",
                        'only_select' => 1,
                    );
        */
        /*
                    if ($data['manufacturers']) {
                        $where['manuf_condition'] = "$tables[products].manufacturer_id IN ('".implode("', '", array_keys($data['manufacturers']))."')";
                        $query_joins['manufacturers']['only_select'] = 0;
                        $query_joins['manufacturers']['is_inner'] = 1;
                    }
                    if ($data['manufacturers_substring']) {
                        $substring = $data['manufacturers_substring'];
                        if (!$data['manufacturers_substring_exact']) $substring = '%'.trim($substring).'%';
                        $where['manuf_condition'] .= "$tables[manufacturers].manufacturer like '$substring'";
                        $query_joins['manufacturers']['only_select'] = 0;
                        $query_joins['manufacturers']['is_inner'] = 1;
                    }
                }
        */
        if ($data['avail_types']) {
            if ($data['avail_types'][1]) {
                $where[] = "{$tables['products_warehouses_amount']}.avail > 0";
            }
            if ($data['avail_types'][2]) {
                $where[] = "{$tables['products_warehouses_amount']}.avail_ordered > 0";
            }
            if ($data['avail_types'][3]) {
                $where[] = "{$tables['products_warehouses_amount']}.avail_sold > 0";
            }
            if ($data['avail_types'][4]) {
                $where[] = "{$tables['products_warehouses_amount']}.avail_reserved > 0";
            }
            if ($data['avail_types'][5]) {
                $where[] = "{$tables['products_warehouses_amount']}.avail < 0";
            }
            if ($data['avail_types'][6]) {
                $where[] = "{$tables['products_warehouses_amount']}.avail = 0";
            }
        }
        if ($data['product_types']) {
            $where[] = "{$tables['products']}.product_type in ('" . implode("', '", array_keys($data['product_types'])) . "')";
        }
    }
    if (($current_area == "C" || $current_area == "B") && $config['General']['disable_outofstock_products'] == "Y") {
        $where[] = "{$tables['products_warehouses_amount']}.avail > 0";
    }
    if ($data['search_sections']['tab_prices'] || $data['flat_search']) {
        $query_joins['products_prices'] = array('parent' => 'products', 'on' => "{$tables['products_prices']}.product_id = {$tables['products']}.product_id and {$tables['products_prices']}.quantity=1 and {$tables['products_prices']}.membership_id in (" . join(',', $memberships) . ")", 'is_inner' => 1);
        if ($data['price_min']) {
            $where['price_min'] = "{$tables['products_prices']}.price >= '{$data['price_min']}'";
        }
        if ($data['price_max']) {
            $where['price_max'] = "{$tables['products_prices']}.price <= '{$data['price_max']}'";
        }
        if ($data['weight_min']) {
            $where['weight_min'] = "{$tables['products']}.weight >= '{$data['weight_min']}'";
        }
        if ($data['weight_max']) {
            $where['weight_max'] = "{$tables['products']}.weight <= '{$data['weight_max']}'";
        }
        /*
                if ($data['list_price_min'])
                    $where[] = "$tables[products_prices].list_price >= '$data[list_price_min]'";
                if ($data['list_price_min'])
                    $where[] = "$tables[products_prices].list_price <= '$data[list_price_max]'";
        */
        if ($data['list_price_min']) {
            $where[] = "{$tables['products']}.list_price >= '{$data['list_price_min']}'";
        }
        if ($data['list_price_min']) {
            $where[] = "{$tables['products']}.list_price <= '{$data['list_price_max']}'";
        }
    }
    if ($data['search_sections']['tab_additional_options'] || $data['flat_search']) {
        if ($data['flag_free_ship']) {
            $where[] = "{$tables['products']}.free_shipping = '" . $data['flag_free_ship'] . "'";
        }
        if ($data['flag_ship_freight']) {
            $where[] = "{$tables['products']}.shipping_freight " . ($data['flag_ship_freight'] == 'Y' ? '>0' : '=0');
        }
        if ($data['flag_global_disc']) {
            $where[] = "{$tables['products']}.discount_avail = '" . $data['flag_global_disc'] . "'";
        }
        if ($data['flag_free_tax']) {
            $where[] = "{$tables['products']}.free_tax = '" . $data['flag_free_tax'] . "'";
        }
        if ($data['flag_min_amount']) {
            if ($data['flag_min_amount'] == "Y") {
                $where[] = "{$tables['products']}.min_amount <= 1";
            } else {
                $where[] = "{$tables['products']}.min_amount = 1";
            }
        }
        if ($data['flag_low_avail_limit']) {
            if ($data['flag_low_avail_limit'] == 'Y') {
                $where[] = "{$tables['products']}.low_avail_limit <= 1";
            } else {
                $where[] = "{$tables['products']}.low_avail_limit > 1";
            }
        }
    }
    if ($data['search_sections']['tab_anagraphic'] || $data['flat_search']) {
        if ($data['blank_descr']) {
            $where[] = "{$tables['products']}.descr = ''";
        }
        if ($data['code']) {
            $search_by_variants = true;
            # kornev, TOFIX
            $productcode_cond_string = empty($addons['product_options']) ? "{$tables['products']}.eancode" : "IFNULL(search_variants.eancode, {$tables['products']}.eancode)";
            $where[] = "({$productcode_cond_string} != '')";
        }
        if ($data['without_code']) {
            $search_by_variants = true;
            # kornev, TOFIX
            $where[] = !$addons['product_options'] ? "({$tables['products']}.productcode = '' or {$tables['products']}.eancode = '')" : "(IFNULL(search_variants.productcode, {$tables['products']}.productcode) = '' OR IFNULL(search_variants.eancode, {$tables['products']}.eancode) = '')";
        }
        $query_joins['products_system_info'] = array('parent' => 'products', 'on' => "{$tables['products_system_info']}.product_id = {$tables['products']}.product_id", 'is_inner' => 1);
        if ($data['creation_date_start']) {
            $where[] = "{$tables['products_system_info']}.creation_date >= '{$data['creation_date_start']}'";
        }
        if ($data['creation_date_end']) {
            $where[] = "{$tables['products_system_info']}.creation_date <= '{$data['creation_date_end']}'";
        }
        if ($data['modify_date_start']) {
            $where[] = "{$tables['products_system_info']}.modification_date >= '{$data['modify_date_start']}'";
        }
        if ($data['modify_date_end']) {
            $where[] = "{$tables['products_system_info']}.modification_date <= '{$data['modify_date_end']}'";
        }
        if ($data['created_by']) {
            $where[] = "{$tables['products_system_info']}.creation_customer_id = '{$data['created_by']}'";
        }
        if ($data['supplier']) {
            $where[] = "{$tables['products_system_info']}.supplier_customer_id = '{$data['supplier']}'";
        }
        if ($data['sold_date_start'] || $data['sold_date_end']) {
            $query_joins['docs_items'] = array('on' => "{$tables['docs_items']}.product_id = {$tables['products']}.product_id", 'is_inner' => 1);
            $query_joins['docs'] = array('on' => "{$tables['docs']}.doc_id = {$tables['docs_items']}.doc_id", 'is_inner' => 1);
            if ($data['sold_date_start']) {
                $where[] = "{$tables['docs']}.date >= '{$data['sold_date_start']}'";
            }
            if ($data['sold_date_end']) {
                $where[] = "{$tables['docs']}.date <= '{$data['sold_date_end']}'";
            }
        }
    }
    if ($data['tag']) {
        $query_joins['tags_products'] = array('on' => "{$tables['tags_products']}.product_id = {$tables['products']}.product_id", 'only_select' => 0);
        $query_joins['tags'] = array('on' => "{$tables['tags']}.tag_id = {$tables['tags_products']}.tag_id", 'only_select' => 0);
        $where[] = "{$tables['tags']}.name = '{$data['tag']}'";
    }
    //   if (in_array($current_area, array('B', 'G'))) {
    $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";
    $query_joins['products_lng'] = array('on' => "{$tables['products_lng']}.product_id = {$tables['products']}.product_id AND {$tables['products_lng']}.code = '{$current_language}'", 'only_select' => 1);
    if ($data['by_title'] || $data['by_shortdescr'] || $data['by_fulldescr']) {
        $query_joins['products_lng']['only_select'] = 0;
    }
    //    }
    if (in_array($current_area, array('C', 'R', 'G'))) {
        if ($config['Appearance']['categories_in_products'] == '1') {
            $query_joins['categories_memberships'] = array('on' => "{$tables['categories_memberships']}.category_id = {$tables['products_categories']}.category_id", 'parent' => 'products_categories', 'is_inner' => 1);
        }
        $query_joins['products_memberships'] = array('parent' => 'products', 'on' => "{$tables['products_memberships']}.product_id = {$tables['products']}.product_id", 'is_inner' => 1);
    }
    if ($current_area == 'C') {
        if ($config['Appearance']['categories_in_products'] == '1') {
            $where[] = "{$tables['categories_memberships']}.membership_id IN (" . join(',', $memberships) . ")";
            $where[] = "{$tables['categories']}.status = 1";
            $query_joins['categories_memberships']['only_select'] = 0;
            $query_joins['categories'] = array('parent' => 'products_categories', 'on' => "{$tables['categories']}.category_id = {$tables['products_categories']}.category_id", 'is_inner' => 1);
        }
        $where[] = "{$tables['products_memberships']}.membership_id IN (" . join(',', $memberships) . ")";
        $query_joins['products_memberships']['only_select'] = 0;
    } elseif ($config['Appearance']['categories_in_products'] == '1' && $current_area == 'B') {
        $where[] = "{$tables['categories']}.status = 1";
        $query_joins['categories'] = array('parent' => 'products_categories', 'on' => "{$tables['categories']}.category_id = {$tables['products_categories']}.category_id", 'is_inner' => 1);
    }
    if ($config['Appearance']['categories_in_products'] == '1' && $data['get_category'] == 'Y') {
        $query_joins['categories'] = array('parent' => 'products_categories', 'on' => "{$tables['categories']}.category_id = {$tables['products_categories']}.category_id");
        $query_joins['categories_lng'] = array("on" => "{$tables['categories_lng']}.category_id = {$tables['categories']}.category_id and {$tables['categories_lng']}.code='{$current_language}'", "parent" => "categories");
        $fields[] = "IF({$tables['categories_lng']}.category_id IS NOT NULL AND {$tables['categories_lng']}.category != '', {$tables['categories_lng']}.category, {$tables['categories']}.category) as category";
    }
    if (isset($data['avail_min'])) {
        $where[] = "{$tables['products_warehouses_amount']}.avail >= '" . $data['avail_min'] . "'";
    }
    if (isset($data['avail_max'])) {
        $where[] = "{$tables['products_warehouses_amount']}.avail <= '" . $data['avail_max'] . "'";
    }
    # kornev, TOFIX
    if ($addons['product_options']) {
        if ($search_by_variants) {
            $query_joins['search_variants'] = array('tblname' => 'product_variants', 'on' => "search_variants.product_id = {$tables['products']}.product_id", 'only_select' => 0);
        }
        if ($current_area == 'A') {
            # kornev, TOFIX
            $query_joins['product_variants'] = array('on' => "{$tables['product_variants']}.product_id = {$tables['products']}.product_id AND {$tables['product_variants']}.variant_id = {$tables['products_prices']}.variant_id", 'parent' => 'products_prices', 'only_select' => 1);
        } else {
            $query_joins['product_variants'] = array('on' => "{$tables['product_variants']}.product_id = {$tables['products']}.product_id AND {$tables['product_variants']}.variant_id = {$tables['products_prices']}.variant_id", 'parent' => 'products_prices', 'only_select' => 1);
        }
        foreach (array('weight', 'productcode') as $property) {
            $fields[] = "ifnull({$tables['product_variants']}.{$property}, {$tables['products']}.{$property}) as " . $property;
        }
    }
    foreach (array('products_images_thumb', 'products_images_det') as $products_images_type) {
        if ($data['has_' . $products_images_type]) {
            global $available_images;
            $exclude_names_products_images = array($available_images[$products_images_type]['default_image'], '');
            if (is_array($data['exclude_filenames_' . $products_images_type])) {
                $exclude_names_products_images = array_merge($exclude_names_products_images, $data['exclude_filenames_' . $products_images_type]);
            }
            $query_joins[$products_images_type] = array('on' => $tables[$products_images_type] . ".id = {$tables['products']}.product_id AND (" . $tables[$products_images_type] . ".filename NOT IN ('" . implode("', '", $exclude_names_products_images) . "') OR " . $tables[$products_images_type] . ".image_path like 'http://%')", 'is_inner' => 1);
        }
    }
    global $allowed_products_sort_fields;
    if (!isset($allowed_products_sort_fields)) {
        $allowed_products_sort_fields = array();
    }
    if (!in_array($data['sort_field'], array('rand', 'productcode', 'title', 'orderby', 'quantity', 'price', 'product_id')) && !in_array($data['sort_field'], $allowed_products_sort_fields)) {
        $data['sort_field'] = $config['Appearance']['products_order'];
    }
    if (!empty($data['sort_field'])) {
        $direction = $data['sort_direction'] ? 'DESC' : 'ASC';
        if ($config['Appearance']['display_productcode_in_list'] != "Y" && ($current_area == 'C' || $current_area == 'B') && $data['sort_field'] == 'productcode') {
            $data['sort_field'] = 'orderby';
        }
        switch ($data['sort_field']) {
            case 'rand':
                $sort_string = 'RAND()';
                break;
            case "productcode":
                $sort_string = "{$tables['products']}.productcode {$direction}";
                break;
            case "title":
                $sort_string = "{$tables['products']}.product {$direction}";
                break;
            case "orderby":
                if ($config['Appearance']['categories_in_products'] == '1') {
                    $sort_string = "{$tables['products_categories']}.orderby {$direction}";
                } else {
                    $sort_string = "{$tables['products']}.productcode {$direction}";
                }
                break;
            case "quantity":
                $sort_string = "{$tables['products_warehouses_amount']}.avail {$direction}";
                break;
            case "price":
                $sort_string = "price {$direction}";
                break;
            case "product_id":
                $sort_string = "{$tables['products']}.product_id {$direction}";
                break;
            default:
                $sort_string = $data['sort_field'] . ' ' . $direction;
                // special case to order by rand(seed) field or custom field
        }
        global $custom_products_sort_string;
        if (!empty($custom_products_sort_string)) {
            $sort_string = $custom_products_sort_string;
        }
    } else {
        $sort_string = "{$tables['products']}.product";
    }
    if (!empty($data['sort_condition'])) {
        $sort_string = $data['sort_condition'];
    }
    /*
        if (($current_area == "C" || $current_area == "B") && $config['General']['disable_outofstock_products'] == "Y") {
            $query_joins['products_warehouses_amount'] = array(
                'tblname' => 'products_warehouses_amount',
                'on' => "$tables[products_warehouses_amount].product_id = $tables[products].product_id and $tables[products_warehouses_amount].variant_id=$tables[product_variants].variant_id and $tables[products_warehouses_amount.avail > 0",
                'only_select' => 0,
            );
        }
    */
    $groupbys[] = "{$tables['products']}.product_id";
    $orderbys[] = $sort_string;
    $orderbys[] = "{$tables['products']}.product ASC";
    if (isset($params['product_id_only']) && $params['product_id_only'] == true) {
        $fields = array($tables['products'] . '.product_id');
    }
    $search_query_count = cw_db_generate_query('count(*)', $from_tbls, $query_joins, $where, $groupbys, $having, array(), 0);
    $search_query = cw_db_generate_query($fields, $from_tbls, $query_joins, $where, $groupbys, $having, $orderbys);
    //var_dump($search_query); die();
    if (!$data['limit'] && !$data['all']) {
        $_res = db_query($search_query_count);
        $total_items = db_num_rows($_res);
        db_free_result($_res);
    }
    # kornev, optimization, we don't need to pre-calculate the amount in some cases
    $page = $data['page'];
    if ($data['count']) {
        return $total_items;
    } elseif ($data['limit']) {
        $limit_str = " LIMIT {$data['limit']}";
    } elseif ($data['all']) {
        $limit_str = '';
    } else {
        $navigation = cw_core_get_navigation($target, $total_items, $page);
        $_objects2load = $navigation['objects_per_page'];
        $_first_object_on_page = $navigation['first_page'];
        if (isset($navigation['preload_objects'])) {
            $_objects2load += $navigation['preload_objects'];
            $_first_object_on_page = max($_first_object_on_page - $navigation['preload_objects'], 0);
        }
        $limit_str = " LIMIT {$_first_object_on_page}, {$_objects2load}";
    }
    $products = $pfr = array();
    if ($params['count_only']) {
        return array($products, $navigation, $pfr);
    }
    if ($total_items > 0 || $data['limit'] || $data['all'] || $data['attributes']) {
        $products = cw_query($search_query . $limit_str);
        if ($data['limit'] || $data['all']) {
            $items_per_page = 20;
            if (!empty($objects_per_page)) {
                $items_per_page = $objects_per_page;
            }
            $navigation = cw_core_get_navigation($target, count($products), $page, $items_per_page);
        }
        /* kornev, not used now
                if ($data['query_manufacturers'] == 'Y') {
                    $query_joins['manufacturers'] = array(
                        'on' => "$tables[products].manufacturer_id=$tables[manufacturers].manufacturer_id",
                        'is_inner' => 1,
                    );
        
                    unset($where['manuf_condition']);
                    $manuf_query = cw_db_generate_query(array("$tables[manufacturers].manufacturer", "$tables[manufacturers].manufacturer_id"), $from_tbls, $query_joins, $where, array("$tables[manufacturers].manufacturer"), $having, array("$tables[manufacturers].orderby"));
        
                    $p_manufacturers = cw_query($manuf_query);
                    if (is_array($p_manufacturers) && is_array($data['manufacturers']))
                    foreach($p_manufacturers as $k=>$v)
                        $p_manufacturers[$k]['selected'] = in_array($v['manufacturer_id'], array_keys($data['manufacturers']));
                    $smarty->assign('product_manufacturers', $p_manufacturers);
                }
        */
        # kornev, query features for the additional product filter
        if ($info_type & 1024 && !($pfr = cw_cache_get(array($search_query . $limit_str), 'PF_search'))) {
            $pfr = array();
            # kornev, we need that for the breadcrumbs
            if ($data['attributes']['substring']) {
                $pfr[] = array('attribute_id' => 'substring', 'name' => cw_get_langvar_by_name('lbl_substring'), 'type' => '', 'is_selected' => 1, 'selected' => array($data['attributes']['substring']), 'values' => array());
            }
            # kornev, firstly select all of the attributes to build the filter - without products count
            $attributes = cw_call('cw_attributes_filter', array(array('item_type' => 'P', 'pf_is_use' => 1, 'active' => 1)));
            uasort($attributes, '_sort_pf_by_pf_orderby');
            if ($attributes) {
                $att_ids = $ss_att = array();
                foreach ($attributes as $k => $v) {
                    $att_ids[] = $v['attribute_id'];
                    // Mark price attribute with special flag is_price
                    if ($v['field'] == 'price') {
                        //$attributes[$k]['attribute_id'] = $v['attribute_id'] = 'price';
                        $attributes[$k]['is_price'] = 1;
                    }
                    // If slider attr is passed in data, then prefill special array for sliders
                    if ($v['pf_display_type'] == 'S' && isset($data['attributes'][$v['attribute_id']])) {
                        $ss_att[] = $v;
                    }
                }
                $query_joins['atv'] = array('tblname' => 'attributes_values', 'on' => "{$tables['products']}.product_id=atv.item_id and atv.attribute_id in ('" . implode("', '", $att_ids) . "') and atv.code in ('{$current_language}', '') and atv.value != ''");
                # kornev, we have to select all of the slider attributes separatelly
                // general selection of all attributes, values, prices for all products according to search query
                $attribute_query = cw_db_generate_query(array("atv.attribute_id", "atv.value", 'atv.item_id', $tables['products_prices'] . '.price'), $from_tbls, $query_joins, $where, null, null, null);
                //$atv = cw_query($attribute_query); // It takes a lot of memory and don't want return back even after unset()
                $tmp = $prices = array();
                if ($p_result = db_query($attribute_query, null)) {
                    while ($v = db_fetch_array($p_result)) {
                        if ($v['item_id']) {
                            $tmp[$v['attribute_id']][$v['value']][$v['item_id']] = $v['price'];
                            // Use price (to calculate min_price later) instead of dummy flag "1"
                        }
                        if ($v['price']) {
                            $tmp[PRICE_ATTRIBUTE_ID][$v['price']][$v['item_id']] = 1;
                        }
                    }
                    db_free_result($p_result);
                }
                # kornev, for the sliders we should select all of the values - so without the appropriate condition for the attribute;
                if ($ss_att && $config['product_filter']['is_slow_mode']) {
                    foreach ($ss_att as $id => $v) {
                        $__query_joins = $query_joins;
                        $__where = $where;
                        if ($id == 'price') {
                            unset($__where['price_min']);
                            unset($__where['price_max']);
                            $flds = array($tables['products_prices'] . '.price', $tables['products_prices'] . '.product_id');
                        } else {
                            unset($__query_joins['atv_' . $v['id']]);
                            $flds = array('atv.attribute_id', 'atv.value', 'atv.item_id');
                            //                        $__where[] = "atv_$v[id]. "
                        }
                        $attribute_query = cw_db_generate_query($flds, $from_tbls, $__query_joins, $__where, null, null, null);
                        if ($p_result = db_query($attribute_query, null)) {
                            while ($v = db_fetch_array($p_result)) {
                                if ($v['item_id']) {
                                    $tmp[$v['attribute_id']][$v['value']][$v['item_id']] = $v['price'];
                                    // Use price (to calculate min_price later) instead of dummy flag "1"
                                }
                                if ($v['price']) {
                                    $tmp[PRICE_ATTRIBUTE_ID][$v['price']][$v['item_id']] = 1;
                                }
                            }
                            db_free_result($p_result);
                        }
                    }
                }
                $atv = null;
                unset($atv, $ss_att);
                # kornev, for now the fake price attribute is used - we should move it to the attributes array
                # kornev, TOFIX - move price to attributes
                //                array_unshift($attributes, array('attribute_id' => 'price', 'name' => cw_get_langvar_by_name('lbl_price'), 'type' => 'decimal', 'field' => 'price', 'pf_display_type' => 'S', 'is_price' => 1));
                foreach ($attributes as $ka => $v) {
                    $images = array();
                    if (!$tmp[$v['attribute_id']]) {
                        continue;
                    }
                    # kornev, array_multisort problem with numbers
                    # kornev, name will be replaced for selectors
                    foreach ($tmp[$v['attribute_id']] as $k => $pids) {
                        $v['values'][$k] = array('name' => $k, 'id' => $k, 'counter' => count($pids));
                        if ($config['product_filter']['show_from_price'] == 'Y') {
                            $v['values'][$k]['min_price'] = cw_func_call('cw_product_filter_get_slider_value', array('value' => min($pids), 'is_price' => true, 'current_area' => $current_area, 'user_account' => $user_account));
                        }
                    }
                    if (isset($data['attributes'][$v['attribute_id']])) {
                        $v['is_selected'] = true;
                        $v['selected'] = $data['attributes'][$v['attribute_id']];
                    }
                    # kornev, we need to apply some order by to the fields
                    # kornev, also we have to add the images for the selectboxes and multi-selectboxes
                    $dfv = cw_call('cw_attributes_get_attribute_default_value', array('attribute_id' => $v['attribute_id']));
                    if (in_array($v['type'], array('multiple_selectbox', 'selectbox'))) {
                        $sort = $images = array();
                        if ($dfv) {
                            $prepared_dfv = array();
                            foreach ($dfv as $k => $d) {
                                $prepared_dfv[$d['attribute_value_id']] = $d;
                            }
                            foreach ($v['values'] as $k => $d) {
                                if (!$prepared_dfv[$k]) {
                                    unset($v['values'][$k]);
                                    continue;
                                }
                                $sort[$k] = $prepared_dfv[$k]['counter'];
                                $v['values'][$k]['name'] = $prepared_dfv[$k]['value'];
                                $v['values'][$k]['description'] = $prepared_dfv[$k]['description'];
                                $v['values'][$k]['facet'] = $prepared_dfv[$k]['facet'];
                                $v['values'][$k]['orderby'] = $prepared_dfv[$k]['orderby'];
                                // if the type includes swatch - find the images
                                if (in_array($v['pf_display_type'], array('W', 'E', 'G'))) {
                                    $images[$k] = $prepared_dfv[$k]['pf_image_id'];
                                }
                            }
                            # kornev, some problems with values - TOFIX - move to attributes
                            /* doesn't work
                                                        if (count($sort) != count($v['values']))
                                                        foreach($v['values'] as $k=>$d)
                                                            if (!isset($sort[$k]))
                                                                db_query("delete from $tables[attributes_values] where attribute_id='$v[attribute_id]' and value='".addslashes($k)."'");
                            */
                        }
                    } else {
                        if (isset($dfv[0]) && $dfv[0]) {
                            foreach ($v['values'] as $k => $d) {
                                $v['values'][$k]['description'] = $dfv[0]['description'];
                                $v['values'][$k]['facet'] = $dfv[0]['facet'];
                            }
                        }
                    }
                    uasort($v['values'], '_sort_pf_by_counter');
                    # kornev, if slider is used - limit the number of chunks to 50
                    if (in_array($v['pf_display_type'], array('S', 'R'))) {
                        # kornev, slider should be sorted in another way - as the deciaml/integer numbers (sql sorted it as a string)
                        ksort($v['values']);
                        $min = array_shift($v['values']);
                        $max = array_pop($v['values']);
                        if (!$max) {
                            $max = $min;
                        }
                        # kornev, slider with one value is not possible
                        if (!$max && !$v['selected']) {
                            continue;
                        }
                        $v['min_name'] = $v['min'] = $min['name'];
                        $v['max_name'] = $v['max'] = $max['name'];
                        if ($v['pf_display_type'] == 'S' && is_numeric($min['name']) && is_numeric($max['name'])) {
                            $approx_range = ($max['name'] - $min['name']) / 50;
                            $start = $min['name'];
                            $is_price = $v['is_price'] && in_array($current_area, array('G', 'C')) && $info_type & 8;
                            $values = array();
                            $values[$min['id']] = cw_func_call('cw_product_filter_get_slider_value', array('field' => $v['field'], 'value' => $min['id'], 'is_price' => $is_price, 'current_area' => $current_area, 'user_account' => $user_account));
                            $current = null;
                            while ($v['values'] || $current) {
                                if (!$current) {
                                    $current = array_shift($v['values']);
                                    $current['name'] = $v['type'] == 'integer' ? intval($current['name']) : floatval($current['name']);
                                    // Foolproof if numeric fields contain text
                                } else {
                                    $start_prev = $start;
                                    $start += $approx_range;
                                }
                                if ($start >= $current['name']) {
                                    if ($current['name'] > $start_prev) {
                                        # kornev, we need calculate the taxes for the price;
                                        $values[$current['id']] = cw_func_call('cw_product_filter_get_slider_value', array('field' => $v['field'], 'value' => $current['id'], 'is_price' => $is_price, 'current_area' => $current_area, 'user_account' => $user_account));
                                        $start_prev = $start;
                                        $start += $approx_range;
                                    }
                                    $current = null;
                                }
                            }
                            $values[$max['id']] = cw_func_call('cw_product_filter_get_slider_value', array('field' => $v['field'], 'value' => $max['id'], 'is_price' => $is_price, 'current_area' => $current_area, 'user_account' => $user_account));
                            $v['values'] = $values;
                            $v['values_counter'] = count($values);
                            //                            if ($is_price) {
                            $v['min_name'] = cw_func_call('cw_product_filter_get_slider_value', array('field' => $v['field'], 'value' => $v['min'], 'is_price' => $is_price, 'current_area' => $current_area, 'user_account' => $user_account));
                            $v['max_name'] = cw_func_call('cw_product_filter_get_slider_value', array('field' => $v['field'], 'value' => $v['max'], 'is_price' => $is_price, 'current_area' => $current_area, 'user_account' => $user_account));
                            if ($v['selected']) {
                                foreach ($v['selected'] as $sk => $sv) {
                                    $v['selected'][$sk . '_name'] = cw_func_call('cw_product_filter_get_slider_value', array('field' => $v['field'], 'value' => $sv, 'is_price' => $is_price, 'current_area' => $current_area, 'user_account' => $user_account));
                                }
                            }
                            //                            }
                        }
                    } elseif (in_array($v['type'], array('integer', 'decimal')) && in_array($v['pf_display_type'], array('P', 'E', 'W', 'G'))) {
                        $v['values'] = cw_call('cw_product_filter_get_price_ranges', array('attribute_id' => $v['attribute_id'], $v['values']));
                        // Images collection
                        if (in_array($v['pf_display_type'], array('W', 'E', 'G'))) {
                            foreach ($v['values'] as $kk => $vv) {
                                $images[$kk] = $dfv[$kk]['pf_image_id'];
                            }
                        }
                        if (isset($data['attributes'][$v['attribute_id']])) {
                            $v['is_selected'] = true;
                            $v['selected'] = $data['attributes'][$v['attribute_id']];
                        }
                    }
                    # kornev, assign the images....
                    # kornev, TOFIX speed up is possible here
                    if ($images) {
                        foreach ($images as $kk => $dd) {
                            $v['values'][$kk]['image'] = cw_image_get('attributes_images', $dd);
                        }
                    }
                    $pfr[] = $v;
                }
                // foreach $attributes
            }
            unset($attributes, $tmp, $dfv, $prepared_dfv, $values, $images);
            cw_cache_save($pfr, array($search_query . $limit_str), 'PF_search');
        }
    }
    if ($products) {
        $cart =& cw_session_register('cart', array());
        cw_load('taxes', 'warehouse', 'cart');
        global $accl;
        cw_call('on_prepare_products_found', array(&$products, $data, $user_account, $info_type));
        $ids = array();
        $ids_options = array();
        foreach ($products as $k => $v) {
            $ids[] = $v['product_id'];
            $ids_options[$v['product_id']] = doubleval($v['price']);
        }
        # kornev, TOFIX
        if ($addons['product_options']) {
            $options_markups = array();
            if ($ids_options) {
                $options_markups = cw_get_default_options_markup_list($ids_options);
            }
            unset($ids_options);
        }
        //        $is_assigned = ($user_account['customer_id'] && cw_warehouse_is_warehouse_assigned($user_account['customer_id']));
        foreach ($products as $k => $v) {
            //            if($current_area == 'C' && $is_assigned)
            if ($current_area == 'C') {
                $products[$k]['avail'] = cw_warehouse_get_avail_for_customer($v['product_id'], $v['variant_id']);
            } elseif ($current_area == 'A') {
                $products[$k]['avails'] = cw_warehouse_get_avails($v['product_id']);
            }
            $products[$k]['display_price'] = $v['display_price'] = $v['price'];
            # kornev, TOFIX
            if ($addons['product-Options'] && !empty($v['is_product_options']) && !empty($options_markups[$v['product_id']])) {
                $products[$k]['price'] += $options_markups[$v['product_id']];
                $products[$k]['display_price'] = $products[$k]['price'];
                $v = $products[$k];
            }
            $in_cart = 0;
            if (in_array($current_area, array('C', 'G')) && !empty($cart['products']) && is_array($cart['products'])) {
                foreach ($cart['products'] as $cv) {
                    if ($cv['product_id'] == $v['product_id'] && intval($v['variant_id']) == intval($cv['variant_id'])) {
                        $in_cart += $cv['amount'];
                    }
                }
                $products[$k]['in_cart'] = $in_cart;
                $products[$k]['avail'] -= $in_cart;
                if ($products[$k]['avail'] < 0) {
                    $products[$k]['avail'] = 0;
                }
            }
            if ($info_type & 128) {
                $products[$k]['image_thumb'] = cw_image_get('products_images_thumb', $v['product_id']);
            }
            if (in_array($current_area, array('G', 'C')) && $info_type & 8) {
                $_tmp_price = $products[$k]['price'];
                $products[$k]['price'] = $products[$k]['list_price'];
                cw_get_products_taxes($products[$k], $user_account, false, '', $current_area == 'G' && $user_account['usertype'] != 'R');
                $products[$k]['list_price'] = $products[$k]['display_price'];
                $products[$k]['price'] = $_tmp_price;
                $products[$k]['taxes'] = cw_get_products_taxes($products[$k], $user_account, false, '', $current_area == 'G' && $user_account['usertype'] != 'R');
            }
            if ($products[$k]['descr'] == strip_tags($products[$k]['descr'])) {
                $products[$k]['descr'] = str_replace("\n", "<br />", $products[$k]['descr']);
            }
            if ($products[$k]['fulldescr'] == strip_tags($products[$k]['fulldescr'])) {
                $products[$k]['fulldescr'] = str_replace("\n", "<br />", $products[$k]['fulldescr']);
            }
        }
    }
    return array($products, $navigation, $pfr);
}
<?php

$ctime = cw_core_get_time();
$start_date = mktime(0, 0, 0, date("m", $ctime), 1, date("Y", $ctime));
$end_date = $ctime;
if ($action == "go") {
    $salesman_condition = $salesman ? " AND {$tables['salesman_payment']}.customer_id='{$salesman}'" : "";
    if ($StartMonth) {
        $start_date = mktime(0, 0, 0, $StartMonth, $StartDay, $StartYear);
        $end_date = mktime(23, 59, 59, $EndMonth, $EndDay, $EndYear);
    }
    $query = "SELECT {$tables['salesman_payment']}.*, {$tables['customers']}.* FROM {$tables['salesman_payment']}, {$tables['customers']} WHERE {$tables['salesman_payment']}.paid='Y' AND {$tables['salesman_payment']}.customer_id={$tables['customers']}.customer_id AND {$tables['salesman_payment']}.add_date>='{$start_date}' AND {$tables['salesman_payment']}.add_date<='{$end_date}' {$salesman_condition} ORDER BY {$tables['salesman_payment']}.add_date desc";
    $total_history = count(cw_query($query));
    $navigation = cw_core_get_navigation($target, $total_history, $page);
    $navigation['script'] = "index.php?target=payment_history&StartMonth={$StartMonth}&StartDay={$StartDay}&StartYear={$StartYear}&EndMonth={$EndMonth}&EndDay={$EndDay}&EndYear={$EndYear}&salesman={$salesman}&mode=go";
    $smarty->assign('navigation', $navigation);
    $smarty->assign("history", cw_query("{$query} LIMIT {$navigation['first_page']}, {$navigation['objects_per_page']}"));
}
$salesmans = cw_query("SELECT * FROM {$tables['customers']} WHERE usertype='B' ORDER BY lastname");
$smarty->assign("salesmans", $salesmans);
$smarty->assign('history', $history);
$smarty->assign('salesman', $salesman);
$smarty->assign('start_date', $start_date);
$smarty->assign('end_date', $end_date);
$smarty->assign('main', 'payment_history');
} else {
    $smarty->assign('clearance', cw_call('cw_sections_get', array('section' => 'clearance', array('all' => 1), 'where' => 'home_page=1', 'info_type' => 136)));
    $smarty->assign('hot_deals_home', cw_call('cw_sections_get', array('section' => 'hot_deals', array('all' => 1), 'where' => 'home_page=1', 'info_type' => 136)));
    $hot_deals_hot = cw_call('cw_sections_get', array('section' => 'hot_deals', array('all' => 1), 'where' => 'hot_deal=1', 'info_type' => 136));
    if (is_array($hot_deals_hot)) {
        $smarty->assign('hot_deals_hot', array_pop($hot_deals_hot));
    }
    $featured_categories = cw_call('cw_featured_categories_get', array('current_language' => $current_language));
    $smarty->assign('featured_categories', $featured_categories);
}
$smarty->assign('tags', cw_tags_get_popular_tags());
$smarty->assign('bottom_line', cw_call('cw_sections_get', array('section' => 'bottom_line', array('all' => 1), '', 'info_type' => 136)));
# kornev, deals of week
$hot_deals_week = cw_call('cw_sections_get', array('section' => 'hot_deals', array('all' => 1), 'where' => 'week_deal=1', 'info_type' => 136));
if (is_array($hot_deals_week)) {
    $week_navigation = cw_core_get_navigation($target, sizeof($hot_deals_week), 1, 4);
    $smarty->assign('week_navigation', $week_navigation);
    $smarty->assign('hot_deals_week', $hot_deals_week);
}
if ($cat) {
    $last = array_pop($location);
    $last['1'] = '';
    $location[] = $last;
    //    $location = array_merge($location, cw_product_get_filter_location($product_filter, $navigation['script']));
    $smarty->assign('product_filter_navigation', cw_product_get_filter_location($product_filter, $navigation['script']));
    $smarty->assign('cat', $cat);
    $smarty->assign('current_section_dir', 'products');
    $smarty->assign('main', 'subcategories');
    $smarty->assign('show_left_bar', TRUE);
    if (defined('IS_AJAX')) {
        define('PREVENT_XML_OUT', 1);
<?php

$search_data =& cw_session_register('search_data', array());
if ($action == 'go') {
    $date_fields = array('' => array('start_date' => 0, 'end_date' => 1));
    cw_core_process_date_fields($posted_data, $date_fields);
    $search_data['payment_history'] = $posted_data;
    cw_header_location('index.php?target=' . $target);
}
$paid_total_result = cw_query_first("SELECT SUM(commissions) AS numba FROM {$tables['salesman_payment']} WHERE paid='Y' AND salesman_customer_id='{$customer_id}'");
$smarty->assign('paid_total', $paid_total);
$data = $search_data['payment_history'];
$where = array();
$from_tbls = array('salesman_payment');
$where[] = 'paid="Y"';
if ($data['start_date']) {
    $where[] = "{$tables['salesman_payment']}.add_date>='{$data['start_date']}'";
}
if ($data['end_date']) {
    $where[] = "{$tables['salesman_payment']}.add_date>='{$data['end_date']}'";
}
$total_payments = cw_query_first_cell(cw_db_generate_query('count(*)', $from_tbls, '', $where, '', '', '', 0));
if ($total_payments) {
    $smarty->assign('payments', cw_query(cw_db_generate_query('*', $from_tbls, '', $where, '', '', array('add_date'))));
}
$navigation = cw_core_get_navigation($target, $total_payments, $page);
$navigation['script'] = 'index.php?target=' . $target;
$smarty->assign('navigation', $navigation);
$smarty->assign('search_prefilled', $data);
$smarty->assign('main', 'payment_history');
function cw_manufacturer_search($params, $return = null)
{
    extract($params);
    global $tables, $current_language, $target;
    $fields = $from_tbls = $query_joins = $where = $groupbys = $having = $orderbys = 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';
    $query_joins['manufacturers_lng'] = array('on' => "{$tables['manufacturers_lng']}.manufacturer_id = {$tables['manufacturers']}.manufacturer_id and {$tables['manufacturers_lng']}.code='{$current_language}'");
    if ($info_type & 2) {
        $attribute_id = cw_call('cw_attributes_get_attribute_by_field', array('field' => 'manufacturer_id'));
        $query_joins['product_counter'] = array('tblname' => 'attributes_values', 'on' => "product_counter.value = {$tables['manufacturers']}.manufacturer_id AND product_counter.attribute_id={$attribute_id}", 'parent' => 'manufacturers', 'only_select' => 1);
        $fields[] = "count(product_counter.item_id) as products_count";
    }
    $groupbys[] = "{$tables['manufacturers']}.manufacturer_id";
    $fields[] = "{$tables['manufacturers']}.*";
    $fields[] = "IFNULL({$tables['manufacturers_lng']}.manufacturer, {$tables['manufacturers']}.manufacturer) as manufacturer";
    $fields[] = "IFNULL({$tables['manufacturers_lng']}.descr, {$tables['manufacturers']}.descr) as descr";
    $where[] = 1;
    if ($data['substring']) {
        $where[] = "(IFNULL({$tables['manufacturers_lng']}.manufacturer, {$tables['manufacturers']}.manufacturer) like '%{$data['substring']}%' or IFNULL({$tables['manufacturers_lng']}.descr, {$tables['manufacturers']}.descr) like '%{$data['substring']}%')";
    }
    if (isset($data['avail'])) {
        $where[] = "{$tables['manufacturers']}.avail = '{$data['avail']}'";
    }
    if (isset($data['featured'])) {
        $where[] = "{$tables['manufacturers']}.featured = '{$data['featured']}'";
    }
    if (!empty($data['sort_field'])) {
        $direction = $data['sort_direction'] ? 'DESC' : 'ASC';
        switch ($data['sort_field']) {
            case '':
                $sort_string = "manufacturer {$direction}";
                break;
            default:
                $orderbys[] = $data['sort_field'] . ' ' . $direction;
        }
    } else {
        $orderbys[] = 'manufacturer';
    }
    $search_query_count = cw_db_generate_query('count(*)', $from_tbls, $query_joins, $where, $groupbys, $having, array(), 0);
    $search_query = cw_db_generate_query($fields, $from_tbls, $query_joins, $where, $groupbys, $having, $orderbys);
    $total_items_res_id = db_query($search_query_count);
    $total_items = db_num_rows($total_items_res_id);
    $page = $data['page'];
    if ($data['count']) {
        return $total_items;
    } elseif ($data['limit']) {
        $limit_str = " LIMIT {$data['limit']}";
    } elseif ($data['all']) {
        $limit_str = '';
    } else {
        $navigation = cw_core_get_navigation($target, $total_items, $page);
        $limit_str = " LIMIT {$navigation['first_page']}, {$navigation['objects_per_page']}";
    }
    $manufacturers = cw_query($search_query . $limit_str);
    if ($info_type & 1 && $manufacturers) {
        foreach ($manufacturers as $k => $v) {
            $manufacturers[$k]['image'] = cw_image_get('manufacturer_images', $v['manufacturer_id']);
        }
    }
    return array($manufacturers, $navigation);
}
function cw_accounting_get_movements($mtype, $data)
{
    global $tables;
    $fields = array();
    $from_tbls = array();
    $query_joins = array();
    $where = array();
    $groupbys = array();
    $having = array();
    $orderbys = array();
    $from_tbls[] = 'movements';
    $query_joins['accounting_categories'] = array('on' => "{$tables['accounting_categories']}.accounting_category_id = {$tables['movements']}.accounting_category_id", 'parent' => 'movements', 'is_inner' => 1);
    $fields[] = "{$tables['accounting_categories']}.category";
    /*
        $query_joins['movements_info_'.$mtype] = array (
            'tblname' => 'movements_'.$mtype,
            'on' => "movements_info.movements_id = $tables[movements].movements_id",
        );
    */
    $fields[] = "{$tables['movements']}.*";
    //    $fields[] = "movements_info.*";
    $where[] = "1";
    if ($data['warehouse_customer_id']) {
        $where[] = "{$tables['movements']}.warehouse_customer_id='" . $data['warehouse_customer_id'] . "'";
    }
    if ($data['substring']) {
        $where[] = "{$tables['movements']}.product like '%" . $data['substring'] . "%'";
    }
    if ($data['productcode']) {
        $where[] = "{$tables['movements']}.productcode like '%" . $data['productcode'] . "%'";
    }
    if ($data['price_min']) {
        $where[] = "{$tables['movements']}.price >= '" . $data['price_min'] . "'";
    }
    if ($data['price_max']) {
        $where[] = "{$tables['movements']}.price <= '" . $data['price_max'] . "'";
    }
    if ($data['amount_min']) {
        $where[] = "{$tables['movements']}.amount >= '" . $data['amount_min'] . "'";
    }
    if ($data['amount_max']) {
        $where[] = "{$tables['movements']}.amount <= '" . $data['amount_max'] . "'";
    }
    if ($data['pos_customer_id']) {
        $movements_info[] = 'G';
        $fields[] = "movements_G.pos_customer_id";
        $where[] = "movements_G.pos_customer_id='" . $data['pos_customer_id'] . "'";
    }
    if ($data['date_start']) {
        $where[] = "{$tables['movements']}.date >= '" . $data['date_start'] . "'";
    }
    if ($data['date_end']) {
        $where[] = "{$tables['movements']}.date <= '" . $data['date_end'] . "'";
    }
    if (count($movements_info)) {
        $movements_info = array_unique($movements_info);
        foreach ($movements_info as $tp) {
            $query_joins['movements_' . $tp] = array('tblname' => 'movements_' . $tp, 'on' => "movements_{$tp}.movements_id = {$tables['movements']}.movements_id", 'parent' => 'movements');
        }
    }
    if ($data['by_doc']) {
        $query_joins['docs'] = array('on' => "{$tables['docs']}.doc_id = {$tables['movements']}.doc_id", 'is_inner' => 1);
        $query_joins['docs_user_info'] = array('on' => "{$tables['docs_user_info']}.doc_info_id = {$tables['docs']}.doc_info_id", 'is_inner' => 1);
        $query_joins['docs_info'] = array('on' => "{$tables['docs_info']}.doc_info_id = {$tables['docs']}.doc_info_id", 'is_inner' => 1);
        $query_joins['warehouse_divisions'] = array('on' => "{$tables['warehouse_divisions']}.division_id = {$tables['movements']}.warehouse_customer_id", 'is_inner' => 1);
        $fields[] = "{$tables['warehouse_divisions']}.title as warehouse_title";
        $fields[] = "{$tables['docs']}.date";
        $fields[] = "{$tables['docs_user_info']}.customer_id";
        $fields[] = "{$tables['docs_info']}.total";
        $fields[] = "{$tables['docs_info']}.warehouse_customer_id";
        $groupbys[] = "{$tables['movements']}.doc_id";
    }
    $count_query = cw_db_generate_query(array('count(*)'), $from_tbls, $query_joins, $where, $groupbys, $having, $orderbys);
    if ($data['by_doc']) {
        $_res = db_query($count_query);
        $total_items = db_num_rows($_res);
        db_free_result($_res);
    } else {
        $total_items = cw_query_first_cell($count_query);
    }
    if ($data['all']) {
        $navigation = cw_core_get_navigation($target, $total_items, 0, $total_items);
    } else {
        $navigation = cw_core_get_navigation($target, $total_items, $data['page']);
    }
    if ($total_items) {
        $movements = cw_query(cw_db_generate_query($fields, $from_tbls, $query_joins, $where, $groupbys, $having, $orderbys) . " LIMIT {$navigation['first_page']}, {$navigation['objects_per_page']}");
        if ($data['by_doc']) {
            foreach ($movements as $k => $v) {
                $movements[$k]['movements'] = cw_query($sql = "select * from {$tables['movements']} where doc_id='{$v['doc_id']}'");
                $movements[$k]['items_count'] = cw_query_first_cell("select count(*) from {$tables['docs_items']} where doc_id='{$v['doc_id']}'");
            }
        }
    }
    return array($movements, $navigation);
}
        $mysql_host = $app_config_file['sql']['host'];
        $shell_comm = "echo {$arch_select_qry} | mysql --host={$mysql_host} --user={$mysql_user} --password={$mysql_password} {$mysql_db} > {$arch_log_name}";
        shell_exec($shell_comm);
        if (file_exists($arch_log_name)) {
            cw_add_top_message("Current log saved to archive: <a style='color:white' href='{$var_dirs_web['logs_archive']}/{$arch_log_file_name}'>{$arch_log_name}");
            if ($drop_archived == "1") {
                db_query("delete from ld using {$tables['logged_data']} as ld {$archive_where_string_qry}");
            }
        } else {
            cw_add_top_message('Cannot save log to file: ' . $arch_log_name, 'E');
        }
    }
    cw_header_location('index.php?target=logging');
}
$total_items = cw_query_first_cell("select count(*) from {$tables['logged_data']} as ld {$where_string_qry}");
$navigation = cw_core_get_navigation($target, $total_items, $page);
$navigation['script'] = 'index.php?target=' . $target;
$smarty->assign('navigation', $navigation);
$smarty->assign('page', $page);
$limit_qry = " LIMIT {$navigation['first_page']}, {$navigation['objects_per_page']}";
$logged_data = cw_query($s = "select ld.*, IF(ld.customer_id>0,1,0) as is_logged from {$tables['logged_data']} as ld {$where_string_qry} {$orderby_qry} {$limit_qry}");
$session_ids = array();
foreach ($logged_data as $ld_k => $ld_v) {
    $session_ids[$ld_v['cwsid']] = 1;
    $logged_data[$ld_k]['GET_POST'] = unserialize($ld_v['GET_POST']);
}
$smarty->assign('logged_data', $logged_data);
$_sess_data = cw_query("select * from {$tables['logged_data_sessions']} where cwsid in ('" . implode("', '", array_keys($session_ids)) . "')");
$sess_data = array();
foreach ($_sess_data as $s_data) {
    $s_data['SERVER'] = unserialize($s_data['SERVER']);
}
if ($rsort == 'rate') {
    // Sort by rate
    $orderbys[] = 'vote ' . ($rsort_direction == 1 ? 'DESC' : 'ASC');
} elseif ($rsort == 'helpful') {
    // Sort by useful
    $orderbys[] = 'p_vote DESC';
    $orderbys[] = 'n_vote ASC';
}
$orderbys[] = 'r.ctime ' . ($rsort_direction == 1 ? 'DESC' : 'ASC');
$groupbys[] = 'r.review_id';
//    $search_query_count = cw_db_generate_query('count(*)',  $from_tbls, $query_joins, $where, $groupbys, $having, array(), 0);
$search_query = cw_db_generate_query($fields, $from_tbls, $query_joins, $where, $groupbys, $having, $orderbys);
$reviews = cw_query($search_query);
$total_items = count($reviews);
$navigation = cw_core_get_navigation('reviews', $total_items, $page, $reviews_per_page);
$navigation['script'] = 'index.php?target=' . $target . '&product_id=' . $product_id . ($rsort ? '&rsort=' . $rsort : '') . ($rsort_direction ? '&rsort_direction=' . $rsort_direction : '');
$smarty->assign('reviews_navigation', $navigation);
$smarty->assign('page', $page);
$smarty->assign('rsort_direction', $rsort_direction);
$smarty->assign('rsort', $rsort);
if (count($reviews)) {
    $vote_reviews = array();
    foreach ($reviews as $k => $review) {
        if ($review['vote'] > 4.7) {
            $vote_reviews[5][0]++;
        } elseif ($review['vote'] >= 4) {
            $vote_reviews[4][0]++;
        } elseif ($review['vote'] >= 3) {
            $vote_reviews[3][0]++;
        } elseif ($review['vote'] >= 2) {