function cw_checkout_userinfo($user_account)
{
    global $customer_id, $config;
    $userinfo = $user_account;
    if ($customer_id) {
        $userinfo = array_merge(cw_user_get_info($customer_id, 65535), $userinfo);
    }
    $userinfo['main_address'] = cw_user_get_address_by_type('main');
    $userinfo['current_address'] = cw_user_get_address_by_type('current');
    return $userinfo;
}
<?php

if (!defined('APP_START')) {
    die("Access denied");
}
$sesses = cw_query("SELECT sess_id, data FROM {$tables['sessions_data']} WHERE usertype IN ('C', 'R')");
$statistics = array();
if ($sesses) {
    foreach ($sesses as $s) {
        $data = array();
        $rec = array("last_date" => $s['expiry']);
        $data = unserialize($data['data']);
        if (!empty($data['customer_id']) && !in_array($data['usertype'], array('C', 'R'))) {
            continue;
        }
        if (!empty($data['customer_id'])) {
            $rec['userinfo'] = cw_user_get_info($data['customer_id']);
        }
        if (!empty($data['cart']['products'])) {
            $rec['products'] = $data['cart']['products'];
        }
        $rec['current_date'] = $data['current_date'];
        $rec['current_url_page'] = $data['current_url_page'];
        if (strstr($data['current_url_page'], $https_location)) {
            $rec['display_url_page'] = str_replace($https_location, "...", $data['current_url_page']);
        } else {
            $rec['display_url_page'] = str_replace($http_location, "...", $data['current_url_page']);
        }
        $statistics[] = $rec;
    }
}
function cw_seller_doc_place_order_seller_email($doc_id, $customer_id, $products)
{
    global $tables, $config, $current_location;
    $user_data = cw_user_get_info($customer_id, 1);
    $product_data = "";
    foreach ($products as $product) {
        $product_info = cw_func_call('cw_product_get', array('id' => $product['product_id'], 'user_account' => $user_data, 'info_type' => 0));
        $product_data .= '<a href="' . $current_location . '/index.php?target=product&product_id=';
        $product_data .= $product['product_id'] . '">' . $product_info['product'] . '</a>, ';
        $product_data .= 'SKU: ' . $product_info['productcode'] . ', ';
        $product_data .= 'Amount: ' . $product['amount'] . ' <br />';
    }
    $from = $config['Company']['site_administrator'];
    $to = $user_data['email'];
    $mail_subject = "The notification about an order contains your product";
    $mail_body = '<b>You have received this notification from <a href="' . $current_location . '">';
    $mail_body .= $config['Company']['company_name'] . '</a></b><br />';
    $mail_body .= 'A system reports that an order(s) contains your product(s):<br />';
    $mail_body .= $product_data;
    cw_send_simple_mail($from, $to, $mail_subject, $mail_body);
}
if ($addons['manufacturers']) {
    cw_include('addons/manufacturers/customer_manufacturers.php');
}
require $app_main_dir . "/include/countries.php";
require $app_main_dir . "/include/states.php";
if ($config['General']['use_counties'] == "Y") {
    include $app_main_dir . "/include/counties.php";
}
if (empty($fill_error) && empty($amount_error)) {
    if ($action == "wl") {
        $smarty->assign('giftcert', unserialize(cw_query_first_cell("SELECT object FROM {$tables['wishlist']} WHERE wishlist_id='{$gcindex}'")));
        $smarty->assign('action', 'wl');
        $smarty->assign('wlitem', $gcindex);
    } elseif (isset($gcindex) && isset($cart['giftcerts'][$gcindex])) {
        $smarty->assign('giftcert', @$cart['giftcerts'][$gcindex]);
    }
} else {
    $smarty->assign('giftcert', $giftcert);
    $smarty->assign('fill_error', $fill_error);
    $smarty->assign('amount_error', $amount_error);
}
if (!empty($customer_id)) {
    $smarty->assign('userinfo', cw_user_get_info($customer_id));
}
$smarty->assign('min_gc_amount', $config['Gift_Certificates']['min_gc_amount']);
$smarty->assign('max_gc_amount', $config['Gift_Certificates']['max_gc_amount']);
cw_session_save();
$smarty->assign("profile_fields", array("recipient_state" => array("avail" => "Y", "required" => "Y"), "recipient_country" => array("avail" => "Y", "required" => "Y")));
$smarty->assign('main', "giftcert");
$location[] = array(cw_get_langvar_by_name("lbl_gift_certificate", ""));
$smarty->assign('gc_templates', cw_gc_get_templates($smarty->template_dir));
function cw_review_send_order_review_reminder_email($customer_products)
{
    global $tables, $config, $smarty, $current_location;
    cw_load('email', 'user');
    if (!empty($customer_products) && is_array($customer_products)) {
        foreach ($customer_products as $customer_id => $product_ids) {
            $user_info = cw_user_get_info($customer_id);
            if (empty($user_info['email']) || empty($product_ids)) {
                continue;
            }
            $key = md5('rps' . $customer_id);
            $link = $current_location . "/index.php?target=product";
            $link .= "&action=review_product&review_key={$key}&review_object={$customer_id}";
            $alinks = array();
            foreach ($product_ids as $product_id) {
                $product_name = cw_query_first_cell("SELECT product FROM {$tables['products']} WHERE product_id = {$product_id}");
                if (empty($product_name)) {
                    continue;
                }
                $alinks[] = array('link' => $link . "&product_id={$product_id}", 'product_name' => $product_name);
                cw_array2insert('products_reviews_reminder', array('product_id' => $product_id, 'customer_id' => $customer_id, 'ctime' => cw_core_get_time()), TRUE);
            }
            if (!empty($alinks)) {
                $smarty->assign('reminders', $alinks);
                cw_call('cw_send_mail', array($config['Company']['site_administrator'], $user_info['email'], 'addons/estore_products_review/mail/reminder_subj.tpl', 'addons/estore_products_review/mail/reminder_body.tpl', $config['default_admin_language']));
            }
        }
    }
    return TRUE;
}
        }
    }
    if ($new_message_id) {
        $recepient_info = cw_user_get_info($new_thread['recepient_id'], 1);
        $top_message = array('content' => "New message has been sent to {$recepient_info['firstname']} {$recepient_info['lastname']} ({$recepient_info['email']})", 'type' => 'I');
    }
    cw_header_location("index.php?target={$target}&mode={$mode}&doc_id={$doc_id}&js_tab=order_messages");
}
$contact_suppliers = array();
foreach ($doc_data['products'] as $doc_product) {
    if ($doc_product['supplier_customer_id']) {
        $contact_suppliers[] = cw_user_get_info($doc_product['supplier_customer_id'], 1);
    }
}
$smarty->assign('contact_suppliers', $contact_suppliers);
$doc_messages_threads = cw_query("select {$tables['order_messages_threads']}.* from {$tables['order_messages_threads']} where doc_id='{$doc_id}'");
foreach ($doc_messages_threads as $dmt_key => $dmt_value) {
    $doc_messages_threads[$dmt_key]['messages'] = cw_query("select * from {$tables['order_messages_messages']} where thread_id = '{$dmt_value['thread_id']}' order by date desc");
    if (!empty($doc_messages_threads[$dmt_key]['messages'])) {
        $doc_messages_threads[$dmt_key]['messages_count'] = count($doc_messages_threads[$dmt_key]['messages']);
        $doc_messages_threads[$dmt_key]['messages_unread'] = cw_query_first_cell("select count(*) from {$tables['order_messages_messages']} where thread_id = '{$dmt_value['thread_id']}' and read_status!=1");
        $doc_messages_threads[$dmt_key]['start_message'] = end($doc_messages_threads[$dmt_key]['messages']);
        $doc_messages_threads[$dmt_key]['start_message']['sender'] = cw_order_messages_convert_anon_email(cw_user_get_info($doc_messages_threads[$dmt_key]['start_message']['sender_id'], 1), $doc_id);
        $doc_messages_threads[$dmt_key]['start_message']['recepient'] = cw_order_messages_convert_anon_email(cw_user_get_info($doc_messages_threads[$dmt_key]['start_message']['recepient_id'], 1), $doc_id);
        $doc_messages_threads[$dmt_key]['last_message'] = reset($doc_messages_threads[$dmt_key]['messages']);
        $doc_messages_threads[$dmt_key]['last_message']['sender'] = cw_order_messages_convert_anon_email(cw_user_get_info($doc_messages_threads[$dmt_key]['last_message']['sender_id'], 1), $doc_id);
        $doc_messages_threads[$dmt_key]['last_message']['recepient'] = cw_order_messages_convert_anon_email(cw_user_get_info($doc_messages_threads[$dmt_key]['last_message']['recepient_id'], 1), $doc_id);
    }
}
usort($doc_messages_threads, 'cw_order_messages_threads_sort');
$smarty->assign('doc_messages_threads', $doc_messages_threads);
    $fillerror = cw_error_check($_POST, $rules);
    if ($fillerror) {
        $top_message = array('content' => $fillerror, 'type' => 'E');
        cw_header_location('index.php?target=cart&mode=checkout');
    }
    $ord_tmp = array();
    foreach ($rules as $k => $tmp) {
        //        $ord_tmp[] = $k.": ".stripslashes($request_prepared[$k]);
        $ord_tmp[] = $k . ": --not saved--";
    }
    $order_details = implode("\n", $ord_tmp);
}
cw_payment_header();
global $userinfo, $app_catalogs;
if ($customer_id) {
    $userinfo = cw_user_get_info($customer_id, 65535);
}
if (empty($userinfo) || cw_is_cart_empty($cart)) {
    cw_header_location($current_location . '/index.php?target=error_message&error=ccprocessor_baddata');
}
$userinfo = cw_array_merge($userinfo, $_POST);
$userinfo = cw_array_merge($userinfo, $user_address);
$order_type = 'O';
if ($action == 'request_for_quote') {
    $order_type = 'I';
}
$secure_oid =& cw_session_register("secure_oid");
if (!$secure_oid) {
    $doc_ids = cw_func_call('cw_doc_place_order', array('order_type' => $order_type, 'order_status' => 'I', 'order_details' => $order_details, 'customer_notes' => $customer_notes, 'userinfo' => $userinfo, 'prefix' => $config[$payment_data['processor']]['prefix']));
    if (!$doc_ids) {
        cw_header_location('index.php?target=error_message&error=product_in_cart_expired');
function cw_user_send_modification_mail($customer_id, $is_new)
{
    global $config, $smarty;
    $userinfo = cw_user_get_info($customer_id, 65535);
    $fields_area = cw_profile_fields_get_area($customer_id);
    list($profile_sections, $profile_fields, $additional_fields) = cw_profile_fields_get_sections('U', true, $fields_area);
    $smarty->assign('userinfo', $userinfo);
    $smarty->assign('profile_sections', $profile_sections);
    $smarty->assign('profile_fields', $profile_fields);
    $smarty->assign('additional_fields', $additional_fields);
    if ($is_new) {
        if ($config['Email']['eml_signin_notif'] == 'Y') {
            cw_call('cw_send_mail', array($config['Company']['users_department'], $userinfo['email'], 'mail/users/signin_subj.tpl', 'mail/users/signin.tpl'));
        }
        if ($config['Email']['eml_signin_notif_admin'] == 'Y') {
            cw_call('cw_send_mail', array($userinfo['email'], $config['Company']['users_department'], 'mail/users/signin_subj.tpl', 'mail/users/signin_admin.tpl', $config['default_admin_language']));
        }
    } else {
        if ($config['Email']['eml_profile_modified_customer'] == 'Y') {
            cw_call('cw_send_mail', array($config['Company']['users_department'], $userinfo['email'], 'mail/users/modified_subj.tpl', 'mail/users/modified.tpl'));
        }
        if ($config['Email']['eml_profile_modified_admin'] == 'Y') {
            cw_call('cw_send_mail', array($userinfo['email'], $config['Company']['users_department'], 'mail/users/modified_admin_subj.tpl', 'mail/users/modified_admin.tpl'));
        }
    }
}
function cw_aom_update_customer(&$doc, $customer_id)
{
    $doc['userinfo']['customer_id'] = $customer_id;
    # kornev, warehouses are different from users
    if ($doc['type'] == 'D') {
        $user_info = cw_warehouse_get_like_user($customer_id, $doc['info']['warehouse_customer_id']);
    } else {
        $user_info = cw_user_get_info($customer_id, 65);
    }
    $doc['userinfo'] = cw_doc_prepare_user_information($user_info, $doc['userinfo']);
    if (!$doc['info']['company_id']) {
        $doc['info']['company_id'] = $doc['userinfo']['company_id'];
    }
    if (!$doc['info']['shipment_paid']) {
        $doc['info']['shipment_paid'] = $user_info['additional_info']['shipment_paid'];
    }
}
<?php

cw_load('product', 'category', 'image', 'file_area', 'cart', 'attributes', 'tags');
global $customer_id, $product_info;
# kornev, required for taxes
$user_info = cw_user_get_info($customer_id, 1);
$product_info = cw_func_call('cw_product_get', array('id' => $product_id, 'user_account' => $user_info, 'info_type' => 65535));
if (!$product_info['product_id']) {
    cw_header_location('index.php?target=error_message&error=product_disabled');
}
if (intval($cat) == 0) {
    $cat = $product_info['category_id'];
}
$smarty->assign('cat', $cat);
$smarty->assign('menu_arrivals', cw_sections_get_featured('new_arrivals', $cat));
if ($product_info['product_id']) {
    $product_info['meta_descr'] = strip_tags($product_info['descr']);
    $product_info['meta_keywords'] = strip_tags($product_info['product']) . " " . preg_replace("/[^a-zA-Z0-9]/", " ", strip_tags($product_info['descr']));
}
cw_include('include/products/send_to_friend.php');
if (!empty($send_to_friend_info)) {
    $smarty->assign('send_to_friend_info', $send_to_friend_info);
    if ($addons['image_verification']) {
        $smarty->assign('antibot_err', $send_to_friend_info['antibot_err']);
    }
    cw_session_unregister("send_to_friend_info");
}
# kornev, TOFIX
if ($addons['magnifier']) {
    cw_include('addons/magnifier/product.php');
}
        if (!empty($config['order_messages']['default_recepient_admin_email'])) {
            $default_recepient_admin_email = $config['order_messages']['default_recepient_admin_email'];
        }
        $msg['sender_id'] = cw_query_first_cell("select customer_id from {$tables['customers']} where usertype='A' and email='{$default_recepient_admin_email}'");
        $thread_messages[$msg_k]['sender_id'] = $msg['sender_id'];
    }
    if (!isset($messages_users[$msg['sender_id']])) {
        $messages_users[$msg['sender_id']] = cw_user_get_info($msg['sender_id'], 1);
    }
    if (!isset($messages_users[$msg['recepient_id']])) {
        $messages_users[$msg['recepient_id']] = cw_user_get_info($msg['recepient_id'], 1);
    }
    if (!$msg['author_id']) {
        if (!empty($config['order_messages']['default_recepient_admin_email'])) {
            $default_recepient_admin_email = $config['order_messages']['default_recepient_admin_email'];
        }
        $msg['author_id'] = cw_query_first_cell("select customer_id from {$tables['customers']} where usertype='A' and email='{$default_recepient_admin_email}'");
        $thread_messages[$msg_k]['author_id'] = $msg['author_id'];
    }
    if (!isset($messages_users[$msg['author_id']])) {
        $messages_users[$msg['author_id']] = cw_user_get_info($msg['author_id'], 1);
    }
    $start_message = $msg;
}
$smarty->assign('thread_messages', $thread_messages);
$smarty->assign('messages_users', $messages_users);
$smarty->assign('start_message', $start_message);
$smarty->assign('thread_id', $thread_id);
$smarty->assign('doc_id', cw_query_first_cell("select doc_id from {$tables['order_messages_threads']} where thread_id = '{$thread_id}'"));
$smarty->assign('home_style', 'popup');
$smarty->assign('main', 'thread_messages');
        $customer_id = cw_user_create_profile(array('usertype' => 'C'));
        $profile_values['status'] = 'Y';
        cw_user_update($profile_values, $customer_id, $customer_id);
        $identifiers =& cw_session_register("identifiers", array());
        $identifiers['C'] = array('customer_id' => $customer_id);
    }
    $paypal_express_details = $result;
    switch ($state_err) {
        case 1:
            $top_message = array("type" => "W", "content" => cw_get_langvar_by_name("lbl_paypal_wrong_country_note"));
            break;
        case 2:
            $top_message = array("type" => "W", "content" => cw_get_langvar_by_name("lbl_paypal_wrong_state_note"));
    }
    # kornev, re-calculate the cart with the address and place the order
    $cart['userinfo'] = $userinfo = cw_user_get_info($customer_id, 65535);
    $products = cw_call('cw_products_in_cart', array($cart, $userinfo));
    $cart = cw_func_call('cw_cart_calc', array('cart' => $cart, 'products' => $products, 'userinfo' => $userinfo));
    $location[] = array(cw_get_langvar_by_name('lbl_paypal_express_confirma_payment'), '');
    cw_include('customer/cart.php');
    $smarty->assign('home_style', 'popup');
    $smarty->assign('current_main_dir', 'addons/paypal_express');
    $smarty->assign('current_section_dir', 'customer');
    $smarty->assign('main', 'confirmation');
} elseif ($action == 'place_order') {
    // finish ExpressCheckout
    if ($pp_subject) {
        $config['paypal_express']['api_access'] = '';
        $config['paypal_express']['api_password'] = '';
        $config['paypal_express']['auth_type'] = false;
        $pp_signature_txt = '';
$review_store_place =& cw_session_register("review_store_place");
// flag for user, had come by link. It gives ability review the product
$extended_review_customer_id =& cw_session_register("extended_review_customer_id", 0);
$user_ip = $_SERVER["REMOTE_ADDR"] . '_' . $_SERVER["HTTP_X_FORWARDED_FOR"] . '_' . $_SERVER["HTTP_CLIENT_IP"];
$_customer_id = $customer_id;
$reviews_per_page = 10;
if ($view_all == 'all') {
    $reviews_per_page = 150;
}
if (empty($page)) {
    $page = 1;
}
// review by link
if ($action == 'review_product') {
    if (!empty($review_object) && !empty($review_key)) {
        $result = cw_user_get_info($review_object);
        $test_key = md5('rps' . $review_object);
        // if user exist and keys equal
        if (!empty($result) && $review_key === $test_key) {
            $extended_review_customer_id = $review_object;
        }
    }
}
if (!empty($extended_review_customer_id)) {
    $_customer_id = $extended_review_customer_id;
}
$where = cw_review_get_where_query_by_settings($_customer_id);
$avail_by_settings = cw_review_avail_by_settings($product_id, $_customer_id, $extended_review_customer_id);
$return_url = cw_call('cw_core_get_html_page_url', array(array('var' => 'product', 'product_id' => $product_id, 'js_tab' => 4, 'delimiter ' => '&')));
// Place review and rates
if ($action == 'review' && $product_id && ($config['estore_products_review']['customer_reviews'] == 'Y' || $config['estore_products_review']['customer_voting'] == 'Y') && $avail_by_settings) {
<?php

if (defined('IS_AJAX')) {
    cw_load('user');
    if (isset($_GET['user_id'])) {
        $id = intval($_GET['user_id']);
        $result = cw_user_get_info($id, 1);
        if ($result) {
            $user = array_shift(array_values($result['addresses']));
            $user['address'] = $user['address'] != '' ? $user['address'] : $user['address_2'];
            $user['email'] = $result['email'];
            echo json_encode($user);
        }
    }
    exit;
}
<?php

global $product_id;
if (!$product_id) {
    cw_header_location("index.php?target=error_message&error=access_denied&id=48");
}
$product_info = cw_func_call('cw_product_get', array('id' => $product_id, 'user_account' => $user_account, 'info_type' => 65535));
if (isset($product_info['category_id']) && is_numeric($product_info['category_id'])) {
    $product_info['category'] = cw_func_call('cw_category_get', array('cat' => $product_info['category_id']));
}
// Created data
$product_info['created_text'] = "";
$creation_customer_id = cw_query_first_cell("SELECT creation_customer_id FROM {$tables['products_system_info']} WHERE product_id='{$product_id}'");
if (!empty($creation_customer_id)) {
    $user_data = cw_user_get_info($creation_customer_id, 1);
    $created_text = "";
    if ($user_data['main_address']) {
        $created_text = $user_data['main_address']['firstname'] . " " . $user_data['main_address']['lastname'] . " / ";
    }
    if ($user_data['email']) {
        $created_text .= $user_data['email'];
    }
    $product_info['created_text'] = $created_text;
}
if (!$product_info) {
    $top_message = array('content' => cw_get_langvar_by_name('lbl_products_deleted'), 'type' => 'E');
    cw_header_location('index.php?target=error_message');
}
$smarty->assign('product', $product_info);
$smarty->assign('main', 'preview');
function cw_ps_offers_exist(&$cart, &$products, $_user_info = array())
{
    static $iter;
    $offers_ids = array('new' => array(), 'suitable' => array(), 'to_delete' => array());
    $offers = array();
    //we should track actions here as well...
    global $action;
    $action = (string) $action;
    $tracking_actions = array('add' => 1, 'update' => 1, 'delete' => 1, 'ajax_update' => 1, 'clear_cart' => 1);
    if (empty($action) || !isset($tracking_actions[$action])) {
        return $offers_ids;
    }
    if (!isset($iter)) {
        $iter = 0;
    }
    $iter++;
    global $customer_id, $user_info;
    if (isset($customer_id) && !empty($customer_id)) {
        if (!isset($user_info) || empty($user_info)) {
            $user_info = cw_user_get_info($customer_id, 1);
        }
    } else {
        $user_info = $_user_info;
        if (empty($_user_info)) {
            $user_info = $cart['userinfo'];
        }
    }
    $ps_offers_info =& cw_session_register('ps_offers_info');
    $current_hash = md5(cw_ps_prods_str($products) . cw_ps_address_str($user_info));
    if (!empty($ps_offers_info) && is_array($ps_offers_info)) {
        if (isset($ps_offers_info['hash']) && !empty($ps_offers_info['hash'])) {
            if (isset($ps_offers_info['hash'][$current_hash])) {
                if (isset($ps_offers_info['offers_ids'])) {
                    return $ps_offers_info['offers_ids'];
                }
            } else {
                $ps_offers_info['hash'] = array();
                if ($iter > 1) {
                    echo '<pre>is differ! ', "{$iter} iteration: ", print_r($products), print_r(cw_ps_save('products', true)), '</pre>';
                    echo '<pre>', print_r($ps_offers_info['hash']), "\n", md5(cw_ps_prods_str($products)), '</pre>';
                }
            }
        }
        /*if (isset($ps_offers_info['processed_data_hash'])) {
        
                    //we have already processed the input data
                    if ($ps_offers_info['processed_data_hash'] == $current_hash) {
                        if (isset($ps_offers_info['offers_ids'])) {
                            return $ps_offers_info['offers_ids'];
                        }
                    }
                }
        
                if (isset($ps_offers_info['data_hash'])) {
        
                    //we have already processed the input data
                    if ($ps_offers_info['data_hash'] == $current_hash) {
                        if (isset($ps_offers_info['offers_ids'])) {
                            return $ps_offers_info['offers_ids'];
                        }
                    }
                }
        
        
                if (isset($ps_offers_info['data_hash']) || isset($ps_offers_info['processed_data_hash'])) {
                    if ($ps_offers_info['data_hash'] != $current_hash && $ps_offers_info['processed_data_hash'] != $current_hash && $iter > 1) {
                        echo '<pre>is differ! ', "$iter iteration: ", print_r($products), print_r(cw_ps_save('products', true)), '</pre>';
                    }
                }*/
        /*
                if (isset($ps_offers_info['hash']) && !empty($ps_offers_info['hash'])) {
                    //if ($ps_offers_info['data_hash'] != $current_hash && $ps_offers_info['processed_data_hash'] != $current_hash && $iter > 1) {
                    if (!isset($ps_offers_info['hash'][$current_hash]) && $iter > 1) {
                        echo '<pre>is differ! ', "$iter iteration: ", print_r($products), print_r(cw_ps_save('products', true)), '</pre>';
                        echo '<pre>', print_r($ps_offers_info['hash']), "\n",  md5(cw_ps_prods_str($products)), '</pre>';
                    }
                }*/
    }
    cw_ps_save('products', $products);
    //if (!empty($ps_offers_info) && is_array($ps_offers_info) && isset($ps_offers_info['data_hash'])) {
    if (isset($ps_offers_info) && isset($ps_offers_info['applied_offers']) && !empty($ps_offers_info['applied_offers']) && isset($ps_offers_info['hash'])) {
        // let's check if there are offers for the original cart
        $_products = $products;
        if (isset($ps_offers_info['added_free_prods']) && is_array($ps_offers_info['added_free_prods']) && isset($ps_offers_info['applied_offers_free']) && is_array($ps_offers_info['applied_offers_free'])) {
            // let's delete free products added if any
            foreach ($products as $key => $cart_record) {
                if (isset($ps_offers_info['added_free_prods'][$cart_record['cartid']])) {
                    unset($_products[$key]);
                }
            }
            if (empty($_products)) {
                //$ps_offers_info = array();
                //cw_session_unregister('ps_offers_info');
                // there are only products for free in the cart, so let's delete them
                //$products = $_products = array();
                $offers_ids['to_delete'] = $ps_offers_info['applied_offers'];
                $ps_offers_info['offers_ids'] = $offers_ids;
                return $offers_ids;
            }
        }
        if (isset($ps_offers_info['disc_prods']) && is_array($ps_offers_info['disc_prods']) && isset($ps_offers_info['applied_offers_discount']) && is_array($ps_offers_info['applied_offers_discount'])) {
            //let's delete all the special discounts applied
            foreach ($products as $key => $cart_record) {
                $_cartid = $cart_record['cartid'];
                if (isset($ps_offers_info['disc_prods'][$_cartid])) {
                    $_products[$key]['price'] = $ps_offers_info['disc_prods'][$_cartid]['price'];
                }
            }
        }
        $offers = cw_ps_get_customer_offers($cart, $_products);
        if (empty($offers) || !is_array($offers)) {
            // no products for free are available after the cart updation, so let's delete the products for free added previously
            //$products = $_products;
            //$ps_offers_info['processed_data_hash'] = $current_hash;
            $ps_offers_info['hash'][$current_hash] = 1;
            //$ps_offers_info['hash'][md5(cw_ps_prods_str($products) . cw_ps_address_str($user_info))] = 2;
        }
        unset($_products);
        // we will not restore products for free which were deleted by a customer
        $new_offers = $offers_to_delete = $suitable_offers = array();
        if (isset($ps_offers_info['applied_offers']) && is_array($ps_offers_info['applied_offers']) && !empty($ps_offers_info['applied_offers'])) {
            $new_offers = array_diff_key($offers, $ps_offers_info['applied_offers']);
            $offers_to_delete = array_diff_key($ps_offers_info['applied_offers'], $offers);
            $suitable_offers = array_diff_key($ps_offers_info['applied_offers'], $offers_to_delete);
        }
        $offers_ids = array('new' => $new_offers, 'to_delete' => $offers_to_delete, 'suitable' => $suitable_offers);
        if (empty($offers) || !is_array($offers)) {
            $ps_offers_info['offers_ids'] = $offers_ids;
            //echo '<pre>', print_r($offers_ids), '</pre>';
            //echo '<pre>', print_r($ps_offers_info), '</pre>';
            //die;
            return $offers_ids;
        }
    }
    if (empty($offers)) {
        //echo '<pre>checking offers: ', print_r($cart), print_r($products), '</pre>';
        $offers_ids['new'] = cw_ps_get_customer_offers($cart, $products);
        //echo '<pre>', print_r($offers_ids['new']), '</pre>';
        //die;
    }
    //echo '<pre>', print_r($offers_ids), '</pre>';
    //die;
    if (!empty($offers_ids['new']) || !empty($offers_ids['suitable'])) {
        $ps_offers_info['applied_offers'] = $offers_ids['new'] + $offers_ids['suitable'];
    }
    //$ps_offers_info['processed_data_hash'] = $current_hash;
    $ps_offers_info['hash'][$current_hash] = 1;
    $ps_offers_info['hash'][md5(cw_ps_prods_str($cart['products']) . cw_ps_address_str($user_info))] = 3;
    cw_ps_save('products', $cart['products']);
    if (!empty($offers_ids['new']) || !empty($offers_ids['suitable']) || !empty($offers_ids['to_delete'])) {
        $ps_offers_info['offers_ids'] = $offers_ids;
    }
    return $offers_ids;
}
function cw_send_survey_invitation($survey_id, $email, $customer_id, $force = false)
{
    global $smarty, $config, $tables, $http_location;
    global $app_main_dir, $admin_safe_mode, $app_catalogs;
    static $store_surveys = array();
    include $app_main_dir . "/include/safe_mode.php";
    cw_load("mail", "user");
    # Check respondent status
    $is_valid = cw_query_first_cell("SELECT COUNT(*) FROM {$tables['survey_maillist']} WHERE survey_id = '{$survey_id}' AND email = '" . addslashes($email) . "' AND sent_date = 0") > 0;
    if (!$is_valid && !$force) {
        return -1;
    }
    if (!isset($store_surveys[$survey_id])) {
        $store_surveys[$survey_id] = cw_get_survey($survey_id);
    }
    $survey = $store_surveys[$survey_id];
    $survey['complete'] = cw_eol2br($survey['complete']);
    $survey['header'] = cw_eol2br($survey['header']);
    $survey['footer'] = cw_eol2br($survey['footer']);
    $smarty->assign('survey', $survey);
    # Geet access key
    $access_key = cw_query_first_cell("SELECT access_key FROM {$tables['survey_maillist']} WHERE survey_id = '{$survey_id}' AND email = '" . addslashes($email) . "'");
    if (empty($access_key)) {
        # Generate access key
        srand(cw_core_microtime());
        $access_key = md5(rand(0, time()));
        cw_array2update("survey_maillist", array("access_key" => $access_key), "survey_id = '{$survey_id}' AND email = '" . addslashes($email) . "'");
    }
    $smarty->assign('link', $http_location . "/survey.php?survey_key=" . $access_key);
    # Get repondents info (if respondent - customer)
    $userinfo = array();
    if (!empty($customer_id)) {
        $userinfo = cw_user_get_info($customer_id);
        $smarty->assign('userinfo', $userinfo);
    } else {
        $smarty->assign('userinfo', false);
    }
    # Send invitation
    $to_customer = $userinfo['language'] ? $userinfo['language'] : $config['default_customer_language'];
    cw_call('cw_send_mail', array($config['Company']['support_department'], $email, "mail/survey_invitation_subj.tpl", "mail/survey_invitation.tpl"));
    cw_array2update("survey_maillist", array("sent_date" => time(), "delay_date" => 0), "survey_id = '{$survey_id}' AND email = '" . addslashes($email) . "'");
    return true;
}
function cw_salesman_change_discount_status($id, $status)
{
    global $tables, $smarty;
    db_query("update {$tables['discount_coupons']} set status='{$status}' where coupon='{$id}'");
    cw_load('mail', 'user');
    $coupon = cw_query_first("select * from {$tables['discount_coupons']} where coupon='{$id}'");
    if (!$coupon) {
        return;
    }
    $smarty->assign('coupon', $coupon);
    $userinfo = cw_user_get_info($coupon['customer_id']);
    $smarty->assign('userinfo', $userinfo);
    cw_call('cw_send_mail', array($config['Company']['orders_department'], $userinfo['email'], 'mail/salesman_coupon_subj.tpl', 'mail/salesman_coupon.tpl'));
}
function cw_order_messages_process_new_emails($condition = "")
{
    global $tables, $config;
    global $take_messages_debug;
    cw_load('doc', 'user');
    $new_emails = cw_query("select * from {$tables['mail_rpool']} {$condition}");
    if (empty($new_emails)) {
        return;
    }
    $processed_mail_ids = array();
    foreach ($new_emails as $email) {
        if (strpos($email['body'], '--------- please reply above this line ----------') !== false) {
            $bodyparts = explode("--------- please reply above this line ----------", $email['body']);
            if (!empty($bodyparts[0])) {
                $email['body'] = $bodyparts[0];
            }
        }
        //remove RE, FWD etc from subject
        $clean_subject = cw_order_messages_remove_re($email['subject']);
        //cw_log_add("order_messages_process_new_emails",array('clean_subject'=>$clean_subject));
        if ($take_messages_debug == 'Y') {
            print_r(array('clean_subject' => $clean_subject));
            print "<br>";
        }
        $related_threads = cw_query($s = "select {$tables['order_messages_messages']}.*, {$tables['order_messages_threads']}.doc_id from {$tables['order_messages_messages']} left join {$tables['order_messages_threads']} on {$tables['order_messages_threads']}.thread_id={$tables['order_messages_messages']}.thread_id where {$tables['order_messages_messages']}.subject = '{$clean_subject}'");
        //cw_log_add("order_messages_process_new_emails", array('related_threads'=>$related_threads, 'sql'=>$s));
        if ($take_messages_debug == 'Y') {
            print_r(array('related_threads' => $related_threads, 'sql' => $s));
            print "<br>";
        }
        if (!empty($related_threads)) {
            foreach ($related_threads as $doc_thread) {
                $doc_data = cw_call('cw_doc_get', array($doc_thread['doc_id'], 8192));
                if ($email['mail_from'] == $doc_data['userinfo']['email']) {
                    $new_message_id = cw_array2insert('order_messages_messages', array('thread_id' => $doc_thread['thread_id'], 'sender_id' => $doc_data['userinfo']['customer_id'], 'recepient_id' => $doc_thread['author_id'], 'author_id' => $doc_data['userinfo']['customer_id'], 'date' => time(), 'subject' => addslashes($email['subject']), 'body' => addslashes($email['body']), 'read_status' => 0));
                    //notify recipient over email when reply is processed
                    cw_order_messages_notify_other_respondent($new_message_id, $doc_thread['author_id'], $doc_thread['doc_id']);
                    $processed_mail_ids[] = $email['mail_id'];
                    break;
                } elseif (cw_query_first_cell("select count(*) from {$tables['customers']} where usertype='A' and email='{$email['mail_from']}'")) {
                    $admin_id = cw_query_first_cell("select customer_id from {$tables['customers']} where usertype='A' and email='{$email['mail_from']}'");
                    $recepient_ids = array();
                    if ($doc_thread['sender_id'] != $admin_id) {
                        $recepient_ids[] = $doc_thread['sender_id'];
                    }
                    if ($doc_thread['recepient_id'] != $admin_id) {
                        $recepient_ids[] = $doc_thread['recepient_id'];
                    }
                    $new_message_id = cw_array2insert('order_messages_messages', array('thread_id' => $doc_thread['thread_id'], 'sender_id' => $admin_id, 'recepient_id' => $recepient_ids[0], 'author_id' => $admin_id, 'date' => time(), 'subject' => addslashes($email['subject']), 'body' => addslashes($email['body']), 'read_status' => 0));
                    //notify recipient over email when reply is processed
                    foreach ($recepient_ids as $recepient_id) {
                        cw_order_messages_notify_other_respondent($new_message_id, $recepient_id, $doc_thread['doc_id']);
                    }
                    $processed_mail_ids[] = $email['mail_id'];
                    break;
                } else {
                    $supplier_info = array();
                    foreach ($doc_data['products'] as $doc_product) {
                        if ($doc_product['supplier_customer_id']) {
                            $supplier_info = cw_user_get_info($doc_product['supplier_customer_id'], 1);
                            if ($supplier_info['email'] == $email['mail_from']) {
                                break;
                            }
                            $supplier_info = array();
                        }
                    }
                    if (!empty($supplier_info)) {
                        $new_message_id = cw_array2insert('order_messages_messages', array('thread_id' => $doc_thread['thread_id'], 'sender_id' => $supplier_info['customer_id'], 'recepient_id' => $doc_thread['author_id'], 'author_id' => $supplier_info['customer_id'], 'date' => time(), 'subject' => addslashes($email['subject']), 'body' => addslashes($email['body']), 'read_status' => 0));
                        //notify recipient over email when reply is processed
                        cw_order_messages_notify_other_respondent($new_message_id, $doc_thread['author_id'], $doc_thread['doc_id']);
                        $processed_mail_ids[] = $email['mail_id'];
                        break;
                    }
                }
            }
        } else {
            //detect thread by {thread_id} or create new thread by #SW [doc_id]
            //cw_log_add("order_messages_process_new_emails", "detect thread by {thread_id}");
            if ($take_messages_debug == 'Y') {
                print_r(array("detect thread by {thread_id}"));
                print "<br>";
            }
            $email_thread_id = intval(cw_order_messages_take_out_from_tags($email['subject'], "{", "}", false));
            $related_thread = cw_query_first("select {$tables['order_messages_threads']}.* from {$tables['order_messages_threads']} where {$tables['order_messages_threads']}.thread_id='{$email_thread_id}'");
            if (empty($related_thread)) {
                $email_thread_id = 0;
            }
            //cw_log_add("order_messages_process_new_emails",array("email_thread_id"=>$email_thread_id));
            if ($take_messages_debug == 'Y') {
                print_r(array("email_thread_id" => $email_thread_id));
                print "<br>";
            }
            if (empty($email_thread_id) && strpos($email['subject'], "#") !== false) {
                $_parts = explode("#", cw_order_messages_remove_doc_prefix($email['subject']));
                $extracted_doc_id = intval(trim($_parts[1]));
                //cw_log_add("order_messages_process_new_emails", array("extracted_doc_id"=>$extracted_doc_id));
                if ($take_messages_debug == 'Y') {
                    print_r(array("extracted_doc_id" => $extracted_doc_id));
                    print "<br>";
                }
                if ($extracted_doc_id) {
                    $doc_data = cw_call('cw_doc_get', array($extracted_doc_id, 8192));
                    if (!empty($doc_data)) {
                        $email_thread_id = cw_array2insert('order_messages_threads', array('doc_id' => $extracted_doc_id, 'type' => 'A'));
                    }
                }
                //cw_log_add("order_messages_process_new_emails", array("created new thread"=>$email_thread_id));
                if ($take_messages_debug == 'Y') {
                    print_r(array("created new thread" => $email_thread_id));
                    print "<br>";
                }
                if (!empty($email_thread_id)) {
                    $related_thread = $email_thread_id;
                }
            }
            if (empty($related_thread)) {
                continue;
            }
            $email_sender_id = cw_query_first_cell("select customer_id from {$tables['customers']} where email='{$email['mail_from']}'");
            //cw_log_add("order_messages_process_new_emails", array("$email[mail_from] email_sender_id $email_sender_id"));
            if ($take_messages_debug == 'Y') {
                print_r(array("{$email['mail_from']} email_sender_id {$email_sender_id}"));
                print "<br>";
            }
            if (empty($email_sender_id)) {
                continue;
            }
            //is sender email related to detected thread
            $is_email_allowed = cw_query_first_cell("select count(*) from {$tables['order_messages_messages']} where {$tables['order_messages_messages']}.thread_id='{$email_thread_id}' and ({$tables['order_messages_messages']}.sender_id='{$email_sender_id}' or {$tables['order_messages_messages']}.recepient_id='{$email_sender_id}' or {$tables['order_messages_messages']}.author_id='{$email_sender_id}')");
            if (!$is_email_allowed) {
                $is_email_allowed = cw_query_first_cell("select count(*) from {$tables['docs_user_info']} dui, {$tables['docs']} d, {$tables['order_messages_threads']} omt where omt.thread_id='{$email_thread_id}' and omt.doc_id=d.doc_id and d.doc_info_id=dui.doc_info_id and dui.email='{$email['mail_from']}'");
            }
            //cw_log_add("order_messages_process_new_emails", "<br>is_email_allowed $is_email_allowed<br>");
            if ($take_messages_debug == 'Y') {
                print_r(array("<br>is_email_allowed {$is_email_allowed}<br>"));
                print "<br>";
            }
            if ($is_email_allowed) {
                //get other respondends in thread
                $other_respondent_id = cw_query_first_cell("select sender_id from {$tables['order_messages_messages']} where thread_id='{$email_thread_id}' and sender_id != '{$email_sender_id}'");
                //cw_log_add("order_messages_process_new_emails","<br>other_respondent_id $other_respondent_id<br>");
                if ($take_messages_debug == 'Y') {
                    print_r(array("<br>other_respondent_id {$other_respondent_id}<br>"));
                    print "<br>";
                }
                if (empty($other_respondent_id)) {
                    $other_respondent_id = cw_query_first_cell("select recepient_id from {$tables['order_messages_messages']} where thread_id='{$email_thread_id}' and recepient_id != '{$email_sender_id}'");
                }
                if (empty($other_respondent_id) || cw_query_first_cell("select count(*) from {$tables['customers']} where usertype='A' and customer_id='{$other_respondent_id}'")) {
                    //use default id to sent email
                    if (!empty($config['order_messages']['default_recepient_admin_email'])) {
                        $default_recepient_admin_email = $config['order_messages']['default_recepient_admin_email'];
                    }
                    $other_respondent_id = cw_query_first_cell("select customer_id from {$tables['customers']} where usertype='A' and email='{$default_recepient_admin_email}'");
                    //cw_log_add("order_messages_process_new_emails","<br>selected default recepient ($default_recepient_admin_email): customer_id = $other_respondent_id<br>");
                    if ($take_messages_debug == 'Y') {
                        print_r(array("<br>selected default recepient ({$default_recepient_admin_email}): customer_id = {$other_respondent_id}<br>"));
                        print "<br>";
                    }
                }
                if (!empty($other_respondent_id)) {
                    global $smarty, $current_language;
                    $rnd_key = time();
                    $smarty->assign('message', array('subject' => $rnd_key, 'thread_id' => $email_thread_id));
                    $smarty->assign('doc_id', $related_thread['doc_id']);
                    $language = $language ? $language : $current_language;
                    $order_subject_template = 'addons/order_messages/mail/customer_subj.tpl';
                    $test_subject = chop(cw_display($order_subject_template, $smarty, false, $language));
                    //cw_log_add("order_messages_process_new_emails","<br>test subject: $test_subject<br>");
                    if ($take_messages_debug == 'Y') {
                        print_r(array("<br>test subject: {$test_subject}<br>"));
                        print "<br>";
                    }
                    $subject_parts = explode($rnd_key, $test_subject);
                    $extracted_replied_subject = str_replace($subject_parts, "", $email['subject']);
                    //cw_log_add("order_messages_process_new_emails","<br>extracted_replied_subject $extracted_replied_subject<br>");
                    if ($take_messages_debug == 'Y') {
                        print_r(array("<br>extracted_replied_subject {$extracted_replied_subject}<br>"));
                        print "<br>";
                    }
                    $new_message_id = cw_array2insert('order_messages_messages', array('thread_id' => $email_thread_id, 'sender_id' => $email_sender_id, 'recepient_id' => $other_respondent_id, 'author_id' => $email_sender_id, 'date' => time(), 'subject' => addslashes($extracted_replied_subject), 'body' => addslashes($email['body']), 'read_status' => 0));
                    cw_order_messages_notify_other_respondent($new_message_id, $other_respondent_id, $related_thread['doc_id']);
                    $processed_mail_ids[] = $email['mail_id'];
                }
            }
        }
    }
    //if ($take_messages_debug != "Y")
    if (!empty($processed_mail_ids)) {
        db_query("delete from {$tables['mail_rpool']} where mail_id in ('" . implode("','", $processed_mail_ids) . "')");
    }
    return $processed_mail_ids;
}
             cw_session_register("login_redirect");
             $login_redirect = 1;
         }
         // Update addresses in session from database
         $user_address =& cw_session_register('user_address', array());
         $user_address['current_address'] = cw_user_get_address($customer_id, 'current');
         $user_address['main_address'] = cw_user_get_address($customer_id, 'main');
         db_query("update {$tables['customers_system_info']} set last_login='******' where customer_id='{$customer_id}'");
         $current_language = $user_data['language'];
         $items_per_page_targets = cw_core_restore_navigation($customer_id);
         cw_include('init/lng.php');
         $cart =& cw_session_register('cart', array());
         if ($current_area == "C" && cw_is_cart_empty($cart)) {
             $cart = cw_user_get_stored_cart($customer_id);
         }
         $userinfo = cw_user_get_info($customer_id);
         $products = cw_call('cw_products_in_cart', array($cart, $userinfo));
         $cart = cw_func_call('cw_cart_calc', array('cart' => $cart, 'products' => $products, 'userinfo' => $userinfo));
         cw_event('on_login', array($customer_id, $current_area, 0));
         if (!empty($instagram_login_info['return_url'])) {
             cw_header_location($instagram_login_info['return_url']);
         } else {
             cw_header_location($instagram_redirect_url);
         }
     }
 } else {
     //For Guest user, get instagram login url
     $instagram_login_authUrl = $instagram->getLoginUrl();
     $smarty->assign('instagram_login_authUrl', $instagram_login_authUrl);
     if (!$is_ajax) {
         $instagram_login_info['return_url'] = $current_host_location . $_SERVER['REQUEST_URI'];
<?php

if (!defined('APP_START')) {
    die('Access denied');
}
cw_load('user', 'salesman');
$affiliates = cw_get_affiliates($customer_id);
$childs_sales = 0;
if (!empty($affiliates)) {
    for ($y = 0; $y < count($affiliates); $y++) {
        $childs_sales += $affiliates[$y]['sales'] + $affiliates[$y]['childs_sales'];
    }
    $smarty->assign("affiliates", $affiliates);
}
$parent_affiliate = cw_user_get_info($customer_id);
$parent_affiliate['level'] = cw_get_affiliate_level(addslashes($customer_id));
$parent_affiliate['sales'] = cw_query_first_cell("SELECT SUM(commissions) FROM {$tables['salesman_payment']} WHERE salesman_customer_id='{$customer_id}'");
$parent_affiliate['childs_sales'] = $childs_sales;
$smarty->assign('parent_affiliate', $parent_affiliate);