function cw_xml_parse($data, &$error, $options = array(), $is_simple = 0)
{
    static $default_options = array('XML_OPTION_CASE_FOLDING' => 0, 'XML_OPTION_SKIP_WHITE' => 1);
    $data = trim($data);
    $vals = $index = $array = array();
    $parser = xml_parser_create();
    $options = cw_array_merge($default_options, $options);
    foreach ($options as $opt => $val) {
        if (!defined($opt)) {
            continue;
        }
        xml_parser_set_option($parser, constant($opt), $val);
    }
    if (!xml_parse_into_struct($parser, $data, $vals, $index)) {
        $error = array('code' => xml_get_error_code($parser), 'string' => xml_error_string(xml_get_error_code($parser)), 'line' => xml_get_current_line_number($parser));
        xml_parser_free($parser);
        return false;
    }
    xml_parser_free($parser);
    $i = 0;
    if ($is_simple) {
        $tagname = $vals[$i]['tag'];
        $array[$tagname] = _func_xml_make_tree($vals, $i, $is_simple);
    } else {
        $tagname = $vals[$i]['tag'];
        if (isset($vals[$i]['attributes'])) {
            $array[$tagname]['@'] = $vals[$i]['attributes'];
        } else {
            $array[$tagname]['@'] = array();
        }
        $array[$tagname]['#'] = _func_xml_make_tree($vals, $i, $is_simple);
    }
    return $array;
}
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 on_add_cart(&$cart, $added_product)
{
    global $smarty;
    cw_load('ajax', 'product');
    $product_id = $cart['products'][$added_product['productindex']]['product_id'];
    $product = cw_func_call('cw_product_get', array('id' => $product_id, 'info_type' => 0 | 128));
    $product = cw_array_merge($product, $added_product);
    $smarty->assign('product', $product);
    cw_add_ajax_block(array('id' => 'add2cart_popup', 'action' => 'update', 'template' => 'addons/ajax_add2cart/add2cart_popup.tpl'), 'add2cart_popup');
    cw_add_ajax_block(array('id' => 'script', 'content' => 'sm("add2cart_popup",add2cart_popup_width,add2cart_popup_height, true, "' . $added_product['added_amount'] . ($added_product['added_amount'] > 1 ? ' items' : ' item') . ' added to cart")'), 'add2cart_popup_script');
}
function cw_image_save(&$image_posted, $added_data = array(), $_image_id = NULL)
{
    global $tables, $available_images, $skip_image, $config;
    $type = $image_posted['type'];
    $image_data = cw_image_prepare($image_posted);
    if ($available_images[$type]['max_width']) {
        cw_image_resize($image_data, $available_images[$type]['max_width']);
    } elseif ($config['Appearance']['size_user_avatar'] && $type == 'customers_images') {
        cw_image_resize($image_data, $config['Appearance']['size_user_avatar']);
    }
    if (!empty($added_data)) {
        $image_data = cw_array_merge($image_data, $added_data);
    }
    if (!$image_data || !$image_data['id']) {
        return false;
    }
    if ($skip_image[$type] == 'Y') {
        if (!empty($image_posted['is_copied'])) {
            @unlink($image_posted['file_path']);
        }
        unset($image_posted);
        return false;
    }
    $image_data['date'] = cw_core_get_time();
    $image_data = cw_addslashes($image_data);
    unset($image_posted);
    $_table = $tables[$type];
    if ($available_images[$type]['type'] == 'U') {
        cw_image_delete($image_data['id'], $type);
    }
    return cw_array2insert($type, $image_data);
}
function cw_get_parents($user)
{
    global $tables, $config;
    $parent = cw_query_first_cell("SELECT salesman_customer_id FROM {$tables['customers_relations']} WHERE customer_id='{$user}'");
    if ($parent) {
        $parents[] = array("customer_id" => $parent, "level" => cw_get_affiliate_level($parent));
        $parents = cw_array_merge($parents, cw_get_parents($parent));
    }
    return $parents;
}
function cw_fedex_prepare_xml_query($packages, $weight, $fedex_options, $to_address, $from_address)
{
    global $config;
    $fedex_weight = cw_units_convert(cw_weight_in_grams($weight), "g", "lbs", 1);
    if ($fedex_weight < 1) {
        $fedex_weight = 1;
    }
    $_time = time() + $config['Appearance']['timezone_offset'] + intval($fedex_options['ship_date']) * 24 * 3600;
    $fedex_options['ship_date_ready'] = date("Y-m-d", $_time) . "T" . date("H:i:s", $_time);
    $fedex_options['original_country_code'] = $from_address["country"];
    if (in_array($fedex_options['original_country_code'], array('US', 'CA'))) {
        $fedex_options['original_postal_code'] = preg_replace("/[^A-Za-z0-9]/", "", $from_address["zipcode"]);
        $fedex_options['original_state_code'] = $from_address["state"];
    } else {
        $fedex_options['original_postal_code'] = preg_replace("/[^A-Za-z0-9]/", "", $from_address["zipcode"]);
        $fedex_options['original_state_code'] = '';
    }
    $fedex_options['destination_country_code'] = $to_address["country"];
    $fedex_options['destination_postal_code'] = preg_replace("/[^A-Za-z0-9]/", "", $to_address["zipcode"]);
    if (in_array($fedex_options['destination_country_code'], array('US', 'CA'))) {
        $fedex_options['destination_state_code'] = $to_address["state"];
    }
    /*
        $return_transit_and_commit = <<<OUT
        <q0:ReturnTransitAndCommit>true</q0:ReturnTransitAndCommit>
    OUT;
    */
    // Carrier codes
    $carriers_xml = '';
    foreach ($fedex_options['carrier_codes'] as $carrier) {
        $carriers_xml .= <<<OUT
    <q0:CarrierCodes>{$carrier}</q0:CarrierCodes>
OUT;
    }
    // Special services
    $special_services_types = $special_services = array('package' => array(), 'shipment' => array());
    if (!empty($fedex_options['cod_value']) && doubleval($fedex_options['cod_value']) > 0) {
        $special_services['shipment'][] = <<<OUT
            <q0:CodDetail>
                <q0:CollectionType>{$fedex_options['cod_type']}</q0:CollectionType>
            </q0:CodDetail>
OUT;
        $special_services['shipment'][] = <<<OUT
        <q0:CodCollectionAmount>
            <q0:Currency>{$fedex_options['currency_code']}</q0:Currency>
            <q0:Amount>{$fedex_options['cod_value']}</q0:Amount>
        </q0:CodCollectionAmount>
OUT;
        $special_services_types['shipment'][] = 'COD';
    }
    if ($fedex_options['hold_at_location'] == 'Y') {
        $special_services_types['shipment'][] = 'HOLD_AT_LOCATION';
        $special_services['shipment'][] = "<q0:HoldAtLocationDetail><q0:PhoneNumber>{$to_address['phone']}</q0:PhoneNumber></q0:HoldAtLocationDetail>";
    }
    if (!empty($fedex_options['dg_accessibility'])) {
        $special_services['package'][] = <<<OUT
        <q0:DangerousGoodsDetail>
            <q0:Accessibility>{$fedex_options['dg_accessibility']}</q0:Accessibility>
        </q0:DangerousGoodsDetail>
OUT;
        $special_services_types['package'][] = 'DANGEROUS_GOODS';
    }
    if ($fedex_options['dry_ice'] == 'Y') {
        $special_services['package'][] = <<<OUT
        <q0:DryIceWeight>
            <q0:Units>LB</q0:Units>
            <q0:Value>{$fedex_weight}</q0:Value>
        </q0:DryIceWeight>
OUT;
        $special_services_types['package'][] = 'DRY_ICE';
    }
    if ($fedex_options['inside_pickup'] == 'Y') {
        $special_services_types['shipment'][] = 'INSIDE_PICKUP';
    }
    if ($fedex_options['inside_delivery'] == 'Y') {
        $special_services_types['shipment'][] = 'INSIDE_DELIVERY';
    }
    if ($fedex_options['saturday_pickup'] == 'Y') {
        $special_services_types['shipment'][] = 'SATURDAY_PICKUP';
    }
    if ($fedex_options['saturday_delivery'] == 'Y') {
        $special_services_types['shipment'][] = 'SATURDAY_DELIVERY';
    }
    if ($fedex_options['nonstandard_container'] == "Y") {
        $special_services_types['package'][] = 'NON_STANDARD_CONTAINER';
    }
    if (!empty($fedex_options['signature'])) {
        $special_services['package'][] = <<<OUT
        <q0:SignatureOptionDetail>
            <q0:OptionType>{$fedex_options['signature']}</q0:OptionType>
        </q0:SignatureOptionDetail>
OUT;
    }
    foreach ($special_services_types as $k => $ss_types) {
        if (!empty($ss_types)) {
            foreach ($ss_types as $key => $ss_type) {
                $special_services_types[$k][$key] = "<q0:SpecialServiceTypes>" . $ss_type . "</q0:SpecialServiceTypes>";
            }
        }
        $special_services[$k] = cw_array_merge($special_services_types[$k], $special_services[$k]);
    }
    foreach ($special_services as $k => $ss) {
        if (!empty($ss)) {
            $special_services_xml[$k] = '';
            foreach ($ss as $_service) {
                $special_services_xml[$k] .= "\t\t" . $_service . "\n";
            }
            $special_services_xml[$k] = "<q0:SpecialServicesRequested>" . $special_services_xml[$k] . "</q0:SpecialServicesRequested>";
        } else {
            $special_services_xml[$k] = '';
        }
    }
    // Packages query
    $package_count = count($packages);
    $i = 1;
    $items_xml = '';
    /*
    global $REMOTE_ADDR;
    if ($REMOTE_ADDR == "85.130.76.171") {
        cw_log_add("fedex_shipping_package", array($packages));
    }
    */
    foreach ($packages as $pack) {
        $dimensions_xml = cw_fedex_prepare_dimensions_xml($pack, $fedex_options);
        // Declared value
        $declared_value_xml = '';
        if ($fedex_options['send_insured_value'] == 'Y' && !empty($pack['price']) && doubleval($pack['price']) > 0) {
            $declared_value_xml = <<<OUT
            <q0:InsuredValue>
                <q0:Currency>{$fedex_options['currency_code']}</q0:Currency>
                <q0:Amount>{$pack['price']}</q0:Amount>
            </q0:InsuredValue>
OUT;
        }
        //        $pack['weight'] = cw_units_convert(cw_weight_in_grams($pack[weight]), "g", "lbs", 1);
        //        if (!$pack['weight']) $pack['weight'] = 1;
        $items_xml .= <<<EOT
        <q0:RequestedPackageLineItems>
            <q0:SequenceNumber>{$i}</q0:SequenceNumber>
            {$declared_value_xml}
            <q0:Weight>
                <q0:Units>LB</q0:Units>
                <q0:Value>{$pack[weight]}</q0:Value>
            </q0:Weight>
            {$dimensions_xml}
            {$special_services_xml['package']}
        </q0:RequestedPackageLineItems>
EOT;
        $i++;
    }
    $residential = $fedex_options['residential_delivery'] == 'Y' ? "<q0:Residential>true</q0:Residential>" : "";
    // Handling charges
    if (!empty($fedex_options['handling_charges_amount']) && doubleval($fedex_options['handling_charges_amount']) > 0) {
        $_handling_type = $fedex_options['handling_charges_type'] == "FIXED_AMOUNT" ? "<q0:FixedValue><q0:Currency>{$fedex_options['currency_code']}</q0:Currency><q0:Amount>{$fedex_options['handling_charges_amount']}</q0:Amount></q0:FixedValue>" : "<q0:PercentValue>{$fedex_options['handling_charges_amount']}</q0:PercentValue>";
        $handling_charges_xml = <<<OUT
    <q0:VariableHandlingChargeDetail>
        <q0:VariableHandlingChargeType>{$fedex_options['handling_charges_type']}</q0:VariableHandlingChargeType>
        {$_handling_type}
    </q0:VariableHandlingChargeDetail>
OUT;
    } else {
        $handling_charges_xml = '';
    }
    // Prepare the XML request
    $xml_query = <<<OUT
<?xml version="1.0" encoding="UTF-8" ?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:q0="http://fedex.com/ws/rate/v7" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<q0:RateRequest>
    <q0:WebAuthenticationDetail>
        <q0:UserCredential>
            <q0:Key>{$fedex_options['key']}</q0:Key>
            <q0:Password>{$fedex_options['password']}</q0:Password>
        </q0:UserCredential>
    </q0:WebAuthenticationDetail>

    <q0:ClientDetail>
        <q0:AccountNumber>{$fedex_options['account_number']}</q0:AccountNumber>
        <q0:MeterNumber>{$fedex_options['meter_number']}</q0:MeterNumber>
    </q0:ClientDetail>

    <q0:TransactionDetail>
        <q0:CustomerTransactionId>Basic Rate</q0:CustomerTransactionId>
    </q0:TransactionDetail>

    <q0:Version>
        <q0:ServiceId>crs</q0:ServiceId>
        <q0:Major>7</q0:Major>
        <q0:Intermediate>0</q0:Intermediate>
        <q0:Minor>0</q0:Minor>
    </q0:Version>

    {$return_transit_and_commit}

    {$carriers_xml}
    
    <q0:RequestedShipment>
        <q0:ShipTimestamp>{$fedex_options['ship_date_ready']}</q0:ShipTimestamp>
        <q0:DropoffType>{$fedex_options['dropoff_type']}</q0:DropoffType>
        <q0:PackagingType>{$fedex_options['packaging']}</q0:PackagingType>

        <q0:Shipper>
            <q0:Address>
                <q0:StateOrProvinceCode>{$fedex_options['original_state_code']}</q0:StateOrProvinceCode>
                <q0:PostalCode>{$fedex_options['original_postal_code']}</q0:PostalCode>
                <q0:CountryCode>{$fedex_options['original_country_code']}</q0:CountryCode>
            </q0:Address>
        </q0:Shipper>

        <q0:Recipient>
            <q0:Address>
                <q0:StateOrProvinceCode>{$fedex_options['destination_state_code']}</q0:StateOrProvinceCode>
                <q0:PostalCode>{$fedex_options['destination_postal_code']}</q0:PostalCode>
                <q0:CountryCode>{$fedex_options['destination_country_code']}</q0:CountryCode>
                {$residential}
            </q0:Address>
        </q0:Recipient>

        <q0:ShippingChargesPayment>
            <q0:PaymentType>SENDER</q0:PaymentType>
            <q0:Payor>
                <q0:AccountNumber>{$fedex_options['account_number']}</q0:AccountNumber>
                <q0:CountryCode>{$fedex_options['original_country_code']}</q0:CountryCode>
            </q0:Payor>
        </q0:ShippingChargesPayment>

        {$special_services_xml['shipment']}

        {$handling_charges_xml}

        <q0:RateRequestTypes>ACCOUNT</q0:RateRequestTypes>
        <q0:PackageCount>{$package_count}</q0:PackageCount>
        <q0:PackageDetail>INDIVIDUAL_PACKAGES</q0:PackageDetail>

        {$items_xml}

    </q0:RequestedShipment>
</q0:RateRequest>
</soapenv:Body>
</soapenv:Envelope>
OUT;
    return $xml_query;
}
    }
    $smarty->assign('survey', $survey);
    $location[] = array(cw_get_langvar_by_name('lbl_survey_surveys'), 'index.php?target=' . $target);
    $location[] = array(cw_get_langvar_by_name('lbl_survey_results'));
    $smarty->assign('current_main_dir', 'addons');
    $smarty->assign('current_section_dir', 'survey');
    $smarty->assign('main', 'view_results');
} else {
    # Get surveys list
    $now = time();
    $allow_ids = array();
    if (!empty($allowed_surveys) && is_array($allowed_surveys)) {
        $allow_ids = cw_array_merge($allow_ids, array_values($allowed_surveys));
    }
    if (!empty($filled_surveys) && is_array($filled_surveys)) {
        $allow_ids = cw_array_merge($allow_ids, $filled_surveys);
    }
    $surveys = cw_query_hash("SELECT {$tables['surveys']}.* FROM {$tables['surveys']}, {$tables['survey_questions']} WHERE {$tables['surveys']}.valid_from_date < {$now} AND {$tables['surveys']}.expires_data > {$now} AND {$tables['surveys']}.survey_id = {$tables['survey_questions']}.survey_id AND ({$tables['surveys']}.survey_type = 'P'" . (empty($customer_id) ? "" : " OR {$tables['surveys']}.survey_type = 'R'") . " OR ({$tables['surveys']}.survey_type = 'H' AND {$tables['surveys']}.survey_id IN ('" . implode("','", $allow_ids) . "'))) GROUP BY {$tables['surveys']}.survey_id ORDER BY {$tables['surveys']}.orderby", "survey_id", false);
    $count_surveys = 0;
    $count_filled = 0;
    if (!empty($surveys)) {
        foreach ($surveys as $sid => $v) {
            list($is_valid, $messages) = cw_check_survey($sid);
            if (!$is_valid) {
                unset($surveys[$sid]);
                continue;
            }
            $count_surveys++;
            if (cw_check_survey_filling($sid)) {
                $surveys[$sid]['is_filled'] = true;
                $count_filled++;
 // Add subindex, e.g. 10->10.2
 # Pass the bonus if it's exclusive but some other bonuses already applied
 if ($b['exclusive'] == 'Y' && !empty($special_offers_apply['supply'])) {
     continue;
 }
 # save the current affected products in case the whole condition is not met
 $_affected_product_ids = $affected_product_ids;
 if (cw_special_offer_check($b['bonusid'])) {
     $current_bonus_supply = cw_query_hash("SELECT type, data FROM {$tables['bonus_supply']} WHERE bonusid='{$b['bonusid']}'", "type", false, true);
     $current_bonus_supply = array_map("unserialize", $current_bonus_supply);
     # Add applicable bonus info
     $special_offers_apply['supply'][$bid] = $current_bonus_supply;
     #
     # Prepare common array of supplies
     #
     $special_offers_apply['free_shipping']['method'] = cw_array_merge($special_offers_apply['free_shipping']['method'], $current_bonus_supply['S']['method']);
     if ($current_bonus_supply['S']['type'] == 'Y') {
         $special_offers_apply['free_shipping']['type'] = 'Y';
     }
     if (in_array($current_bonus_supply['S']['type'], array('C', 'S')) && $special_offers_apply['free_shipping']['type'] != 'Y') {
         $special_offers_apply['free_shipping']['type'] = $current_bonus_supply['S']['type'];
     }
     if ($current_bonus_supply['S']['type'] == 'C') {
         foreach ($_affected_product_ids['ids'] as $pid => $qty) {
             $special_offers_apply['free_shipping']['products'][$pid] += $qty - $affected_product_ids['ids'][$pid];
         }
     }
     if ($current_bonus_supply['S']['type'] == 'S') {
         if (is_array($current_bonus_supply['S']['product'])) {
             foreach ($current_bonus_supply['S']['product'] as $i => $product) {
                 $special_offers_apply['free_shipping']['products'][$product['pid']] += $product['quantity'];
$hash['s_city'] = $order['userinfo']['s_city'];
$hash['s_state'] = $order['userinfo']['s_state'];
$hash['s_zip'] = $order['userinfo']['s_zipcode'];
$hash['s_country'] = $order['userinfo']['s_country'];
$hash['shipmethod'] = $stype;
$hash['insuredvalue'] = $order['order']['total'];
$hash['weight'] = 0;
if (in_array($hash['s_country'], array("DO", "PR", "US"))) {
    $UPS_wunit = "LBS";
} else {
    $UPS_wunit = "KGS";
}
if (!empty($order['products'])) {
    foreach ($order['products'] as $p) {
        $hash['weight'] += $p['weight'] * $p['amount'];
    }
    $hash['weight'] = max(0.1, round(cw_weight_in_grams($hash['weight']) / ($UPS_wunit == "LBS" ? 453.6 : 1000), 1));
}
$strs[] = implode($delimiter, $hash);
# Create header
$header = implode($delimiter, cw_array_merge(array_keys($hash), $p_head));
# Create response
$response = array("result" => 'ok', "image" => $header . "\n" . implode("\n", $strs), "image_type" => "text/csv");
if ($is_first_ups_label) {
    $all_ups_shipping_labels['result'] = 'ok';
    $all_ups_shipping_labels['image'] = $header . "\n" . implode("\n", $strs);
    $all_ups_shipping_labels['image_type'] = 'text/csv';
    $is_first_ups_label = false;
} else {
    $all_ups_shipping_labels['image'] .= "\n" . implode("\n", $strs);
}
function cw_load_lang(&$smarty, $resource_name, $vars_list)
{
    if (empty($resource_name) || empty($vars_list)) {
        return;
    }
    $hash_file = cw_get_tpl_hash_name($smarty, $resource_name, $lng_code);
    $var_names = explode(',', $vars_list);
    $vars = false;
    $vars = cw_tpl_read_lng_hash($hash_file);
    if ($vars === false) {
        cw_tpl_build_lang($hash_file, $var_names, $lng_code);
        if (!file_exists($hash_file)) {
            return;
        }
        $vars = cw_tpl_read_lng_hash($hash_file, false);
    }
    if (!is_array($vars) || empty($vars)) {
        return;
    }
    $smarty->_tpl_vars['lng'] = cw_array_merge($smarty->_tpl_vars['lng'], $vars);
}
list($hour, $minute) = explode(':', $time_dump);
$log['init'] = '#' . $counter . ': ' . $log['init'];
cw_load('cron');
if (empty($manual_run)) {
    // New cron handlers are functions
    // Subscribe to one of this event with all your crontab functions, see cw_event_listen
    // on_cron_regular, on_cron_hourly, on_cron_daily and so on (see above)
    $tasks = $last_run['queue'];
    foreach ($run_periods as $p => $s) {
        if ($time - $last_run[$p] > $s - 10) {
            // 10 seconds gap for crontab/script starting process
            $on_cron = cw_get_hooks('on_cron_' . $p);
            unset($on_cron[0]);
            if (is_array($on_cron)) {
                $on_cron = array_fill_keys($on_cron, $p);
                $tasks = cw_array_merge($tasks, $on_cron);
                // Collect all tasks for execution
            }
            $last_run[$p] = $time;
        }
    }
    $log['scheduled'] = $tasks;
    cw_log_add('cron', $log, false);
    $log = array();
    $log['execution'] = '#' . $counter . ': Exec at ' . date('H:i:s', time());
    $executed = 0;
    // Exec all regular tasks and one scheduled
    foreach ($tasks as $task => $period) {
        if ($period == 'regular' || $executed == 0) {
            $log[$task] = cw_event($task, array($time, $last_run[$period]));
            if (empty($log[$task])) {
    } else {
        $top_message = array('content' => $fillerror, 'type' => 'E');
        $payment_modified_data = $posted_data;
    }
    cw_header_location("index.php?target={$target}&mode={$mode}&payment_id={$payment_id}&js_tab={$js_tab}");
}
$location[] = array(cw_get_langvar_by_name('lbl_payment_methods'), '');
if (isset($payment_id)) {
    $cc_addon_files = cw_query($sql = "select addon from {$tables['addons']} where parent='payment_system' and active=1");
    $smarty->assign('cc_addons', $cc_addon_files);
    $smarty->assign('memberships', cw_user_get_memberships(array('C', 'R')));
    $possible_shippings = cw_query("select shipping_id, shipping from {$tables['shipping']} where active=1");
    $smarty->assign('shippings', $possible_shippings);
    $payment = cw_payment_get($payment_id);
    if ($payment_modified_data) {
        $payment = cw_array_merge($payment, $payment_modified_data);
    }
    $smarty->assign('payment', $payment);
    $smarty->assign('payment_id', $payment_id);
    $smarty->assign('js_tab', $js_tab);
    $location[] = array(cw_get_langvar_by_name('lbl_modify_payment_method'), '');
    $smarty->assign('main', 'method');
    $attributes = cw_func_call('cw_attributes_get', array('item_id' => $payment_id, 'item_type' => 'G', 'prefilled' => $payment_modified_data['attributes'], 'language' => $edited_language));
    $smarty->assign('attributes', $attributes);
    $payment_modified_data = array();
    $payment_methods = cw_func_call('cw_payment_search', array('data' => array(0, false, 3, $edited_language)));
    $smarty->assign('payment_methods', $payment_methods);
} else {
    $payment_methods = cw_func_call('cw_payment_search', array('language' => $edited_language));
    $smarty->assign('payment_methods', $payment_methods);
    $smarty->assign('main', 'methods');
function export()
{
    global $REQUEST_METHOD, $smarty, $config, $addons, $top_message, $customer_id, $tables;
    global $mode, $action, $ebay_config;
    if ($REQUEST_METHOD != 'POST') {
        cw_header_location('index.php?target=' . addon_target);
    }
    $result = cw_ebay_check_fields($_POST);
    if (count($result)) {
        $top_message = array('content' => implode("<br />", $result), 'type' => 'E');
        cw_header_location('index.php?target=' . addon_target);
    }
    if (empty($_POST['file_name'])) {
        $_filename = addon_files_location_path . 'ebay_export_' . date('Ymd') . '_' . date('His') . '.csv';
    } else {
        $_filename = addon_files_location_path . $_POST['file_name'] . '.csv';
    }
    $_copy_filename = $_filename;
    if (($filename = cw_allow_file($_filename, true)) && ($file = cw_fopen($_filename, 'w', true))) {
        $pids = cw_call('cw_objects_get_list_ids', array('P'));
        if (empty($pids)) {
            $pids = cw_query_column("SELECT product_id FROM {$tables['products']} WHERE status=1");
            // Very bad. Use API
        }
        if ($pids) {
            $ebay_config = cw_array_merge($ebay_config, $config['ebay'], $_POST);
            cw_config_update('ebay', $_POST);
            $data = array();
            $header_put = false;
            $count_files = 0;
            foreach ($pids as $v) {
                $variants = array();
                $prod = cw_func_call('cw_product_get', array('id' => $v, 'info_type' => 8 | 64 | 128 | 256 | 512 | 2048));
                $attr = cw_query_hash("SELECT a.field, av.value\n\t                    FROM {$tables['attributes_values']} av, {$tables['attributes']} a\n\t                    WHERE av.item_id={$v} AND av.item_type='P' \n\t                    \tAND a.attribute_id=av.attribute_id", 'field', false, true);
                // very bad. Use API
                if ($prod['is_variants']) {
                    $variants = cw_call('cw_get_product_variants', array($v));
                } else {
                    $variants[0] = $prod;
                }
                foreach ($variants as $var) {
                    $var = cw_array_merge($var, $attr);
                    $ebay_category = cw_ebay_get_category_value($prod['category_id'], $ebay_config['ebay_category']);
                    if (!$ebay_category) {
                        fclose($file);
                        $top_message = array('content' => 'For <a href="index.php?target=categories&mode=edit&cat=' . $prod['category_id'] . '">Main category</a> for the product "' . $prod['product'] . '" option "Category" does not set.', 'type' => 'E');
                        cw_header_location('index.php?target=' . addon_target);
                    }
                    if (!$header_put) {
                        // Set smart headers
                        $data = array('Action' => $ebay_config['ebay_action'], 'ImmediatePayRequired=' . ($ebay_config['ebay_immediate_pay_required'] == 'Y' ? "1" : "0") => "", 'Category' => $ebay_category, 'ConditionID' => cw_ebay_get_condition_value($var, $ebay_config['ebay_condition_id']), 'Description' => substr(nl2br($var['descr']), 0, 500000), 'Duration=' . $ebay_config['ebay_duration'] => "", 'Format=' . $ebay_config['ebay_format'] => "", 'Location=' . $ebay_config['ebay_location'] => "", 'PayPalAccepted=' . ($ebay_config['ebay_paypal_accepted'] == 'Y' ? "1" : "0") => "", 'PayPalEmailAddress' => $ebay_config['ebay_paypal_accepted'] == 'Y' ? $ebay_config['ebay_paypal_email_address'] : "", 'Quantity' => $var['avail'], 'Title' => substr($var['product'], 0, 80), 'DispatchTimeMax=' . $ebay_config['ebay_dispatch_time_max'] => "", 'ReturnsAcceptedOption=' . $ebay_config['ebay_returns_accepted_option'] => "", 'StartPrice' => $var['price']);
                    } else {
                        $data = array('Action' => $ebay_config['ebay_action'], 'ImmediatePayRequired' => "", 'Category' => $ebay_category, 'ConditionID' => cw_ebay_get_condition_value($var, $ebay_config['ebay_condition_id']), 'Description' => substr(nl2br($var['descr']), 0, 500000), 'Duration' => "", 'Format' => "", 'Location' => "", 'PayPalAccepted' => "", 'PayPalEmailAddress' => $ebay_config['ebay_paypal_accepted'] == 'Y' ? $ebay_config['ebay_paypal_email_address'] : "", 'Quantity' => $var['avail'], 'Title' => substr($var['product'], 0, 80), 'DispatchTimeMax' => "", 'ReturnsAcceptedOption' => "", 'StartPrice' => $var['price']);
                    }
                    if (!$header_put) {
                        fputcsv($file, array_keys($data), ",");
                        $header_put = true;
                    }
                    fputcsv($file, $data, ",");
                    // A single file cannot exceed 15 MB
                    if (filesize($_filename) > 14680064) {
                        fclose($file);
                        $new_filename = str_replace(".csv", "_" . $count_files . ".csv", $_copy_filename);
                        rename($_filename, $new_filename);
                        $count_files++;
                        $_filename = str_replace(".csv", "_" . $count_files . ".csv", $_copy_filename);
                        $file = cw_fopen($_filename, 'w', true);
                        $header_put = false;
                    }
                }
            }
        }
        fclose($file);
        $top_message = array('content' => 'File <b>' . $_filename . '</b> successfully created');
    }
    cw_header_location('index.php?target=' . addon_target);
}
    $allowable_search_fields[] = 'status';
}
if ($REQUEST_METHOD == 'GET' && $mode == 'search') {
    # Check the variables passed from GET-request
    $get_vars = array();
    foreach ($_GET as $k => $v) {
        if (in_array($k, $allowable_search_fields)) {
            $get_vars[$k] = $v;
        }
    }
    if ($new_search) {
        $search_data['products'][$use_search_conditions] = array();
    }
    # Prepare the search data
    if (!empty($get_vars)) {
        $search_data['products'][$use_search_conditions] = cw_array_merge($search_data['products'][$use_search_conditions], $get_vars);
        $search_data['products'][$use_search_conditions]['flat_search'] = 1;
    }
    unset($get_vars);
}
$search_data['products'][$use_search_conditions]["substring"] = html_entity_decode(urldecode($search_data['products'][$use_search_conditions]["substring"]));
$sort_fields = cw_call('cw_product_get_sort_fields');
$smarty->assign('sort_fields', $sort_fields);
$noindex = !empty($sort) || !empty($page) && $page > 1 || !empty($att);
$smarty->assign('noindex', $noindex);
if ($config['Appearance']['display_productcode_in_list'] != "Y" && ($current_area == 'C' || $current_area == 'B')) {
    unset($sort_fields['productcode']);
}
if ($current_area == 'A' || $current_area == 'P') {
    $sort_fields['quantity'] = cw_get_langvar_by_name("lbl_in_stock");
}
function cw_add_new_smethod($method, $code, $added = array())
{
    global $tables;
    if (cw_query_first_cell("SELECT COUNT(*) FROM {$tables['shipping']} WHERE code = '" . addslashes($code) . "'") == 0) {
        return false;
    }
    if (cw_query_first_cell("SELECT COUNT(*) FROM {$tables['shipping']} WHERE shipping = '" . addslashes($method) . "' AND code = '" . addslashes($code) . "'") > 0) {
        return false;
    }
    if (isset($added['service_code'])) {
        if (cw_query_first_cell("SELECT COUNT(*) FROM {$tables['shipping']} WHERE code = '" . addslashes($code) . "' AND service_code = '" . addslashes($added['service_code']) . "'") > 0) {
            return false;
        }
    }
    $max_subcode = cw_query_first_cell("SELECT MAX(subcode+0) FROM {$tables['shipping']}") + 1;
    $data = array("shipping" => addslashes($method), "subcode" => $max_subcode, "active" => 0, "is_new" => "Y", "code" => $code);
    if (!empty($added) && is_array($added)) {
        $data = cw_array_merge($data, $added);
    }
    $id = cw_array2insert("shipping", $data);
    if (empty($id)) {
        return false;
    }
    return $id;
}
function cw_paypal_pro_payflow_do($post)
{
    global $config;
    $str = array();
    $str['vendor'] = $config['paypal_pro_payflow']['vendor'];
    $str['partner'] = $config['paypal_pro_payflow']['partner'];
    $str['user'] = $config['paypal_pro_payflow']['user'];
    $str['pwd'] = $config['paypal_pro_payflow']['password'];
    $requestid = isset($post['requestid']) ? $post['requestid'] : time();
    cw_unset($post, "requestid");
    if ($config['paypal_pro_payflow']['currency']) {
        $post['currency'] = $config['paypal_pro_payflow']['currency'];
    }
    if (isset($post['invnum'])) {
        $post['invnum'] = $config['paypal_pro_payflow']['prefix'] . $post['invnum'];
    }
    $post['reqconfirmshipping'] = $config['paypal_pro_payflow']['is_confirmed_address'] == 'Y' ? 1 : 0;
    if ($config['paypal_pro_payflow']['page_style']) {
        $post['page_style'] = $config['paypal_pro_payflow']['page_style'];
    }
    if ($config['paypal_pro_payflow']['header_image_url']) {
        $post['hdrimg'] = $config['paypal_pro_payflow']['header_image_url'];
    }
    if (isset($post['notifyurl'])) {
        global $current_location;
        $post['notifyurl'] = $current_location . '/payment/index.php?target=paypal_pro-vendor';
    }
    $str = cw_array_merge($str, $post);
    $data = array();
    foreach ($str as $k => $v) {
        $data[] = strtoupper($k) . "=" . $v;
    }
    #$url = $config['paypal_pro_payflow']['test_mode'] ? "https://pilot-payflowpro.verisign.com:443/transaction" : "https://payflowpro.verisign.com:443/transaction";
    $url = $config['paypal_pro_payflow']['test_mode'] == 'Y' ? "https://pilot-payflowpro.paypal.com:443/" : "https://payflowpro.paypal.com:443/";
    $headers = array("X-VPS-REQUEST-ID" => $requestid, "X-VPS-VIT-CLIENT-CERTIFICATION-ID" => "7894b92104f04ffb4f38a8236ca48db3");
    //cw_log_add('payflow_pro', array('url'=>$url, 'data'=>$data, 'headers'=>$headers));
    # kornev, we are making the implode here - because we don't need the urlencode
    list($headers, $response) = cw_https_request("POST", $url, array(implode('&', $data)), "", "", "application/x-www-form-urlencoded", "", "", "", $headers);
    //cw_log_add('payflow_pro', array('headers'=>$headers, 'response'=>$response));
    if (empty($response)) {
        return array($headers, $response);
    }
    $result = array();
    $tmp = array();
    parse_str($response, $tmp);
    if (empty($tmp) || !is_array($tmp)) {
        return array($headers, $response);
    }
    foreach ($tmp as $k => $v) {
        $result[strtolower($k)] = urldecode($v);
    }
    return array($headers, $response, $result);
}
function cw_gift_get_giftcert_wishlist($customer_id)
{
    global $tables;
    $wl_giftcerts = array();
    if (empty($customer_id)) {
        return $wl_giftcerts;
    }
    $wl_raw = cw_query("select wishlist_id, amount, amount_purchased, object from {$tables['wishlist']} WHERE customer_id='{$customer_id}' AND event_id='0' AND product_id='0'");
    if (is_array($wl_raw)) {
        foreach ($wl_raw as $k => $v) {
            $object = unserialize($v['object']);
            $wl_giftcerts[] = cw_array_merge($v, $object);
        }
    }
    return $wl_giftcerts;
}
function cw_doc_details_fields($all = false)
{
    global $store_cc, $store_ch, $store_cvv2;
    static $all_fields = array("CC" => array("card_name" => "{CardOwner}", "card_type" => "{CardType}", "card_number" => "{CardNumber}", "card_valid_from" => "{ValidFrom}", "card_expire" => "{ExpDate}", "card_issue_no" => "{IssueNumber}"), "CC_EXT" => array("card_cvv2" => "CVV2"), "CH" => array("check_name" => "{AccountOwner}", "check_ban" => "{BankAccount}", "check_brn" => "{BankNumber}", "check_number" => "{FractionNumber}", "debit_name" => "{AccountOwner}", "debit_bank_account" => "{BankAccount}", "debit_bank_number" => "{BankNumber}", "debit_bank_name" => "{BankName}"));
    $keys = array();
    if ($store_cc || $all) {
        $keys[] = "CC";
        if ($store_cvv2 || $all) {
            $keys[] = "CC_EXT";
        }
    }
    if ($store_ch || $all) {
        $keys[] = "CH";
    }
    $rval = array();
    foreach ($keys as $key) {
        $rval = cw_array_merge($rval, $all_fields[$key]);
    }
    return $rval;
}
                         if ($bonus['apply'] != PS_APPLY_PRODS) {
 							unset($bonus['object_id'],$bonus['quantity'],$bonus['object_type']);
 						}
                         $current_bonuses[$type][$kk] = array_intersect_key($bonus,array('object_id'=>1,'quantity'=>1,'discount'=>1,'disctype'=>1,'apply'=>1,'object_type'=>1));
                     }
                 }
 */
 # Add applicable offer info
 $special_offers_apply['supply'][$bid] = $current_bonuses;
 #
 # Prepare common array of bonuses including current bonuses
 #
 /*
  * Prepare common free_shipping array
  */
 $special_offers_apply['free_shipping']['methods'] = cw_array_merge($special_offers_apply['free_shipping']['methods'], $current_bonuses[PS_FREE_SHIP]['methods']);
 // If at least one bonus gives free shipping to whole cart, then free shipping will be applied to cart
 if ($current_bonuses[PS_FREE_SHIP]['apply'] == PS_APPLY_CART) {
     $special_offers_apply['free_shipping']['apply'] = PS_APPLY_CART;
 }
 if (in_array($current_bonuses[PS_FREE_SHIP]['apply'], array(PS_APPLY_COND, PS_APPLY_PRODS)) && $special_offers_apply['free_shipping']['apply'] != PS_APPLY_CART) {
     $special_offers_apply['free_shipping']['apply'] = $current_bonuses[PS_FREE_SHIP]['apply'];
 }
 $special_offers_apply['free_shipping']['rate'] += $current_bonuses[PS_FREE_SHIP]['discount'];
 // If free shipping applicable to products from condition
 // Possible bug - $_affected_product_ids contains products from previous offers too?
 if ($current_bonuses[PS_FREE_SHIP]['apply'] == PS_APPLY_COND) {
     foreach ($_affected_product_ids['ids'] as $pid => $qty) {
         $special_offers_apply['free_shipping']['products'][$pid] += $qty - $affected_product_ids['ids'][$pid];
     }
 }
            $ids[] = addslashes($v['customer_id']);
        }
        $counts = cw_query_hash("SELECT {$tables['wishlist']}.customer_id, COUNT({$tables['products']}.product_id) as products_count FROM {$tables['wishlist']}, {$tables['products']} WHERE {$tables['wishlist']}.product_id = {$tables['products']}.product_id AND {$tables['wishlist']}.customer_id IN ('" . implode("','", $ids) . "') GROUP BY {$tables['wishlist']}.customer_id", "customer_id", false, true);
        foreach ($wishlists as $k => $v) {
            $wishlists[$k]['products_count'] = intval($counts[$v['customer_id']]);
        }
        $smarty->assign('wishlists', $wishlists);
    }
    # Display wishlist
} elseif ($mode == "wishlist" && $customer) {
    $wishlist = cw_query("SELECT * FROM {$tables['wishlist']}, {$tables['products']}, {$tables['customers']} WHERE {$tables['wishlist']}.product_id = {$tables['products']}.product_id AND {$tables['wishlist']}.customer_id={$tables['customers']}.customer_id AND {$tables['wishlist']}.customer_id='{$customer}' ");
    if (empty($wishlist)) {
        cw_header_location("index.php?target=wishlists");
    }
    foreach ($wishlist as $k => $v) {
        if (!empty($v['options'])) {
            $v['options'] = unserialize($v['options']);
            list($variant, $v['product_options']) = cw_get_product_options_data($v['product_id'], $v['options'], $v['membership_id']);
            if (!empty($variant)) {
                $v = cw_array_merge($v, $variant);
            }
            $wishlist[$k] = $v;
        }
    }
    $location[count($location) - 1][1] = "wishlists.php";
    $location[] = array(cw_get_langvar_by_name("lbl_wish_list"), "");
    $smarty->assign('wishlist', $wishlist);
    $smarty->assign('main', "wishlist");
}
$smarty->assign('mode', $mode);
$smarty->assign('search_data', $search_data);
 /* Search in deleted ordered products */
 if ($request_prepared['origin'] == 'user_C') {
     $substring = $request_prepared['search'];
     $search_words = explode(" ", $substring);
     if (!empty($search_words)) {
         $search_words = array_map('trim', $search_words);
         $prodname_cond = array();
         foreach ($search_words as $s_word) {
             if ($s_word) {
                 $prodname_cond[] = "p.product LIKE '%{$s_word}%'";
             }
         }
         $prodname_condition = " OR (" . implode(" AND ", $prodname_cond) . ")";
     }
     $deleted_products = cw_query("SELECT d.product_id, d.product, '1' as deleted\n        FROM {$tables['docs_items']} as d\n        LEFT JOIN  {$tables['products']} as p ON d.product_id = p.product_id\n        WHERE (d.product LIKE '%{$substring}%' {$prodname_condition})\n            AND (p.product_id IS NULL)\n        ORDER BY d.product\n        LIMIT " . $config['ajax_search']['as_suggested_products']);
     $products = cw_array_merge($products, $deleted_products);
 }
 /* Prepare output */
 if (count($products) == 0) {
     array_push($prod_resp, array('id' => 0, 'value' => '', 'label' => '<i>no suggestions</i>'));
 } else {
     foreach ($products as $product) {
         $substring = str_replace('/', '\\/', $substring);
         $substring = str_replace("\\'", "'", $substring);
         $label = preg_replace('/' . $substring . '/i', '<span class="search_match">$0</span>', $product['product']);
         if ($label == '') {
             $label = $product['product'];
         }
         if ($product['deleted']) {
             $label .= ' (deleted)';
         }
function cw_product_get($params, $return = null)
{
    extract($params);
    global $customer_id, $customer_id_type, $current_area, $cart, $current_location;
    global $current_language, $tables, $config, $addons;
    cw_load('files', 'taxes', 'tags');
    $lang = $lang ? $lang : $current_language;
    $variant_id = $variant_id ? $variant_id : 0;
    $amount = intval($amount > 0 ? $amount : 1);
    $fields = $from_tbls = $query_joins = $where = array();
    # kornev, merge standart and additional variables
    if ($return) {
        foreach ($return as $saname => $sadata) {
            if (isset(${$saname}) && is_array(${$saname}) && empty(${$saname})) {
                ${$saname} = $sadata;
            }
        }
    }
    $from_tbls[] = 'products';
    $where[] = "{$tables['products']}.product_id='{$id}'";
    # kornev
    # customer area - all of the checkings
    # pos area - not check for membership, just available for sale property
    if (in_array($current_area, array('C'))) {
        $memberships = array(0);
        if ($user_account['membership_id'] > 0) {
            $memberships[] = intval($user_account['membership_id']);
        }
        $where[] = "{$tables['products_memberships']}.membership_id IN (" . join(',', $memberships) . ")";
        $where[] = "{$tables['products_prices']}.quantity <= {$amount} and {$tables['products_prices']}.membership_id in (" . join(',', $memberships) . ")";
        if ($config['Appearance']['categories_in_products'] == '1') {
            $where[] = "{$tables['categories_memberships']}.membership_id IN (" . join(',', $memberships) . ")";
            $query_joins['products_categories'] = array('on' => "{$tables['products_categories']}.product_id = {$tables['products']}.product_id", 'pos' => '0', 'is_straight' => 1);
            $query_joins['categories'] = array('on' => "{$tables['products_categories']}.category_id = {$tables['categories']}.category_id", 'parent' => 'products_categories');
            $query_joins['categories_memberships'] = array('on' => "{$tables['categories_memberships']}.category_id = {$tables['categories']}.category_id", 'parent' => 'categories', 'is_straight' => 1);
        }
        $where[] = "{$tables['products']}.status in ('" . implode("', '", cw_core_get_required_status($current_area)) . "')";
    } elseif (in_array($current_area, array('G'))) {
        $where[] = "{$tables['products']}.product_id = {$tables['products_prices']}.product_id AND {$tables['products_prices']}.quantity <= {$amount} and {$tables['products_prices']}.membership_id in (" . join(',', $memberships) . ")";
    }
    $fields[] = "{$tables['products']}.*";
    $query_joins['products_warehouses_amount'] = array('on' => "{$tables['products']}.product_id = {$tables['products_warehouses_amount']}.product_id and {$tables['products_warehouses_amount']}.warehouse_customer_id=0 and {$tables['products_warehouses_amount']}.variant_id='{$variant_id}'");
    $in_cart = 0;
    if ($current_area == 'C' && !empty($cart) && !empty($cart['products'])) {
        foreach ($cart['products'] as $cart_item) {
            if ($cart_item['product_id'] == $id) {
                $in_cart += $cart_item['amount'];
            }
        }
    }
    $fields[] = "{$tables['products_warehouses_amount']}.avail-{$in_cart} AS avail";
    # kornev, TOFIX
    if ($addons['product_options'] && in_array($current_area, array('A', 'P'))) {
        $query_joins['product_variants'] = array('on' => "{$tables['products']}.product_id = {$tables['product_variants']}.product_id");
        $fields[] = "IF({$tables['product_variants']}.product_id IS NULL, '', 'Y') as is_variants";
    }
    /*
        if ($addons['manufacturers']) {
            $query_joins['manufacturers'] = array(
                'on' => "$tables[manufacturers].manufacturer_id = $tables[products].manufacturer_id",
            );
            $fields[] = "$tables[manufacturers].manufacturer";
        }
    */
    // statistic
    $fields[] = "{$tables['products_stats']}.views_stats";
    $fields[] = "{$tables['products_stats']}.sales_stats";
    $fields[] = "{$tables['products_stats']}.del_stats";
    $fields[] = "{$tables['products_stats']}.add_to_cart";
    $query_joins['products_stats'] = array('on' => "{$tables['products_stats']}.product_id = {$tables['products']}.product_id");
    if ($current_area == 'A' || $current_area == 'P') {
        $fields[] = "{$tables['products_prices']}.price";
        $fields[] = "{$tables['products_prices']}.list_price";
        $query_joins['products_prices'] = array('on' => "{$tables['products_prices']}.product_id={$tables['products']}.product_id AND {$tables['products_prices']}.variant_id = '{$variant_id}' and {$tables['products_prices']}.quantity <= {$amount}");
    } else {
        $query_joins['products_prices'] = array('on' => "{$tables['products_prices']}.product_id={$tables['products']}.product_id", 'is_inner' => 1);
        # kornev, find the min price and select only this record.
        $fields[] = "min({$tables['products_prices']}.price) as price";
        $fields[] = "{$tables['products_prices']}.variant_id";
        $fields[] = "min({$tables['products_prices']}.list_price) as list_price";
    }
    $fields[] = "IF({$tables['products_lng']}.product_id != '', {$tables['products_lng']}.product, {$tables['products']}.product) as product";
    $fields[] = "IF({$tables['products_lng']}.product_id != '', {$tables['products_lng']}.descr, {$tables['products']}.descr) as descr";
    $fields[] = "IF({$tables['products_lng']}.product_id != '', {$tables['products_lng']}.fulldescr, {$tables['products']}.fulldescr) as fulldescr";
    $fields[] = "IF({$tables['products_lng']}.product_id != '', {$tables['products_lng']}.features_text, {$tables['products']}.features_text) as features_text";
    $fields[] = "IF({$tables['products_lng']}.product_id != '', {$tables['products_lng']}.specifications, {$tables['products']}.specifications) as specifications";
    $query_joins['products_lng'] = array('on' => "{$tables['products_lng']}.code='{$lang}' AND {$tables['products_lng']}.product_id = {$tables['products']}.product_id");
    if (in_array($current_area, array('C', 'G', 'S'))) {
        $fields[] = "{$tables['products_flat']}.*";
        $query_joins['products_flat'] = array('on' => "{$tables['products']}.product_id = {$tables['products_flat']}.product_id");
        if ($current_area == 'C') {
            $query_joins['products_memberships'] = array('on' => "{$tables['products_memberships']}.product_id = {$tables['products']}.product_id", 'is_inner' => 1);
        }
    }
    if ($config['Appearance']['categories_in_products'] == '1') {
        $fields[] = "{$tables['products_categories']}.category_id";
        $query_joins['categories'] = array('parent' => 'products_categories', 'on' => "{$tables['categories']}.category_id = {$tables['products_categories']}.category_id");
        $query_joins['products_categories'] = array('on' => "{$tables['products_categories']}.product_id = {$tables['products']}.product_id and {$tables['products_categories']}.main=1", 'pos' => '0', 'is_straight' => 1);
    }
    $fields[] = "{$tables['products']}.product_id";
    $query = cw_db_generate_query($fields, $from_tbls, $query_joins, $where, array("{$tables['products']}.product_id"), array(), array());
    $product = cw_query_first($query);
    # Error handling
    if (!$product || $current_area == 'C' && !$product['category_id'] && $config['Appearance']['categories_in_products'] == '1') {
        return false;
    }
    $product['system'] = cw_call('cw_product_get_system_info', array($product['product_id']));
    $product['attribute_class_ids'] = cw_func_call('cw_items_attribute_classes_get', array('item_id' => $product['product_id'], 'item_type' => 'P', 'for_product_modify' => $for_product_modify));
    if ($info_type & 1) {
        $product['membership_ids'] = cw_query_key("select membership_id from {$tables['products_memberships']} where product_id = '{$product['product_id']}'");
    }
    # kornev, TOFIX
    if ($info_type & 64 && $product['variant_id'] && $addons['product_options']) {
        $tmp = cw_query_first("SELECT * FROM {$tables['product_variants']} WHERE variant_id = '{$product['variant_id']}'");
        if (!empty($tmp)) {
            cw_unset($tmp, "def");
            $product = cw_array_merge($product, $tmp);
        } else {
            cw_unset($product, 'variant_id');
        }
    }
    if ($info_type & 128) {
        cw_load('image');
        $product['image_thumb'] = cw_image_get('products_images_thumb', $id);
    }
    if ($info_type & 512) {
        $product['image_det'] = cw_image_get('products_images_det', $id);
        # kornev, TOFIX
        if (in_array($current_area, array('C', 'B')) && $product['variant_id'] && $addons['product_options']) {
            $var_image = cw_image_get('products_images_var', $id);
            if (!$var_image['is_default']) {
                $product['image_det'] = $var_image;
            }
        }
    }
    # TOFIX
    if (in_array($current_area, array('C', 'B', 'G'))) {
        if (!$addons['egoods']) {
            $product['distribution'] = '';
        }
        $product['display_price'] = $product['price'];
        if ($current_area == 'C' && $info_type & 8) {
            $_tmp_price = $product['price'];
            $product['price'] = $product['list_price'];
            cw_get_products_taxes($product, $user_account);
            $product['list_price_net'] = $product['list_price'];
            $product['list_price'] = $product['taxed_price'];
            $product['price'] = $_tmp_price;
        }
        $product['taxes'] = cw_get_products_taxes($product, $user_account, false, '', $current_area == 'G' && $user_account['usertype'] != 'R');
    }
    if (in_array($current_area, array('C', 'B'))) {
        $product['descr'] = cw_eol2br($product['descr']);
        $product['fulldescr'] = cw_eol2br($product['fulldescr']);
    }
    $product['uns_shippings'] = unserialize($product['shippings']);
    $product['tags'] = cw_tags_get_product_tags($id);
    if ($info_type & 4096 && $product['warranty_id']) {
        $wr = cw_get_warranty($product['warranty_id'], $lang);
        $product['warranties'] = $wr['body'];
    }
    // TODO: move to addon as on_product_get handler
    if ($info_type & 8192) {
        cw_load('warehouse');
        if ($addons['warehouse']) {
            if (AREA_TYPE == 'A') {
                $product['avail_ordered'] = cw_warehouse_get_avail($id, 0, 'avail_ordered');
                $product['avail_sold'] = cw_warehouse_get_avail($id, 0, 'avail_sold');
                $product['avail_reserved'] = cw_warehouse_get_avail($id, 0, 'avail_reserved');
            } elseif (AREA_TYPE == 'P') {
                $product['avail'] = cw_warehouse_get_warehouse_avail($customer_id, $id);
                $product['avail_ordered'] = cw_warehouse_get_warehouse_avail($customer_id, $id, 'avail_ordered');
            } else {
                // TOFIX:  $product['avail'] becomes different meanings when info_type & 8192 flag is raised or not
                // without flag - avail of all variants without products already in cart
                // with flag - total avail as set in admin per variant
                //                $product['avail'] = cw_warehouse_get_avail_for_customer($id, $product['variant_id']);
                //                $product['avails']= cw_warehouse_get_avails_customer($id);
                $product['avail'] = cw_warehouse_get_avail_for_customer($id, $product['variant_id']);
            }
        } else {
            $product['avails'] = cw_warehouse_get_avails_customer($id, $product['avail'] + $product['avail_ordered']);
        }
    }
    return $product;
}
function cw_products_from_scratch($scratch_products, $user_info, $persistent_products, $leave_info = false)
{
    global $addons, $tables, $config, $app_main_dir;
    global $current_area, $current_language, $customer_id;
    cw_load('image');
    $products = array();
    if (empty($scratch_products)) {
        return $products;
    }
    $pids = array();
    foreach ($scratch_products as $product_data) {
        $pids[] = $product_data['product_id'];
    }
    $int_res = cw_query_hash("SELECT * FROM {$tables['products_lng']} WHERE code = '{$current_language}' AND product_id IN ('" . implode("','", $pids) . "')", "product_id", false);
    unset($pids);
    cw_event('on_before_products_from_scratch', array(&$scratch_products));
    $hash = array();
    cw_load('warehouse');
    foreach ($scratch_products as $product_data) {
        $product_id = $product_data['product_id'];
        $cartid = $product_data['cartid'];
        $amount = $product_data['amount'];
        $variant_id = $product_data['variant_id'];
        $warehouse = $product_data['warehouse_customer_id'];
        if (!cw_warehouse_is_customer($customer_id, $warehouse)) {
            continue;
        }
        if (!is_numeric($amount)) {
            $amount = 0;
        }
        $options = $product_data['options'];
        $product_options = false;
        $variant = array();
        # kornev, TOFIX
        if ($addons['product_options'] && !empty($options) && is_array($options)) {
            if (!cw_check_product_options($product_id, $options)) {
                continue;
            }
            list($variant, $product_options) = cw_get_product_options_data($product_id, $options, $membership_id);
            if (empty($variant_id) && isset($variant['variant_id'])) {
                $variant_id = $variant['variant_id'];
            }
        }
        $fields[] = "p.*";
        # kornev, supplier has got it's own prices
        if ($current_area != 'S') {
            $fields[] = "min(pq.price) as price";
        }
        $fields[] = 'avail';
        $status = cw_core_get_required_status($current_area);
        $products_array = cw_func_call('cw_product_get', array('id' => $product_id, 'variant_id' => $variant_id, 'amount' => $amount, 'user_account' => $user_info, 'info_type' => 8192));
        //cw_query_first($sql="select ".implode(', ', $fields)." from $tables[products] as p, $tables[products_prices] as pq, $tables[products_enabled] as pe left join $tables[products_warehouses_amount] as pwa on pwa.product_id=pe.product_id and pwa.variant_id='$variant_id' and pwa.warehouse_customer_id='$warehouse' WHERE p.product_id= pe.product_id and pe.product_id=pq.product_id AND pe.status in (".implode(", ", $status).") AND pe.product_id='$product_id' AND pq.quantity<='$amount' AND pq.membership_id IN(0, '$user_info[membership_id]') AND pq.variant_id = '$variant_id' ORDER BY pq.quantity DESC");
        $unlimited_products = true;
        if ($products_array['avail'] < $amount && in_array($current_area, array('G', 'C'))) {
            $unlimited_products = cw_query_first_cell("select backorder & " . ($current_area == 'G' ? 2 : 1) . " from {$tables['warehouse_divisions']} where division_id = '{$warehouse}'");
            if (!$unlimited_products) {
                $amount = $products_array['avail'];
            }
        }
        if ($products_array) {
            $products_array = cw_array_merge($product_data, $products_array);
            if ($leave_info) {
                $products_array['price'] = abs($product_data['price']);
            }
            $products_array['warehouse_customer_id'] = $warehouse;
            $hash_key = $product_id . "|" . $warehouse;
            cw_event('on_product_from_scratch', array(&$products_array));
            #
            # If priduct's price is 0 then use customer-defined price
            #
            $free_price = false;
            if ($products_array['price'] == 0) {
                $free_price = true;
                $products_array['taxed_price'] = $products_array['price'] = price_format($product_data['free_price'] ? $product_data['free_price'] : 0);
            }
            # kornev, TOFIX
            if ($addons['product_options'] && $options) {
                if (!empty($variant)) {
                    # kornev, it's not allow to set the variant price.
                    //					unset($variant['price']);
                    if (is_null($variant['pimage_path'])) {
                        cw_unset($variant, "pimage_path", "pimage_x", "pimage_y");
                    } else {
                        $variant['is_pimage'] = 'W';
                    }
                    $products_array = cw_array_merge($products_array, $variant);
                }
                $hash_key .= "|" . $products_array['variant_id'];
                if ($product_options === false) {
                    unset($product_options);
                } else {
                    $variant['price'] = $products_array['price'];
                    $variant['cost'] = $products_array['cost'];
                    $products_array['options_surcharge'] = 0;
                    $products_array['cost_surcharge'] = 0;
                    if ($product_options) {
                        foreach ($product_options as $o) {
                            $products_array['options_surcharge'] += $o['modifier_type'] ? $products_array['price'] * $o['price_modifier'] / 100 : $o['price_modifier'];
                            $products_array['cost_surcharge'] += $o['cost_modifier_type'] ? $products_array['cost'] * $o['cost_modifier'] / 100 : $o['cost_modifier'];
                        }
                    }
                }
            }
            if (!$unlimited_products && !$persistent_products && $products_array['avail'] - $hash[$hash_key] < $amount) {
                continue;
            }
            # Get thumbnail's URL (uses only if images stored in FS)
            $products_array['image_thumb'] = cw_image_get('products_images_thumb', $product_id);
            $products_array['price'] += $products_array['options_surcharge'];
            $products_array['cost'] += $products_array['cost_surcharge'];
            if ($products_array['price'] < 0) {
                $products_array['price'] = 0;
            }
            if ($products_array['cost'] < 0) {
                $products_array['cost'] = 0;
            }
            if (in_array($current_area, array('C', 'G'))) {
                $products_array['taxes'] = cw_get_products_taxes($products_array, $user_info, false, '', $current_area == 'G' && $customer_info['usertype'] != 'R');
                if ($config['Taxes']['display_taxed_order_totals'] == 'Y') {
                    $products_array['display_price'] = $products_array['taxed_price'];
                    $products_array['display_net_price'] = $products_array['taxed_net_price'];
                } else {
                    $products_array['display_price'] = $products_array['price'];
                    $products_array['display_net_price'] = $products_array['net_price'];
                }
            }
            $products_array['total'] = $amount * $products_array['price'];
            $products_array['product_options'] = $product_options;
            $products_array['options'] = $options;
            $products_array['amount'] = $amount;
            $products_array['cartid'] = $cartid;
            $products_array['product_orig'] = $products_array['product'];
            if (isset($int_res[$product_id])) {
                $products_array['product'] = stripslashes($int_res[$product_id]['product']);
                $products_array['descr'] = stripslashes($int_res[$product_id]['descr']);
                $products_array['fulldescr'] = stripslashes($int_res[$product_id]['fulldescr']);
                cw_unset($int_res, $product_id);
            }
            if ($products_array['descr'] == strip_tags($products_array['descr'])) {
                $products_array['descr'] = str_replace("\n", "<br />", $products_array['descr']);
            }
            if ($products_array['fulldescr'] == strip_tags($products_array['fulldescr'])) {
                $products_array['fulldescr'] = str_replace("\n", "<br />", $products_array['fulldescr']);
            }
            // Order hash defines how all products in cart will be split by orders
            // Listen for the event and return own part of hash
            $order_hash = cw_event('on_build_order_hash', array($products_array), array());
            $order_hash[] = 'W' . $products_array['warehouse_customer_id'];
            $products_array['order_hash'] = join('-', $order_hash);
            $products[] = $products_array;
            $hash[$hash_key] += $amount;
        }
    }
    //cw_var_dump($products);
    return $products;
}
    if (!empty($cart['info']['quote_doc_id'])) {
        $top_message['type'] = "E";
        $top_message['content'] = cw_get_langvar_by_name("err_add_product_to_cart_with_quote");
        cw_header_location('index.php?target=gifts&mode=wishlist');
    }
    define('DO_NOT_REDIRECT_CART', true);
    $action = 'add';
    // Add to cart product from wish list
    $wl = cw_wl_get_item($wlitem);
    if ($wl) {
        // Add gift certificate to the cart
        $giftcert = unserialize($wl['object']);
        if (!isset($cart['giftcerts'])) {
            $cart['giftcerts'] = array();
        }
        $cart['giftcerts'][] = cw_array_merge($giftcert, array('wishlistid' => $wlitem));
        $top_message = array('type' => 'I', 'content' => 'Wishlist item has been added to cart');
        $products = cw_call('cw_products_in_cart', array($cart, $userinfo));
        $cart = cw_func_call('cw_cart_calc', array('cart' => $cart, 'products' => $products, 'userinfo' => $userinfo));
    }
}
// Redirect
if (!empty($action)) {
    cw_header_location("index.php?target={$target}&mode={$redirect_mode}&event_id={$event_id}&js_tab={$js_tab}");
}
if ($mode == 'friends') {
    $wishlist = cw_gift_get_wishlist($wlid, true);
} else {
    $wishlist = cw_gift_get_giftreg_wishlist($customer_id, $event_id);
}
if ($mode != 'friends') {
            cw_array2insert("shipping_rates", array("shipping_id" => $shipping_id_new, "minweight" => cw_convert_number($minweight_new), "maxweight" => cw_convert_number($maxweight_new), "maxamount" => cw_convert_number($maxamount_new), "mintotal" => cw_convert_number($mintotal_new), "maxtotal" => cw_convert_number($maxtotal_new), "rate" => cw_convert_number($rate_new), "item_rate" => cw_convert_number($item_rate_new), "rate_p" => cw_convert_number($rate_p_new), "weight_rate" => cw_convert_number($weight_rate_new), "warehouse_customer_id" => $user_account['warehouse_customer_id'], "zone_id" => $zone_id_new, "type" => $type, "overweight" => cw_convert_number($overweight_new), "overweight_rate" => cw_convert_number($overweight_rate_new)));
            $top_message['content'] = cw_get_langvar_by_name("msg_shipping_rate_add");
        }
    }
    cw_header_location("index.php?target=shipping_rates&zone_id={$zone_id}&shipping_id={$shipping_id}&type={$type}");
}
$zone_condition = $zone_id != "" ? "and {$tables['shipping_rates']}.zone_id='{$zone_id}'" : "";
$method_condition = $shipping_id != "" ? "and {$tables['shipping_rates']}.shipping_id='{$shipping_id}'" : "";
$shipping_rates = cw_query("SELECT {$tables['shipping_rates']}.*, {$tables['shipping']}.shipping, {$tables['shipping']}.shipping_time, {$tables['shipping']}.destination FROM {$tables['shipping']}, {$tables['shipping_rates']} WHERE {$tables['shipping_rates']}.shipping_id={$tables['shipping']}.shipping_id AND {$tables['shipping']}.active=1 {$warehouse_condition} {$type_condition} {$zone_condition} {$method_condition} " . ($type == "R" ? " AND code!='' " : '') . " ORDER BY {$tables['shipping']}.orderby, {$tables['shipping_rates']}.maxweight");
#
# Prepare zones list
#
$zones = array(array("zone_id" => 0, "zone" => cw_get_langvar_by_name("lbl_zone_default")));
$_tmp = cw_query("SELECT zone_id, zone_name as zone FROM {$tables['zones']} WHERE 1 {$warehouse_condition} and is_shipping=1 ORDER BY zone_id");
if (!empty($_tmp)) {
    $zones = cw_array_merge($zones, $_tmp);
}
if (is_array($zones) && is_array($shipping_rates)) {
    foreach ($zones as $zone) {
        $shipping_rates_list = array();
        foreach ($shipping_rates as $shipping_rate) {
            if ($shipping_rate['zone_id'] != $zone['zone_id']) {
                continue;
            }
            $shipping_rates_list[$shipping_rate['shipping_id']]['shipping'] = $shipping_rate['shipping'];
            $shipping_rates_list[$shipping_rate['shipping_id']]['destination'] = $shipping_rate['destination'];
            $shipping_rates_list[$shipping_rate['shipping_id']]['rates'][] = $shipping_rate;
        }
        $_zones_list = array();
        $_zones_list['zone'] = $zone;
        $_zones_list['shipping_methods'] = $shipping_rates_list;
function cw_add_to_cart(&$cart, $product_data)
{
    global $user_account;
    global $addons, $config, $top_message, $app_main_dir, $HTTP_REFERER, $app_catalogs, $tables;
    global $from, $current_area;
    $return = array();
    # Extracts to: $product_id, $amount, $product_options, $price, $warehouse_customer_id
    extract($product_data);
    $warehouse = $product_data['warehouse_customer_id'];
    cw_load('warehouse');
    $added_product = cw_func_call('cw_product_get', array('id' => $product_id, 'user_account' => $user_account, 'info_type' => 3));
    if ($added_product['product_type'] == 10) {
        $warehouse = $added_product['warehouse_customer_id'];
    }
    if (!$warehouse) {
        $possible_warehouse = cw_warehouse_get_max_amount_warehouse($product_id);
    }
    if (!empty($addons['egoods']) && !empty($added_product['distribution'])) {
        $amount = 1;
    } else {
        $amount = abs(intval($amount));
    }
    if ($amount == 0) {
        $amount = 1;
    }
    # kornev, TOFIX
    if ($addons['product_options']) {
        #
        # Prepare the product options for added products
        #
        if (!empty($product_options)) {
            # Check the received options
            if (!cw_check_product_options($product_id, $product_options)) {
                $return['redirect_to'] = "product.php?product_id={$product_id}&err=options";
                return $return;
            }
        } else {
            # Get default options
            $product_options = cw_get_default_options($product_id, $amount, @$user_account['membership_id']);
            if ($product_options === false) {
                $return['redirect_to'] = 'index.php?target=error_message&error=access_denied&id=30';
                return $return;
            } elseif ($product_options === true) {
                $product_options = "";
                unset($product_options);
            }
        }
        # Get the variant_id of options
        $variant_id = cw_get_variant_id($product_options, $product_id);
        if (!empty($variant_id)) {
            $possible_warehouse = cw_warehouse_get_max_amount_warehouse($product_id, $variant_id);
            if (empty($warehouse)) {
                $warehouse = $possible_warehouse;
            }
            # Get the variant amount
            $added_product['avail'] = cw_warehouse_get_warehouse_avail($warehouse, $product_id, null, $variant_id);
            //cw_get_options_amount($product_options, $product_id);
            if (!empty($cart['products'])) {
                foreach ($cart['products'] as $k => $v) {
                    if ($v['product_id'] == $product_id && $variant_id == $v['variant_id']) {
                        $added_product['avail'] -= $v['amount'];
                    }
                }
            }
        } else {
            if (empty($warehouse)) {
                $warehouse = $possible_warehouse;
            }
            $added_product['avail'] = cw_warehouse_get_warehouse_avail($warehouse, $product_id);
        }
    }
    /*
    kornev, the amount is checked by another function - during the calculation
    	if ($config['General']['unlimited_products'] == "N" && $added_product['product_type'] != 10) {
    		#
    		# Add to cart amount of items that is not much than in stock
    		#
    		if ($amount > $added_product['avail'])
    			$amount = $added_product['avail'];
    	}
    */
    if ($from == 'salesman' && empty($amount)) {
        $return['redirect_to'] = $app_catalogs['customer'] . "/product.php?product_id=" . $product_id;
        return $return;
    }
    if ($product_id && $amount) {
        if ($amount < $added_product['min_amount']) {
            $return['redirect_to'] = "index.php?target=error_message&error=access_denied&id=31";
            return $return;
        }
        $found = false;
        $_product = cw_array_merge($product_data, $added_product, array('options' => $product_options, 'free_price' => $price));
        // Product hash defines how to differ/join products in cart
        // Listen for the event and return own part of hash. See also default handler.
        $product_hash = cw_event('on_build_cart_product_hash', array($_product), array());
        $product_data['product_hash'] = $_product['product_hash'] = join('-', $product_hash);
        if (!empty($cart) && @$cart['products']) {
            foreach ($cart['products'] as $k => $v) {
                $product_hash = join('-', cw_event('on_build_cart_product_hash', array($v), array()));
                if ($product_hash == $_product['product_hash']) {
                    if (doubleval($v['free_price']) != $price) {
                        continue;
                    }
                    $found = true;
                    if ($cart['products'][$k]['amount'] >= 1 && (!empty($added_product['distribution']) || !empty($subscribed_product))) {
                        $cart['products'][$k]['amount'] = 1;
                        $amount = 0;
                    }
                    $cart['products'][$k]['amount'] += $amount;
                    $return['added_amount'] += $amount;
                    $return['productindex'] = $k;
                    $return['cartid'] = $v['cartid'];
                    $return['merged'] = true;
                    break;
                }
            }
        }
        if (!$found) {
            #
            # Add product to the cart
            #
            if (!empty($price)) {
                # price value is defined by customer if admin set it to '0.00'
                $free_price = abs(doubleval($price));
            }
            $cartid = cw_generate_cartid($cart['products']);
            if (empty($cart['products'])) {
                $add_to_cart_time = time();
            }
            $_product = array("cartid" => $cartid, "product_id" => $product_id, "amount" => $amount, "options" => $product_options, "free_price" => @price_format(@$free_price), "salesman_doc_id" => $salesman_doc_id, "distribution" => $added_product['distribution'], "variant_id" => $variant_id, "warehouse_customer_id" => $warehouse);
            // Add all custom fields from added products
            foreach ($product_data as $k => $v) {
                if (!isset($_product[$k])) {
                    $_product[$k] = $v;
                }
            }
            $cart['products'][] = $_product;
            // count add to cart
            cw_call('cw_product_run_counter', array('product_id' => $product_id, 'count' => 1, 'type' => 3));
            $return['added_amount'] = $amount;
            $_ak = array_keys($cart['products']);
            $return['productindex'] = end($_ak);
            $return['cartid'] = $cartid;
            $return['merged'] = false;
        }
    }
    return $return;
}
    $pids = cw_query("SELECT {$tables['order_details']}.item_id, {$tables['order_details']}.product_id, {$tables['products']}.distribution FROM {$tables['order_details']}, {$tables['products']} WHERE {$tables['order_details']}.doc_id = '{$doc_id}' AND {$tables['order_details']}.product_id = {$tables['products']}.product_id AND {$tables['products']}.distribution != ''");
    if ($pids) {
        $keys = array();
        foreach ($pids as $v) {
            if (cw_query_first_cell("SELECT COUNT(*) FROM {$tables['download_keys']} WHERE item_id = '{$v['item_id']}'")) {
                continue;
            }
            $keys[$v['item_id']]['download_key'] = keygen($v['product_id'], $config['egoods']['download_key_ttl'], $v['item_id']);
            $keys[$v['item_id']]['distribution_filename'] = basename($v['distribution']);
        }
        if (!empty($keys)) {
            $order = cw_order_data($doc_id);
            if (!empty($order)) {
                foreach ($order['products'] as $k => $v) {
                    if (isset($keys[$v['item_id']])) {
                        $order['products'][$k] = cw_array_merge($v, $keys[$v['item_id']]);
                    }
                }
                $smarty->assign('products', $order['products']);
                $smarty->assign('order', $order['order']);
                $smarty->assign('userinfo', $order['userinfo']);
                cw_call('cw_send_mail', array($config['Company']['orders_department'], $order['userinfo']['email'], "mail/egoods_download_keys_subj.tpl", "mail/egoods_download_keys.tpl"));
            }
        }
    }
    cw_header_location("index.php?target={$target}&mode=details&doc_id=" . $doc_id);
}
if (in_array($current_area, array('A', 'P')) && $action == 'send_ip' && $doc_id) {
    #
    # Send customer IP address to Anti Fraud server
    #
function cw_get_lang_vars($code, &$variables, &$lng)
{
    global $tables, $app_config_file;
    global $cw__langvars, $current_area;
    if (is_null($cw__langvars[$code])) {
        $cw__langvars[$code] = cw_cache_get($code . '_' . $current_area, 'lang');
    }
    if (!empty($variables) && is_array($variables)) {
        foreach ($variables as $lang_name => $_v) {
            if (isset($cw__langvars[$code][$lang_name])) {
                $lng[$lang_name] = $cw__langvars[$code][$lang_name];
                unset($variables[$lang_name]);
                continue;
            }
        }
    }
    if (empty($variables)) {
        return true;
    }
    $variables = array_fill_keys(array_keys($variables), '');
    $cw__langvars[$code] = cw_array_merge($cw__langvars[$code], $variables);
    $labels = db_query("\n        SELECT name, value, tooltip\n        FROM {$tables['languages']}\n        WHERE code = '{$code}' AND name IN ('" . implode("','", array_keys($variables)) . "')\n\t");
    if ($labels) {
        while ($v = db_fetch_array($labels)) {
            if ($app_config_file['debug']['show_langvars']) {
                $v['tooltip'] = $v['name'] . $v['tooltip'];
            }
            if (!empty($v['tooltip'])) {
                $lng[$v['name']] = '<span class="lng_tooltip" title="' . str_replace('"', '&quot;', $v['tooltip']) . '">' . $v['value'] . '</span>';
            } else {
                $lng[$v['name']] = $v['value'];
            }
            $cw__langvars[$code][$v['name']] = $lng[$v['name']];
            unset($variables[$v['name']]);
        }
        $cw__langvars[$code]['updated'] = true;
        db_free_result($labels);
    }
}
    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');
    }
    if (!empty($cart['info']['quote_doc_id'])) {
        // Change invoice status to "paid"
        $doc_id = $cart['info']['quote_doc_id'];
        $status = 'C';
        cw_call('cw_doc_change_status', array($doc_id, $status));
        $min_amount = cw_query_first_cell("SELECT min_amount FROM {$tables['products']} WHERE productid='{$pid}'");
        if ($qty >= $min_amount) {
            $add_product = array();
            $add_product["productid"] = $pid;
            $add_product["amount"] = $qty;
            $add_product["product_options"] = "";
            $add_product["price"] = 0.0;
            $result = cw_add_to_cart($cart, $add_product);
            # Adjust just added product
            foreach ($cart['products'] as $ck => $cv) {
                if ($cv["cartid"] == $result['productindex']) {
                    $cart['products'][$ck]["special_offer"]["free_product"] = 'Y';
                    $cart['products'][$ck]["free_amount"] = $qty;
                }
            }
        } else {
            unset($special_offers_apply['free_products'][$pid]);
        }
    }
    $products = cw_products_in_cart($cart, !empty($user_account["membershipid"]) ? $user_account["membershipid"] : "");
    # Make it really free
    foreach ($products as $k => $v) {
        if ($v["special_offer"]["free_product"] == 'Y') {
            $products[$k]['price'] = 0.0;
            $products[$k]['taxed_price'] = 0.0;
        }
    }
    $cart = cw_array_merge($cart, cw_calculate($cart, $products, $logged_userid, $current_area, 0));
    include $xcart_dir . '/minicart.php';
}
// CartWorks.com - Promotion Suite