function cw_error_check(&$array_to_check, $rules, $attributes_type = '')
{
    $error = array();
    $index = 1;
    foreach ($rules as $k => $v) {
        $func = is_array($v) && isset($v['func']) ? $v['func'] : $v;
        if ($func && function_exists($func)) {
            $is_error = $func($array_to_check[$k], $k, $array_to_check);
        } else {
            $is_error = empty($array_to_check[$k]) || !$array_to_check[$k];
        }
        if ($is_error) {
            $var = 'err_field_' . ($v['lng'] ? $v['lng'] : $k);
            $lng = cw_get_langvar_by_name($var, '', false, true);
            $error[] = $index++ . '. ' . ($lng ? $lng : $var);
        }
    }
    if ($attributes_type) {
        $error = array_merge($error, cw_call('cw_attributes_check', array($array_to_check['attribute_class_id'], &$array_to_check['attributes'], $attributes_type, $index)));
    }
    if (!count($error)) {
        return false;
    }
    return implode("<br/>\n", $error);
}
function cw_ps_bundle_update($product_id)
{
    global $tables, $config;
    $product_id = (int) $product_id;
    if ($_SERVER['REQUEST_METHOD'] != 'POST') {
        cw_ps_bundle_redirect($product_id);
    }
    $offer_id = cw_call('cw_ps_offer_bundle_update', array($product_id, $_POST));
    // Delete selected products
    if (is_array($_POST['del_cond'])) {
        foreach ($_POST['del_cond'] as $k => $v) {
            $k = intval($k);
            db_query("DELETE FROM {$tables['ps_cond_details']} WHERE offer_id='{$offer_id}' AND object_id='{$k}' AND object_type='" . PS_OBJ_TYPE_PRODS . "'");
            db_query("DELETE FROM {$tables['ps_bonus_details']} WHERE offer_id='{$offer_id}' AND object_id='{$k}' AND object_type='" . PS_OBJ_TYPE_PRODS . "'");
        }
    }
    $cond_products = cw_query_column("SELECT object_id FROM {$tables['ps_cond_details']} WHERE offer_id='{$offer_id}' AND object_type='" . PS_OBJ_TYPE_PRODS . "'");
    if (count($cond_products) <= 1) {
        //delete offer
        cw_call('cw_ps_offer_delete', array($offer_id));
    }
    cw_array2update('ps_offers', array('auto' => 0), "offer_id='{$offer_id}'");
    // TODO: Domain assignation
    cw_ps_bundle_redirect($product_id);
}
function cw_speed_bar_delete($item_id)
{
    global $tables;
    db_query("delete from {$tables['speed_bar']} where item_id='{$item_id}'");
    db_query("delete from {$tables['speed_bar_lng']} where item_id='{$item_id}'");
    cw_call('cw_attributes_cleanup', array($item_id, 'B'));
}
function cw_product_filter_get_price_ranges($attribute_id, $price_values = null)
{
    global $config, $tables;
    $values = cw_call('cw_attributes_get_attribute_default_value', array($attribute_id));
    $ranges = array();
    foreach ($values as $v) {
        $pr = explode('-', $v['value_key']);
        $range['counter'] = 0;
        if (is_array($price_values)) {
            foreach ($price_values as $k => $p) {
                if ($k >= $pr[0] && $k <= $pr[1]) {
                    $range['counter'] += $p['counter'];
                }
            }
        }
        if ($range['counter'] == 0 || $v['active'] == 0) {
            continue;
        }
        $range['id'] = $v['attribute_value_id'];
        $range['url'] = cw_query_first_cell("SELECT value FROM {$tables['attributes_values']} WHERE item_id = '{$v['attribute_value_id']}'");
        $range['value'] = $v['value_key'];
        if ($config['product_filter']['show_ranges_values'] == "Y") {
            $range['name'] = $v['value'] . '(' . $config['General']['currency_symbol'] . str_replace('-', ' - ' . $config['General']['currency_symbol'], $v['value_key']) . ')';
        } else {
            $range['name'] = $v['value'];
        }
        array_push($ranges, $range);
    }
    return $ranges;
}
/**
 * get mail lists by customer
 *
 * @param $customer_id
 * @return null
 */
function cw_vertical_response_get_newslists_by_customer($customer_id)
{
    global $config;
    $return = cw_get_return();
    if ($customer_id) {
        $userinfo = cw_call('cw_user_get_info', array($customer_id, 0));
    } else {
        return $return;
    }
    $vertical_response_data =& cw_session_register('vertical_response_data', array());
    // clear data after day
    if (isset($vertical_response_data['time']) && $vertical_response_data['time'] + SECONDS_PER_DAY < cw_core_get_time()) {
        $vertical_response_data = array();
    }
    if (isset($vertical_response_data['lists']) && !empty($vertical_response_data['lists'])) {
        foreach ($vertical_response_data['lists'] as $list) {
            if ($list->status == 'active') {
                $return['vr_' . $list->id] = array('list_id' => 'vr_' . $list->id, 'name' => $list->name, 'descr' => $list->name, 'direct' => in_array($list->id, $vertical_response_data['user_lists']) ? 1 : 0);
            }
        }
    } else {
        $vertical_response_email = trim($config[vertical_response_addon_name]['vertical_response_email']);
        $vertical_response_password = trim($config[vertical_response_addon_name]['vertical_response_password']);
        try {
            $vertical_response_data['time'] = cw_core_get_time();
            // lifetime
            $vr = new SoapClient(vertical_response_wsdl, array('connection_timeout' => 5));
            $sid = $vr->login(array('username' => "{$vertical_response_email}", 'password' => "{$vertical_response_password}", 'session_duration_minutes' => vertical_response_ses_time));
            // get all lists
            $lists = $vr->enumerateLists(array('session_id' => $sid, 'type' => 'email', 'include_field_info' => false, 'limit' => 20));
            $vertical_response_data['lists'] = $lists;
            if (!empty($lists) && count($lists)) {
                foreach ($lists as $list) {
                    if ($list->status == 'active') {
                        // find lists with user with email $userinfo['email']
                        $list_members = $vr->searchListMembers(array('session_id' => $sid, 'field_name' => 'email_address', 'field_value' => $userinfo['email'], 'list_id' => $list->id, 'max_records' => 1));
                        if (!empty($list_members) && count($list_members)) {
                            $vertical_response_data['user_lists'][] = $list_members[0]->list_id;
                            $vertical_response_data['user_lists'] = array_unique($vertical_response_data['user_lists']);
                            if (empty($vertical_response_data['hash'])) {
                                foreach ($list_members[0]->member_data as $data) {
                                    if ($data->name == 'hash') {
                                        $vertical_response_data['hash'] = $data->value;
                                        break;
                                    }
                                }
                            }
                        }
                        $return['vr_' . $list->id] = array('list_id' => 'vr_' . $list->id, 'name' => $list->name, 'descr' => $list->name, 'direct' => !empty($list_members) ? 1 : 0);
                    }
                }
            }
        } catch (SoapFault $exception) {
            //exit ('fault: "' . $exception->faultcode . '" - ' . $exception->faultstring . "\n");
            return $return;
        }
    }
    return $return;
}
function smarty_function_pages_url($params, &$smarty)
{
    if ($params['assign']) {
        $smarty->assign($params['assign'], cw_call('cw_core_get_html_page_url', array($params)));
    } else {
        return cw_call('cw_core_get_html_page_url', array($params));
    }
}
function view($product_id)
{
    global $smarty;
    $product_video = cw_call('cw\\' . addon_name . '\\get_product_video', array($product_id));
    $smarty->assign('product_video', $product_video);
    //cw_var_dump($product_video);
    return true;
}
function product_stages_view()
{
    global $smarty, $product_id, $tables;
    $product_stages = cw_call('cw\\' . addon_name . '\\cw_product_stages_get_product_settings', array($product_id));
    $lib_stages = cw_query("select * from {$tables['product_stages_library']} order by title");
    $smarty->assign('product_stages', $product_stages);
    $smarty->assign('lib_stages', $lib_stages);
}
function export()
{
    global $REQUEST_METHOD, $smarty, $config, $addons, $top_message, $customer_id, $tables;
    global $mode, $action, $amazon_config;
    $success = false;
    if ($REQUEST_METHOD != 'POST') {
        cw_header_location('index.php?target=' . addon_target);
    }
    if ($_POST['export_type'] == 'PaQ' && (empty($_POST['price']) && empty($_POST['quantity']))) {
        $top_message = array('content' => 'At least Price or Quantity must be exported.', 'type' => 'E');
        cw_header_location('index.php?target=' . addon_target);
        return false;
    }
    $_filename = 'files/amazon/' . date('Ymd') . '_' . date('His') . '_' . $_POST['export_type'] . '.csv';
    if (($filename = cw_allow_file($_filename, true)) && ($file = cw_fopen($_filename, 'w', true))) {
        $pids = cw_call('cw_objects_get_list_ids', array('P'));
        if (empty($pids)) {
            $pids = cw_query_column("SELECT product_id FROM {$tables['products']} WHERE status=1");
            // Very bad. Use API
        }
        if ($pids) {
            $amazon_config = cw_array_merge($amazon_config, $config['amazon'], $_POST);
            cw_config_update('amazon', $_POST);
            $warnings = array();
            $data = array();
            $header_put = false;
            foreach ($pids as $v) {
                $variants = array();
                $prod = cw_func_call('cw_product_get', array('id' => $v, 'info_type' => 8 | 64 | 128 | 256 | 512 | 2048));
                $attr = cw_query_hash("SELECT a.field, av.value\n                    FROM {$tables['attributes_values']} av, {$tables['attributes']} a\n                    WHERE av.item_id={$v} AND av.item_type='P' AND a.attribute_id=av.attribute_id", 'field', false, true);
                // very bad. Use API
                if ($prod['is_variants']) {
                    $variants = cw_call('cw_get_product_variants', array($v));
                } else {
                    $variants[0] = $prod;
                }
                foreach ($variants as $var) {
                    $var = cw_array_merge($var, $attr);
                    if ($_POST['export_type'] == 'PaQ') {
                        $data = array('sku' => $var['productcode'], 'price' => $_POST['price'] ? $var['price'] : '', 'quantity' => $_POST['quantity'] ? $var['avail'] : '', 'leadtime-to-ship' => $amazon_config['default_leadtime_to_ship']);
                    }
                    if ($_POST['export_type'] == 'InvLoad') {
                        $data = array('sku' => $var['productcode'], 'product-id' => empty($amazon_config['product_id_type']) ? '' : (string) $var[$amazon_config['product_id']], 'product-id-type' => $amazon_config['product_id_type'], 'price' => $var['price'], 'item-condition' => empty($var[$amazon_config['item_condition']]) ? $amazon_config['default_item_condition'] : $var[$amazon_config['item_condition']], 'quantity' => empty($amazon_config['fulfillment_center_id']) ? $var['avail'] : '', 'add-delete' => empty($_POST['add-delete']) ? 'a' : $_POST['add-delete'], 'will-ship-internationally' => empty($var[$amazon_config['ship_internationally']]) ? $amazon_config['default_ship_internationally'] : $var[$amazon_config['ship_internationally']], 'expedited-shipping' => empty($var[$amazon_config['expedited_shipping']]) ? $amazon_config['default_expedited_shipping'] : $var[$amazon_config['expedited_shipping']], 'standard-plus' => empty($var[$amazon_config['standard_plus']]) ? $amazon_config['default_standard_plus'] : $var[$amazon_config['standard_plus']], 'item-note' => $var[$amazon_config['item_note']], 'fulfillment-center-id' => $amazon_config['fulfillment_center_id'], 'product-tax-code' => $amazon_config['default_product_tax_code'], 'leadtime-to-ship' => $amazon_config['default_leadtime_to_ship']);
                    }
                    if (!$header_put) {
                        fputcsv($file, array_keys($data), "\t");
                        $header_put = true;
                    }
                    fputcsv($file, $data, "\t");
                }
            }
        }
        fclose($file);
        $top_message = array('content' => 'File <b>' . $_filename . '</b> successfully created');
    }
    cw_header_location('index.php?target=' . addon_target);
}
function cw_pages_delete_page($page_id)
{
    global $tables, $var_dirs;
    $page_data = cw_query_first("select * from {$tables['pages']} where page_id='{$page_id}'");
    if (!$page_data['page_id']) {
        return;
    }
    db_query("delete from {$tables['pages']} where page_id='{$page_id}'");
    cw_call('cw_attributes_cleanup', array($page_id, 'S'));
}
function smarty_function_select_country($params, &$smarty)
{
    extract($params);
    if (empty($assign)) {
        $smarty->trigger_error("assign: missing 'assign' parameter");
        return;
    }
    cw_load('map');
    $smarty->assign($assign, cw_call('cw_map_get_countries'));
}
function cw_product_shipping_option_default(&$product)
{
    if (empty($product['product_shipping_option'])) {
        $shipping_options_data = cw_call('cw_product_shipping_get_options', array($product['product_id']));
        if (!empty($shipping_options_data['shipping_values'])) {
            $product['product_shipping_option'] = $shipping_options_data['shipping_values'][0]['shipping_id'];
        }
    }
    return $product;
}
function cw_group_edit_copy_product_status($status)
{
    global $ge_id;
    if (!$ge_id) {
        return;
    }
    while ($pid = cw_group_edit_each($ge_id, 1, $product_id)) {
        cw_call('cw_product_update_status', array($pid, $status));
    }
}
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 cw_payment_process_void($order)
{
    global $config;
    $doc_id = $order['doc_id'];
    $result = cw_call('cw_payment_do_void', array($order));
    if (!is_error($result)) {
        cw_call('cw_doc_place_extras_data', array($doc_id, array('capture_status' => 'V')));
        cw_call('cw_doc_change_status', array($doc_id, 'D'));
        cw_add_top_message('Payment voided, order status is changed to Declined');
    }
    return $result;
}
/**
 * Check unique productcode
 * @see hook for cw_can_edit_on_place()
 */
function cw_can_edit_on_place_productcode($token_data)
{
    if ($token_data['table'] == 'products' && $token_data['field'] == 'productcode' && !empty($token_data['pk'])) {
        $rules = array('productcode' => array('func' => 'cw_error_sku_exists'));
        $product_data = array('productcode' => $value);
        $fillerror = cw_call('cw_error_check', array(&$product_data, $rules, 'P'));
        if ($fillerror) {
            return error($fillerror);
        }
    }
    return true;
}
function cw_ps_products_in_cart_pre($cart, $user_info)
{
    $special_offers_apply =& cw_session_register("special_offers_apply");
    # Delete all free added products
    if (is_array($cart['products'])) {
        foreach ($cart['products'] as $kk => $vv) {
            if ($vv["promotion_suite"]["free_product"] == 'Y') {
                cw_call('cw_delete_from_cart', array(&$cart, $vv['cartid']));
            }
        }
    }
    # / Delete all free added products
    if (!empty($special_offers_apply['free_products'])) {
        foreach ($special_offers_apply['free_products'] as $pid => $qty) {
            #
            # Add product to the cart
            #
            $product = cw_func_call('cw_product_get', array('id' => $pid, 'info_type' => 8192));
            $avail_amount = $product['avail'];
            $qty = min($qty, $avail_amount);
            $min_amount = $product['min_amount'];
            if ($qty >= $min_amount) {
                cw_load('warehouse');
                $possible_warehouses = cw_warehouse_get_avails_customer($pid);
                $warehouse = key($possible_warehouses);
                $add_product = array();
                $add_product["product_id"] = $pid;
                $add_product["amount"] = $qty;
                $add_product["product_options"] = "";
                $add_product["price"] = 0.0;
                // warehouse is required, otherwise free product will be placed as separate order
                $add_product['warehouse_customer_id'] = $warehouse;
                // do to use cw_warehouse_add_to_cart_simple. It operates with global $cart while we use here local $cart copy
                //  $result = cw_call('cw_warehouse_add_to_cart_simple', array($pid, $qty, '', 0.00));
                $result = cw_call('cw_add_to_cart', array(&$cart, $add_product));
                # Adjust just added product
                foreach ($cart['products'] as $ck => $cv) {
                    if ($cv["cartid"] == $result['cartid']) {
                        $cart['products'][$ck]["promotion_suite"]["free_product"] = true;
                        // mark just added product as offered
                    }
                }
            } else {
                unset($special_offers_apply['free_products'][$pid]);
            }
        }
        // foreach
    }
    // if
    return new EventReturn($cart['products'], array($cart, $user_info));
    // replace cart in input params for main function
}
function order_tracking_redirect()
{
    global $smarty, $request_prepared;
    cw_load('doc');
    $order = cw_call('cw_doc_get', array($request_prepared['doc_id'], 0));
    if (empty($order) || $order['info']['tracking'] != $request_prepared['tracking']) {
        cw_header_location('index.php?target=error_message&error=access_denied&id=59');
    }
    $smarty->assign('order', $order);
    $form = cw_display('addons/shipping_system/tracking.tpl', $smarty, false);
    echo $form;
    exit;
}
function estimate_cart()
{
    global $request_prepared;
    $user_address =& cw_session_register('user_address', array());
    // Declare session var for addresses
    $user_address['current_address']['zipcode'] = $request_prepared['zipcode'];
    $user_address['current_address']['state'] = $request_prepared['state'];
    $user_address['current_address']['country'] = $request_prepared['country'];
    if (empty($user_address['current_address']['state']) && $user_address['current_address']['country'] == 'US') {
        cw_load('map');
        $user_address['current_address']['state'] = cw_call('cw_map_get_state_by_zip', array($user_address['current_address']['zipcode']));
    }
    cw_header_location('index.php?target=cart');
}
function cw_checkout_login_prepare()
{
    global $smarty, $user_account, $customer_id, $user_address;
    $customer_id =& cw_session_register('customer_id', 0);
    $fields_area = cw_profile_fields_get_area($customer_id, $salesman_membership, 1);
    list($profile_sections, $profile_fields, $additional_fields) = cw_profile_fields_get_sections('U', true, $fields_area);
    # kornev, the login information is not required here.
    if ($customer_id) {
        unset($profile_sections['web']);
    }
    $smarty->assign('profile_fields', $profile_fields);
    $smarty->assign('profile_sections', $profile_sections);
    cw_include('include/check_userdata.php');
    cw_include('include/check_usercart.php');
    $userinfo = cw_call('cw_checkout_userinfo', array($user_account));
    $smarty->assign('userinfo', $userinfo);
    $smarty->assign('user_account', $user_account);
}
function cw_top_menu_make_sql_query()
{
    global $tables, $app_web_dir;
    cw_load('category');
    $pcats_ = cw_func_call('cw_category_search', array('data' => array('active' => 1, 'all' => 1)));
    $pcats_ = $pcats_[0];
    foreach ($pcats_ as $v) {
        extract($v);
        $mid = 'p' . $category_id;
        $pmid = $parent_id;
        if ($pmid != 0) {
            $pmid = 'p' . $pmid;
        }
        $title = $category;
        $pcount = $product_count_web;
        //$link="$app_web_dir/?target=index&cat=$category_id";
        $link = cw_call('cw_core_get_html_page_url', array(array('var' => 'index', 'cat' => $category_id)));
        $pos = $tm_pos;
        $active = $tm_active;
        $title2 = $tm_title;
        $type = 'pcat';
        if (APP_AREA != 'customer' || $active != 0) {
            $pcats[] = compact('mid', 'pmid', 'title', 'pcount', 'link', 'pos', 'active', 'title2', 'type');
        }
    }
    unset($pcats_);
    $fields = "CONCAT('u',category_id) as mid, CONCAT(parent_id_tag,parent_id) as pmid, category as title,\n";
    $fields .= "0 as pcount, link, pos, active, '' as title2, 'ucat' as type\n";
    if (APP_AREA == 'customer') {
        $where = "where active=1";
    } else {
        $where = "";
    }
    $sql = "select {$fields} from {$tables['top_menu_user_categories']} {$where};";
    $ucats = cw_query($sql);
    $cats = array_merge($pcats, $ucats);
    foreach ($cats as $k => $v) {
        $sorter[$k] = $v['pos'];
    }
    array_multisort($sorter, $cats);
    return $cats;
}
function cw_messages_create_new_message($customer_id, $sender_name, $recipient_id, $recipient_email, $subject, $body, $conversation_id)
{
    global $config, $current_location;
    cw_load('email');
    // sent message (incoming folder)
    $new_message_id = cw_array2insert('messages', array('subject' => $subject, 'body' => $body, 'sender_id' => $customer_id, 'recipient_id' => $recipient_id, 'sending_date' => cw_core_get_time(), 'conversation_id' => !empty($conversation_id) ? $conversation_id : 0, 'conversation_customer_id' => $recipient_id));
    // duplicate for sent folder
    $current_conversation_id = !empty($conversation_id) ? $conversation_id : $new_message_id;
    $duplicate_message_id = cw_array2insert('messages', array('subject' => $subject, 'body' => $body, 'sender_id' => $customer_id, 'recipient_id' => $recipient_id, 'sending_date' => cw_core_get_time(), 'read_status' => 1, 'conversation_id' => $current_conversation_id, 'conversation_customer_id' => $customer_id, 'type' => 2, 'link_id' => $new_message_id));
    // unite message if they have not been united
    $data = array('link_id' => $duplicate_message_id);
    if (empty($conversation_id)) {
        $data['conversation_id'] = $new_message_id;
    }
    cw_array2update('messages', $data, "message_id = '{$new_message_id}'");
    // send notification email to recipient
    // notification is sent from system email and says about new received message from Sender at <sitename>
    $from = $config['Company']['site_administrator'];
    /*
        $mail_subject = "The notification of a new message";
        $mail_body = '<b>You have received a new message from "' . $sender_name . '" at <a href="' . $current_location . '">';
        $mail_body .= $config['Company']['company_name'] . '</a></b><br />';
        $mail_body .= '<b>Subject:</b> ' . $subject . '<br />';
        $mail_body .= '<b>Body:</b> ' . nl2br($body) . '<br />';
        $mail_body .= '<a href="' . $current_location . '/index.php?target=message_box&mode=new';
        $mail_body .= '&contact_id=' . $customer_id . '&conversation_id=' . $current_conversation_id . '">Link to reply</a><br />';
        cw_send_simple_mail($from, $recipient_email, $mail_subject, $mail_body);
    */
    global $smarty;
    $smarty->assign('sender_name', $sender_name);
    $smarty->assign('current_location', $current_location);
    $smarty->assign('config', $config);
    $smarty->assign('subject', $subject);
    $smarty->assign('body', $body);
    $smarty->assign('customer_id', $customer_id);
    $smarty->assign('recipient_id', $recipient_id);
    $smarty->assign('current_conversation_id', $current_conversation_id);
    $smarty->assign('new_message_id', $new_message_id);
    cw_call('cw_send_mail', array($from, $recipient_email, 'addons/messaging_system/mail/new_message_subj.tpl', 'addons/messaging_system/mail/new_message.tpl'));
    return $new_message_id;
}
function cw_payment_paypal_run_processor($params, $return)
{
    if ($params['payment_data']['processor'] == 'paypal') {
        global $config, $tables, $current_location;
        $cart =& cw_session_register('cart');
        $skey = cw_call('cw_payment_start');
        cw_call('cw_payment_put_data', array($skey, array('state' => 'GO', 'doc_ids' => $params['doc_ids'])));
        if ($params['userinfo']['current_address']['country'] == "US") {
            $_customer_state = $params['userinfo']['current_address']['state'];
        } else {
            $_customer_state = $params['userinfo']['current_address']['statename'];
        }
        $u_phone = preg_replace('![^\\d]+!', '', $params['userinfo']['current_address']['phone']);
        $pp_ordr = $config['paypal']['prefix'] . join("-", $params['doc_ids']);
        $fields = array("charset" => 'UTF-8', "cmd" => "_ext-enter", "custom" => $skey, "invoice" => $pp_ordr, "redirect_cmd" => "_xclick", 'item_name' => $config['paypal']['pp_payment_for'] . ' (Order #' . $pp_ordr . ')', "mrb" => "R-2JR83330TB370181P", "pal" => "RDGQCFJTT6Y6A", "rm" => "2", "email" => $params['userinfo']['email'], "first_name" => $params['userinfo']['current_address']['firstname'], "last_name" => $params['userinfo']['current_address']['firstname'], "country" => $params['userinfo']['current_address']['country'], "address1" => $params['userinfo']['current_address']['address'], "address2" => $params['userinfo']['current_address']['address_2'], "city" => $params['userinfo']['current_address']['city'], "zip" => $params['userinfo']['current_address']['zipcode'], "state" => $_customer_state, "day_phone_a" => substr($u_phone, -10, -7), "day_phone_b" => substr($u_phone, -7, -4), "day_phone_c" => substr($u_phone, -4), "night_phone_a" => substr($u_phone, -10, -7), "night_phone_b" => substr($u_phone, -7, -4), "night_phone_c" => substr($u_phone, -4), "business" => $config['paypal']['pp_account'], "item_name" => $config['paypal']['pp_payment_for'], "amount" => sprintf("%0.2f", $cart['info']['total']), "currency_code" => $config['paypal']['pp_currency'], "return" => $current_location . '/index.php?target=paypal&mode=success&secureid=' . $skey, 'cancel_return' => $current_location . '/index.php?target=paypal&mode=cancel&secureid=' . $skey, 'shopping_url' => $current_location . '/index.php?target=paypal&mode=cancel&secureid=' . $skey, "notify_url" => $current_location . '/index.php?target=paypal', "bn" => "cartworks");
        if ($config['paypal']['use_preauth'] == 'Y') {
            $fields['paymentaction'] = 'authorization';
        }
        cw_func_call('cw_payment_create_form', array('url' => 'https://' . ($config['paypal']['test_mode'] == 'N' ? "www.paypal.com" : "www.sandbox.paypal.com") . '/cgi-bin/webscr', 'fields' => $fields, 'name' => $params['payment_data']['title']));
        die;
    }
    return $return;
}
function smarty_function_tunnel($params, &$smarty)
{
    global $cw_allowed_tunnels;
    if (empty($params['func'])) {
        $smarty->trigger_error("tunnel: missing 'func' parameter");
        return;
    }
    if (!in_array($params['func'], $cw_allowed_tunnels, true)) {
        $smarty->trigger_error("tunnel: function {$params['func']} is not allowed for call from templates", E_USER_ERROR);
        return;
    }
    if ($params['load']) {
        cw_load($params['load']);
    }
    $assign = $params['assign'];
    $func = $params['func'];
    if ($params['via'] == 'cw_call') {
        // order and number of params is important for cw_call()
        // we accept only paramX as params
        $func_params = array();
        foreach ($params as $k => $v) {
            if (strpos($k, 'param') !== false) {
                $func_params[$k] = $v;
            }
        }
        ksort($func_params);
        $result = cw_call($params['func'], $func_params);
    } else {
        unset($params['load'], $params['func'], $params['assign']);
        $result = cw_func_call($func, $params);
    }
    if ($assign) {
        $smarty->assign($assign, $result);
    } else {
        echo $result;
    }
}
        cw_header_location("index.php?target=popup_poptions&target={$target}&id={$id}&err=exception");
    }
    if ($mode == 'wishlist') {
        db_query("UPDATE {$tables['wishlist']} SET options = '" . addslashes(serialize($poptions)) . "' WHERE wishlist_id = '{$id}' AND event_id = '{$eventid}'");
    } else {
        $variant_id = cw_get_variant_id($product_options, $product_id);
        $amount = cw_warehouse_get_warehouse_avail($cart['products'][$cartindex]['warehouse'], $product_id, null, $variant_id);
        //		$amount = cw_get_options_amount($poptions, $cart['products'][$cartindex]['product_id']);
        if ($amount >= $cart['products'][$cartindex]['amount']) {
            $cart['products'][$cartindex]['options'] = $poptions;
            cw_unset($cart['products'][$cartindex], 'variant_id');
        } else {
            cw_header_location("index.php?target=popup_poptions&target={$target}&id={$id}&err=avail");
        }
        # Recalculate cart totals after updating
        $products = cw_call('cw_products_in_cart', array($cart, $user_account));
        $cart = cw_func_call('cw_cart_calc', array('cart' => $cart, 'products' => $products, 'userinfo' => $user_account));
    }
    ?>
<script type="text/javascript">
<!--
if (window.opener) window.opener.location.reload();
window.close();
-->
</script>
<?php 
    exit;
}
if (!$min_avail) {
    $min_avail = cw_query_first_cell("SELECT min_amount FROM {$tables['products']} WHERE product_id = '{$product_id}'");
}
             $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'];
     }
                        cw_doc_make_relation($relation_doc_id, $rel_item_id, $v['amount']);
                    }
                    cw_doc_recalc($relation_doc_id);
                }
            }
            if ($doc_data['giftcerts'] && is_numeric($relation_doc_id)) {
                cw_doc_make_related_doc($doc_id, $relation_doc_id);
            }
        }
    }
    $secure_oid = $doc_ids;
} else {
    $doc_ids = $secure_oid;
}
cw_session_save();
if ($action == 'request_for_quote') {
    cw_call('cw_doc_change_status', array($doc_ids, "Q"));
    $request = $app_catalogs['customer'] . "/index.php?target=order-message&doc_ids=" . implode(",", $doc_ids);
    $cart = $secure_oid = array();
    cw_save_customer_cart($customer_id, $cart);
    cw_header_location($request);
} else {
    $return = cw_func_call('cw_payment_run_processor', array('payment_data' => $payment_data, 'doc_ids' => $doc_ids, 'userinfo' => $userinfo));
    if ($return && $payment_data['payment_type'] == 'cc') {
        $a = strlen($userinfo['card_cvv2']);
        $return['cvvmes'] = ($a ? $a . " digit(s)" : "not set") . " / ";
    }
    $return = cw_call('cw_payment_check_results', array($return));
    cw_call('cw_payment_stop', array($return));
}
exit;
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'));
}
<?php

global $docs_type;
$docs_type = 'O';
cw_load('doc');
$search_data =& cw_session_register('search_data');
$search_data['orders'][$docs_type]['warehouse_area'] = $customer_id;
if ($doc_id) {
    $doc_data = cw_call('cw_doc_get', array($request_prepared['doc_id'], 0));
    if ($customer_id != $doc_data['info']['warehouse_customer_id']) {
        cw_header_location("index.php?target=error_message&error=access_denied&id=40");
    }
    cw_include('include/orders/order.php');
} else {
    cw_include('include/orders/orders.php');
}
$smarty->assign('page_acl', '__18');
$smarty->assign('current_section_dir', 'orders');
     if ($list['lngcode'] != $current_language && is_array($d_langs) && !in_array($list['lngcode'], $d_langs)) {
         cw_header_location("index.php?target={$target}&mode=modify&list_id={$list_id}&edit_lng={$list['lngcode']}&old_lng={$current_language}");
     }
 }
 $memberships = cw_query("select membership_id from {$tables['newslists_memberships']} where list_id='{$list['list_id']}'");
 if ($memberships) {
     foreach ($memberships as $val) {
         $list['memberships'][$val['membership_id']] = true;
     }
 }
 $list_idname = cw_query_first_cell("SELECT name FROM {$tables['newslists']} WHERE list_id='{$list_id}'");
 $smarty->assign('list_idname', $list_idname);
 $smarty->assign('list_id', $list_id);
 $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)) {