function export()
{
    global $REQUEST_METHOD, $smarty, $config, $addons, $top_message, $customer_id, $tables;
    global $mode, $action, $amazon_config;
    $success = false;
    if ($REQUEST_METHOD != 'POST') {
        cw_header_location('index.php?target=' . addon_target);
    }
    if ($_POST['export_type'] == 'PaQ' && (empty($_POST['price']) && empty($_POST['quantity']))) {
        $top_message = array('content' => 'At least Price or Quantity must be exported.', 'type' => 'E');
        cw_header_location('index.php?target=' . addon_target);
        return false;
    }
    $_filename = 'files/amazon/' . date('Ymd') . '_' . date('His') . '_' . $_POST['export_type'] . '.csv';
    if (($filename = cw_allow_file($_filename, true)) && ($file = cw_fopen($_filename, 'w', true))) {
        $pids = cw_call('cw_objects_get_list_ids', array('P'));
        if (empty($pids)) {
            $pids = cw_query_column("SELECT product_id FROM {$tables['products']} WHERE status=1");
            // Very bad. Use API
        }
        if ($pids) {
            $amazon_config = cw_array_merge($amazon_config, $config['amazon'], $_POST);
            cw_config_update('amazon', $_POST);
            $warnings = array();
            $data = array();
            $header_put = false;
            foreach ($pids as $v) {
                $variants = array();
                $prod = cw_func_call('cw_product_get', array('id' => $v, 'info_type' => 8 | 64 | 128 | 256 | 512 | 2048));
                $attr = cw_query_hash("SELECT a.field, av.value\n                    FROM {$tables['attributes_values']} av, {$tables['attributes']} a\n                    WHERE av.item_id={$v} AND av.item_type='P' AND a.attribute_id=av.attribute_id", 'field', false, true);
                // very bad. Use API
                if ($prod['is_variants']) {
                    $variants = cw_call('cw_get_product_variants', array($v));
                } else {
                    $variants[0] = $prod;
                }
                foreach ($variants as $var) {
                    $var = cw_array_merge($var, $attr);
                    if ($_POST['export_type'] == 'PaQ') {
                        $data = array('sku' => $var['productcode'], 'price' => $_POST['price'] ? $var['price'] : '', 'quantity' => $_POST['quantity'] ? $var['avail'] : '', 'leadtime-to-ship' => $amazon_config['default_leadtime_to_ship']);
                    }
                    if ($_POST['export_type'] == 'InvLoad') {
                        $data = array('sku' => $var['productcode'], 'product-id' => empty($amazon_config['product_id_type']) ? '' : (string) $var[$amazon_config['product_id']], 'product-id-type' => $amazon_config['product_id_type'], 'price' => $var['price'], 'item-condition' => empty($var[$amazon_config['item_condition']]) ? $amazon_config['default_item_condition'] : $var[$amazon_config['item_condition']], 'quantity' => empty($amazon_config['fulfillment_center_id']) ? $var['avail'] : '', 'add-delete' => empty($_POST['add-delete']) ? 'a' : $_POST['add-delete'], 'will-ship-internationally' => empty($var[$amazon_config['ship_internationally']]) ? $amazon_config['default_ship_internationally'] : $var[$amazon_config['ship_internationally']], 'expedited-shipping' => empty($var[$amazon_config['expedited_shipping']]) ? $amazon_config['default_expedited_shipping'] : $var[$amazon_config['expedited_shipping']], 'standard-plus' => empty($var[$amazon_config['standard_plus']]) ? $amazon_config['default_standard_plus'] : $var[$amazon_config['standard_plus']], 'item-note' => $var[$amazon_config['item_note']], 'fulfillment-center-id' => $amazon_config['fulfillment_center_id'], 'product-tax-code' => $amazon_config['default_product_tax_code'], 'leadtime-to-ship' => $amazon_config['default_leadtime_to_ship']);
                    }
                    if (!$header_put) {
                        fputcsv($file, array_keys($data), "\t");
                        $header_put = true;
                    }
                    fputcsv($file, $data, "\t");
                }
            }
        }
        fclose($file);
        $top_message = array('content' => 'File <b>' . $_filename . '</b> successfully created');
    }
    cw_header_location('index.php?target=' . addon_target);
}
function cw_tabs_get_section($area)
{
    global $tables, $addons, $accl;
    $accl_cond = '\'\'' . (is_array($accl) ? ', \'' . implode('\', \'', array_keys($accl)) . '\'' : '');
    $tabs = cw_query_hash("select n.section_id, nt.link from {$tables['navigation_sections']} as ns, {$tables['navigation_tabs']} as nt, {$tables['navigation_targets']} as n left join {$tables['addons']} as m on m.addon=n.addon where (m.active or m.addon is null) and nt.tab_id=n.tab_id and nt.link != '' and nt.access_level in ({$accl_cond}) and n.section_id=ns.section_id and ns.main='Y' order by nt.orderby", 'section_id', false, true);
    $sections = cw_query("select * from {$tables['navigation_sections']} as ns left join {$tables['addons']} as m on m.addon=ns.addon where (m.active or m.addon is null) and area='{$area}' and main='Y' and access_level in ({$accl_cond}) order by ns.orderby");
    if ($sections) {
        foreach ($sections as $k => $v) {
            $sections[$k]['title_lng'] = cw_get_langvar_by_name($v['title']);
            $sections[$k]['link'] = $tabs[$v['section_id']];
        }
    }
    return $sections;
}
            fclose($fp);
        }
    }
    cw_header_location("index.php?target=languages&language={$new_language}&topic={$topic}&page={$page}");
}
if ($action == "change_defaults") {
    if (!empty($new_customer_language)) {
        db_query("update {$tables['config']} set value='{$new_customer_language}' where name='default_customer_language'");
    }
    if (!empty($new_admin_language)) {
        db_query("update {$tables['config']} set value='{$new_admin_language}' where name='default_admin_language'");
    }
    cw_header_location("index.php?target=languages&language={$language}");
}
if ($language) {
    $language_info = cw_query_hash("select ls.*, lng.value as language from {$tables['languages_settings']} as ls left join {$tables['languages']} as lng ON lng.code = '{$current_language}' and lng.name = CONCAT('language_', ls.code) where ls.code='{$language}'");
    $smarty->assign("language_info", $language_info);
    $data = $search_data['languages'];
    $conditions = array();
    if ($data['topic']) {
        $conditions[] = "lng.topic='{$data['topic']}'";
    } else {
        $conditions[] = "lng.topic<>''";
    }
    if ($data['filter']) {
        $conditions[] = "(lng.name LIKE '%{$data['filter']}%' or lng.value LIKE '%{$data['filter']}%')";
    }
    if ($data['not_translated']) {
        $conditions[] = "lng.value = lng_e.value";
    }
    $query = "select lng.* from {$tables['languages']} as lng left join {$tables['languages']} as lng_e on lng.name=lng_e.name and lng_e.code='EN' where lng.code='{$language}' and " . implode(' and ', $conditions) . " order by lng.topic, lng.name";
function dod_get_generator_bonuses($generator_id = null)
{
    global $tables;
    $result = array();
    $generator_id = (int) $generator_id;
    if (empty($generator_id)) {
        return array();
    }
    $bonuses = cw_query("SELECT * FROM {$tables['dod_bonuses']} WHERE generator_id = '{$generator_id}'");
    $bonus_details = cw_query("SELECT * FROM {$tables['dod_bonus_details']} WHERE generator_id = '{$generator_id}'");
    $_bonus_details = array();
    if (!empty($bonus_details) && is_array($bonus_details)) {
        $products = array();
        $cats = array();
        $mans = array();
        $attr = array();
        foreach ($bonus_details as $details) {
            switch ($details['object_type']) {
                case DOD_OBJ_TYPE_PRODS:
                    $products[$details['object_id']] = null;
                    break;
                case DOD_OBJ_TYPE_CATS:
                    $cats[$details['object_id']] = null;
                    break;
                case DOD_OBJ_TYPE_MANS:
                    $mans[$details['object_id']] = null;
                    break;
                case DOD_OBJ_TYPE_ATTR:
                    $attr[$details['object_id']] = null;
                    break;
                default:
                    break;
            }
        }
        if (!empty($products)) {
            $products = cw_query_hash("SELECT product_id, product FROM {$tables['products']} WHERE product_id IN ('" . implode("', '", array_keys($products)) . "')", 'product_id', false, true);
        }
        if (!empty($cats)) {
            $cats = cw_query_hash("SELECT category_id, category FROM {$tables['categories']} WHERE category_id IN ('" . implode("', '", array_keys($cats)) . "')", 'category_id', false, true);
        }
        if (!empty($mans)) {
            $mans = cw_query_hash("SELECT manufacturer_id, manufacturer FROM {$tables['manufacturers']} WHERE manufacturer_id IN ('" . implode("', '", array_keys($mans)) . "')", 'manufacturer_id', false, true);
        }
        foreach ($bonus_details as $details) {
            if (!isset($_bonus_details[$details['bonus_id']]['products'])) {
                $_bonus_details[$details['bonus_id']]['products'] = array();
            }
            if (!isset($_bonus_details[$details['bonus_id']]['cats'])) {
                $_bonus_details[$details['bonus_id']]['cats'] = array();
            }
            if (!isset($_bonus_details[$details['bonus_id']]['mans'])) {
                $_bonus_details[$details['bonus_id']]['mans'] = array();
            }
            if (!isset($_bonus_details[$details['bonus_id']]['attr'])) {
                $_bonus_details[$details['bonus_id']]['attr'] = array();
            }
            switch ($details['object_type']) {
                case DOD_OBJ_TYPE_PRODS:
                    $_bonus_details[$details['bonus_id']]['products'][] = array('id' => $details['object_id'], 'name' => $products[$details['object_id']], 'quantity' => $details['quantity']);
                    $products[$details['object_id']] = null;
                    break;
                case DOD_OBJ_TYPE_CATS:
                    $_bonus_details[$details['bonus_id']]['cats'][] = array('id' => $details['object_id'], 'name' => $cats[$details['object_id']], 'quantity' => $details['quantity']);
                    $cats[$details['object_id']] = null;
                    break;
                case DOD_OBJ_TYPE_MANS:
                    $_bonus_details[$details['bonus_id']]['mans'][] = array('id' => $details['object_id']);
                    $mans[$details['object_id']] = null;
                    break;
                case DOD_OBJ_TYPE_ATTR:
                    $_bonus_details[$details['bonus_id']]['attr'][] = array('id' => $details['object_id'], 'quantity' => $details['quantity'], 'bd_id' => $details['bd_id']);
                    $attr[$details['object_id']] = null;
                    break;
                case DOD_OBJ_TYPE_SHIPPING:
                    $_bonus_details[$details['bonus_id']]['methods'][$details['object_id']] = $details['object_id'];
                    break;
                default:
                    break;
            }
        }
    }
    $bonus_details = $_bonus_details;
    unset($_bonus_details);
    if (empty($bonuses) || !is_array($bonuses)) {
        return array();
    }
    foreach ($bonuses as $bonus) {
        $result[$bonus['type']] = $bonus;
        if ($bonus['type'] == DOD_FREE_SHIP) {
            $result[$bonus['type']]['methods'] = $bonus_details[$bonus['bonus_id']]['methods'];
        }
        if ($bonus['type'] != DOD_COUPON && ($bonus['apply'] == DOD_APPLY_PRODS || $bonus['type'] == DOD_FREE_PRODS || $bonus['type'] == DOD_DISCOUNT)) {
            $result[$bonus['type']]['products'] = $bonus_details[$bonus['bonus_id']]['products'];
            $result[$bonus['type']]['cats'] = $bonus_details[$bonus['bonus_id']]['cats'];
            $result[$bonus['type']]['mans'] = $bonus_details[$bonus['bonus_id']]['mans'];
            $result[$bonus['type']]['attr'] = $bonus_details[$bonus['bonus_id']]['attr'];
        }
    }
    return $result;
}
<?php

$params = array('mode' => 'dashboard', 'sections' => cw_query_hash("SELECT * FROM {$tables['dashboard']}", 'name', false, false));
$dashboard = cw_func_call('dashboard_build_sections', $params);
// Re-check if some addon ignored active flag
foreach ($dashboard as $name => $dash) {
    $dashboard[$name] = array_merge(array('frame' => 1, 'header' => 1), $dashboard[$name]);
    if (isset($params['sections'][$name])) {
        $dashboard[$name] = array_merge($dashboard[$name], $params['sections'][$name]);
    }
    if ($dashboard[$name]['active'] == 0) {
        unset($dashboard[$name]);
    }
}
uasort($dashboard, 'cw_uasort_by_order');
$smarty->assign('dashboard', $dashboard);
function cw_check_field_names($fields, $tbl)
{
    # kornev, if there was any fields defined - we should update only that
    if (is_array($fields) && count($fields)) {
        return $fields;
    }
    static $table_fields;
    if (!is_array($table_fields[$tbl])) {
        $table_fields[$tbl] = array_keys(cw_query_hash("desc {$tbl}", 'Field'));
    }
    return $table_fields[$tbl];
}
function cw_products_from_scratch($scratch_products, $user_info, $persistent_products, $leave_info = false)
{
    global $addons, $tables, $config, $app_main_dir;
    global $current_area, $current_language, $customer_id;
    cw_load('image');
    $products = array();
    if (empty($scratch_products)) {
        return $products;
    }
    $pids = array();
    foreach ($scratch_products as $product_data) {
        $pids[] = $product_data['product_id'];
    }
    $int_res = cw_query_hash("SELECT * FROM {$tables['products_lng']} WHERE code = '{$current_language}' AND product_id IN ('" . implode("','", $pids) . "')", "product_id", false);
    unset($pids);
    cw_event('on_before_products_from_scratch', array(&$scratch_products));
    $hash = array();
    cw_load('warehouse');
    foreach ($scratch_products as $product_data) {
        $product_id = $product_data['product_id'];
        $cartid = $product_data['cartid'];
        $amount = $product_data['amount'];
        $variant_id = $product_data['variant_id'];
        $warehouse = $product_data['warehouse_customer_id'];
        if (!cw_warehouse_is_customer($customer_id, $warehouse)) {
            continue;
        }
        if (!is_numeric($amount)) {
            $amount = 0;
        }
        $options = $product_data['options'];
        $product_options = false;
        $variant = array();
        # kornev, TOFIX
        if ($addons['product_options'] && !empty($options) && is_array($options)) {
            if (!cw_check_product_options($product_id, $options)) {
                continue;
            }
            list($variant, $product_options) = cw_get_product_options_data($product_id, $options, $membership_id);
            if (empty($variant_id) && isset($variant['variant_id'])) {
                $variant_id = $variant['variant_id'];
            }
        }
        $fields[] = "p.*";
        # kornev, supplier has got it's own prices
        if ($current_area != 'S') {
            $fields[] = "min(pq.price) as price";
        }
        $fields[] = 'avail';
        $status = cw_core_get_required_status($current_area);
        $products_array = cw_func_call('cw_product_get', array('id' => $product_id, 'variant_id' => $variant_id, 'amount' => $amount, 'user_account' => $user_info, 'info_type' => 8192));
        //cw_query_first($sql="select ".implode(', ', $fields)." from $tables[products] as p, $tables[products_prices] as pq, $tables[products_enabled] as pe left join $tables[products_warehouses_amount] as pwa on pwa.product_id=pe.product_id and pwa.variant_id='$variant_id' and pwa.warehouse_customer_id='$warehouse' WHERE p.product_id= pe.product_id and pe.product_id=pq.product_id AND pe.status in (".implode(", ", $status).") AND pe.product_id='$product_id' AND pq.quantity<='$amount' AND pq.membership_id IN(0, '$user_info[membership_id]') AND pq.variant_id = '$variant_id' ORDER BY pq.quantity DESC");
        $unlimited_products = true;
        if ($products_array['avail'] < $amount && in_array($current_area, array('G', 'C'))) {
            $unlimited_products = cw_query_first_cell("select backorder & " . ($current_area == 'G' ? 2 : 1) . " from {$tables['warehouse_divisions']} where division_id = '{$warehouse}'");
            if (!$unlimited_products) {
                $amount = $products_array['avail'];
            }
        }
        if ($products_array) {
            $products_array = cw_array_merge($product_data, $products_array);
            if ($leave_info) {
                $products_array['price'] = abs($product_data['price']);
            }
            $products_array['warehouse_customer_id'] = $warehouse;
            $hash_key = $product_id . "|" . $warehouse;
            cw_event('on_product_from_scratch', array(&$products_array));
            #
            # If priduct's price is 0 then use customer-defined price
            #
            $free_price = false;
            if ($products_array['price'] == 0) {
                $free_price = true;
                $products_array['taxed_price'] = $products_array['price'] = price_format($product_data['free_price'] ? $product_data['free_price'] : 0);
            }
            # kornev, TOFIX
            if ($addons['product_options'] && $options) {
                if (!empty($variant)) {
                    # kornev, it's not allow to set the variant price.
                    //					unset($variant['price']);
                    if (is_null($variant['pimage_path'])) {
                        cw_unset($variant, "pimage_path", "pimage_x", "pimage_y");
                    } else {
                        $variant['is_pimage'] = 'W';
                    }
                    $products_array = cw_array_merge($products_array, $variant);
                }
                $hash_key .= "|" . $products_array['variant_id'];
                if ($product_options === false) {
                    unset($product_options);
                } else {
                    $variant['price'] = $products_array['price'];
                    $variant['cost'] = $products_array['cost'];
                    $products_array['options_surcharge'] = 0;
                    $products_array['cost_surcharge'] = 0;
                    if ($product_options) {
                        foreach ($product_options as $o) {
                            $products_array['options_surcharge'] += $o['modifier_type'] ? $products_array['price'] * $o['price_modifier'] / 100 : $o['price_modifier'];
                            $products_array['cost_surcharge'] += $o['cost_modifier_type'] ? $products_array['cost'] * $o['cost_modifier'] / 100 : $o['cost_modifier'];
                        }
                    }
                }
            }
            if (!$unlimited_products && !$persistent_products && $products_array['avail'] - $hash[$hash_key] < $amount) {
                continue;
            }
            # Get thumbnail's URL (uses only if images stored in FS)
            $products_array['image_thumb'] = cw_image_get('products_images_thumb', $product_id);
            $products_array['price'] += $products_array['options_surcharge'];
            $products_array['cost'] += $products_array['cost_surcharge'];
            if ($products_array['price'] < 0) {
                $products_array['price'] = 0;
            }
            if ($products_array['cost'] < 0) {
                $products_array['cost'] = 0;
            }
            if (in_array($current_area, array('C', 'G'))) {
                $products_array['taxes'] = cw_get_products_taxes($products_array, $user_info, false, '', $current_area == 'G' && $customer_info['usertype'] != 'R');
                if ($config['Taxes']['display_taxed_order_totals'] == 'Y') {
                    $products_array['display_price'] = $products_array['taxed_price'];
                    $products_array['display_net_price'] = $products_array['taxed_net_price'];
                } else {
                    $products_array['display_price'] = $products_array['price'];
                    $products_array['display_net_price'] = $products_array['net_price'];
                }
            }
            $products_array['total'] = $amount * $products_array['price'];
            $products_array['product_options'] = $product_options;
            $products_array['options'] = $options;
            $products_array['amount'] = $amount;
            $products_array['cartid'] = $cartid;
            $products_array['product_orig'] = $products_array['product'];
            if (isset($int_res[$product_id])) {
                $products_array['product'] = stripslashes($int_res[$product_id]['product']);
                $products_array['descr'] = stripslashes($int_res[$product_id]['descr']);
                $products_array['fulldescr'] = stripslashes($int_res[$product_id]['fulldescr']);
                cw_unset($int_res, $product_id);
            }
            if ($products_array['descr'] == strip_tags($products_array['descr'])) {
                $products_array['descr'] = str_replace("\n", "<br />", $products_array['descr']);
            }
            if ($products_array['fulldescr'] == strip_tags($products_array['fulldescr'])) {
                $products_array['fulldescr'] = str_replace("\n", "<br />", $products_array['fulldescr']);
            }
            // Order hash defines how all products in cart will be split by orders
            // Listen for the event and return own part of hash
            $order_hash = cw_event('on_build_order_hash', array($products_array), array());
            $order_hash[] = 'W' . $products_array['warehouse_customer_id'];
            $products_array['order_hash'] = join('-', $order_hash);
            $products[] = $products_array;
            $hash[$hash_key] += $amount;
        }
    }
    //cw_var_dump($products);
    return $products;
}
function cw_ps_update_shipping(&$cart, &$products, $user_info, &$return, $offers_ids = array())
{
    global $tables;
    if (empty($products) || empty($cart)) {
        return false;
    }
    if (empty($offers_ids) || !isset($offers_ids['new']) || !isset($offers_ids['to_delete']) || !isset($offers_ids['suitable'])) {
        return false;
    }
    $offers = $offers_ids['new'] + $offers_ids['suitable'];
    // check if the suitable products exist...
    $fields = $from_tbls = $query_joins = $where = $groupbys = $having = $orderbys = array();
    $fields = array("{$tables['ps_bonuses']}.offer_id", "{$tables['ps_bonuses']}.apply", "{$tables['ps_bonuses']}.offer_id as offerid", "{$tables['ps_bonuses']}.bonus_id");
    $from_tbls[] = 'ps_bonuses';
    $where[] = "{$tables['ps_bonuses']}.offer_id IN ('" . implode("', '", array_keys($offers)) . "')";
    $where[] = "{$tables['ps_bonuses']}.type = '" . PS_FREE_SHIP . "'";
    $search_query = cw_db_generate_query($fields, $from_tbls, $query_joins, $where, $groupbys, $having, $orderbys);
    $offers_data = cw_query_hash($search_query, 'offer_id', false);
    //echo '<pre>', print_r($offers_data), '</pre>';
    //die;
    /*$fields = $from_tbls = $query_joins = $where = $groupbys = $having = $orderbys = array();
    
        $fields = array("$tables[ps_bonuses].offer_id", 'object_id', 'quantity', "$tables[ps_bonuses].offer_id as offerid", "$tables[ps_bonuses].bonus_id");
    
        $from_tbls[] = 'ps_bonuses';
    
        $query_joins['ps_bonus_details'] = array(
            'on' => "$tables[ps_bonuses].bonus_id = $tables[ps_bonus_details].bonus_id",
       		'is_inner' => 1,
        );
    
        $where[] = "$tables[ps_bonuses].offer_id IN ('" . implode("', '", array_keys($offers)) .  "')";
        $where[] = "$tables[ps_bonuses].type = '" . PS_FREE_SHIP .  "'";
        $where[] = "$tables[ps_bonus_details].object_type = '" . PS_OBJ_TYPE_PRODS .  "'";
    
    
        $search_query = cw_db_generate_query($fields, $from_tbls, $query_joins, $where, $groupbys, $having, $orderbys);
        $free_products = cw_query_hash($search_query, 'object_id', false);
    
        if (empty($free_products) || !is_array($free_products)) {
            return false;
        }
        */
}
         $top_message = array("content" => cw_get_langvar_by_name(""), "type" => "E");
         cw_header_location("index.php?target={$target}&js_tab=instances&survey_id=" . $survey_id);
     }
     $smarty->assign('survey', $survey);
 } else {
     # Get survey instances list
     $where = "";
     if (!empty($filter_surveys[$survey_id])) {
         $where = "date > " . intval($filter_surveys[$survey_id]['date_from']) . " AND date < " . intval($filter_surveys[$survey_id]['date_to']) . " AND";
     }
     $total_items = cw_query_first_cell("SELECT COUNT(survey_id) FROM {$tables['survey_results']} WHERE {$where} survey_id = '{$survey_id}'");
     $navigation = cw_core_get_navigation($target, $total_items, $page);
     $navigation['script'] = "survey.php?js_tab=instances&survey_id=" . $survey_id;
     $smarty->assign('navigation', $navigation);
     if ($total_items > 0) {
         $results = cw_query_hash("SELECT {$tables['survey_results']}.*, {$tables['customers']}.usertype FROM {$tables['survey_results']} LEFT JOIN {$tables['customers']} ON {$tables['survey_results']}.customer_id={$tables['customers']}.customer_id WHERE {$where} {$tables['survey_results']}.survey_id = '{$survey_id}' ORDER BY {$tables['survey_results']}.date DESC LIMIT {$navigation['first_page']}, {$navigation['objects_per_page']}", "survey_result_id", false);
         if (!empty($results)) {
             foreach ($results as $k => $v) {
                 if (!empty($v['completed'])) {
                     $results[$k]['completed_msg'] = cw_get_langvar_by_name("lbl_survey_completed_type_" . $v['completed']);
                 }
                 if (!empty($v['as_result'])) {
                     $results[$k]['obj_link'] = cw_as_result2obj_link($v['as_result']);
                 }
             }
             $smarty->assign('results', $results);
         }
     }
     $smarty->assign('filter', $filter_surveys[$survey_id]);
     $smarty->assign('is_filter', !empty($filter_surveys[$survey_id]['date_from']) && !empty($filter_surveys[$survey_id]['date_to']));
 }
function ps_get_offer_conditions($offer_id = null)
{
    global $tables;
    $result = array();
    $offer_id = (int) $offer_id;
    if (empty($offer_id)) {
        return array();
    }
    $conditions = cw_query("SELECT * FROM {$tables['ps_conditions']} WHERE offer_id = '{$offer_id}'");
    $condition_details = cw_query("SELECT * FROM {$tables['ps_cond_details']} WHERE offer_id = '{$offer_id}'");
    $_condition_details = array();
    if (!empty($condition_details) && is_array($condition_details)) {
        $products = array();
        $cats = array();
        $mans = array();
        $zones = array();
        foreach ($condition_details as $details) {
            switch ($details['object_type']) {
                case PS_OBJ_TYPE_PRODS:
                    $products[$details['object_id']] = null;
                    break;
                case PS_OBJ_TYPE_CATS:
                    $cats[$details['object_id']] = null;
                    break;
                case PS_OBJ_TYPE_MANS:
                    $mans[$details['object_id']] = null;
                    break;
                case PS_OBJ_TYPE_ATTR:
                    $attr[$details['object_id']] = null;
                    break;
                case PS_OBJ_TYPE_ZONES:
                    $zones[$details['object_id']] = null;
                    break;
                default:
                    break;
            }
        }
        if (!empty($products)) {
            $products = cw_query_hash("SELECT product_id, product FROM {$tables['products']} WHERE product_id IN ('" . implode("', '", array_keys($products)) . "')", 'product_id', false, true);
        }
        if (!empty($cats)) {
            $cats = cw_query_hash("SELECT category_id, category FROM {$tables['categories']} WHERE category_id IN ('" . implode("', '", array_keys($cats)) . "')", 'category_id', false, true);
        }
        if (!empty($mans)) {
            $mans = cw_query_hash("SELECT manufacturer_id, manufacturer FROM {$tables['manufacturers']} WHERE manufacturer_id IN ('" . implode("', '", array_keys($mans)) . "')", 'manufacturer_id', false, true);
        }
        if (!empty($zones)) {
            $zones = cw_query_hash("SELECT zone_id, zone_name FROM {$tables['zones']} WHERE zone_id IN ('" . implode("', '", array_keys($zones)) . "')", 'zone_id', false, true);
        }
        foreach ($condition_details as $details) {
            if (!isset($_condition_details[$details['cond_id']]['products'])) {
                $_condition_details[$details['cond_id']]['products'] = array();
            }
            if (!isset($_condition_details[$details['cond_id']]['cats'])) {
                $_condition_details[$details['cond_id']]['cats'] = array();
            }
            if (!isset($_condition_details[$details['cond_id']]['mans'])) {
                $_condition_details[$details['cond_id']]['mans'] = array();
            }
            if (!isset($_condition_details[$details['cond_id']]['attr'])) {
                $_condition_details[$details['cond_id']]['attr'] = array();
            }
            if (!isset($_condition_details[$details['cond_id']]['zones'])) {
                $_condition_details[$details['cond_id']]['zones'] = array();
            }
            switch ($details['object_type']) {
                case PS_OBJ_TYPE_PRODS:
                    $_condition_details[$details['cond_id']]['products'][] = array('id' => $details['object_id'], 'name' => $products[$details['object_id']], 'quantity' => $details['quantity']);
                    $products[$details['object_id']] = null;
                    break;
                case PS_OBJ_TYPE_CATS:
                    $_condition_details[$details['cond_id']]['cats'][] = array('id' => $details['object_id'], 'name' => $cats[$details['object_id']], 'quantity' => $details['quantity']);
                    $cats[$details['object_id']] = null;
                    break;
                case PS_OBJ_TYPE_MANS:
                    $_condition_details[$details['cond_id']]['mans'][] = array('id' => $details['object_id'], 'name' => $mans[$details['object_id']], 'quantity' => $details['quantity']);
                    $mans[$details['object_id']] = null;
                    break;
                case PS_OBJ_TYPE_ATTR:
                    $_condition_details[$details['cond_id']]['attr'][] = array('id' => $details['object_id'], 'quantity' => $details['quantity'], 'cd_id' => $details['cd_id']);
                    $attr[$details['object_id']] = null;
                    break;
                case PS_OBJ_TYPE_ZONES:
                    $_condition_details[$details['cond_id']]['zones'][$details['object_id']] = array('id' => $details['object_id'], 'name' => $zones[$details['object_id']], 'quantity' => $details['quantity']);
                    $zones[$details['object_id']] = null;
                    break;
                case PS_OBJ_TYPE_FROM:
                    $_condition_details[$details['cond_id']] = 'from';
                    break;
                case PS_OBJ_TYPE_TILL:
                    $_condition_details[$details['cond_id']] = 'till';
                    break;
                case PS_OBJ_TYPE_MEMBERSHIP:
                    $_condition_details[$details['cond_id']]['membership'] = $details['object_id'];
                    break;
                default:
                    break;
            }
        }
    }
    $condition_details = $_condition_details;
    unset($_condition_details);
    if (empty($conditions) || !is_array($conditions)) {
        return array();
    }
    $save_weight_fields = $save_total_fields = array();
    foreach ($conditions as $condition) {
        $result[$condition['type']] = $condition;
        if ($condition['type'] == PS_SPEC_PRODUCTS) {
            $result[$condition['type']]['products'] = $condition_details[$condition['cond_id']]['products'];
            $result[$condition['type']]['cats'] = $condition_details[$condition['cond_id']]['cats'];
            $result[$condition['type']]['mans'] = $condition_details[$condition['cond_id']]['mans'];
            $result[$condition['type']]['attr'] = $condition_details[$condition['cond_id']]['attr'];
        } elseif ($condition['type'] == PS_SHIP_ADDRESS) {
            $result[$condition['type']]['zones'] = $condition_details[$condition['cond_id']]['zones'];
        } elseif ($condition['type'] == PS_WEIGHT) {
            $field = $condition_details[$condition['cond_id']];
            $save_weight_fields[$condition['type']][$field] = $condition['total'];
            $result[$condition['type']] = array_merge($result[$condition['type']], $save_weight_fields[$condition['type']]);
        } elseif ($condition['type'] == PS_TOTAL) {
            $field = $condition_details[$condition['cond_id']];
            $save_total_fields[$condition['type']][$field] = $condition['total'];
            $result[$condition['type']] = array_merge($result[$condition['type']], $save_total_fields[$condition['type']]);
        } elseif ($condition['type'] == PS_MEMBERSHIP) {
            $result[$condition['type']]['membership'] = $condition_details[$condition['cond_id']]['membership'];
        }
    }
    return $result;
}
             break;
     }
     $result = array();
     $start_time = $from;
     $end_time = $to;
     // fill result array
     while ($end_time >= $start_time) {
         $result[] = array('count' => 0, 'amount' => 0, 'margin' => 0, 'date' => date('Y-m-d H:i:s', $start_time), 'timestamp' => $start_time);
         $start_time += $step;
     }
     // if last time not present in array, then need add
     if ($result[count($result) - 1]['timestamp'] < $to) {
         $result[] = array('count' => 0, 'amount' => 0, 'margin' => 0, 'date' => date('Y-m-d H:i:s', $to), 'timestamp' => $to);
     }
     $q = "SELECT d.doc_id, d.date, di.total, de.value as margin\n\t\t\tFROM {$tables['docs']} d\n\t\t\tLEFT JOIN {$tables['docs_info']} di ON d.doc_info_id = di.doc_info_id\n\t\t\tLEFT JOIN {$tables['docs_extras']} de ON d.doc_id = de.doc_id AND de.khash = 'margin_value'\n\t\t\tWHERE (d.date BETWEEN {$from} AND {$to}) AND d.type = 'O'\n\t\t\tORDER BY d.date ASC";
     $orders = cw_query_hash($q);
     if (is_array($orders) && count($orders)) {
         $key = 0;
         foreach ($orders as $order) {
             // find next period
             while ($order[0]['date'] > $result[$key]['timestamp'] && isset($result[$key])) {
                 $key++;
             }
             $result[$key]['count'] += 1;
             $result[$key]['amount'] += floatval($order[0]['total']);
             $result[$key]['margin'] += floatval($order[0]['margin']);
         }
     }
     exit(json_encode($result));
 }
 // search users
function cw_manufacturers_product_search($params, $return)
{
    if ($return[2]) {
        foreach ($return[2] as $k => $v) {
            if ($v['field'] == 'manufacturer_id') {
                // This approach with all manufacturers in cache better works for huge amount of manufacturers over 1K
                $all_manufacturers = cw_cache_get(null, 'manufacturers_all');
                if (empty($all_manufacturers)) {
                    $all_manufacturers = cw_query_hash("SELECT manufacturer_id, manufacturer FROM cw_manufacturers", 'manufacturer_id', false, true);
                    cw_cache_save($all_manufacturers, null, 'manufacturers_all');
                }
                if ($v['values']) {
                    foreach ($v['values'] as $kk => $vv) {
                        if (!isset($all_manufacturers[$vv['id']])) {
                            unset($return[2][$k]['values'][$kk]);
                        } else {
                            $return[2][$k]['values'][$kk]['name'] = $all_manufacturers[$vv['id']];
                        }
                    }
                }
                if (!$return[2][$k]['values']) {
                    unset($return[2][$k]);
                }
                break;
            }
        }
    }
    if ($return[0]) {
        global $tables;
        $attribute_id = cw_call('cw_attributes_get_attribute_by_field', array('field' => 'manufacturer_id'));
        if ($attribute_id) {
            foreach ($return[0] as $k => $v) {
                $product_id = $v['product_id'];
                $manufacturer = cw_query_first_cell("\n                    SELECT m.manufacturer\n                    FROM {$tables['manufacturers']} m\n                    LEFT JOIN {$tables['attributes_values']} av ON av.value = m.manufacturer_id\n                    WHERE av.item_id = '{$product_id}' AND av.attribute_id = '{$attribute_id}' AND av.item_type = 'P'\n                ");
                $return[0][$k]['manufacturer'] = $manufacturer;
            }
        }
    }
    return $return;
}
function export()
{
    global $REQUEST_METHOD, $smarty, $config, $addons, $top_message, $customer_id, $tables;
    global $mode, $action, $ebay_config;
    if ($REQUEST_METHOD != 'POST') {
        cw_header_location('index.php?target=' . addon_target);
    }
    $result = cw_ebay_check_fields($_POST);
    if (count($result)) {
        $top_message = array('content' => implode("<br />", $result), 'type' => 'E');
        cw_header_location('index.php?target=' . addon_target);
    }
    if (empty($_POST['file_name'])) {
        $_filename = addon_files_location_path . 'ebay_export_' . date('Ymd') . '_' . date('His') . '.csv';
    } else {
        $_filename = addon_files_location_path . $_POST['file_name'] . '.csv';
    }
    $_copy_filename = $_filename;
    if (($filename = cw_allow_file($_filename, true)) && ($file = cw_fopen($_filename, 'w', true))) {
        $pids = cw_call('cw_objects_get_list_ids', array('P'));
        if (empty($pids)) {
            $pids = cw_query_column("SELECT product_id FROM {$tables['products']} WHERE status=1");
            // Very bad. Use API
        }
        if ($pids) {
            $ebay_config = cw_array_merge($ebay_config, $config['ebay'], $_POST);
            cw_config_update('ebay', $_POST);
            $data = array();
            $header_put = false;
            $count_files = 0;
            foreach ($pids as $v) {
                $variants = array();
                $prod = cw_func_call('cw_product_get', array('id' => $v, 'info_type' => 8 | 64 | 128 | 256 | 512 | 2048));
                $attr = cw_query_hash("SELECT a.field, av.value\n\t                    FROM {$tables['attributes_values']} av, {$tables['attributes']} a\n\t                    WHERE av.item_id={$v} AND av.item_type='P' \n\t                    \tAND a.attribute_id=av.attribute_id", 'field', false, true);
                // very bad. Use API
                if ($prod['is_variants']) {
                    $variants = cw_call('cw_get_product_variants', array($v));
                } else {
                    $variants[0] = $prod;
                }
                foreach ($variants as $var) {
                    $var = cw_array_merge($var, $attr);
                    $ebay_category = cw_ebay_get_category_value($prod['category_id'], $ebay_config['ebay_category']);
                    if (!$ebay_category) {
                        fclose($file);
                        $top_message = array('content' => 'For <a href="index.php?target=categories&mode=edit&cat=' . $prod['category_id'] . '">Main category</a> for the product "' . $prod['product'] . '" option "Category" does not set.', 'type' => 'E');
                        cw_header_location('index.php?target=' . addon_target);
                    }
                    if (!$header_put) {
                        // Set smart headers
                        $data = array('Action' => $ebay_config['ebay_action'], 'ImmediatePayRequired=' . ($ebay_config['ebay_immediate_pay_required'] == 'Y' ? "1" : "0") => "", 'Category' => $ebay_category, 'ConditionID' => cw_ebay_get_condition_value($var, $ebay_config['ebay_condition_id']), 'Description' => substr(nl2br($var['descr']), 0, 500000), 'Duration=' . $ebay_config['ebay_duration'] => "", 'Format=' . $ebay_config['ebay_format'] => "", 'Location=' . $ebay_config['ebay_location'] => "", 'PayPalAccepted=' . ($ebay_config['ebay_paypal_accepted'] == 'Y' ? "1" : "0") => "", 'PayPalEmailAddress' => $ebay_config['ebay_paypal_accepted'] == 'Y' ? $ebay_config['ebay_paypal_email_address'] : "", 'Quantity' => $var['avail'], 'Title' => substr($var['product'], 0, 80), 'DispatchTimeMax=' . $ebay_config['ebay_dispatch_time_max'] => "", 'ReturnsAcceptedOption=' . $ebay_config['ebay_returns_accepted_option'] => "", 'StartPrice' => $var['price']);
                    } else {
                        $data = array('Action' => $ebay_config['ebay_action'], 'ImmediatePayRequired' => "", 'Category' => $ebay_category, 'ConditionID' => cw_ebay_get_condition_value($var, $ebay_config['ebay_condition_id']), 'Description' => substr(nl2br($var['descr']), 0, 500000), 'Duration' => "", 'Format' => "", 'Location' => "", 'PayPalAccepted' => "", 'PayPalEmailAddress' => $ebay_config['ebay_paypal_accepted'] == 'Y' ? $ebay_config['ebay_paypal_email_address'] : "", 'Quantity' => $var['avail'], 'Title' => substr($var['product'], 0, 80), 'DispatchTimeMax' => "", 'ReturnsAcceptedOption' => "", 'StartPrice' => $var['price']);
                    }
                    if (!$header_put) {
                        fputcsv($file, array_keys($data), ",");
                        $header_put = true;
                    }
                    fputcsv($file, $data, ",");
                    // A single file cannot exceed 15 MB
                    if (filesize($_filename) > 14680064) {
                        fclose($file);
                        $new_filename = str_replace(".csv", "_" . $count_files . ".csv", $_copy_filename);
                        rename($_filename, $new_filename);
                        $count_files++;
                        $_filename = str_replace(".csv", "_" . $count_files . ".csv", $_copy_filename);
                        $file = cw_fopen($_filename, 'w', true);
                        $header_put = false;
                    }
                }
            }
        }
        fclose($file);
        $top_message = array('content' => 'File <b>' . $_filename . '</b> successfully created');
    }
    cw_header_location('index.php?target=' . addon_target);
}
function cw_web_get_layout_elements($params)
{
    global $tables;
    if (!$params['layout_id'] && !$params['layout']) {
        return;
    }
    if ($params['layout_id']) {
        return cw_query_hash("select le.* from {$tables['layouts_elements']} as le where le.layout_id='{$params['layout_id']}' and id != ''", 'id', false);
    }
    return cw_query_hash("select le.* from {$tables['layouts_elements']} as le, {$tables['layouts']} as l where l.layout_id=le.layout_id and l.layout='{$params['layout']}' and l.is_default=1 and id != ''", 'id', false);
}
function xcm_install_all_config()
{
    static $_installed;
    //global $xcm_thumb_def_config;
    //global $xcm_thumb_appname;
    if (isset($_installed)) {
        return true;
    }
    $xcm_vars = xcm_get_vars();
    extract($xcm_vars);
    if ($xcm_thumb_appname == "cartworks") {
        global $config, $sql_db, $tables, $app_config_file, $app_main_dir, $addons;
        if (isset($tables[$xcm_thumb_cache_tbl])) {
            $_installed = true;
            return true;
        }
    }
    foreach ($xcm_thumb_def_config as $var_name => $var_data) {
        //                xcm_install_config($var_name);
        if ($xcm_thumb_appname == "xcart") {
            global $config;
            $category = $xcm_thumb_def_config[$var_name]["category"];
            $comment = $xcm_thumb_def_config[$var_name]["comment"];
            $value = $xcm_thumb_def_config[$var_name]["value"];
            $orderby = $xcm_thumb_def_config[$var_name]["orderby"];
            $type = $xcm_thumb_def_config[$var_name]["type"];
            $variants = $xcm_thumb_def_config[$var_name]["variants"];
            if (in_array($var_name, $xcm_thumb_di_only_config) && !isset($config["Dynamic_Images_3"]["det_image_thumbnails"])) {
                continue;
            }
            if (!isset($config[$category][$var_name])) {
                db_query("INSERT INTO xcart_config SET name='{$var_name}', comment='{$comment}', value='{$value}', category='{$category}', orderby='{$orderby}', type='{$type}', variants='{$variants}'");
                $config[$category][$var_name] = $value;
            }
        } elseif ($xcm_thumb_appname == "cartworks") {
            if (isset($config[$category][$var_name])) {
                continue;
            }
            $category = $xcm_thumb_def_config[$var_name]["category"];
            $comment = $xcm_thumb_def_config[$var_name]["comment"];
            $value = $xcm_thumb_def_config[$var_name]["value"];
            $orderby = $xcm_thumb_def_config[$var_name]["orderby"];
            $type = $xcm_thumb_def_config[$var_name]["type"];
            $variants = $xcm_thumb_def_config[$var_name]["variants"];
            if (in_array($var_name, $xcm_thumb_di_only_config) && !isset($addons[xcm_get_detimages_category_name()])) {
                continue;
            }
            if (!isset($config[$category][$var_name])) {
                db_query("INSERT INTO {$tables['config']} SET name='{$var_name}', comment='{$comment}', value='{$value}', config_category_id='" . xcm_set_config_category_id($category) . "', orderby='{$orderby}', type='{$type}', variants='{$variants}'");
                $config[$category][$var_name] = $value;
            }
        }
    }
    if ($xcm_thumb_appname == "xcart") {
        global $sql_db;
        if (!cw_query_first_cell("show tables where Tables_in_" . $sql_db . " = '{$xcm_thumb_cache_tbl}'")) {
            db_query("CREATE TABLE {$xcm_thumb_cache_tbl} (imageid int(11) NOT NULL auto_increment,image_path varchar(255) NOT NULL default '',image_type varchar(64) NOT NULL default 'image/jpeg',image_x int(11) NOT NULL default '0',image_y int(11) NOT NULL default '0',image_size int(11) NOT NULL default '0',filename varchar(255) NOT NULL default '',date int(11) NOT NULL default '0',md5key varchar(32) NOT NULL default '',PRIMARY KEY (imageid),KEY image_path (image_path), KEY md5key (md5key)) TYPE=MyISAM;");
        }
        //Setting up the new separator line at the General settings page
        if (!cw_query_first_cell("SELECT COUNT(*) FROM xcart_config WHERE name='xcm_thumb_sep'")) {
            db_query("INSERT INTO xcart_config SET name='xcm_thumb_sep', comment='CartWorks.com xcm_thumb Smarty plugin options', value='', category='General', orderby='1050', type='separator', defvalue='', variants=''");
        }
        //adding the clear cache link to the comment of the cached_thumbs_dir config variable
        global $xcart_dir;
        $comment_no_clear = "Store cached resized thumbs in directory";
        $comment_clear_cache = "Store cached resized thumbs in directory <br /><a style='color: #0000ff; text-decoration: underline;' href='xcm_thumb_clear.php'>Clear cache dir</a>";
        $cached_thumbs_dir_comment = cw_query_first_cell("SELECT comment FROM xcart_config WHERE name='cached_thumbs_dir'");
        if (file_exists($xcart_dir . "/admin/xcm_thumb_clear.php")) {
            if ($cached_thumbs_dir_comment != $comment_clear_cache) {
                db_query("UPDATE xcart_config SET comment='" . addslashes($comment_clear_cache) . "' WHERE name='cached_thumbs_dir'");
            }
        } else {
            if ($cached_thumbs_dir_comment != $comment_no_clear) {
                db_query("UPDATE xcart_config SET comment='{$comment_no_clear}' WHERE name='cached_thumbs_dir'");
            }
        }
    } elseif ($xcm_thumb_appname == "cartworks") {
        if (!cw_query_first_cell("show tables where Tables_in_" . $app_config_file[sql][db] . " = '{$xcm_thumb_cache_tbl}'")) {
            db_query("CREATE TABLE {$xcm_thumb_cache_tbl} (imageid int(11) NOT NULL auto_increment,image_path varchar(255) NOT NULL default '',image_type varchar(64) NOT NULL default 'image/jpeg',image_x int(11) NOT NULL default '0',image_y int(11) NOT NULL default '0',image_size int(11) NOT NULL default '0',filename varchar(255) NOT NULL default '',date int(11) NOT NULL default '0',md5key varchar(32) NOT NULL default '',PRIMARY KEY (imageid),KEY image_path (image_path), KEY md5key (md5key)) TYPE=MyISAM;");
        }
        $current_language = $config['default_customer_language'];
        $all_languages = cw_query_hash("select ls.*, lng.value as language from {$tables['languages_settings']} as ls left join {$tables['languages']} as lng ON lng.code = '{$current_language}' and lng.name = CONCAT('language_', ls.code) where ls.enable=1", 'code', false);
        if (is_array($all_languages)) {
            $lang_cat_name = "option_title_" . xcm_get_smarty_category_name();
            $lang_opt_name = 'opt_xcm_thumb_sep';
            foreach ($all_languages as $lang => $lang_data) {
                if (!cw_query_first_cell("SELECT name FROM {$tables['languages']} WHERE code = '{$lang}' and name = '{$lang_cat_name}'")) {
                    db_query("INSERT INTO {$tables['languages']} SET code = '{$lang}', name = '{$lang_cat_name}', value = 'Smarty plugins options', topic = 'Options'");
                }
                if (!cw_query_first_cell("SELECT name FROM {$tables['languages']} WHERE code = '{$lang}' and name = '{$lang_opt_name}'")) {
                    db_query("INSERT INTO {$tables['languages']} SET code = '{$lang}', name = '{$lang_opt_name}', value = 'Image thumbnails options', topic = 'Options'");
                }
            }
        }
        //Setting up the new separator line at the General settings page
        if (!cw_query_first_cell("SELECT COUNT(*) FROM {$tables['config']} WHERE name='xcm_thumb_sep'")) {
            db_query("INSERT INTO {$tables['config']} SET name='xcm_thumb_sep', comment='Image thumbnails options', value='', config_category_id='" . xcm_set_config_category_id() . "', orderby='1050', type='separator', defvalue='', variants=''");
        }
        //adding the clear cache link to the comment of the cached_thumbs_dir config variable
        $comment_no_clear = "Store cached resized thumbs in directory";
        $comment_clear_cache = "Store cached resized thumbs in directory <br /><a style='color: #0000ff; text-decoration: underline;' href='index.php?target=thumbs_clear'>Clear cache dir</a>";
        $cached_thumbs_dir_comment = cw_query_first_cell("SELECT comment FROM {$tables['config']} WHERE name='cached_thumbs_dir'");
        if (file_exists($app_main_dir . "/admin/thumbs_clear.php")) {
            if ($cached_thumbs_dir_comment != $comment_clear_cache) {
                db_query("UPDATE {$tables['config']} SET comment='" . addslashes($comment_clear_cache) . "' WHERE name='cached_thumbs_dir'");
            }
        } else {
            if ($cached_thumbs_dir_comment != $comment_no_clear) {
                db_query("UPDATE {$tables['config']} SET comment='{$comment_no_clear}' WHERE name='cached_thumbs_dir'");
            }
        }
    }
    $_installed = true;
}
            $top_message = array("content" => cw_get_langvar_by_name("txt_surveys_are_cloned"));
        }
    }
    cw_header_location("index.php?target=surveys");
}
if ($action == 'finish') {
    $top_message = array('content' => cw_get_langvar_by_name('lbl_survey_successfull_updated'));
    cw_header_location('index.php?target=' . $target);
}
if ($action == 'create') {
    $time = cw_core_get_time();
    $query_data = array('survey_type' => 'D', 'created_date' => $time, 'valid_from_date' => $time, 'expires_data' => $time + 86400, 'orderby' => cw_query_first_cell("SELECT MAX(orderby) FROM {$tables['surveys']}") + 10);
    $survey_id = cw_array2insert('surveys', $query_data);
    cw_header_location("index.php?target={$target}&survey_id=" . $survey_id . "&js_tab=question");
}
# Get surveys list
$surveys = cw_query_hash("SELECT {$tables['surveys']}.*, COUNT({$tables['survey_maillist']}.email) as count_maillist, SUM(IF({$tables['survey_maillist']}.sent_date > 0, 1, 0)) as count_sent FROM {$tables['surveys']} LEFT JOIN {$tables['survey_maillist']} ON {$tables['surveys']}.survey_id = {$tables['survey_maillist']}.survey_id GROUP BY {$tables['surveys']}.survey_id ORDER BY {$tables['surveys']}.orderby", "survey_id", false);
if (!empty($surveys)) {
    $surveys_completed = cw_query_hash("SELECT survey_id, COUNT(survey_result_id) as count_completed, MAX(date) as max_completed, MAX(CONCAT(date,'_',survey_result_id)) as code FROM {$tables['survey_results']} GROUP BY survey_id", "survey_id", false);
    foreach ($surveys as $sid => $s) {
        $surveys[$sid]['survey'] = cw_get_languages_alt("survey_name_" . $sid, false, true);
        if (isset($surveys_completed[$sid])) {
            $surveys[$sid]['max_completed'] = $surveys_completed[$sid]['max_completed'];
            $surveys[$sid]['count_completed'] = $surveys_completed[$sid]['count_completed'];
            $surveys[$sid]['last_survey_result_id'] = intval(preg_replace("/^\\d+_/S", "", $surveys_completed[$sid]['code']));
        }
    }
    unset($surveys_completed);
    $smarty->assign('surveys', $surveys);
}
$smarty->assign('survey_types', cw_get_survey_types());
function cw_config_advanced_search_attributes($custom_area = true)
{
    global $tables, $config, $current_language;
    $allowed_types = array('selectbox', 'text', 'textarea', 'decimal', 'multiple_selectbox', 'integer');
    $adv_search_attributes_config = $config['adv_search_attributes_config'];
    if (!empty($adv_search_attributes_config)) {
        $adv_search_attributes_config = unserialize($adv_search_attributes_config);
    }
    $adv_search_attributes = cw_query_hash("select at.*, lng.value as addon_name, 0 as orderby_adv_search, ad.active as addon_active from {$tables['attributes']} at left join {$tables['languages']} lng on lng.name=concat('addon_name_',at.addon)  and lng.code='" . (empty($current_language) ? 'EN' : $current_language) . "' left join {$tables['addons']} ad on ad.addon=at.addon where at.item_type='P' and at.type in ('" . implode("','", $allowed_types) . "') order by at.addon, at.orderby, at.field", 'attribute_id', false);
    if (!empty($adv_search_attributes_config)) {
        foreach ($adv_search_attributes_config as $attr_id => $attr_data) {
            if (empty($adv_search_attributes[$attr_id])) {
                continue;
            }
            $adv_search_attributes[$attr_id]['enabled_adv_search'] = $attr_data['enabled'];
            $adv_search_attributes[$attr_id]['orderby_adv_search'] = $attr_data['orderby'];
            $adv_search_attributes[$attr_id]['enabled_adv_search_more'] = $attr_data['enabled_more'];
        }
    }
    $count_numeric = 0;
    $count_text = 0;
    $count_multiselect = 0;
    if ($custom_area) {
        uasort($adv_search_attributes, 'cw_config_advanced_search_sort');
        $_adv_search_attributes = array();
        foreach ($adv_search_attributes as $attr_id => $attr_data) {
            if ($attr_data['enabled_adv_search'] || $attr_data['enabled_adv_search_more']) {
                $_adv_search_attributes[$attr_id] = $attr_data;
            }
            if (in_array($attr_data['type'], array('decimal', 'integer')) && $attr_data['enabled_adv_search_more']) {
                $count_numeric++;
            }
            if (in_array($attr_data['type'], array('selectbox', 'text', 'textarea', 'multiple_selectbox')) && $attr_data['enabled_adv_search']) {
                $count_text++;
            }
            if (in_array($attr_data['type'], array('selectbox', 'multiple_selectbox')) && $attr_data['enabled_adv_search_more']) {
                $count_multiselect++;
                $_adv_search_attributes[$attr_id]['options'] = cw_query("select * from {$tables['attributes_default']} where attribute_id='{$attr_id}' and active=1 order by value");
            }
        }
        $adv_search_attributes = $_adv_search_attributes;
    }
    return array('attributes' => $adv_search_attributes, 'count_numeric' => $count_numeric, 'count_text' => $count_text, 'count_multiselect' => $count_multiselect);
}
function cw_doc_get_relations_items($doc_id)
{
    global $tables;
    return cw_query_hash("select di.* from {$tables['docs_items']} as di where di.doc_id='{$doc_id}'", 'item_id', false);
}
function get_subscribers($list_id, $direct_only = null, $limit = null)
{
    global $tables;
    $direct_subscribers = $membership_subscribers = array();
    if (is_null($direct_only) || $direct_only === true) {
        $direct_subscribers = cw_query_hash("select email as hashkey, email, since_date, 1 as direct, '' as membership from {$tables['newslist_subscription']} WHERE list_id='{$list_id}' ORDER by email", 'hashkey', false, false);
    }
    if (is_null($direct_only) || $direct_only === false) {
        $mems = cw_query_column("select membership_id from {$tables['newslists_memberships']} where list_id='{$list_id}'");
        if (!count($mems)) {
            $mems = array(-1);
        }
        $membership_subscribers = cw_query_hash("select email as hashkey, email, 0 as since_date, 0 as direct, m.membership from {$tables['customers']} c LEFT JOIN {$tables['memberships']} m ON m.membership_id = c.membership_id WHERE c.membership_id IN (" . implode(', ', $mems) . ") ORDER by email", 'hashkey', false, false);
    }
    $result = array_merge($membership_subscribers, $direct_subscribers);
    ksort($result, SORT_STRING | SORT_FLAG_CASE);
    return $result;
}
function cw_clone_survey($survey_id)
{
    global $tables;
    if (!is_array($survey_id)) {
        $survey_id = array($survey_id);
    }
    $i = 0;
    foreach ($survey_id as $id) {
        $data = cw_query_first("SELECT * FROM {$tables['surveys']} WHERE survey_id = '{$id}'");
        if (empty($data)) {
            continue;
        }
        # Clone survey details
        unset($data['survey_id']);
        $data['survey_type'] = 'D';
        cw_addslashes($data);
        $newid = cw_array2insert("surveys", $data);
        if (!$newid) {
            continue;
        }
        # Clone survey multilanguage variables
        $vars = array("name", "header", "footer", "complete");
        foreach ($vars as $v) {
            $lang = cw_query_hash("SELECT code, value FROM {$tables['languages_alt']} WHERE name = 'survey_" . $v . "_" . $id . "'", "code", false, true);
            if (empty($lang)) {
                continue;
            }
            foreach ($lang as $c => $l) {
                if ($v == 'name') {
                    $l .= " (CLONE)";
                }
                cw_languages_alt_insert("survey_" . $v . "_" . $newid, addslashes($l), $c);
            }
        }
        # Clone survey questions
        $questions = cw_query_hash("SELECT * FROM {$tables['survey_questions']} WHERE survey_id = '{$id}'", "question_id", false);
        if (!empty($questions)) {
            foreach ($questions as $qid => $q) {
                $q = cw_addslashes($q);
                $q['survey_id'] = $newid;
                $newqid = cw_array2insert("survey_questions", $q);
                if (empty($newqid)) {
                    continue;
                }
                # Clone question names
                $lang = cw_query_hash("SELECT code, value FROM {$tables['languages_alt']} WHERE name = 'question_name_" . $qid . "'", "code", false, true);
                if (!empty($lang)) {
                    foreach ($lang as $c => $l) {
                        cw_languages_alt_insert("question_name_" . $newqid, addslashes($l), $c);
                    }
                }
                if ($q['answers_type'] == 'N') {
                    continue;
                }
                # Clone question answers
                $answers = cw_query_hash("SELECT * FROM {$tables['survey_answers']} WHERE question_id = '{$qid}'", "answer_id", false);
                if (empty($answers)) {
                    continue;
                }
                foreach ($answers as $aid => $a) {
                    $a = cw_addslashes($a);
                    $a['question_id'] = $newqid;
                    $newaid = cw_array2insert("survey_answers", $a);
                    if (empty($newaid)) {
                        continue;
                    }
                    # Clone answer names
                    $lang = cw_query_hash("SELECT code, value FROM {$tables['languages_alt']} WHERE name = 'answer_name_" . $aid . "'", "code", false, true);
                    if (!empty($lang)) {
                        foreach ($lang as $c => $l) {
                            cw_languages_alt_insert("answer_name_" . $newaid, addslashes($l), $c);
                        }
                    }
                }
            }
        }
        # Clone events
        $events = cw_query("SELECT * FROM {$tables['survey_events']} WHERE survey_id = '{$id}'");
        if (!empty($events)) {
            foreach ($events as $e) {
                $e['survey_id'] = $newid;
                cw_array2insert("survey_events", $e);
            }
        }
        $i++;
    }
    return $i;
}
 # / Delete all free added products
 $affected_product_ids = array("all" => false, "ids" => array());
 if (!empty($bonuses) and is_array($bonuses)) {
     $bonus_subindex = 0;
     for ($k = 0; $k < count($bonuses); $k++) {
         $b = $bonuses[$k];
         $bid = $b['bonusid'] . '.' . $bonus_subindex++;
         // Add subindex, e.g. 10->10.2
         # Pass the bonus if it's exclusive but some other bonuses already applied
         if ($b['exclusive'] == 'Y' && !empty($special_offers_apply['supply'])) {
             continue;
         }
         # save the current affected products in case the whole condition is not met
         $_affected_product_ids = $affected_product_ids;
         if (cw_special_offer_check($b['bonusid'])) {
             $current_bonus_supply = cw_query_hash("SELECT type, data FROM {$tables['bonus_supply']} WHERE bonusid='{$b['bonusid']}'", "type", false, true);
             $current_bonus_supply = array_map("unserialize", $current_bonus_supply);
             # Add applicable bonus info
             $special_offers_apply['supply'][$bid] = $current_bonus_supply;
             #
             # Prepare common array of supplies
             #
             $special_offers_apply['free_shipping']['method'] = cw_array_merge($special_offers_apply['free_shipping']['method'], $current_bonus_supply['S']['method']);
             if ($current_bonus_supply['S']['type'] == 'Y') {
                 $special_offers_apply['free_shipping']['type'] = 'Y';
             }
             if (in_array($current_bonus_supply['S']['type'], array('C', 'S')) && $special_offers_apply['free_shipping']['type'] != 'Y') {
                 $special_offers_apply['free_shipping']['type'] = $current_bonus_supply['S']['type'];
             }
             if ($current_bonus_supply['S']['type'] == 'C') {
                 foreach ($_affected_product_ids['ids'] as $pid => $qty) {
    if (!empty($where)) {
        $where_str = " AND " . implode(" AND ", $where);
    }
    $_res = db_query("SELECT COUNT({$tables['wishlist']}.wishlist_id) FROM {$tables['wishlist']}, {$tables['products']}, {$tables['customers']} WHERE {$tables['wishlist']}.product_id = {$tables['products']}.product_id AND {$tables['wishlist']}.customer_id={$tables['customers']}.customer_id" . $where_str . " GROUP BY {$tables['wishlist']}.customer_id");
    $total_items = db_num_rows($_res);
    db_free_result($_res);
    $navigation = cw_core_get_navigation($target, $total_items, $page);
    $navigation['script'] = "index.php?target=wishlists&mode=search";
    $smarty->assign('navigation', $navigation);
    $wishlists = cw_query("SELECT {$tables['wishlist']}.wishlist_id, {$tables['customers']}.*, COUNT({$tables['products']}.product_id) as products_count FROM {$tables['wishlist']}, {$tables['products']}, {$tables['customers']} WHERE {$tables['wishlist']}.product_id = {$tables['products']}.product_id AND {$tables['wishlist']}.customer_id={$tables['customers']}.customer_id" . $where_str . " GROUP BY {$tables['wishlist']}.customer_id LIMIT {$navigation['first_page']}, {$navigation['objects_per_page']}");
    if (!empty($wishlists)) {
        $ids = array();
        foreach ($wishlists as $v) {
            $ids[] = addslashes($v['customer_id']);
        }
        $counts = cw_query_hash("SELECT {$tables['wishlist']}.customer_id, COUNT({$tables['products']}.product_id) as products_count FROM {$tables['wishlist']}, {$tables['products']} WHERE {$tables['wishlist']}.product_id = {$tables['products']}.product_id AND {$tables['wishlist']}.customer_id IN ('" . implode("','", $ids) . "') GROUP BY {$tables['wishlist']}.customer_id", "customer_id", false, true);
        foreach ($wishlists as $k => $v) {
            $wishlists[$k]['products_count'] = intval($counts[$v['customer_id']]);
        }
        $smarty->assign('wishlists', $wishlists);
    }
    # Display wishlist
} elseif ($mode == "wishlist" && $customer) {
    $wishlist = cw_query("SELECT * FROM {$tables['wishlist']}, {$tables['products']}, {$tables['customers']} WHERE {$tables['wishlist']}.product_id = {$tables['products']}.product_id AND {$tables['wishlist']}.customer_id={$tables['customers']}.customer_id AND {$tables['wishlist']}.customer_id='{$customer}' ");
    if (empty($wishlist)) {
        cw_header_location("index.php?target=wishlists");
    }
    foreach ($wishlist as $k => $v) {
        if (!empty($v['options'])) {
            $v['options'] = unserialize($v['options']);
            list($variant, $v['product_options']) = cw_get_product_options_data($v['product_id'], $v['options'], $v['membership_id']);
    $location[] = array(cw_get_langvar_by_name('lbl_survey_surveys'), 'index.php?target=' . $target);
    $location[] = array(cw_get_langvar_by_name('lbl_survey_results'));
    $smarty->assign('current_main_dir', 'addons');
    $smarty->assign('current_section_dir', 'survey');
    $smarty->assign('main', 'view_results');
} else {
    # Get surveys list
    $now = time();
    $allow_ids = array();
    if (!empty($allowed_surveys) && is_array($allowed_surveys)) {
        $allow_ids = cw_array_merge($allow_ids, array_values($allowed_surveys));
    }
    if (!empty($filled_surveys) && is_array($filled_surveys)) {
        $allow_ids = cw_array_merge($allow_ids, $filled_surveys);
    }
    $surveys = cw_query_hash("SELECT {$tables['surveys']}.* FROM {$tables['surveys']}, {$tables['survey_questions']} WHERE {$tables['surveys']}.valid_from_date < {$now} AND {$tables['surveys']}.expires_data > {$now} AND {$tables['surveys']}.survey_id = {$tables['survey_questions']}.survey_id AND ({$tables['surveys']}.survey_type = 'P'" . (empty($customer_id) ? "" : " OR {$tables['surveys']}.survey_type = 'R'") . " OR ({$tables['surveys']}.survey_type = 'H' AND {$tables['surveys']}.survey_id IN ('" . implode("','", $allow_ids) . "'))) GROUP BY {$tables['surveys']}.survey_id ORDER BY {$tables['surveys']}.orderby", "survey_id", false);
    $count_surveys = 0;
    $count_filled = 0;
    if (!empty($surveys)) {
        foreach ($surveys as $sid => $v) {
            list($is_valid, $messages) = cw_check_survey($sid);
            if (!$is_valid) {
                unset($surveys[$sid]);
                continue;
            }
            $count_surveys++;
            if (cw_check_survey_filling($sid)) {
                $surveys[$sid]['is_filled'] = true;
                $count_filled++;
            }
            if (!empty($filled_surveys) && in_array($sid, $filled_surveys) && $v['publish_results'] == 'Y') {
function dashboard_section_system_info($params, $return = null)
{
    global $tables, $smarty;
    // Set the dashboard code name here
    $name = 'system_info';
    // If the section is disabled then skip it on dashboard
    if ($params['mode'] == 'dashboard' && $params['sections'][$name]['active'] === '0') {
        return $return;
    }
    // Define basic data for configuration
    $return[$name] = array('title' => 'System Information', 'description' => 'This is example of dashboard section explains how to build your own widget', 'active' => 1, 'pos' => 60, 'size' => 'small', 'frame' => 1, 'header' => 1);
    if ($params['mode'] == 'setting') {
        return $return;
    }
    // Add content for dashboard in 'dashboard' mode
    // Define either content or template name or both
    // Categories counter
    $cat_cnt = cw_query_first_cell("SELECT count(*) FROM {$tables['categories']}");
    $facet_cnt = cw_query_first_cell("SELECT count(*) FROM {$tables['clean_urls_custom_facet_urls']}");
    cw_system_messages_add('category_count', cw_get_langvar_by_name('lbl_category') . ' | ' . cw_get_langvar_by_name('lbl_facet_count') . ' - <a href="index.php?target=categories">' . $cat_cnt . '</a> | <a href="index.php?target=custom_facet_urls">' . $facet_cnt . '</a>', constant('SYSTEM_MESSAGE_SYSTEM'));
    // Products counter
    $product_cnt = cw_query_first_cell("SELECT count(*) FROM {$tables['products']}");
    cw_system_messages_add('product_count', cw_get_langvar_by_name('lbl_product_count') . ' -
	<a href="index.php?target=products&mode=search&new_search=1">' . $product_cnt . '</a>', constant('SYSTEM_MESSAGE_SYSTEM'));
    // Orders counter
    $order_cnt = cw_query_hash("SELECT status, count(*)  FROM {$tables['docs']} WHERE type='O' GROUP BY status", 'status', false, true);
    $msg = cw_get_langvar_by_name('lbl_order_count') . ' -';
    foreach ($order_cnt as $status => $count) {
        $msg .= ' <a href="index.php?target=docs_O&mode=search&data[status]=' . $status . '" class="order_' . $status . '" title="' . $status . '">&nbsp;' . $count . '&nbsp;</a>';
    }
    cw_system_messages_add('order_count', $msg, constant('SYSTEM_MESSAGE_SYSTEM'));
    // Customers counter
    $customer_cnt = cw_query_first_cell("SELECT count(*) FROM {$tables['customers']} WHERE usertype='C'");
    cw_system_messages_add('customer_count', cw_get_langvar_by_name('lbl_customer_count') . ' - 
	<a href="index.php?target=user_C&mode=search&new_search=1">' . $customer_cnt . '</a>', constant('SYSTEM_MESSAGE_SYSTEM'));
    // Mail counter
    $mail_cnt = cw_query_first_cell("SELECT count(*) FROM {$tables['mail_spool']} WHERE send=0");
    cw_system_messages_add('mail_count', cw_get_langvar_by_name('lbl_mail_queue') . ' - 
	<a href="index.php?target=mail_queue">' . $mail_cnt . '</a>', constant('SYSTEM_MESSAGE_SYSTEM'));
    // Sess counter
    $sess_cnt = cw_query_first_cell("SELECT count(*) FROM {$tables['sessions_data']} WHERE expiry>" . cw_core_get_time());
    cw_system_messages_add('session_count', cw_get_langvar_by_name('lbl_active_sessions') . ' - 
	<a href="index.php?target=sessions">' . $sess_cnt . '</a>', constant('SYSTEM_MESSAGE_SYSTEM'));
    cw_event('on_dashboard_system_info');
    // Handlers must add lines via cw_system_messages_add (type = SYSTEM_MESSAGE_SYSTEM)
    /*
     * GET SYSTEM MESSAGES
     */
    $system_messages = cw_system_messages(constant('SYSTEM_MESSAGE_SYSTEM'), true);
    $smarty->assign('system_info', $system_messages);
    $return[$name]['template'] = 'addons/dashboard/admin/sections/system_info.tpl';
    if (empty($system_messages)) {
        unset($return[$name]);
    }
    return $return;
}
function cw_user_get_salesmans_groups_for_register()
{
    global $tables, $current_language;
    $usertype = 'B';
    return cw_query_hash("select c.customer_id, c.customer_id, ca.firstname, ca.lastname, c.membership_id, IFNULL(ml.membership, m.membership) as membership from {$tables['customers']} as c left join {$tables['customers_addresses']} as ca on ca.customer_id=c.customer_id and ca.main=1, {$tables['memberships']} as m left join {$tables['memberships_lng']} as ml on ml.membership_id=m.membership_id and ml.code='{$current_language}' where m.membership_id=c.membership_id and c.usertype='{$usertype}' order by membership", array('membership'));
}
    }
    // Copy default fields setting for new membership
    db_query("INSERT INTO {$tables['register_fields_avails']} ( `field_id` , `area` , `is_avail` , `is_required` ) (\n    SELECT field_id, CONCAT(area, '_{$id}' ) , is_avail, is_required\n    FROM {$tables['register_fields_avails']}\n    WHERE area IN ('{$add['area']}', '#{$add['area']}')\n    )");
    cw_header_location("index.php?target={$target}");
}
if ($action == 'delete' && !empty($to_delete)) {
    cw_call('cw_user_delete_memberships', array($to_delete));
    cw_header_location("index.php?target={$target}");
}
$memberships = array();
$memberships['A'] = array();
$memberships['C'] = array();
$memberships['V'] = array();
$tmp = cw_query("SELECT {$tables['memberships']}.*, COUNT({$tables['customers']}.customer_id) as users, IFNULL({$tables['memberships_lng']}.membership, {$tables['memberships']}.membership) as membership FROM {$tables['memberships']} LEFT JOIN {$tables['customers']} ON {$tables['customers']}.membership_id = {$tables['memberships']}.membership_id LEFT JOIN {$tables['memberships_lng']} ON {$tables['memberships']}.membership_id = {$tables['memberships_lng']}.membership_id AND {$tables['memberships_lng']}.code = '{$edited_language}' GROUP BY {$tables['memberships']}.membership_id ORDER BY IF(FIELD({$tables['memberships']}.area, 'A','P','C','R','B','V') > 0, FIELD({$tables['memberships']}.area, 'A','P','C','R','B','V'), 100), {$tables['memberships']}.orderby");
if (!empty($tmp)) {
    foreach ($tmp as $v) {
        if (isset($memberships[$v['area']])) {
            $memberships[$v['area']][] = $v;
        }
    }
}
$memberships_lbls = array();
foreach ($memberships as $k => $v) {
    $memberships_lbls[$k] = cw_get_langvar_by_name('lbl_' . $k . '_membership_levels');
}
$no_membership = cw_query_hash("SELECT usertype, count(customer_id) as users FROM {$tables['customers']} WHERE membership_id = 0 GROUP BY usertype", 'usertype', false, true);
$smarty->assign('no_membership', $no_membership);
$smarty->assign('memberships', $memberships);
$smarty->assign('memberships_lbls', $memberships_lbls);
$location[] = array(cw_get_langvar_by_name('lbl_edit_membership_levels'), '');
$smarty->assign('main', 'memberships');
    $userinfo["b_zipcode"] = $userinfo["s_zipcode"] = $config["General"]["default_zipcode"];
    $userinfo["b_city"] = $userinfo["s_city"] = $config["General"]["default_city"];
    $userinfo["b_countryname"] = $userinfo["s_countryname"] = cw_get_country($userinfo["s_country"]);
    $userinfo["b_statename"] = $userinfo["s_statename"] = cw_get_state($userinfo["s_state"], $userinfo["s_country"]);
}
if (!empty($logged_userid)) {
    $userinfo = cw_userinfo($logged_userid, $current_area);
}
$where_statement = '';
$join_statement = '';
# Multidomain addon integration
if (!empty($domain_info)) {
    $join_statement = " LEFT JOIN {$tables['domain_bonuses']} ON {$tables['domain_bonuses']}.bonusid = b.bonusid AND {$tables['domain_bonuses']}.domainid = {$domain_info['domainid']}";
    $where_statement = " AND  {$tables['domain_bonuses']}.bonusid IS NOT NULL";
}
# / Multidomain addon integration
$user_bonuses = cw_query_hash("SELECT b.bonusid, b.*, IF(bl.bonus_name IS NOT NULL,bl.bonus_name,b.bonus_name) as bonus_name, bl.bonus_desc as bonus_desc, IF(bi.id IS NULL,'','Y') as is_image FROM {$tables['bonuses']} b LEFT JOIN {$tables['images_PS']} bi ON bi.id=b.bonusid LEFT JOIN {$tables['bonuses_lng']} bl ON b.bonusid=bl.bonusid AND bl.code='{$shop_language}' {$join_statement} WHERE b.bonus_active='Y' and b.start_date<UNIX_TIMESTAMP() and b.end_date>UNIX_TIMESTAMP() AND b.pid=0 {$where_statement} ORDER BY " . (empty($cat) ? 'pos' : 'priority'), 'bonusid', 0, 0);
if (!empty($user_bonuses)) {
    foreach ($user_bonuses as $_bid => $v) {
        $user_bonuses[$_bid]['bonusid'] = $_bid;
        if (!empty($logged_userid) || $config["General"]["apply_default_country"] == "Y") {
            if (!cw_check_condition_Z($_bid)) {
                unset($user_bonuses[$_bid]);
                continue;
            }
        }
    }
}
$user_bonuses_logged_userid = $logged_userid;
x_session_save('user_bonuses', 'user_bonuses_logged_userid');
// CartWorks.com - Promotion Suite
function cw_review_get_attribute_vote_values($review)
{
    global $tables;
    $rating_cond = $review['product_id'] > 0 ? "type='rating'" : "type='global_rating'";
    list($attributes, $nav) = cw_func_call('cw_attributes_search', array('data' => array('active' => 1, 'is_show' => 1, 'sort_field' => 'orderby')), array('where' => array($rating_cond)));
    $votes = array();
    if (!empty($attributes)) {
        $where = cw_review_get_where_query_by_settings($review['customer_id']);
        $rates = cw_query_hash("SELECT vote_value as vote, attribute_id FROM {$tables['products_votes']}\n          WHERE {$where} AND review_id='{$review['review_id']}' AND attribute_id IN ('" . join("','", array_column($attributes, 'attribute_id')) . "')", 'attribute_id', false, true);
        foreach ($attributes as $v) {
            $votes[$v['attribute_id']]['name'] = $v['name'];
            $votes[$v['attribute_id']]['vote'] = $rates[$v['attribute_id']];
        }
    }
    return $votes;
}
function cw_core_get_available_languages()
{
    global $tables, $current_language;
    return cw_query_hash("select ls.*, lng.value as language from {$tables['languages_settings']} as ls left join {$tables['languages']} as lng ON lng.code = '{$current_language}' and lng.name = CONCAT('language_', ls.code) where ls.enable=1", 'code', false);
}
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);
}