function cw_fbauth_user_login($user)
{
    global $tables, $current_area;
    cw_load('crypt', 'user', 'mail');
    $user_data = cw_query_first("SELECT customer_id, email, password\n\t\t\t\t\t\t\t\t\tFROM {$tables['customers']} \n\t\t\t\t\t\t\t\t\tWHERE oauth_uid='" . $user['id'] . "' AND oauth_type='F'  \n\t\t\t\t\t\t\t\t\t\tAND usertype='" . $current_area . "' \n\t\t\t\t\t\t\t\t\t\tAND status='Y'");
    if (!empty($user_data)) {
        // login user
        global $email, $password, $action;
        $email = $user_data['email'];
        $password = text_decrypt($user_data['password']);
        $action = 'login';
        cw_include('include/login.php');
    } else {
        // create user
        $register = array();
        $register['email'] = $user['email'];
        if (strpos($user['email'], "proxymail.facebook.com") !== FALSE) {
            cw_header_location("index.php?target=fb_auth_get_email", TRUE);
        }
        $register['password'] = $register['password2'] = md5(uniqid('cw_', TRUE), TRUE);
        $register['usertype'] = $current_area;
        $partner_membership =& cw_session_register('partner_membership');
        $register['membership_id'] = $partner_membership;
        $customer_id = cw_user_create_profile($register);
        $identifiers =& cw_session_register('identifiers', array());
        $identifiers[$current_area] = array('customer_id' => $customer_id);
        $customer = array('oauth_uid' => $user['id']);
        cw_array2update('customers', $customer, "customer_id='{$customer_id}'");
        $address = array('main' => 1, 'firstname' => $user['first_name'], 'lastname' => $user['last_name']);
        $additional_info = array('sex' => $user['gender'] == 'male' ? 1 : 0);
        $userinfo = array('addresses' => $address, 'additional_info' => $additional_info);
        cw_user_update($userinfo, $customer_id, $customer_id);
        cw_user_send_modification_mail($customer_id, TRUE);
    }
}
function cw_get_salesman_order($doc_id)
{
    global $tables;
    $obj = cw_query_first("select * from {$tables['salesman_orders']} where id='{$doc_id}'");
    $obj['products'] = unserialize($obj['cart']);
    return $obj;
}
function cw_pos_get_doc_info($doc_info_id) {
    global $tables;

    $ret = cw_query_first("select * from $tables[docs_pos_info] where doc_info_id='$doc_info_id'");
    $ret['pos_user_info'] = cw_pos_user_info($ret['pos_customer_id']);
    return $ret;
}
function cw_session_id($sess_id = "")
{
    global $tables, $APP_SESSION_VARS, $APP_SESS_ID, $APP_SESSION_UNPACKED_VARS;
    $APP_SESSION_VARS = array();
    if ($sess_id) {
        $sess_data = cw_query_first("SELECT * FROM {$tables['sessions_data']} WHERE sess_id='{$sess_id}'");
        $APP_SESS_ID = $sess_id;
        if ($sess_data) {
            $APP_SESSION_VARS = unserialize($sess_data['data']);
            if (!empty($APP_SESSION_UNPACKED_VARS)) {
                foreach ($APP_SESSION_UNPACKED_VARS as $var => $v) {
                    if (isset($GLOBALS[$var])) {
                        unset($GLOBALS[$var]);
                    }
                    unset($APP_SESSION_UNPACKED_VARS[$var]);
                }
            }
        } else {
            cw_session_start($sess_id);
        }
    } else {
        $sess_id = $APP_SESS_ID;
    }
    return $sess_id;
}
function cw_ean_get_product_info($ean)
{
    global $tables, $config, $addons;
    if (empty($ean)) {
        return array();
    }
    cw_ean_clear($ean);
    $where = array();
    if (in_array(1, $config['pos']['fields_for_ean'])) {
        $where[] = "productcode='{$ean}'";
    }
    if (in_array(0, $config['pos']['fields_for_ean'])) {
        $where[] = "eancode='{$ean}'";
    }
    if (!count($where)) {
        $where[] = "eancode='{$ean}'";
    }
    $where = implode(' or ', $where);
    $product_info = array();
    # kornev, TOFIX
    if ($addons['product_options']) {
        $product_info = cw_query_first("select product_id, variant_id from {$tables['product_variants']} where {$where}");
    }
    if (!$product_info['product_id']) {
        $product_info = cw_query_first("select product_id, 0 as variant_id from {$tables['products']} where {$where}");
    }
    if (!$product_info['product_id'] && in_array(2, $config['pos']['fields_for_ean'])) {
        $product_info = cw_query_first("select product_id, variant_id from {$tables['products_supplied_amount']} where productcode='{$ean}'");
    }
    if (!$product_info['product_id'] && in_array(3, $config['pos']['fields_for_ean']) && $addons['sn']) {
        $product_info = cw_query_first("select product_id, 0 as variant_id from {$tables['serial_numbers']} where sn='{$ean}'");
    }
    return $product_info;
}
function cw_in_images_get_image_info($image_id, $title)
{
    global $tables;
    $tmp = cw_query_first("select * from {$tables['webmaster_images']} where id='{$image_id}'");
    $tmp = cw_image_info('webmaster_images', $tmp);
    $tmp['id'] = $image_id;
    $tmp['title'] = cw_get_langvar_by_name('image_' . $title);
    return $tmp;
}
function cw_file_get_doc($type, $file_id)
{
    global $tables;
    if (!$tables[$type]) {
        return false;
    }
    $file = cw_query_first("select * from " . $tables[$type] . " where file_id='{$file_id}'");
    return cw_file_get_info($type, $file);
}
function cw_check_confirmation($confirmation_code)
{
    global $tables;
    if ($return = cw_query_first("SELECT reg_id, event_id, 'Y' as status FROM {$tables['giftreg_maillist']} WHERE MD5(CONCAT(confirmation_code,'_confirmed'))='{$confirmation_code}'")) {
        return $return;
    } elseif ($return = cw_query_first("SELECT reg_id, event_id, 'N' as status FROM {$tables['giftreg_maillist']} WHERE MD5(CONCAT(confirmation_code,'_declined'))='{$confirmation_code}'")) {
        return $return;
    }
    return false;
}
function cw_on_warehouse_recalculate($product_id)
{
    global $tables;
    if (cw_product_has_variants($product_id)) {
        $to_update = cw_query_first("select sum(avail) as avail, sum(avail_ordered) as avail_ordered, sum(avail_sold) as avail_sold, sum(avail_reserved) as avail_reserved from {$tables['products_warehouses_amount']} where product_id='{$product_id}' and warehouse_customer_id = 0 and variant_id != 0");
        $to_update['warehouse_customer_id'] = 0;
        $to_update['product_id'] = $product_id;
        $to_update['variant_id'] = 0;
        cw_call('cw_warehouse_insert_avail', array('insert' => $to_update));
    }
}
function dashboard_action_setting()
{
    global $smarty, $tables;
    $params = array('mode' => 'setting', 'sections' => null);
    $dashboard = cw_func_call('dashboard_build_sections', $params);
    foreach ($dashboard as $name => $dash) {
        $dashboard[$name] = array_merge($dashboard[$name], cw_query_first('SELECT * FROM ' . $tables['dashboard'] . ' WHERE name="' . mysql_real_escape_string($name) . '"'));
    }
    uasort($dashboard, 'cw_uasort_by_order');
    $smarty->assign('dashboard', $dashboard);
}
function cw_flexible_import_get_profile($params)
{
    global $tables;
    extract($params);
    $profile = cw_query_first("SELECT * FROM {$tables['flexible_import_profiles']} WHERE id = {$id}");
    $options = @unserialize($profile['options']);
    if (empty($options)) {
        $options = unserialize(base64_decode($profile['options']));
        $options = json_decode(stripslashes(json_encode($options)), true);
    }
    unset($profile['options']);
    $result = array_merge($profile, $options);
    return $result;
}
/**
 * Optimize table, try to analyze for InnoDB
 * 
 * @return array of strings with mysql replies
 */
function cw_cron_optimize_table($time, $prev_time)
{
    $return = array();
    $tbls = cw_query_column("SHOW TABLES");
    foreach ($tbls as $t) {
        $m = cw_query_first("OPTIMIZE TABLE {$t}");
        $return[] = join(' | ', $m);
        if ($m['Msg_type'] != 'status') {
            $m = cw_query_first("ANALYZE TABLE {$t}");
            $return[] = join(' | ', $m);
        }
    }
    return $return;
}
function cw_system_messages_add($code, $msg, $type = SYSTEM_MESSAGE_COMMON, $severity = SYSTEM_MESSAGE_INFO)
{
    global $tables;
    $code = mysql_real_escape_string($code);
    $msg = mysql_real_escape_string($msg);
    $type = intval($type);
    $existing = cw_query_first("SELECT code, hidden FROM {$tables['system_messages']} WHERE code='{$code}'");
    $data = array('date' => cw_core_get_time(), 'message' => $msg, 'type' => $type, 'severity' => $severity);
    if ($existing) {
        $ret = cw_array2update('system_messages', $data, "code='{$code}'");
    } else {
        $data['code'] = $code;
        $data['hidden'] = 0;
        $ret = cw_array2insert('system_messages', $data);
    }
    return $ret;
}
function cw_mobile_get_domain_data()
{
    global $tables, $HTTPS, $app_dir;
    $current_domain = cw_session_register('current_domain', -1);
    $mobile_mobile_flag = cw_session_register('mobile_mobile_flag');
    if (is_numeric($current_domain) && $current_domain > 0 && !empty($tables['domains'])) {
        $domain = cw_query_first("SELECT * FROM {$tables['domains']} WHERE domain_id = " . $current_domain);
        $domain['mobile_host'] = cw_mobile_get_mobile_host_attr_by_domain_id($current_domain);
        if (($mobile_mobile_flag == 'on' && $_GET['mobile_version'] != 'off' || $_GET['mobile_version'] == 'on' || $mobile_mobile_flag != 'on' && !empty($domain['mobile_host']) && $domain['mobile_host'] == cw_mobile_get_host()) && is_dir($app_dir . $domain['skin'] . mobile_addon_skin_prefix)) {
            $domain['skin'] .= mobile_addon_skin_prefix;
        }
        return $domain;
    }
    $host_value = cw_mobile_get_host();
    $result = cw_mobile_get_domain_by_mobile_host_attr($host_value);
    return $result;
}
function cw_web_get_layout_inner($sql)
{
    global $tables, $smarty, $top_message;
    $data = cw_query_first("select * from {$tables['layouts']} where {$sql}");
    $data['data'] = unserialize($data['data']);
    $smarty->assign('layout', $data);
    $templates = cw_query("select * from {$tables['layouts_templates']} where layout_id='{$data['layout_id']}' order by orderby");
    if (is_array($templates)) {
        foreach ($templates as $template) {
            $template['content'] = cw_display($template['template'], $smarty, false);
            preg_match_all('/id[ ]*=[ ]*"(.*)"/Uims', $template['content'], $out);
            $template['sub_ids'] = $out[1];
            $data['parts'][] = $template;
        }
    }
    unset($smarty->_included_files);
    $data['elements'] = cw_query("select le.* from {$tables['layouts_elements']} as le where le.layout_id='{$data['layout_id']}' and display='none'");
    return $data;
}
function cw_copy_class($product_option_id, $product_id = false)
{
    global $tables, $ge_id;
    $data['class'] = cw_query_first("SELECT * FROM {$tables['product_options']} WHERE product_option_id = '{$product_option_id}'");
    $data['product_options_values'] = cw_query("SELECT * FROM {$tables['product_options_values']} WHERE product_option_id = '{$product_option_id}'");
    $data['product_options_lng'] = cw_query("select * from {$tables['product_options_lng']} where product_option_id = '{$product_option_id}'");
    $data['product_options_values_lng'] = cw_query("SELECT {$tables['product_options_values_lng']}.* FROM {$tables['product_options_values_lng']}, {$tables['product_options_values']} WHERE {$tables['product_options_values_lng']}.option_id = {$tables['product_options_values']}.option_id AND {$tables['product_options_values']}.product_option_id = '{$product_option_id}'");
    if (empty($product_id)) {
        while ($pid = cw_group_edit_each($ge_id, 1, $product_id)) {
            cw_add_class_data($data, $pid);
        }
    } else {
        if (!is_array($product_id)) {
            $product_id = array($product_id);
        }
        foreach ($product_id as $pid) {
            cw_add_class_data($data, $pid);
        }
    }
}
function cw_breadcrumbs_get_breadcrumbs($link, $query_link)
{
    global $tables;
    $breadcrumbs = array();
    preg_match('/[0-9]+/', $query_link, $matches_id);
    $breadcrumb = cw_breadcrumbs_get_breadcrumb($link, $query_link, "AND b.parent_id <> -1");
    if (!empty($breadcrumb)) {
        $all_get_breadcrumb_links = array();
        // for stop while if has some problem
        while ($breadcrumb['parent_id'] != 0 && !in_array($breadcrumb['link'], $all_get_breadcrumb_links)) {
            array_unshift($breadcrumbs, $breadcrumb);
            $all_get_breadcrumb_links[] = $breadcrumb['link'];
            $breadcrumb = cw_query_first("\n                SELECT b.*\n                FROM {$tables['breadcrumbs']} b\n                LEFT JOIN {$tables['addons']} as a ON a.addon = b.addon\n                WHERE (a.active OR a.addon IS NULL) AND b.breadcrumb_id = '{$breadcrumb['parent_id']}' AND b.parent_id <> -1\n            ");
            if (!empty($matches_id) && is_numeric($matches_id[0])) {
                $breadcrumb['link'] = str_replace('[[ANY]]', $matches_id[0], $breadcrumb['link']);
            }
        }
        array_unshift($breadcrumbs, $breadcrumb);
    }
    return $breadcrumbs;
}
<?php

global $product_id;
if ($mode == 'wishlist') {
    $tmp = cw_query_first("SELECT product_id, amount FROM {$tables['wishlist']} WHERE wishlist_id = '{$id}' AND event_id = '{$eventid}'");
    $product_id = $tmp['product_id'];
    $min_avail = $tmp['amount'];
} else {
    $cart =& cw_session_register('cart', array());
    if (is_array($cart['products'])) {
        foreach ($cart['products'] as $k => $p) {
            if ($p['cartid'] == $id) {
                $cartindex = $k;
                break;
            }
        }
    }
    if (isset($cartindex)) {
        $product_id = $cart['products'][$cartindex]['product_id'];
        # kornev, we will need to alert customer if the stock of some option is less then current amount
        $min_avail = $cart['products'][$cartindex]['amount'];
    }
}
if (empty($product_id)) {
    cw_close_window();
}
if (!$eventid) {
    $eventid = '0';
}
if ($mode == 'wishlist') {
    $options = unserialize(cw_query_first_cell("SELECT options FROM {$tables['wishlist']} WHERE wishlist_id = '{$id}' AND event_id = '{$eventid}'"));
         cw_header_location($instagram_redirect_url);
     }
 } else {
     //add new customer to database
     $register = array();
     $register['email'] = $instagram_email;
     $register['usertype'] = $current_area;
     $partner_membership =& cw_session_register('partner_membership');
     $register['membership_id'] = $partner_membership;
     $customer_id = cw_user_create_profile($register);
     cw_array2update('customers', array('oauth_uid' => $instagram_user_id, 'oauth_type' => 'I'), "customer_id='{$customer_id}'");
     $user_name = explode(" ", $instagram_user_name);
     $address = array('main' => 1, 'firstname' => $user_name[0], 'lastname' => $user_name[1]);
     $userinfo = array('addresses' => $address);
     cw_user_update($userinfo, $customer_id, $customer_id);
     $user_data = cw_query_first("SELECT {$tables['customers']}.* FROM {$tables['customers']} WHERE customer_id='{$customer_id}'");
 }
 if (!empty($user_data)) {
     //perform login
     $email = $user_data['email'];
     if ($usertype == 'R') {
         $usertype = 'C';
         $product_list_template =& cw_session_register("product_list_template");
         $product_list_template = 2;
     }
     $identifiers[$current_area == 'R' ? 'C' : $current_area] = array('customer_id' => $user_data['customer_id']);
     $customer_id = $user_data['customer_id'];
     if (in_array($current_area, array("C", "R"))) {
         cw_session_register("login_redirect");
         $login_redirect = 1;
     }
function cw_salesman_get_customer($customer_id)
{
    global $tables;
    return cw_query_first("select p.* from {$tables['customers']} as p, {$tables['customers_salesman_info']} as csi where p.customer_id=csi.parent_customer_id and csi.customer_id='{$customer_id}'");
}
function cw_faq_get_main($rubrik_id)
{
    global $tables;
    return cw_query_first("select c.* FROM {$tables['faq_rubrik']} as c, {$tables['faq_rubrik_parents']} as cp where cp.rubrik_id='{$rubrik_id}' and cp.level=0 and c.rubrik_id=cp.parent_rubrik_id order by cp.level");
}
function cw_ups_check_shipping_id($shipping_id)
{
    global $tables;
    $shipping = cw_query_first("SELECT * FROM {$tables['shipping']} WHERE code = 'UPS' AND shipping_id = '" . $shipping_id . "'");
    if (empty($shipping)) {
        return false;
    }
    $service_type = false;
    switch ($shipping['shipping']) {
        case 'UPS Ground':
            $service_type = 'Ground';
            break;
        case 'UPS 3 Day Select##SM##':
            $service_type = '3 Day Select';
            break;
        case 'UPS 2nd Day Air##R##':
            $service_type = '2nd Day Air';
            break;
        case 'UPS 2nd Day Air A.M.##R##':
            $service_type = '2nd Day Air AM';
            break;
        case 'UPS Next Day Air Saver##R##':
            $service_type = 'Next Day Air Saver';
            break;
        case 'UPS Next Day Air##R##':
            $service_type = 'Next Day Air';
            break;
        case 'UPS Next Day Air##R## Early A.M.##R##':
            $service_type = 'Next Day Air Early AM';
            break;
        case 'UPS Worldwide Express Plus##SM##':
            $service_type = 'Worlwide Express Plus';
            break;
        case 'UPS Worldwide Express##SM##':
            $service_type = 'Worlwide Express';
            break;
        case 'UPS Worldwide Expedited##SM##':
            $service_type = 'Worlwide Expedited';
            break;
    }
    return $service_type;
}
function cw_dod_generate()
{
    global $tables, $config, $current_language;
    $generator = cw_query_first("select * from {$tables['dod_generators']} where active=1 and startdate<='" . time() . "' and enddate>'" . time() . "'  and dod_interval<>0 order by position asc, generator_id asc");
    if (!empty($generator)) {
        //check last generation date
        $last_gen_date = $generator['current_offer_date'];
        $hrs_since_last_generation = intval((time() - $last_gen_date) / 3600);
        $generate_again = false;
        if ($generator['dod_interval_type'] == 'D') {
            $generate_again = $hrs_since_last_generation >= $generator['dod_interval'] * 24;
            $offer_enddate = min($generator['enddate'], time() + $generator['dod_interval'] * 24 * 3600);
        } elseif ($generator['dod_interval_type'] == 'T') {
            $dod_period_hrs = intval(($generator['enddate'] - $generator['startdate']) / 3600);
            $hrs_interval = intval($dod_period_hrs / $generator['dod_interval']);
            $generate_again = $hrs_since_last_generation >= $hrs_interval;
            $offer_enddate = min($generator['enddate'], time() + $dod_period_hrs / $generator['dod_interval'] * 3600);
        }
        if ($generate_again || $_GET['force_generate']) {
            if (!empty($generator['used_pids'])) {
                $used_pids = explode(';', $generator['used_pids']);
            } else {
                $used_pids = array();
            }
            $dod_products = cw_query_column("select dbd.object_id from {$tables['dod_bonus_details']} dbd inner join {$tables['dod_bonuses']} db on db.generator_id=dbd.generator_id and db.bonus_id=dbd.bonus_id and db.type='" . DOD_DISCOUNT . "' where dbd.generator_id='{$generator['generator_id']}' and dbd.object_type='" . DOD_OBJ_TYPE_PRODS . "'");
            $dod_categories = cw_query_column("select dbd.object_id from {$tables['dod_bonus_details']} dbd inner join {$tables['dod_bonuses']} db on db.generator_id=dbd.generator_id and db.bonus_id=dbd.bonus_id and db.type='" . DOD_DISCOUNT . "' where dbd.generator_id='{$generator['generator_id']}' and dbd.object_type='" . DOD_OBJ_TYPE_CATS . "'");
            $dod_manufacturers = cw_query_column("select dbd.object_id from {$tables['dod_bonus_details']} dbd inner join {$tables['dod_bonuses']} db on db.generator_id=dbd.generator_id and db.bonus_id=dbd.bonus_id and db.type='" . DOD_DISCOUNT . "' where dbd.generator_id='{$generator['generator_id']}' and dbd.object_type='" . DOD_OBJ_TYPE_MANS . "'");
            $dod_attributes = cw_query("select dbd.*  from {$tables['dod_bonus_details']} dbd inner join {$tables['dod_bonuses']} db on db.generator_id=dbd.generator_id and db.bonus_id=dbd.bonus_id and db.type='" . DOD_DISCOUNT . "' where dbd.generator_id='{$generator['generator_id']}' and dbd.object_type='" . DOD_OBJ_TYPE_ATTR . "'");
            //select products by dod conditions
            $data = array();
            $dod_data_where_pids = '';
            if ($dod_products) {
                $dod_data_where_pids = "{$tables['products']}.product_id in ('" . implode("','", $dod_products) . "')";
            }
            if ($dod_categories) {
                $data['search_in_subcategories'] = 1;
                $data['category_ids'] = $dod_categories;
            }
            if ($dod_manufacturers) {
                $manufacturer_id_attribute = cw_query_first_cell("select attribute_id from {$tables['attributes']} where field='manufacturer_id' and addon='manufacturers'");
                if ($manufacturer_id_attribute) {
                    if (!isset($ret_params)) {
                        $ret_params = array();
                    }
                    if (!isset($ret_params['query_joins'])) {
                        $ret_params['query_joins'] = array();
                    }
                    $ret_params['query_joins']['atv_manufacturer'] = array('tblname' => 'attributes_values', 'on' => "{$tables['products']}.product_id=atv_manufacturer.item_id and atv_manufacturer.item_type='P' and atv_manufacturer.attribute_id = '{$manufacturer_id_attribute}' and atv_manufacturer.code in ('{$current_language}', '') and atv_manufacturer.value in ('" . implode("','", $dod_manufacturers) . "')", 'is_inner' => 1);
                }
            }
            if ($dod_attributes) {
                $param2_sql = array('eq' => '=', 'lt' => '<', 'le' => '<=', 'gt' => '>', 'ge' => '=>');
                foreach ($dod_attributes as $attr_data_k => $attr_data) {
                    $is_def_values = cw_query_first("select * from {$tables['attributes_default']} where attribute_value_id='{$attr_data['param1']}' and attribute_id='{$attr_data['object_id']}'");
                    //print_r($is_def_values);print("<br><br>");
                    $sql_operation = $param2_sql[$attr_data['param2']];
                    if (empty($sql_operation)) {
                        continue;
                    }
                    if (!isset($ret_params)) {
                        $ret_params = array();
                    }
                    if (!isset($ret_params['query_joins'])) {
                        $ret_params['query_joins'] = array();
                    }
                    if ($is_def_values) {
                        $ret_params['query_joins']['atv_dod_' . $attr_data_k] = array('tblname' => 'attributes_values', 'on' => "{$tables['products']}.product_id=atv_dod_{$attr_data_k}.item_id and atv_dod_{$attr_data_k}.item_type='P' and atv_dod_{$attr_data_k}.attribute_id = '{$attr_data['object_id']}' and atv_dod_{$attr_data_k}.code in ('{$current_language}', '')", 'is_inner' => 1);
                        $ret_params['query_joins']['atd_dod_' . $attr_data_k] = array('tblname' => 'attributes_default', 'on' => "atd_dod_{$attr_data_k}.attribute_value_id=atv_dod_{$attr_data_k}.value and atv_dod_{$attr_data_k}.attribute_id=atd_dod_{$attr_data_k}.attribute_id and atd_dod_{$attr_data_k}.value{$sql_operation}'" . addslashes($is_def_values['value']) . "'", 'is_inner' => 1);
                    } else {
                        $ret_params['query_joins']['atv_dod_' . $attr_data_k] = array('tblname' => 'attributes_values', 'on' => "{$tables['products']}.product_id=atv_dod_{$attr_data_k}.item_id and atv_dod_{$attr_data_k}.item_type='P' and atv_dod_{$attr_data_k}.attribute_id = '{$attr_data['object_id']}' and atv_dod_{$attr_data_k}.code in ('{$current_language}', '') and atv_dod_{$attr_data_k}.value{$sql_operation}'{$attr_data['param1']}'", 'is_inner' => 1);
                    }
                }
            }
            global $user_account, $current_area, $items_per_page_targets, $target;
            $items_per_page_targets[$target] = 1;
            $new_pid = 0;
            $safety_cnt = 1000;
            while (!$new_pid && $safety_cnt > 0) {
                if (!empty($data) || !empty($dod_data_where_pids)) {
                    $data['sort_field'] = 'rand';
                    $data['flat_search'] = 1;
                    $dod_data_where = array();
                    if (!empty($dod_data_where_pids)) {
                        $dod_data_where[] = $dod_data_where_pids;
                    }
                    if (!empty($used_pids)) {
                        $dod_data_where[] = "{$tables['products']}.product_id not in ('" . implode("','", $used_pids) . "')";
                    }
                    $data['where'] = implode(' and ', $dod_data_where);
                    list($products, $nav, $product_filter) = cw_func_call('cw_product_search', array('data' => $data, 'user_account' => $user_account, 'current_area' => $current_area, 'info_type' => 8, 'product_id_only' => 1), $ret_params);
                }
                $product = reset($products);
                //print_r(array('product'=>$product));print("<br><br>");
                $new_pid = $product['product_id'];
                if (!$new_pid) {
                    if ($generator['no_item_repeat']) {
                        break;
                    } else {
                        if (!empty($used_pids)) {
                            array_shift($used_pids);
                        } else {
                            break;
                        }
                    }
                }
                $safety_cnt--;
            }
            //die;
            if ($new_pid) {
                $used_pids[] = $new_pid;
            }
            $generator['used_pids'] = implode(';', $used_pids);
            $regenerate_offer = true;
            if ($regenerate_offer) {
                //regenerate offer
                if (!empty($generator['current_offer_id'])) {
                    $offer_ids = array($generator['current_offer_id']);
                    $offer_ids_query = implode("', '", $offer_ids);
                    db_query("DELETE FROM {$tables['ps_offers']} WHERE offer_id IN ('" . $offer_ids_query . "')");
                    db_query("DELETE FROM {$tables['ps_bonuses']} WHERE offer_id IN ('" . $offer_ids_query . "')");
                    db_query("DELETE FROM {$tables['ps_bonus_details']} WHERE offer_id IN ('" . $offer_ids_query . "')");
                    db_query("DELETE FROM {$tables['ps_conditions']} WHERE offer_id IN ('" . $offer_ids_query . "')");
                    db_query("DELETE FROM {$tables['ps_cond_details']} WHERE offer_id IN ('" . $offer_ids_query . "')");
                    db_query("DELETE FROM {$tables['attributes_values']} WHERE item_id IN ('" . $offer_ids_query . "') and item_type='PS'");
                    foreach ($offer_ids as $offer_id) {
                        cw_image_delete($offer_id, PS_IMG_TYPE);
                    }
                    cw_attributes_cleanup($offer_ids, PS_ATTR_ITEM_TYPE);
                    cw_cache_clean('shipping_rates');
                }
                if ($new_pid) {
                    cw_log_add('dod_generator', array('new DOD product selected' => $new_pid));
                    $new_offer_id = cw_array2insert('ps_offers', array('title' => 'Deal Of The Day', 'description' => $generator['description'], 'startdate' => time(), 'enddate' => $offer_enddate, 'active' => 1));
                }
                $current_offer_id = 0;
                if ($new_offer_id) {
                    $mdm_attribute_id = cw_query_first_cell("select attribute_id from {$tables['attributes']} where addon='multi_domains' and item_type='PS'");
                    if ($mdm_attribute_id) {
                        cw_array2insert('attributes_values', array('item_id' => $new_offer_id, 'attribute_id' => $mdm_attribute_id, 'value' => 0, 'code' => '', 'item_type' => 'PS'));
                    }
                    //copy bonus and bonus details
                    $dod_bonuses = cw_query("select * from {$tables['dod_bonuses']} where generator_id='{$generator['generator_id']}' and unused=0");
                    foreach ($dod_bonuses as $dod_bonus) {
                        $_dod_bonus = $dod_bonus;
                        unset($_dod_bonus['generator_id']);
                        $_dod_bonus['offer_id'] = $new_offer_id;
                        $new_bonus_id = cw_array2insert('ps_bonuses', $_dod_bonus);
                        if ($_dod_bonus['type'] == 'D' && $_dod_bonus['apply'] == 3) {
                            cw_array2insert('ps_bonus_details', array('bonus_id' => $new_bonus_id, 'offer_id' => $new_offer_id, 'object_id' => $new_pid, 'quantity' => 1, 'object_type' => DOD_OBJ_TYPE_PRODS));
                        } else {
                            $dod_bonus_details = cw_query("select * from {$tables['dod_bonus_details']} where generator_id='{$generator['generator_id']}' and bonus_id='{$dod_bonus['bonus_id']}'");
                            if (!empty($dod_bonus_details)) {
                                foreach ($dod_bonus_details as $dod_bonus_detail) {
                                    $_dod_bonus_detail = $dod_bonus_detail;
                                    unset($_dod_bonus_detail['generator_id']);
                                    $_dod_bonus_detail['offer_id'] = $new_offer_id;
                                    $_dod_bonus_detail['bonus_id'] = $new_bonus_id;
                                    cw_array2insert('ps_bonus_details', $_dod_bonus_detail);
                                }
                            }
                        }
                    }
                    $new_cond_id = cw_array2insert('ps_conditions', array('type' => 'P', 'total' => '0.00', 'offer_id' => $new_offer_id));
                    if ($new_cond_id) {
                        cw_array2insert('ps_cond_details', array('cond_id' => $new_cond_id, 'offer_id' => $new_offer_id, 'object_id' => $new_pid, 'quantity' => 1, 'object_type' => DOD_OBJ_TYPE_PRODS));
                    }
                    $current_offer_id = $new_offer_id;
                }
            }
            //update dod_generator fields
            cw_array2update('dod_generators', array('current_offer_id' => $current_offer_id, 'used_pids' => $generator['used_pids'], 'current_offer_date' => $current_offer_id ? time() : 0), "generator_id='{$generator['generator_id']}'");
            if ($current_offer_id && !empty($config['deal_of_day']['dod_news_template']) && $config['deal_of_day']['dod_newslist']) {
                $newslist = cw_query_first("select * from {$tables['newslists']} where list_id='" . $config['deal_of_day']['dod_newslist'] . "' and avail=1");
                if (!empty($newslist)) {
                    //create message
                    global $smarty;
                    $smarty->assign('promotion', $generator);
                    $smarty->assign('product_id', $new_pid);
                    $product_info = cw_func_call('cw_product_get', array('id' => $new_pid, 'user_account' => $user_account, 'info_type' => 65535));
                    $smarty->assign('product', $product_info);
                    $smarty->assign('news_message', $config['deal_of_day']['dod_news_template']);
                    $message = cw_display("addons/deal_of_day/admin/generate_news.tpl", $smarty, false, $newslist['lngcode']);
                    $smarty->assign('news_message', $config['deal_of_day']['dod_news_template_subject']);
                    $message_subject = cw_display("addons/deal_of_day/admin/generate_news.tpl", $smarty, false, $newslist['lngcode']);
                    //                    $message = $smarty->display('addons/deal_of_day/admin/generate_news.tpl');
                    print $message_subject . "<hr />" . $message;
                    if (!empty($message)) {
                        cw_array2insert('newsletter', array('subject' => $message_subject, 'body' => $message, 'created_date' => time(), 'send_date' => time(), 'updated_date' => time(), 'status' => 'N', 'list_id' => $config['deal_of_day']['dod_newslist'], 'show_as_news' => 1, 'allow_html' => 1));
                    }
                }
            }
        }
    }
    return $new_pid;
}
     $smarty->assign('list', $list);
     # subscribers tabs
     $total_items = count($subscribers = cw_call('cw\\news\\get_subscribers', array($list_id)));
     if (!empty($total_items)) {
         $navigation = cw_core_get_navigation($target, $total_items, $page);
         $navigation['script'] = "index.php?target={$target}&js_tab=subscriptions&list_id=" . $list_id;
         $smarty->assign('navigation', $navigation);
         $subscribers = array_slice($subscribers, $navigation['first_page'], $navigation['objects_per_page']);
     }
     $smarty->assign('subscribers', $subscribers);
     # messages tab
     cw_load('map');
     $countries = cw_map_get_countries();
     $smarty->assign('countries', $countries);
     if (isset($messageid)) {
         $message = cw_query_first("SELECT * FROM {$tables['newsletter']} WHERE news_id='{$messageid}'");
         $countries = cw_query("select * from {$tables['newsletter_countries']} where news_id='{$messageid}'");
         if (is_array($countries)) {
             foreach ($countries as $val) {
                 $message['countries'][$val['code']] = true;
             }
         }
         $smarty->assign('message', $message);
         $smarty->assign('messageid', $messageid);
     }
     $messages = cw_query("SELECT * FROM {$tables['newsletter']} WHERE list_id='{$list_id}'");
     $smarty->assign('messages', $messages);
     $smarty->assign('main', 'management');
 } else {
     $smarty->assign('main', 'details');
     $list['usertype'] = 'C';
function cw_ps_offer($offer_id)
{
    global $tables;
    $offer_id = intval($offer_id);
    $offer = cw_query_first("SELECT * FROM {$tables['ps_offers']} WHERE offer_id='{$offer_id}'");
    $offer['bonuses'] = cw_call('cw_ps_offer_bonuses', array($offer_id));
    $offer['conditions'] = cw_call('cw_ps_offer_conditions', array($offer_id));
    // TODO: fetch an image
    return $offer;
}
                db_query("INSERT INTO {$tables['zone_element']} (zone_id, field, field_type) VALUES ('{$new_zone_id}', '" . addslashes($zone_element['field']) . "', '{$zone_element['field_type']}')");
            }
        }
        $top_message['content'] = cw_get_langvar_by_name("msg_zone_cloned");
    }
    cw_header_location('index.php?target=' . $target . '&zone_id=' . $new_zone_id);
}
$location[] = array(cw_get_langvar_by_name("lbl_destination_zones"), "");
if ($mode == "add" or !empty($zone_id)) {
    #
    # Display zone details page
    #
    $location[count($location) - 1][1] = "index.php?target=zones";
    $location[] = array(cw_get_langvar_by_name("lbl_zone_details"), "");
    if (!empty($zone_id)) {
        $zone = cw_query_first("SELECT * FROM {$tables['zones']} WHERE zone_id='{$zone_id}' {$zones_condition}");
    }
    if (empty($zone)) {
        $action = "add";
    }
    #
    # Countries in this zone and rest
    #
    $zone_countries = cw_query("SELECT {$tables['map_countries']}.code, {$tables['languages']}.value as country FROM {$tables['zone_element']}, {$tables['map_countries']}, {$tables['languages']} WHERE {$tables['zone_element']}.field_type='C' AND {$tables['zone_element']}.field={$tables['map_countries']}.code AND {$tables['languages']}.name = CONCAT('country_', {$tables['map_countries']}.code) AND {$tables['languages']}.code='{$current_language}' AND {$tables['map_countries']}.active=1 AND {$tables['zone_element']}.zone_id='{$zone_id}' ORDER BY country");
    $rest_countries = cw_query("SELECT {$tables['map_countries']}.code, {$tables['map_countries']}.region, {$tables['languages']}.value as country, {$tables['zone_element']}.zone_id FROM {$tables['languages']}, {$tables['map_countries']} LEFT JOIN {$tables['zone_element']} ON {$tables['zone_element']}.field_type='C' AND {$tables['zone_element']}.field={$tables['map_countries']}.code AND {$tables['zone_element']}.zone_id='{$zone_id}' WHERE {$tables['map_countries']}.active=1 AND {$tables['languages']}.name = CONCAT('country_', {$tables['map_countries']}.code) AND {$tables['languages']}.code='{$current_language}' AND zone_id IS NULL ORDER BY country");
    $rest_zones = array();
    if ($rest_countries) {
        foreach ($rest_countries as $v) {
            $rest_zones[$v['region']][] = $v['code'];
        }
        $rest_zones['SU'] = array('AM', 'AZ', 'BY', 'EE', 'GE', 'KZ', 'KG', 'LV', 'LT', 'MD', 'RU', 'TJ', 'TM', 'UA', 'UZ');
function dod_get_attr_ajax()
{
    global $smarty, $tables;
    global $attribute_id, $bd_id;
    $value = $operation = $quantity = '';
    if (!empty($bd_id)) {
        // extract from DB certain condition details
        $bonus_details = cw_query_first("SELECT * FROM {$tables['dod_bonus_details']} WHERE bd_id='{$bd_id}'");
        $attribute_id = $bonus_details['object_id'];
        $quantity = $bonus_details['quantity'];
        $value = $bonus_details['param1'];
        $operation = $bonus_details['param2'];
    }
    if (empty($attribute_id)) {
        return false;
    }
    cw_load('attributes');
    $attribute = cw_func_call('cw_attributes_get_attribute', array('attribute_id' => $attribute_id));
    $attribute['value'] = $value;
    $attribute['values'] = array($value);
    $smarty->assign(array('attribute' => $attribute, 'index' => empty($bd_id) ? time() : 'bd_id' . $bd_id, 'quantity' => $quantity, 'value' => $value, 'operation' => $operation));
    cw_ajax_add_block(array('action' => 'append', 'id' => 'dod_attributes', 'template' => 'addons/deal_of_day/admin/attribute_row.tpl'));
    return true;
}
<?php

if ($REQUEST_METHOD == "POST" && $action == "add_review") {
    if (!empty($review_new['message'])) {
        $review_new['status'] = $config['estore_products_review']['status_created_reviews'];
        $review_new['email'] = $user_account['email'];
        $review_id = cw_call('cw_review_add_new_review_manual', array($review_new, 0));
    }
    if (!empty($review_id)) {
        $review_data = cw_query_first("SELECT * FROM {$tables['products_reviews']} WHERE review_id='{$review_id}'");
        foreach ($rating as $attr_id => $vote) {
            // update vote value
            $exists = cw_query_first_cell("SELECT vote_id FROM {$tables['products_votes']} WHERE review_id = '{$review_id}' AND attribute_id ='{$attr_id}'");
            if ($exists) {
                cw_array2update('products_votes', array('vote_value' => $vote), "review_id = '{$review_id}' AND attribute_id ='{$attr_id}'");
            } else {
                cw_array2insert('products_votes', array('remote_ip' => $review_data['remote_ip'], 'vote_value' => $vote, 'product_id' => $review_data['product_id'], 'customer_id' => $review_data['customer_id'], 'review_id' => $review_id, 'attribute_id' => $attr_id));
            }
            cw_review_recalculate_avg_rating($review_data['product_id'], $attr_id);
        }
        cw_review_recalculate_avg_rating($review_data['product_id']);
        cw_add_top_message(cw_get_langvar_by_name('txt_thank_you_for_review'));
    } else {
        cw_add_top_message(cw_get_langvar_by_name('err_filling_form'), 'E');
    }
    cw_header_location("index.php?target=global_reviews");
}
$items_per_page_targets[$target] = 10;
$total_items = cw_call('cw_review_get_global_review', array());
$navigation = cw_core_get_navigation($target, $total_items, $page);
$global_reviews = cw_call('cw_review_get_global_review', array('', '', " ORDER BY {$tables['products_reviews']}.ctime DESC ", "LIMIT {$navigation['first_page']}, {$navigation['objects_per_page']}", FALSE));
function cw_import_users($xcart_conf)
{
    cw_load('crypt', 'user');
    extract($xcart_conf);
    extract(cw_vers_diff_attr($conn));
    fout("<br /><br />Import of Users...<br />");
    if ($clean_users) {
        $cw_admins = cw_query("select * from cw_customers u left join cw_customers_addresses a\n\t\t\ton u.customer_id=a.customer_id and a.main=1 where u.usertype='A'");
        db_query("TRUNCATE TABLE cw_customers");
        db_query("TRUNCATE TABLE cw_customers_system_info");
        db_query("TRUNCATE TABLE cw_customers_customer_info");
    }
    $users_per_run = 500;
    global $page;
    if (!isset($page)) {
        $page = 1;
    }
    $users_offset = $users_per_run * ($page - 1);
    $users_count = $users_per_run;
    $where_ids_range = "WHERE id > 58965";
    $users = cw_query("select * from xcart_customers {$where_ids_range} order by usertype in ('P','A') desc, login=email desc limit {$users_offset}, {$users_count}", $conn);
    $users_count = count($users);
    $processed_customers = array();
    $i = 1;
    $em = array();
    $user_ind = array();
    foreach ($users as $k => $v) {
        $v['password'] = cw_user_get_hashed_password(text_decrypt($v['password'], $blowfish_key));
        extract($v);
        $membership_id = $membershipid;
        //$email=$login;
        if ($uwithid) {
            $customer_id = $id;
        } else {
            $customer_id = $i++;
        }
        $processed_customers[] = $id;
        $language = strtoupper($language);
        if (in_array($email, $em)) {
            $log = str_replace(" ", "-", $login);
            $email = "{$log}-{$email}";
            $users[$k]['email'] = "{$log}-{$email}";
        }
        $em[] = $email;
        if ($usertype == 'A' || $usertype == 'P') {
            $usertype = 'A';
        } else {
            $usertype = 'C';
        }
        $arr = compact('customer_id', 'usertype', 'password', 'email', 'status', 'membership_id', 'language');
        $usrs[$customer_id] = $arr;
        cw_array2insert_esc('cw_customers', $arr);
        $creation_customer_id = $customer_id;
        $creation_date = $first_login;
        //time();
        $modification_customer_id = $customer_id;
        $modification_date = time();
        //$last_login=time(); - already extracted
        $arr = compact('customer_id', 'creation_customer_id', 'creation_date', 'modification_customer_id', 'modification_date', 'last_login');
        cw_array2insert_esc('cw_customers_system_info', $arr);
        $web_user = 1;
        cw_array2insert_esc('cw_customers_customer_info', compact('customer_id', 'web_user'));
        $ul[] = $email;
        $companies[$customer_id] = $company;
        $user_ind[$login] = $customer_id;
        $users[$k]['userid'] = $customer_id;
        fout();
    }
    fout("<br /><br />Import of an Address Book...<br />");
    if ($clean_users) {
        db_query("TRUNCATE TABLE cw_customers_addresses");
    }
    //$i=10000; //address book id start
    if ($withab) {
        $addresses = cw_query("select * from xcart_address_book where userid in ('" . implode("','", $processed_customers) . "')", $conn);
    } else {
        foreach ($users as $v) {
            extract($v);
            if ($b_firstname != '' || 1) {
                //$id=$i++;
                $firstname = $b_firstname;
                $lastname = $b_lastname;
                $address = $b_address;
                $city = $b_city;
                $county = $b_county;
                $state = $b_state;
                $country = $b_country;
                $zipcode = $b_zipcode;
                $default_b = 'Y';
                $default_s = 'N';
                $addresses[] = compact('id', 'userid', 'firstname', 'lastname', 'address', 'city', 'county', 'state', 'country', 'zipcode', 'default_b', 'default_s', 'phone', 'fax');
            }
            if ($s_firstname != '' || 1) {
                //$id=$i++;
                $firstname = $s_firstname;
                $lastname = $s_lastname;
                $address = $s_address;
                $city = $s_city;
                $county = $s_county;
                $state = $s_state;
                $country = $s_country;
                $zipcode = $s_zipcode;
                $default_b = 'N';
                $default_s = 'Y';
                $addresses[] = compact('id', 'userid', 'firstname', 'lastname', 'address', 'city', 'county', 'state', 'country', 'zipcode', 'default_b', 'default_s', 'phone', 'fax');
            }
        }
    }
    unset($users);
    $cust_addr_ids = array();
    foreach ($addresses as $v) {
        extract($v);
        $address_id = $id;
        $customer_id = $userid;
        $region = $county;
        $main = $default_b == 'Y' ? 1 : 0;
        $current = $default_s == 'Y' ? 1 : 0;
        if (isset($companies[$customer_id])) {
            $company = $companies[$customer_id];
        } else {
            $company = '';
        }
        $arr = compact('address_id', 'customer_id', 'main', 'current', 'firstname', 'lastname', 'address', 'city', 'state', 'country', 'region', 'zipcode', 'phone', 'fax', 'company');
        cw_array2insert_esc('cw_customers_addresses', $arr);
        $cust_addr_ids[$customer_id] = array();
        if ($main) {
            $cust_addr_ids[$customer_id]['main'] = $address_id;
        }
        if ($current) {
            $cust_addr_ids[$customer_id]['current'] = $address_id;
        }
        fout();
    }
    unset($addresses);
    if (isset($cw_admins) && is_array($cw_admins) && !empty($cw_admins)) {
        $uid = intval(cw_query_first_cell("select customer_id from cw_customers order by customer_id desc limit 1")) + 1;
        foreach ($cw_admins as $v) {
            if (!in_array($v['email'], $ul)) {
                $v['customer_id'] = $uid;
                extract($v);
                compact('customer_id', 'usertype', 'password', 'email', 'status', 'membership_id', 'language');
                cw_array2insert_esc('cw_customers', $v);
                $ul[] = $v['email'];
                $creation_date = time();
                $creation_customer_id = $customer_id;
                $modification_customer_id = $customer_id;
                $modification_date = time();
                $last_login = time();
                $arr = compact('customer_id', 'creation_customer_id', 'creation_date', 'modification_customer_id', 'modification_date', 'last_login');
                cw_array2insert_esc('cw_customers_system_info', $arr);
                $web_user = 1;
                cw_array2insert_esc('cw_customers_customer_info', compact('customer_id', 'web_user'));
                if (!isset($firstname) || ($firstname = '')) {
                    $firstname = 'Admin';
                }
                if (!isset($lastname) || ($lastname = '')) {
                    $lastname = 'Admin';
                }
                $main = 1;
                $arr = compact('customer_id', 'main', 'current', 'firstname', 'lastname', 'address', 'state', 'country', 'region', 'zipcode', 'phone', 'fax', 'company');
                cw_array2insert_esc('cw_customers_addresses', $arr);
                $uid++;
            }
        }
    }
    // wishlists
    /*
    	$wishlist=cw_query("select * from xcart_wishlist",$conn);
    	db_query ("TRUNCATE TABLE cw_wishlist");
    	foreach ($wishlist as $v) {
    		extract($v);
    		if ($uwithid) $customer_id=$userid; else $customer_id=$user_ind[$login];
    		$wishlist_id=$wishlistid; $product_id=$productid;
    		$arr=compact('wishlist_id','customer_id','product_id','amount','amount_purchased','options','event_id','object');
    		cw_array2insert_esc ('cw_wishlist',$arr);
    		fout();
    	}
    */
    fout("<br /><br />Import of Orders & Invoices...<br />");
    //print_r($cust_addr_ids);
    // orders, invoices
    if ($clean_docs) {
        db_query("TRUNCATE TABLE cw_docs");
        db_query("TRUNCATE TABLE cw_docs_info");
        db_query("TRUNCATE TABLE cw_docs_settings");
        db_query("TRUNCATE TABLE cw_docs_user_info");
    }
    $orders_per_run = 250;
    $orders_offset = $orders_per_run * ($page - 1);
    $orders_count = $orders_per_run;
    $where_orderids_range = "WHERE orderid > 63375";
    $orders = cw_query("select * from xcart_orders {$where_orderids_range} limit {$orders_offset}, {$orders_count}", $conn);
    $orders_count = count($orders);
    $doc_ids = array();
    $processed_orders = array();
    //$doc_id=$doc_info_id=1;
    $type = "O";
    //$_display_id=$_display_doc_id=1;
    foreach ($orders as $v) {
        extract($v);
        //$doc_ids[$orderid]=$doc_id;
        $doc_id = $orderid;
        $processed_orders[] = $orderid;
        $doc_info_id = $doc_id;
        $doc_ids[$orderid] = $orderid;
        $year = date("Y", $date);
        $display_id = "SW " . $doc_id;
        $display_doc_id = $doc_id;
        $arr = compact('doc_id', 'doc_info_id', 'type', 'display_id', 'display_doc_id', 'year', 'date', 'status');
        cw_array2insert_esc('cw_docs', $arr);
        $payment_id = $paymentid;
        $display_total = $total;
        $display_subtotal = $subtotal;
        $shipping_id = $shippingid;
        $details = cw_crypt_text(text_decrypt($details, $blowfish_key));
        $applied_taxes = $taxes_applied;
        $shipping_id = $shippingid;
        $display_shipping_cost = $shipping_cost;
        $shipping_label = isset($shipping) ? $shipping : '';
        $payment_label = $payment_method;
        $discount_value = $discount;
        $arr = compact('doc_info_id', 'total', 'display_total', 'subtotal', 'display_subtotal', 'extra', 'details', 'payment_id', 'shipping_id', 'shipping_cost', 'notes', 'tax', 'applied_taxes', 'customer_notes', 'payment_label', 'payment_surcharge', 'shipping_id', 'shipping_cost', 'display_shipping_cost', 'shipping_label', 'giftcert_discount', 'coupon', 'coupon_discount', 'discount', 'discount_value');
        cw_array2insert_esc('cw_docs_info', $arr);
        $show_price = 0;
        $arr = compact('doc_info_id', 'show_price');
        cw_array2insert_esc('cw_docs_settings', $arr);
        if ($uwithid) {
            $customer_id = $userid;
        } else {
            $customer_id = $user_ind[$login];
        }
        $cust_inf = cw_query_first("select c.usertype, c.email from cw_customers where customer_id='{$customer_id}'");
        $usertype = $cust_inf['usertype'];
        $email = $cust_inf['email'];
        $main_address_id = cw_query_first_cell("select address_id from cw_customers_addresses where customer_id='{$customer_id}' and main=1");
        $current_address_id = cw_query_first_cell("select address_id from cw_customers_addresses where customer_id='{$customer_id}' and current=1");
        /*
        		$usertype=$usrs[$customer_id]['usertype'];
        		if (isset($cust_addr_ids[$customer_id]['main']))
        			$main_address_id=$cust_addr_ids[$customer_id]['main']; else $main_address_id=0;
        		if (isset($cust_addr_ids[$customer_id]['current']))
        			$current_address_id=$cust_addr_ids[$customer_id]['current']; else $current_address_id=0;
        		$email=$usrs[$customer_id]['email'];
        */
        $arr = compact('doc_info_id', 'customer_id', 'usertype', 'main_address_id', 'current_address_id', 'email', 'tax_number', 'tax_exempt');
        cw_array2insert_esc('cw_docs_user_info', $arr);
        $display_id++;
        $display_doc_id++;
        $doc_id++;
        $doc_info_id++;
        fout();
    }
    unset($orders);
    unset($usrs);
    if ($clean_docs) {
        db_query("TRUNCATE TABLE cw_docs_items");
    }
    $details = cw_query("select * from xcart_order_details where orderid in ('" . implode("','", $processed_orders) . "')", $conn);
    foreach ($details as $v) {
        extract($v);
        $item_id = $itemid;
        $doc_id = $doc_ids[$orderid];
        $product_id = $productid;
        if ($uwithid) {
            $warehouse_customer_id = $provider;
        } else {
            $warehouse_customer_id = $user_ind[$provider];
        }
        $arr = compact('item_id', 'doc_id', 'product_id', 'productcode', 'product', 'product_options', 'price', 'amount', 'extra_data', 'warehouse_customer_id');
        cw_array2insert_esc('cw_docs_items', $arr);
    }
    if ($users_count || $orders_count) {
        return $page + 1;
    } else {
        return 0;
    }
}
    db_query("update {$tables['docs_info']} set layout_id='{$template['layout_id']}' where doc_info_id='{$doc_data['doc_info_id']}'");
    cw_header_location("index.php?target={$target}&mode=layout&doc_id={$doc_id}");
}
$smarty->assign('order_details_fields_labels', cw_doc_details_fields_as_labels());
if ($doc_data) {
    $owner_condition = " and {$tables['docs']}.type = '" . $doc_data['type'] . "'";
    if (AREA_TYPE == 'C') {
        $owner_condition = " AND {$tables['docs_user_info']}.customer_id='{$customer_id}'";
    } elseif (AREA_TYPE == 'P' || AREA_TYPE == 'V') {
        $owner_condition = " AND {$tables['docs_info']}.warehouse_customer_id='{$customer_id}'";
    } elseif (AREA_TYPE == 'B') {
        $owner_condition = " AND {$tables['docs_info']}.salesman_customer_id='{$customer_id}'";
    }
    $tmp = cw_query_first("SELECT {$tables['docs']}.* FROM {$tables['docs']}, {$tables['docs_info']}, {$tables['docs_user_info']} WHERE {$tables['docs_info']}.doc_info_id={$tables['docs']}.doc_info_id and {$tables['docs_user_info']}.doc_info_id={$tables['docs']}.doc_info_id and {$tables['docs']}.doc_id > '{$doc_id}' {$owner_condition} ORDER BY {$tables['docs']}.doc_id ASC LIMIT 1");
    $smarty->assign('doc_id_next', $tmp);
    $tmp = cw_query_first("SELECT {$tables['docs']}.* FROM {$tables['docs']}, {$tables['docs_info']}, {$tables['docs_user_info']} WHERE {$tables['docs_info']}.doc_info_id={$tables['docs']}.doc_info_id and {$tables['docs_user_info']}.doc_info_id={$tables['docs']}.doc_info_id and {$tables['docs']}.doc_id <'{$doc_id}' {$owner_condition} order by {$tables['docs']}.doc_id DESC LIMIT 1");
    $smarty->assign('doc_id_prev', $tmp);
}
$smarty->assign('doc', $doc_data);
if ($current_area == 'C' && $doc_data['userinfo']['customer_id'] != $customer_id) {
    cw_header_location('index.php');
}
if ($current_area == 'B' && $doc_data['info']['salesman_customer_id'] != $customer_id) {
    cw_header_location("index.php?target=error_message&error=access_denied&id=40");
}
if ($current_area == 'P' && in_array($docs_type, array('I', 'O', 'S')) && $doc_data['info']['warehouse_customer_id'] != $user_account['warehouse_customer_id']) {
    cw_header_location("index.php?target=error_message&error=access_denied&id=40");
}
if ($action == 'print_barcode' && $addons['barcode']) {
    if (!$print['template_id']) {
        cw_header_location("index.php?target={$target}&mode=details&doc_id={$doc_id}");