function delete($id)
{
    global $tables;
    db_query('DELETE FROM ' . $tables['customers'] . ' WHERE customer_id="' . intval($id) . '"');
    cw_event('on_customer_delete', array($id));
    get(null);
}
function update($id, $data)
{
    // ....
    cw_event('on_product_update', array($id));
    // event triggered after product update
    // TODO: flush product cache
}
function cw_log_add($label, $message, $add_backtrace = true, $stack_skip = 0, $email_addresses = false, $email_only = false)
{
    global $var_dirs;
    global $PHP_SELF;
    global $config;
    $filename = sprintf("%s/%s-%s.php", $var_dirs['log'], strtolower($label), date('ymd'));
    if ($label == 'SQL') {
        $type = 'error';
    } elseif ($label == 'INI' || $label == 'SHIPPING') {
        $type = 'warning';
    } else {
        $type = 'message';
    }
    $uri = $PHP_SELF;
    if (!empty($_SERVER['QUERY_STRING'])) {
        $uri .= '?' . $_SERVER['QUERY_STRING'];
    }
    if ($add_backtrace) {
        $stack = cw_get_backtrace(1 + $stack_skip);
        $backtrace = "Backtrace:\n" . implode("\n", $stack) . "\n";
    } else {
        $backtrace = '';
    }
    if (is_array($message) || is_object($message)) {
        ob_start();
        print_r($message);
        $message = ob_get_contents();
        ob_end_clean();
    } else {
        $message = trim($message);
    }
    $local_time = "";
    if (!empty($config)) {
        $local_time = '(local: ' . date('d-M-Y H:i:s', cw_core_get_time()) . ')';
    }
    $message = str_replace("\n", "\n    ", "\n" . $message);
    $message = str_replace("\t", "    ", $message);
    $data = sprintf("[%s] %s %s %s:%s\nRequest URI: %s\n%s-------------------------------------------------\n", date('d-M-Y H:i:s'), $local_time, $label, $type, $message, $uri, $backtrace);
    cw_event('on_log_add', array($label, $data, $filename));
    if (!$email_only && cw_log_check_file($filename) !== false) {
        $fmode = $label == 'bench_exec' ? 'w' : 'a+';
        $fp = @fopen($filename, $fmode);
        if ($fp !== false) {
            fwrite($fp, $data);
            fclose($fp);
        }
    }
    if (!empty($email_addresses) && is_array($email_addresses)) {
        cw_load('mail');
        foreach ($email_addresses as $k => $email) {
            cw_send_simple_mail($config['Company']['site_administrator'], $email, $config['Company']['company_name'] . ": {$label} {$type} notification", $data);
        }
    }
}
/**
 * Main validation function
 * @return an Error instance generated by error() function
 * 
 * you can hook this function for custom validation, return Error or true
 */
function cw_can_edit_on_place($token_data)
{
    global $user_account;
    static $core_allowed_tables = array('domains', 'products', 'products_warehouses_amount', 'zones');
    $addon_allowed_tables = array();
    cw_event('on_edit_on_place_allowed_tables', array($token_data, &$addon_allowed_tables));
    $allowed_tables = array_merge($core_allowed_tables, $addon_allowed_tables);
    $valid = $user_account['usertype'] == 'A' && in_array($token_data['table'], $allowed_tables);
    if (!$valid) {
        return error('You are not permitted to edit this value');
    }
    return $valid;
}
{
    global $smarty, $app_dir;
    cw_load('files');
    $result = FALSE;
    if (!in_array($type, array("", "tpl", "cache"))) {
        $type = "";
    }
    if ($type == "tpl") {
        $result = $smarty->clear_compiled_tpl();
        cw_rm_dir($app_dir . '/var/templates');
    } elseif ($type == "cache") {
        $result = $smarty->clear_all_cache();
        cw_rm_dir($app_dir . '/var/cache');
    } elseif ($type == "") {
        $result = $smarty->clear_compiled_tpl();
        $result &= $smarty->clear_all_cache();
        cw_rm_dir($app_dir . '/var/templates');
        cw_rm_dir($app_dir . '/var/cache');
    }
    return $result;
}
$type = trim($_GET['type']);
$result = cw_cleanup_cache($type);
cw_event('on_cleanup', array($type));
$messages = array("" => "cache and templates ", "tpl" => "templates ", "cache" => "cache ");
echo "Cleanup " . $messages[$type] . "is complete.";
if (!$result) {
    echo "<br /><b>Note:</b> Some files could not be removed. Please remove them yourself.";
}
echo "<br /> <a href='" . $current_location . "/index.php'>Home page</a>";
exit(0);
                    case 'image':
                        if (!empty($contentsection_id) && !empty($file_upload_data) && is_array($file_upload_data)) {
                            $is_image_uploaded_and_saved = false;
                            if (cw_image_check_posted($file_upload_data['cms_images'])) {
                                if (cw_image_save($file_upload_data['cms_images'], array('id' => $contentsection_id, 'code' => $current_language))) {
                                    $is_image_uploaded_and_saved = true;
                                }
                            }
                            if (!$is_image_uploaded_and_saved) {
                                cw_add_top_message(cw_get_langvar_by_name('msg_ab_err_banner_image_not_uploaded_or_saved'), 'E');
                                cw_header_location('index.php?target=cms&mode=add');
                            }
                        }
                        break;
                }
                cw_event('on_cms_update', array($contentsection_id, $content_section));
                $presaved_content_section = array();
                cw_header_location('index.php?target=cms&mode=update&contentsection_id=' . $contentsection_id);
            }
            break;
    }
    cw_header_location('index.php?target=cms&mode=add');
}
$categories = cw_ab_get_cms_categories($contentsection_id);
$products = cw_ab_get_cms_products($contentsection_id);
$manufacturers = cw_ab_get_cms_manufacturers($contentsection_id);
$clean_urls = cw_ab_get_cms_clean_urls($contentsection_id);
$restricted_attributes = cw_ab_get_cms_restrict_attributes($contentsection_id);
$skins = cw_files_get_dir($app_dir . '/skins/addons/cms/skins', 2);
$skins = array_map('basename', $skins);
$presaved_content_section['image'] = 0;
$smarty->assign('left_sections', cw_query("select * from {$tables['sections_pos']} where location='L' order by orderby"));
$smarty->assign('right_sections', cw_query("select * from {$tables['sections_pos']} where location='R' order by orderby"));
# kornev, may be the same sections like in admin are required
global $app_skins_dirs;
$smarty->assign('current_main_dir', $app_skins_dirs[AREA_TYPE]);
$smarty->assign('current_section_dir', 'main');
$smarty->assign('current_target', $target);
if ($target != 'ajax' && $target != 'image') {
    $avatar = cw_user_get_avatar($customer_id);
    $smarty->assign('user_avatar', $avatar);
    cw_include('include/area_sections.php');
    $smarty->assign('current_target', $target);
}
// Get menu items from addons
$main_menu_list = array();
cw_event('on_cart_menu_build', array(&$main_menu_list));
foreach ($main_menu_list as $k => $v) {
    $main_menu_list[$k]["path"] = trim($v["path"], "\\/");
}
$smarty->assign('main_menu_list', $main_menu_list);
cw_call('cw_auth_security');
if (!(defined('IS_AJAX') && !defined('PREVENT_XML_OUT'))) {
    /*
    // This causes error - link www.saratogawine.com/?gclid=CPzYx7XJvMUCFQsCwwodupsA5A goes to 404 instead of home
    
        if ($area == "customer" && $target == "index" && empty($cat)) {
            global $clean_url_request_uri;
    
            if (!empty($app_web_dir) && strpos($REQUEST_URI, $app_web_dir) !== false) {
                $clean_url_request_uri = str_replace($app_web_dir, '', $REQUEST_URI);
            } else 
function cw_cron_sessions_delete($time, $prev_time)
{
    global $tables;
    $expired_session_ids = cw_query_column("SELECT sess_id FROM {$tables['sessions_data']} where expiry<{$time}");
    db_query("delete from {$tables['sessions_data']} where expiry<{$time}");
    db_query("delete from {$tables['temporary_data']} where expire<{$time}");
    // get group edit data of expired sessions
    $ge_ids = cw_query_column("select {$tables['group_editing']}.ge_id from {$tables['group_editing']} left join {$tables['sessions_data']} on {$tables['group_editing']}.sess_id = {$tables['sessions_data']}.sess_id where {$tables['sessions_data']}.sess_id IS NULL");
    if ($ge_ids) {
        foreach ($ge_ids as $ge_id) {
            db_query("delete from {$tables['group_editing']} where ge_id='{$ge_id}'");
        }
    }
    cw_event('on_sessions_delete', array($expired_session_ids));
    return count($expired_session_ids) . ' expired sessions were deleted';
}
function cw_call($func, $params = array())
{
    return cw_event($func, $params);
}
function cw_doc_place_order($params, $return = null)
{
    extract($params);
    global $cart, $discount_coupon, $smarty, $config, $addons, $salesman, $adv_campaign_id, $salesman_click_id;
    global $tables, $to_customer;
    global $wlid;
    global $app_main_dir, $REMOTE_ADDR, $PROXY_IP, $CLIENT_IP, $add_to_cart_time;
    $mintime = 10;
    cw_load('web');
    cw_lock('cw_doc_place_order');
    $doc_ids = array();
    foreach ($cart['orders'] as $cart_order_idx => $current_order) {
        # $extra - one serialized field in doc details
        # 	use $extra as storage of details which will not be used for orders search or aggregate
        # $extras - key=>value pairs in doc extras table
        # 	use $extras for scalar values which can be used in SQL queries
        $extra = cw_event('on_place_order_extra', array($current_order));
        $extra['additional_fields'] = $userinfo['additional_fields'];
        if (!empty($current_order['info']['shipping_no_offer'])) {
            $extra['shipping_no_offer'] = $current_order['info']['shipping_no_offer'];
        }
        $extras = cw_event('on_place_order_extras', array($current_order));
        //$extras['ip'] = $CLIENT_IP;
        //$extras['proxy_ip'] = $PROXY_IP;
        # kornev, each doc has got the same attributes as the other elements, like products
        # kornev, the attributes should be defined in the params by the pre function
        $doc_id = cw_doc_create_empty($order_type, array('warehouse_customer_id' => $current_order['warehouse_customer_id']), $params['prefix'], array(), $return['attributes']);
        $cart['orders'][$cart_order_idx]['created_doc_id'] = $doc_id;
        $extra['tax_info'] = array('display_taxed_order_totals' => $config['Taxes']['display_taxed_order_totals'], 'display_cart_products_tax_rates' => $config['Taxes']['display_cart_products_tax_rates'] == "Y", 'taxed_subtotal' => $current_order['display_subtotal'], 'taxed_discounted_subtotal' => $current_order['display_discounted_subtotal'], 'taxed_shipping' => $current_order['display_shipping_cost']);
        $giftcert_discount = $current_order['info']['giftcert_discount'];
        $applied_taxes = addslashes(serialize($current_order['info']['taxes']));
        $discount_coupon = $current_order['coupon'];
        if (!empty($current_order['coupon'])) {
            $current_order['coupon'] = cw_query_first_cell("SELECT coupon_type FROM {$tables['discount_coupons']} WHERE coupon='" . addslashes($current_order['coupon']) . "'") . "``" . $current_order['coupon'];
        }
        $current_order['userinfo'] = $userinfo;
        $current_order['new'] = true;
        // Flag can be used in cw_doc_update to differ just placed empty doc from update of existing doc
        $current_order['info']['shipping_id'] = $cart['info']['shipping_id'];
        $current_order['info']['payment_id'] = $cart['info']['payment_id'];
        $current_order['info']['payment_label'] = $cart['info']['payment_label'];
        $current_order['info']['quote_doc_id'] = isset($cart['info']['quote_doc_id']) ? $cart['info']['quote_doc_id'] : null;
        $current_order['info']['details'] = addslashes(cw_crypt_text($order_details));
        $current_order['info']['customer_notes'] = addslashes($customer_notes);
        if ($config['Appearance']['show_cart_summary'] == 'Y') {
            $current_order['info']['shipping_id'] = $cart['info']['shipping_arr'][$current_order['warehouse_customer_id']];
        }
        $current_order['info']['extra'] = $extra;
        $current_order['info']['extras'] = $_extras;
        $current_order['status'] = $order_status;
        $doc_info = cw_doc_get_basic_info($doc_id);
        $current_order['info']['doc_info_id'] = $doc_info['doc_info_id'];
        $current_order['info']['warehouse_customer_id'] = $current_order['warehouse_customer_id'];
        $current_order['userinfo']['main_address']['address_id'] = $doc_info['main_address_id'];
        $current_order['userinfo']['current_address']['address_id'] = $doc_info['current_address_id'];
        cw_log_add('doc_placed', array('doc_id' => $doc_id, 'current_order' => $current_order, 'cart' => $cart));
        cw_call('cw_doc_update', array($doc_id, $current_order));
        $doc_ids[] = $doc_id;
        $order = cw_call('cw_doc_get', array($doc_id));
        if ($discount_coupon) {
            // artem, TODO: no SQL
            $_per_user = cw_query_first_cell("SELECT per_user FROM {$tables['discount_coupons']} WHERE coupon='{$discount_coupon}' LIMIT 1");
            if ($_per_user == "Y") {
                $_need_to_update = cw_query_first_cell("SELECT COUNT(*) FROM {$tables['discount_coupons_login']} WHERE coupon='{$discount_coupon}' AND customer_id='" . intval($userinfo['customer_id']) . "' LIMIT 1");
                if ($_need_to_update > 0) {
                    db_query("UPDATE {$tables['discount_coupons_login']} SET times_used=times_used+1 WHERE coupon='{$discount_coupon}' AND customer_id='" . intval($userinfo['customer_id']) . "'");
                } else {
                    db_query("INSERT INTO {$tables['discount_coupons_login']} (coupon, customer_id, times_used) VALUES ('{$discount_coupon}', '" . intval($userinfo['customer_id']) . "', '1')");
                }
            } else {
                db_query("UPDATE {$tables['discount_coupons']} SET times_used=times_used+1 WHERE coupon='{$discount_coupon}'");
                db_query("UPDATE {$tables['discount_coupons']} SET status='U' WHERE coupon='{$discount_coupon}' AND times_used=times");
            }
            $discount_coupon = "";
        }
        # Mail template processing
        $admin_notify = $order_status == "Q" && $config['Email']['enable_order_notif'] == "Y" || $order_status == "I" && $config['Email']['enable_init_order_notif'] == "Y";
        $customer_notify = $order_status == "Q" || $order_status == "I" && $config['Email']['enable_init_order_notif_customer'] == "Y";
        $doc_data = $doc_data_customer = cw_call('cw_doc_get', array($doc_id));
        if ($customer_notify) {
            $to_customer = $userinfo['language'] ? $userinfo['language'] : $config['default_customer_language'];
            $doc_data_customer['products'] = cw_doc_translate_products($doc_data['products'], $to_customer);
            $smarty->assign('doc_data', $doc_data_customer);
            if ($doc_data['info']['layout_id']) {
                $layout = cw_web_get_layout_by_id($doc_data['info']['layout_id']);
            } else {
                $layout = cw_call('cw_web_get_layout', array('docs_' . $doc_data['type']), true);
            }
            $smarty->assign('layout_data', $layout);
            $smarty->assign('info', $doc_data['info']);
            $smarty->assign('products', $doc_data_customer['products']);
            $smarty->assign('order', $doc_data);
            $smarty->assign('doc', $doc_data);
            $smarty->assign('is_email_invoice', 'Y');
            cw_call('cw_send_mail', array($config['Company']['orders_department'], $userinfo['email'], 'mail/docs/customer_subj.tpl', 'mail/docs/customer.tpl', null, false, true));
            $smarty->assign('is_email_invoice', 'N');
        }
        if ($admin_notify) {
            # Notify orders department by email
            $smarty->assign('doc_data', $doc_data);
            $smarty->assign('usertype_layout', 'A');
            $smarty->assign('is_email_invoice', 'Y');
            cw_call('cw_send_mail', array($userinfo['email'], $config['Company']['orders_department'], 'mail/docs/admin_subj.tpl', 'mail/docs/admin.tpl', $config['default_admin_language'], true));
            $smarty->assign('is_email_invoice', 'N');
            $smarty->assign('usertype_layout', '');
            # Notify warehouse (or warehouses) by email
            if ($config['Email']['send_notifications_to_warehouse'] == "Y") {
                $pr_result = cw_query_first("SELECT email, language FROM {$tables['customers']} WHERE customer_id='{$current_order['warehouse_customer_id']}'");
                $prov_email = $pr_result['email'];
                if ($prov_email != $config['Company']['orders_department']) {
                    $to_customer = $pr_result['language'];
                    if (empty($to_customer)) {
                        $to_customer = $config['default_admin_language'];
                    }
                    $smarty->assign('is_email_invoice', 'Y');
                    cw_call('cw_send_mail', array($userinfo['email'], $prov_email, 'mail/docs/admin_subj.tpl', 'mail/docs/admin.tpl'));
                    $smarty->assign('is_email_invoice', 'N');
                }
            }
        }
        if ($addons['survey'] && AREA_TYPE == 'C') {
            cw_load('surveys');
            cw_check_surveys_events("OPL", $doc_data);
        }
        //cw_call('cw_doc_save_history_totals_by_customer', array(array(intval($userinfo['customer_id']))));
        cw_call('cw_doc_save_history_categories', array(array($doc_id)));
        cw_call('cw_doc_save_history_attributes', array(array($doc_id)));
    }
    # Send notifications to orders department and warehouses when product amount in stock is low
    foreach ($cart['products'] as $product) {
        if (!empty($product['distribution']) && $addons['egoods']) {
            continue;
        }
        # kornev, TOFIX
        if ($addons['product_options'] && $product['extra_data']['product_options']) {
            $avail_now = cw_get_options_amount($product['extra_data']['product_options'], $product['product_id']);
        } else {
            $avail_now = cw_query_first_cell("SELECT avail FROM {$tables['products_warehouses_amount']} WHERE product_id='" . $product['product_id'] . "' AND warehouse_customer_id ='" . $product['warehouse_customer_id'] . "'");
        }
        if ($product['low_avail_limit'] >= $avail_now && $config['Email']['eml_lowlimit_warning'] == 'Y') {
            # Mail template processing
            $product['avail'] = $avail_now;
            $smarty->assign('product', $product);
            cw_call('cw_send_mail', array($config['Company']['orders_department'], $config['Company']['orders_department'], 'mail/lowlimit/subj.tpl', 'mail/lowlimit/body.tpl'));
            $pr_result = cw_query_first("SELECT email, language FROM {$tables['customers']} WHERE customer_id='" . $product['warehouse_customer_id'] . "'");
        }
    }
    cw_unlock('cw_doc_place_order');
    return $doc_ids;
}
Esempio n. 11
0
             $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])) {
             $log[$task] = null;
         }
         unset($tasks[$task]);
     }
     if ($period != 'regular') {
         $executed++;
     }
 }
 $last_run['queue'] = $tasks;
 // Old fashion cron handlers are files in cron folder
 $targets = cw_func_call('cw_cron_get_targets', array('time' => $time_dump, 'hour' => $hour, 'minute' => $minute, 'manual_run' => $manual_run));
 foreach ($targets as $target) {
     $log['include:' . $target] = cw_include($area . '/' . $target . '.php');
 }
function cw_manufacturer_delete($manufacturer_id)
{
    global $tables;
    db_query("delete from {$tables['manufacturers']} where manufacturer_id='{$manufacturer_id}'");
    db_query("delete from {$tables['manufacturers_lng']} where manufacturer_id='{$manufacturer_id}'");
    $id = cw_call('cw_attributes_get_attribute_by_field', array('field' => 'manufacturer_id'));
    db_query("delete from {$tables['attributes_values']} where attribute_id='{$id}' and value='{$manufacturer_id}'");
    cw_call('cw_attributes_cleanup', array($manufacturer_id, 'M'));
    cw_image_delete($manufacturer_id, 'manufacturer_images');
    cw_event('on_manufacturer_delete', array($manufacturer_id));
}
<?php

if (!$use_search_conditions) {
    $use_search_conditions = 'general';
}
# The list of the fields allowed for searching can be extended by addons
cw_event('on_allowable_search_fields', array(&$allowable_search_fields, $current_area));
$allowable_search_fields = cw_array_merge($allowable_search_fields, array("substring", "tag", "by_title", "by_shortdescr", "by_fulldescr", "by_ean", "by_productcode", "category_id", "category_main", "category_extra", "search_in_subcategories", "price_min", "price_max", "avail_min", "avail_max", "weight_min", "weight_max", "created_by", 'avail_types'));
if ($current_area != 'C') {
    $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');
function cw_shipping_get_list($params)
{
    extract($params);
    global $tables, $config, $smarty, $addons;
    global $current_carrier, $cart;
    global $saved_rates;
    if (empty($products)) {
        return;
    }
    $to_address = $userinfo['current_address'];
    $from_address = $config['Company'];
    $current_carrier = $cart['info']['current_carrier'];
    if (isset($saved_rates[$order_hash])) {
        // if used quote
        if ($addons['quote_system'] && isset($cart['info']['quote_doc_id']) && !empty($cart['info']['quote_doc_id']) && isset($cart['info']['shipping_id'])) {
            if (isset($saved_rates[$order_hash][$cart['info']['shipping_id']])) {
                return array($cart['info']['shipping_id'] => $saved_rates[$order_hash][$cart['info']['shipping_id']]);
            } else {
                return array();
            }
        }
        return $saved_rates[$order_hash];
    }
    /*
        if ($warehouse_customer_id != 0) {
            $warehouseinfo = cw_user_get_info($warehouse_customer_id, 1);
            $from_address = $warehouseinfo['main_address'];
        }
    */
    if (empty($userinfo['customer_id']) && $config['General']['apply_default_country'] != "Y" && $config['Shipping']['enable_all_shippings'] == "Y") {
        $enable_all_shippings = true;
        $smarty->assign('force_delivery_dropdown_box', 'Y');
    }
    $what_to_ship_params = cw_call('cw_what_to_ship', array($products));
    cw_load('http');
    $key = md5(serialize($aa = array('to_address' => $to_address, 'from_address' => $from_address, 'what_to_ship' => $what_to_ship_params, 'order_hash' => $order_hash, 'extra_hash' => cw_event('on_collect_shipping_rates_hash', array($products), array()))));
    if (!($rates = cw_cache_get($key, 'shipping_rates'))) {
        $rates = cw_func_call('cw_shipping_get_rates', array('weight' => $what_to_ship_params['apply']['weight'], 'to_address' => $to_address, 'from_address' => $from_address, 'cart' => $cart, 'products' => $products, 'userinfo' => $userinfo, 'what_to_ship_params' => $what_to_ship_params));
        if (!empty($rates)) {
            uasort($rates, 'cw_uasort_by_order');
        }
        cw_cache_save($rates, $key, 'shipping_rates');
    }
    if ($what_to_ship_params['apply']['items'] == 0) {
        foreach ($rates as &$r) {
            $r['original_rate'] = 0;
        }
        unset($r);
    }
    # kornev, it's required for original_rate saving
    $saved_rates[$order_hash] = $rates;
    if ($rates) {
        foreach ($rates as $k => $rate) {
            $tmp_cart = $cart;
            $tmp_cart['info']['shipping_id'] = $rate['shipping_id'];
            # kornev, warehouses fix
            $tmp_cart['info']['shipping_arr'][$warehouse_customer_id] = $rate['shipping_id'];
            $calc_result = cw_func_call('cw_cart_calc', array('cart' => $tmp_cart, 'products' => $products, 'userinfo' => $userinfo));
            $rates[$k]['rate'] = $calc_result['info']['display_shipping_cost'];
            $rates[$k]['tax_cost'] = price_format($calc_result['info']['tax_cost']);
            // TOFIX: Why rate info contains tax for whole cart
            // parse delivery time "3-4 days" to "3" and "4"
            if (preg_match_all('/\\d+/', $rate['shipping_time'], $delivery_time)) {
                $rates[$k]['min_delivery_time'] = $delivery_time[0][0];
                $rates[$k]['max_delivery_time'] = $delivery_time[0][1] ? $delivery_time[0][1] : $rates[$k]['min_delivery_time'];
            }
        }
    }
    # kornev, only available for each products shippings are enabled
    if (is_array($products) && is_array($rates)) {
        $res = null;
        $common_delivery = array('min_delivery_time' => 0, 'max_delivery_time' => 0);
        foreach ($products as $product) {
            // Find longest supplier delivery time among all products
            if ($product['system']['supplier_customer_id']) {
                $product_delivery = cw_user_get_custom_fields($product['system']['supplier_customer_id'], 0, '', 'field');
                if ($product_delivery['min_delivery_time'] > $common_delivery['min_delivery_time']) {
                    $common_delivery['min_delivery_time'] = $product_delivery['min_delivery_time'];
                }
                if ($product_delivery['max_delivery_time'] > $common_delivery['max_delivery_time']) {
                    $common_delivery['max_delivery_time'] = $product_delivery['max_delivery_time'];
                }
            }
            $ps = unserialize($product['shippings']);
            if (is_array($ps) && count($ps)) {
                if (is_null($res)) {
                    $res = array_keys($ps);
                } else {
                    $res = array_intersect($res, array_keys($ps));
                }
            }
        }
        foreach ($rates as $k => $v) {
            if (is_array($res) && !in_array($v['shipping_id'], $res)) {
                unset($rates[$k]);
                continue;
            }
            // Increase delivery time by supplier delivery..
            $rates[$k]['min_delivery_time'] += $common_delivery['min_delivery_time'];
            $rates[$k]['max_delivery_time'] += $common_delivery['max_delivery_time'];
            // ..and re-build shipping time into string
            $rates[$k]['shipping_time_label'] = $rates[$k]['shipping_time'];
            if ($rates[$k]['min_delivery_time'] == $rates[$k]['max_delivery_time']) {
                $rates[$k]['shipping_time'] = $rates[$k]['max_delivery_time'];
            } else {
                $rates[$k]['shipping_time'] = $rates[$k]['min_delivery_time'] . '-' . $rates[$k]['max_delivery_time'];
            }
        }
    } else {
        $rates = array();
    }
    # kornev, final save
    $saved_rates[$order_hash] = $rates;
    // if used quote
    if ($addons['quote_system'] && isset($cart['info']['quote_doc_id']) && !empty($cart['info']['quote_doc_id']) && isset($cart['info']['shipping_id'])) {
        if (isset($rates[$cart['info']['shipping_id']])) {
            return array($cart['info']['shipping_id'] => $rates[$cart['info']['shipping_id']]);
        } else {
            return array();
        }
    }
    return $rates;
}
<?php

//error_reporting(E_ALL ^ E_NOTICE);
set_time_limit(86400);
cw_load('import_export_csv', 'product', 'category');
$import =& cw_session_register('import');
// List of tables for export (could be changed any time)
$export_list = "categories,products,product_variants,product_variant_items,\n\t\tproduct_options,product_options_values,customers,customers_addresses,docs,docs_info";
$export_list = preg_replace("'\\s+'s", "", $export_list);
$export_list = explode(',', $export_list);
cw_event('on_export_tables_list', array(&$export_list));
// Append your tables to $export_list array
foreach ($export_list as $k => $v) {
    if (!isset($tables[$v])) {
        unset($export_list[$k]);
    }
}
$smarty->assign('export_list', $export_list);
if ($delimiter == 'tab') {
    $delimiter = "\t";
}
if ($action == 'export') {
    foreach ($export_list as $v) {
        if (isset(${$v}) && ${$v} == 1) {
            cw_table2csv($v, $delimiter);
        }
    }
}
if ($action == 'delete' && isset($filenames) && is_array($filenames)) {
    foreach ($filenames as $v) {
        if (file_exists(csv_path . '/' . $v)) {
global $tables, $smarty, $HTTPS, $mobile_attributes;
global $app_dir, $app_config_file;
$mobile_device_type =& cw_session_register('mobile_device_type', '');
// user device type ('mobile' : 'computer')
$mobile_select_type =& cw_session_register('mobile_select_type', 2);
// selected version (1 - mobile, 2 - computer)
$mobile_mobile_flag =& cw_session_register('mobile_mobile_flag');
// if user select mobile version by link (used flag)
$mobile_was_redirect =& cw_session_register('mobile_was_redirect', 0);
// is was sistem redirect to mobile version, then 1
// Detect device if empty
if (empty($mobile_device_type)) {
    $detect = new Mobile_Detect();
    $mobile_device_type = $detect->isMobile() && !$detect->isTablet() ? 'mobile' : 'computer';
    cw_event('on_detect_mobile_device', array($mobile_device_type));
}
// if user select mobile version by link (used flag mobile_version)
if (isset($_GET['mobile_version'])) {
    $mobile_mobile_flag = $_GET['mobile_version'];
}
$domain = cw_mobile_get_domain_data();
$domain_mobile_host = $HTTPS ? 'https://' : 'http://';
$domain_mobile_host .= !empty($domain['mobile_host']) ? $domain['mobile_host'] : $domain['http_host'];
$domain_full_host = $HTTPS ? $domain['https_host'] : $domain['http_host'];
// if user select mobile version
if ($mobile_mobile_flag == 'on' || cw_mobile_get_host() == $domain['mobile_host'] && $mobile_mobile_flag != 'on' && $mobile_select_type == 2) {
    $mobile_select_type = 1;
} else {
    if ($mobile_mobile_flag == 'off' || cw_mobile_get_host() == $domain_full_host && $mobile_mobile_flag != 'off' && $mobile_select_type == 1) {
        $mobile_select_type = 2;
function cw_accounting_update_stock($doc_data, $product, $way, $field, $destination_warehouse_id = 0, $affect_prices = false, $movements_id = 0, $source_pwa_id = 0)
{
    global $addons, $tables;
    cw_load('product');
    # kornev
    # way = 1, the products has been purchased - we have to create new record with supplier
    #          ps: the record can be already created... if a few movements have to be generated
    # way = 2, the products has been sold - we have to decrease the most old records
    # kornev
    # if we are making the warehouse movements, we have to increase the products in one and decrease in another and visa versa
    $warehouse_customer_id = $doc_data['info']['warehouse_customer_id'];
    if ($destination_warehouse_id) {
        $warehouse_customer_id = $destination_warehouse_id;
        $way = $way == 2 ? 1 : 2;
    }
    $variant_id = 0;
    # kornev, TOFIX
    if ($addons['product_options'] && (!empty($product['extra_data']['product_options']) || !empty($product['options']))) {
        $options = !empty($product['extra_data']['product_options']) ? $product['extra_data']['product_options'] : $product['options'];
        $variant_id = cw_get_variant_id($options);
    }
    $return = array();
    if ($way == 1) {
        $return = $product['amount'];
    } elseif ($way == 2) {
        $return = -$product['amount'];
        if ($field == 'avail' && in_array($doc_data['type'], array('O', 'I', 'G', 'S'))) {
            cw_call('cw_product_run_counter', array('product_id' => $product['product_id'], 'count' => $return, 'type' => 1));
        }
    }
    //    cw_warehouse_check_avail_record($warehouse_customer_id, $product['product_id'], $variant_id);
    if ($return) {
        db_query("update {$tables['products_warehouses_amount']} set {$field} = {$field} + {$return} where product_id='{$product['product_id']}' and warehouse_customer_id=0 and variant_id='{$variant_id}'");
        cw_event('on_accounting_update_stock', array($product, $variant_id, $field, $return));
    }
    cw_warehouse_recalculate($product['product_id'], $variant_id);
    cw_func_call('cw_product_build_flat', array('product_id' => $product['product_id']));
    return $return;
}
<?php

cw_load('ajax');
if (defined('IS_AJAX') && constant('IS_AJAX')) {
    global $config;
    if ($_GET['get_top_minicart']) {
        cw_add_ajax_block(array('id' => 'microcart_content', 'action' => 'update', 'template' => 'addons/ajax_add2cart/top_minicart.tpl'));
    } else {
        if ($config['Appearance']['place_where_display_minicart'] == 0) {
            // Update minicart
            cw_add_ajax_block(array('id' => 'minicart', 'action' => 'update', 'template' => 'addons/ajax_add2cart/minicart.tpl'));
        }
        cw_add_ajax_block(array('id' => 'microcart', 'action' => 'replace', 'template' => 'customer/menu/microcart.tpl'));
    }
    cw_event('on_minicart_update');
}
             break;
         case 'phone':
             $orderbys[] = "phone {$direction}";
             break;
         case 'zipcode':
             $orderbys[] = "zipcode {$direction}";
             break;
         case "usertype":
         case "email":
             $orderbys[] = "{$tables['customers']}." . $data['sort_field'] . " {$direction}";
     }
 }
 if ($to_join['customers_customer_info']) {
     $query_joins['customers_customer_info'] = array('on' => "{$tables['customers_customer_info']}.customer_id = {$tables['customers']}.customer_id");
 }
 cw_event('on_search_users', array(&$fields, &$from_tbls, &$query_joins, &$where, &$groupbys, &$having, &$orderbys));
 $count_query = cw_db_generate_query(array('count(*)'), $from_tbls, $query_joins, $where, $groupbys, $having, array());
 $_res = db_query($count_query);
 $total_items = db_num_rows($_res);
 db_free_result($_res);
 $navigation = cw_call('cw_core_get_navigation', array($target, $total_items, $page));
 $navigation['script'] = "index.php?target={$target}&mode=search";
 $smarty->assign('navigation', $navigation);
 if ($total_items) {
     $page = $data['page'];
     $user_search_query = cw_db_generate_query($fields, $from_tbls, $query_joins, $where, $groupbys, $having, $orderbys);
     $users = cw_query($q = "{$user_search_query} LIMIT {$navigation['first_page']}, {$navigation['objects_per_page']}");
     if ($action == 'export_emails') {
         $export_columns_names = array('firstname' => 'Firstname', 'lastname' => 'Lastname', 'email' => 'Email');
         $delimiter = $config['General']['user_emails_export_delimiter'];
         header("Content-Type: text/csv");
         $orderbys[] = "total_sales {$direction}";
         break;
     case 'total_profit':
         $orderbys[] = "total_profit {$direction}";
         break;
     case 'margin':
         $orderbys[] = "margin {$direction}";
         break;
     case 'markup':
         $orderbys[] = "markup {$direction}";
         break;
     default:
         $orderbys[] = "{$tables['products']}.{$data['sort_field']} {$direction}";
 }
 $groupbys[] = "{$tables['products']}.product_id";
 cw_event('on_prepare_search_orders', array($data, $docs_type, &$fields, &$query_joins, &$where, &$groupbys, &$having, &$orderbys));
 # kornev, we don't need to sort the result in counter - because it's faster to do it this way
 $count_query = cw_db_generate_query(array('count(*)'), $from_tbls, $query_joins, $where, $groupbys, $having, null);
 $_res = db_query($count_query);
 $total_items = db_num_rows($_res);
 db_free_result($_res);
 $app_config_file['interface']['items_per_page'] = array(20, 50, 100, 500, 1000, 5000, 10000);
 $smarty->assign('app_config_file', $app_config_file);
 $navigation = cw_core_get_navigation($target, $total_items, $page);
 $navigation['script'] = "index.php?target={$target}&mode=search";
 $smarty->assign('navigation', $navigation);
 if ($total_items > 0) {
     $page = $data['page'];
     $products = cw_query($qry = cw_db_generate_query($fields, $from_tbls, $query_joins, $where, $groupbys, $having, $orderbys) . " LIMIT {$navigation['first_page']}, {$navigation['objects_per_page']}");
 }
 $smarty->assign('products', $products);
Esempio n. 21
0
    if (!empty($cart['info']['quote_doc_id'])) {
        $top_message['type'] = "E";
        $top_message['content'] = cw_get_langvar_by_name("err_delete_product_from_cart_with_quote");
        cw_header_location('index.php?target=' . $target);
    }
    cw_event('on_delete_cart', array($productindex));
    $product_id = cw_delete_from_cart($cart, $productindex);
    $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_add_top_message(cw_get_langvar_by_name('msg_product_deleted_from_cart'));
    cw_header_location('index.php?target=' . $target);
}
if (in_array($action, array('update', 'ajax_update', 'checkout'))) {
    if (!empty($productindexes)) {
        $warehouse_selection = array();
        cw_event('on_cart_productindexes_update', array(&$cart, $productindexes));
        $min_amount_warns = cw_call('cw_update_quantity_in_cart', array(&$cart, $productindexes, $warehouse_selection));
        if (!empty($min_amount_warns) && !empty($cart['products'])) {
            $min_amount_ids = array();
            foreach ($cart['products'] as $k => $v) {
                if (!isset($min_amount_warns[$v['cartid']]) || !isset($productindexes[$k]) || isset($min_amount_ids[$v['product_id']])) {
                    continue;
                }
                $product_name = cw_query_first_cell("SELECT IF({$tables['products_lng']}.product IS NULL OR {$tables['products_lng']}.product = '', {$tables['products']}.product, {$tables['products_lng']}.product) as product FROM {$tables['products']} LEFT JOIN {$tables['products_lng']} ON {$tables['products']}.product_id = {$tables['products_lng']}.product_id AND {$tables['products_lng']}.code = '{$current_language}' WHERE {$tables['products']}.product_id = '{$v['product_id']}'");
                cw_add_top_message(cw_get_langvar_by_name('lbl_cannot_buy_less_X', array('quantity' => $min_amount_warns[$v['cartid']], 'product' => $product_name)), 'W');
                $min_amount_ids[$v['product_id']] = true;
            }
        }
    }
    if (!empty($shipping_id)) {
        $cart['info']['shipping_id'] = $shipping_id;
function dashboard_section_system_info($params, $return = null)
{
    global $tables, $smarty;
    // Set the dashboard code name here
    $name = 'system_info';
    // If the section is disabled then skip it on dashboard
    if ($params['mode'] == 'dashboard' && $params['sections'][$name]['active'] === '0') {
        return $return;
    }
    // Define basic data for configuration
    $return[$name] = array('title' => 'System Information', 'description' => 'This is example of dashboard section explains how to build your own widget', 'active' => 1, 'pos' => 60, 'size' => 'small', 'frame' => 1, 'header' => 1);
    if ($params['mode'] == 'setting') {
        return $return;
    }
    // Add content for dashboard in 'dashboard' mode
    // Define either content or template name or both
    // Categories counter
    $cat_cnt = cw_query_first_cell("SELECT count(*) FROM {$tables['categories']}");
    $facet_cnt = cw_query_first_cell("SELECT count(*) FROM {$tables['clean_urls_custom_facet_urls']}");
    cw_system_messages_add('category_count', cw_get_langvar_by_name('lbl_category') . ' | ' . cw_get_langvar_by_name('lbl_facet_count') . ' - <a href="index.php?target=categories">' . $cat_cnt . '</a> | <a href="index.php?target=custom_facet_urls">' . $facet_cnt . '</a>', constant('SYSTEM_MESSAGE_SYSTEM'));
    // Products counter
    $product_cnt = cw_query_first_cell("SELECT count(*) FROM {$tables['products']}");
    cw_system_messages_add('product_count', cw_get_langvar_by_name('lbl_product_count') . ' -
	<a href="index.php?target=products&mode=search&new_search=1">' . $product_cnt . '</a>', constant('SYSTEM_MESSAGE_SYSTEM'));
    // Orders counter
    $order_cnt = cw_query_hash("SELECT status, count(*)  FROM {$tables['docs']} WHERE type='O' GROUP BY status", 'status', false, true);
    $msg = cw_get_langvar_by_name('lbl_order_count') . ' -';
    foreach ($order_cnt as $status => $count) {
        $msg .= ' <a href="index.php?target=docs_O&mode=search&data[status]=' . $status . '" class="order_' . $status . '" title="' . $status . '">&nbsp;' . $count . '&nbsp;</a>';
    }
    cw_system_messages_add('order_count', $msg, constant('SYSTEM_MESSAGE_SYSTEM'));
    // Customers counter
    $customer_cnt = cw_query_first_cell("SELECT count(*) FROM {$tables['customers']} WHERE usertype='C'");
    cw_system_messages_add('customer_count', cw_get_langvar_by_name('lbl_customer_count') . ' - 
	<a href="index.php?target=user_C&mode=search&new_search=1">' . $customer_cnt . '</a>', constant('SYSTEM_MESSAGE_SYSTEM'));
    // Mail counter
    $mail_cnt = cw_query_first_cell("SELECT count(*) FROM {$tables['mail_spool']} WHERE send=0");
    cw_system_messages_add('mail_count', cw_get_langvar_by_name('lbl_mail_queue') . ' - 
	<a href="index.php?target=mail_queue">' . $mail_cnt . '</a>', constant('SYSTEM_MESSAGE_SYSTEM'));
    // Sess counter
    $sess_cnt = cw_query_first_cell("SELECT count(*) FROM {$tables['sessions_data']} WHERE expiry>" . cw_core_get_time());
    cw_system_messages_add('session_count', cw_get_langvar_by_name('lbl_active_sessions') . ' - 
	<a href="index.php?target=sessions">' . $sess_cnt . '</a>', constant('SYSTEM_MESSAGE_SYSTEM'));
    cw_event('on_dashboard_system_info');
    // Handlers must add lines via cw_system_messages_add (type = SYSTEM_MESSAGE_SYSTEM)
    /*
     * GET SYSTEM MESSAGES
     */
    $system_messages = cw_system_messages(constant('SYSTEM_MESSAGE_SYSTEM'), true);
    $smarty->assign('system_info', $system_messages);
    $return[$name]['template'] = 'addons/dashboard/admin/sections/system_info.tpl';
    if (empty($system_messages)) {
        unset($return[$name]);
    }
    return $return;
}
     $is_new_profile = false;
     if ($mode == 'add') {
         $new_profile['usertype'] = $usertype;
         $user = cw_user_create_profile($new_profile);
         // Login registered user
         $identifiers =& cw_session_register('identifiers', array());
         $identifiers['C'] = array('customer_id' => $user);
         $is_new_profile = true;
         cw_event('on_login', array($user, 'C', 1));
     }
     cw_user_update($new_profile, $user, $customer_id);
     // Sign in confirmation letter sending have to be apparently blocked if an user is fake
     if (!isset($is_anonymous) || $is_anonymous != 1) {
         cw_user_send_modification_mail($user, $is_new_profile);
     }
     cw_event('on_profile_modify', array($user, $new_profile));
     if ($mode == 'add' && $is_anonymous) {
         $top_message_text = 'Please proceed to shipping and payment';
     } else {
         $top_message_text = $mode == 'add' ? cw_get_langvar_by_name('msg_user_has_been_added_' . (empty($usertype) ? 'C' : $usertype)) : cw_get_langvar_by_name('msg_profile_upd');
     }
     cw_add_top_message($top_message_text, 'I');
 } else {
     $filled_profile = $update_fields;
     cw_add_top_message(cw_check_user_get_error($fill_error), 'E');
 }
 if (AREA_TYPE == 'A') {
     if (empty($fill_error)) {
         $mode = 'modify';
     }
     cw_header_location("index.php?target={$target}&mode={$mode}&user={$user}&js_tab={$js_tab}");
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;
}
function cw_products_from_scratch($scratch_products, $user_info, $persistent_products, $leave_info = false)
{
    global $addons, $tables, $config, $app_main_dir;
    global $current_area, $current_language, $customer_id;
    cw_load('image');
    $products = array();
    if (empty($scratch_products)) {
        return $products;
    }
    $pids = array();
    foreach ($scratch_products as $product_data) {
        $pids[] = $product_data['product_id'];
    }
    $int_res = cw_query_hash("SELECT * FROM {$tables['products_lng']} WHERE code = '{$current_language}' AND product_id IN ('" . implode("','", $pids) . "')", "product_id", false);
    unset($pids);
    cw_event('on_before_products_from_scratch', array(&$scratch_products));
    $hash = array();
    cw_load('warehouse');
    foreach ($scratch_products as $product_data) {
        $product_id = $product_data['product_id'];
        $cartid = $product_data['cartid'];
        $amount = $product_data['amount'];
        $variant_id = $product_data['variant_id'];
        $warehouse = $product_data['warehouse_customer_id'];
        if (!cw_warehouse_is_customer($customer_id, $warehouse)) {
            continue;
        }
        if (!is_numeric($amount)) {
            $amount = 0;
        }
        $options = $product_data['options'];
        $product_options = false;
        $variant = array();
        # kornev, TOFIX
        if ($addons['product_options'] && !empty($options) && is_array($options)) {
            if (!cw_check_product_options($product_id, $options)) {
                continue;
            }
            list($variant, $product_options) = cw_get_product_options_data($product_id, $options, $membership_id);
            if (empty($variant_id) && isset($variant['variant_id'])) {
                $variant_id = $variant['variant_id'];
            }
        }
        $fields[] = "p.*";
        # kornev, supplier has got it's own prices
        if ($current_area != 'S') {
            $fields[] = "min(pq.price) as price";
        }
        $fields[] = 'avail';
        $status = cw_core_get_required_status($current_area);
        $products_array = cw_func_call('cw_product_get', array('id' => $product_id, 'variant_id' => $variant_id, 'amount' => $amount, 'user_account' => $user_info, 'info_type' => 8192));
        //cw_query_first($sql="select ".implode(', ', $fields)." from $tables[products] as p, $tables[products_prices] as pq, $tables[products_enabled] as pe left join $tables[products_warehouses_amount] as pwa on pwa.product_id=pe.product_id and pwa.variant_id='$variant_id' and pwa.warehouse_customer_id='$warehouse' WHERE p.product_id= pe.product_id and pe.product_id=pq.product_id AND pe.status in (".implode(", ", $status).") AND pe.product_id='$product_id' AND pq.quantity<='$amount' AND pq.membership_id IN(0, '$user_info[membership_id]') AND pq.variant_id = '$variant_id' ORDER BY pq.quantity DESC");
        $unlimited_products = true;
        if ($products_array['avail'] < $amount && in_array($current_area, array('G', 'C'))) {
            $unlimited_products = cw_query_first_cell("select backorder & " . ($current_area == 'G' ? 2 : 1) . " from {$tables['warehouse_divisions']} where division_id = '{$warehouse}'");
            if (!$unlimited_products) {
                $amount = $products_array['avail'];
            }
        }
        if ($products_array) {
            $products_array = cw_array_merge($product_data, $products_array);
            if ($leave_info) {
                $products_array['price'] = abs($product_data['price']);
            }
            $products_array['warehouse_customer_id'] = $warehouse;
            $hash_key = $product_id . "|" . $warehouse;
            cw_event('on_product_from_scratch', array(&$products_array));
            #
            # If priduct's price is 0 then use customer-defined price
            #
            $free_price = false;
            if ($products_array['price'] == 0) {
                $free_price = true;
                $products_array['taxed_price'] = $products_array['price'] = price_format($product_data['free_price'] ? $product_data['free_price'] : 0);
            }
            # kornev, TOFIX
            if ($addons['product_options'] && $options) {
                if (!empty($variant)) {
                    # kornev, it's not allow to set the variant price.
                    //					unset($variant['price']);
                    if (is_null($variant['pimage_path'])) {
                        cw_unset($variant, "pimage_path", "pimage_x", "pimage_y");
                    } else {
                        $variant['is_pimage'] = 'W';
                    }
                    $products_array = cw_array_merge($products_array, $variant);
                }
                $hash_key .= "|" . $products_array['variant_id'];
                if ($product_options === false) {
                    unset($product_options);
                } else {
                    $variant['price'] = $products_array['price'];
                    $variant['cost'] = $products_array['cost'];
                    $products_array['options_surcharge'] = 0;
                    $products_array['cost_surcharge'] = 0;
                    if ($product_options) {
                        foreach ($product_options as $o) {
                            $products_array['options_surcharge'] += $o['modifier_type'] ? $products_array['price'] * $o['price_modifier'] / 100 : $o['price_modifier'];
                            $products_array['cost_surcharge'] += $o['cost_modifier_type'] ? $products_array['cost'] * $o['cost_modifier'] / 100 : $o['cost_modifier'];
                        }
                    }
                }
            }
            if (!$unlimited_products && !$persistent_products && $products_array['avail'] - $hash[$hash_key] < $amount) {
                continue;
            }
            # Get thumbnail's URL (uses only if images stored in FS)
            $products_array['image_thumb'] = cw_image_get('products_images_thumb', $product_id);
            $products_array['price'] += $products_array['options_surcharge'];
            $products_array['cost'] += $products_array['cost_surcharge'];
            if ($products_array['price'] < 0) {
                $products_array['price'] = 0;
            }
            if ($products_array['cost'] < 0) {
                $products_array['cost'] = 0;
            }
            if (in_array($current_area, array('C', 'G'))) {
                $products_array['taxes'] = cw_get_products_taxes($products_array, $user_info, false, '', $current_area == 'G' && $customer_info['usertype'] != 'R');
                if ($config['Taxes']['display_taxed_order_totals'] == 'Y') {
                    $products_array['display_price'] = $products_array['taxed_price'];
                    $products_array['display_net_price'] = $products_array['taxed_net_price'];
                } else {
                    $products_array['display_price'] = $products_array['price'];
                    $products_array['display_net_price'] = $products_array['net_price'];
                }
            }
            $products_array['total'] = $amount * $products_array['price'];
            $products_array['product_options'] = $product_options;
            $products_array['options'] = $options;
            $products_array['amount'] = $amount;
            $products_array['cartid'] = $cartid;
            $products_array['product_orig'] = $products_array['product'];
            if (isset($int_res[$product_id])) {
                $products_array['product'] = stripslashes($int_res[$product_id]['product']);
                $products_array['descr'] = stripslashes($int_res[$product_id]['descr']);
                $products_array['fulldescr'] = stripslashes($int_res[$product_id]['fulldescr']);
                cw_unset($int_res, $product_id);
            }
            if ($products_array['descr'] == strip_tags($products_array['descr'])) {
                $products_array['descr'] = str_replace("\n", "<br />", $products_array['descr']);
            }
            if ($products_array['fulldescr'] == strip_tags($products_array['fulldescr'])) {
                $products_array['fulldescr'] = str_replace("\n", "<br />", $products_array['fulldescr']);
            }
            // Order hash defines how all products in cart will be split by orders
            // Listen for the event and return own part of hash
            $order_hash = cw_event('on_build_order_hash', array($products_array), array());
            $order_hash[] = 'W' . $products_array['warehouse_customer_id'];
            $products_array['order_hash'] = join('-', $order_hash);
            $products[] = $products_array;
            $hash[$hash_key] += $amount;
        }
    }
    //cw_var_dump($products);
    return $products;
}
function cw_display($tpl, &$templater, $to_display = true, $lng_code = '')
{
    global $config, $location, $HTTPS;
    global $predefined_lng_variables, $current_language, $__smarty_time, $__smarty_size;
    global $app_main_dir;
    global $__X_LNG, $REQUEST_URI, $REQUEST_METHOD;
    global $ars_hooks;
    global $target, $action;
    if ($to_display) {
        cw_event('on_after_' . $target);
        cw_event('on_after_' . $target . '_' . $action);
    }
    $include = array('css' => array(), 'js' => array());
    if (is_array($ars_hooks['css']['all'])) {
        $include['css'] = array_merge($include['css'], $ars_hooks['css']['all']);
    }
    if (is_array($ars_hooks['css'][AREA_TYPE])) {
        $include['css'] = array_merge($include['css'], $ars_hooks['css'][AREA_TYPE]);
    }
    if (is_array($ars_hooks['js']['all'])) {
        $include['js'] = array_merge($include['js'], $ars_hooks['js']['all']);
    }
    if (is_array($ars_hooks['js'][AREA_TYPE])) {
        $include['js'] = array_merge($include['js'], $ars_hooks['js'][AREA_TYPE]);
    }
    $templater->assign('include', $include);
    $templater->assign('config', $config);
    $templater->assign('location', $location);
    $templater->assign('lng', array());
    cw_load('templater');
    if (!empty($config['Security']['compiled_tpl_check_md5']) && $config['Security']['compiled_tpl_check_md5'] == 'Y') {
        $templater->compile_check_md5 = true;
    } else {
        $templater->compile_check_md5 = false;
    }
    if (!empty($predefined_lng_variables)) {
        if (empty($lng_code)) {
            $lng_code = $current_language;
        }
        if (!empty($predefined_lng_variables)) {
            $predefined_lng_variables = array_flip($predefined_lng_variables);
            $predefined_vars = array();
            cw_get_lang_vars_extra($lng_code, $predefined_lng_variables, $predefined_vars);
            $templater->_tpl_vars['lng'] = cw_array_merge($templater->_tpl_vars['lng'], $predefined_vars);
            if (!isset($__X_LNG[$current_language])) {
                $__X_LNG[$current_language] = $predefined_vars;
            } else {
                $__X_LNG[$current_language] = cw_array_merge($__X_LNG[$current_language], $predefined_vars);
            }
            unset($predefined_vars);
        }
        unset($predefined_lng_variables);
    }
    $templater->register_postfilter("cw_tpl_add_hash");
    $templater->register_postfilter('cw_tpl_postfilter');
    $templater->register_outputfilter('cw_convert_lang_var');
    $templater->register_outputfilter('cw_generate_css_sprites');
    $templater->load_filter('post', 'cw_hooks');
    $templater->register_outputfilter('cw_load_head_resource');
    global $current_area;
    if ($config['General']['defer_load_js_code'] == 'Y' && $current_area == 'C' && !(defined('IS_AJAX') && constant('IS_AJAX'))) {
        $templater->register_outputfilter('cw_defer_load_js_code');
    }
    if ($config['General']['sprite_all_images'] == 'Y' && $current_area == 'C' && !(defined('IS_AJAX') && constant('IS_AJAX'))) {
        $templater->register_outputfilter('cw_sprite_all_images');
    }
    if ($config['General']['list_available_cdn_servers'] && !$HTTPS) {
        $templater->register_outputfilter('cw_sharing_cdn');
    }
    cw_track_navigation_history($REQUEST_URI, $REQUEST_METHOD, TRUE);
    if ($to_display == true) {
        $templater->display($tpl);
        $ret = "";
        # Display page content
        cw_flush();
    } else {
        $ret = $templater->fetch($tpl);
    }
    return $ret;
}
function cw_user_update($userinfo, $customer_id, $by_customer_id)
{
    global $tables, $addons;
    foreach (array('email', 'status', 'membership_id', 'language', 'change_password') as $fld) {
        if (isset($userinfo[$fld])) {
            $customer[$fld] = $userinfo[$fld];
        }
    }
    if (AREA_TYPE == 'A' && $userinfo['usertype']) {
        $customer['usertype'] = $userinfo['usertype'];
    }
    if (AREA_TYPE == 'A' && $userinfo['customer_id']) {
        $customer['customer_id'] = $userinfo['customer_id'];
    }
    $current = cw_user_get_info($customer_id, 0);
    //allow password update only by the profile owner or by admin
    if (isset($userinfo['password'])) {
        if (!empty($userinfo['password']) && ($customer_id == $by_customer_id || AREA_TYPE == 'A')) {
            $customer['password'] = cw_call('cw_user_get_hashed_password', array($userinfo['password']));
        }
    }
    cw_event('on_user_update', array($customer_id, $by_customer_id, $customer, $userinfo));
    cw_array2update('customers', $customer, "customer_id='{$customer_id}'");
    $additional_info = $userinfo['additional_info'];
    $customer_info_fields = array('ssn', 'tax_number', 'birthday', 'birthday_place', 'sex', 'married', 'nationality', 'company', 'employees', 'foundation', 'foundation_place', 'company_type', 'company_id', 'can_change_company_id', 'contact_date', 'tax_id', 'payment_id', 'payment_note', 'tax_exempt', 'separate_invoices', 'shipping_operated', 'shipment_paid', 'shipping_company_to_carrier_id', 'shipping_company_from_carrier_id', 'cod_delivery_type_id', 'leaving_type', 'department_id', 'division_id', 'doc_prefix', 'order_entering_format', 'status_note');
    if (!cw_query_first_cell("select count(*) from {$tables['customers_customer_info']} where customer_id='{$customer_id}'")) {
        cw_array2insert('customers_customer_info', array('customer_id' => $customer_id));
    }
    cw_array2update('customers_customer_info', $additional_info, "customer_id='{$customer_id}'", $customer_info_fields);
    /*
          db_query("update $tables[customers_addresses] set main=0, current=0 where customer_id = '$customer_id'");
        foreach(array('main_address', 'current_address') as $addr)  {
            if (!$userinfo[$addr]) continue;
    
            $userinfo[$addr]['main'] = $addr == 'main_address';
            $userinfo[$addr]['current'] = $addr == 'current_address';
    
            $address_id = $userinfo[$addr]['address_id'];
            if (!$address_id) $address_id = cw_array2insert('customers_addresses', array('customer_id' => $customer_id, 'main' => $userinfo[$addr]['main'], 'current' => $userinfo[$addr]['current']));
    
            cw_user_update_address($customer_id, $address_id, $userinfo[$addr]);
        }
    */
    foreach (cw_user_address_array($userinfo['addresses']) as $address_id => $address) {
        cw_user_update_address($customer_id, $address['address_id'], $address);
    }
    cw_user_check_addresses($customer_id);
    $relations = $userinfo['relations'];
    $relations_info = array('salesman_customer_id' => $relations['salesman_customer_id'], 'employee_customer_id' => $relations['employee_customer_id'], 'warehouse_customer_id' => $relations['warehouse_customer_id']);
    if (!cw_query_first_cell("select count(*) from {$tables['customers_relations']} where customer_id='{$customer_id}'")) {
        db_query("insert into {$tables['customers_relations']}(customer_id) values('{$customer_id}')");
    }
    cw_array2update('customers_relations', $relations_info, "customer_id='{$customer_id}'");
    if ($userinfo['chamber_certificate_uploaded']['file_path']) {
        db_query("delete from {$tables['customers_chamber_certificates']} where customer_id='{$customer_id}'");
        cw_file_area_save('customers_chamber_certificates', $customer_id, $userinfo['chamber_certificate_uploaded']);
    }
    if (is_array($userinfo['custom_fields'])) {
        foreach ($userinfo['custom_fields'] as $field_id => $value) {
            db_query("delete from {$tables['register_fields_values']} where customer_id='{$customer_id}' AND field_id='{$field_id}'");
            cw_array2insert('register_fields_values', array('field_id' => $field_id, 'value' => $value, 'customer_id' => $customer_id));
        }
    }
    $customer_system_info = cw_query_first("select * from {$tables['customers_system_info']} where customer_id='{$customer_id}'");
    $customer_system_info['customer_id'] = $customer_id;
    if (!$customer_system_info['creation_customer_id']) {
        $customer_system_info['creation_customer_id'] = $by_customer_id;
        $customer_system_info['creation_date'] = cw_core_get_time();
    }
    $customer_system_info['modification_customer_id'] = $by_customer_id;
    $customer_system_info['modification_date'] = cw_core_get_time();
    cw_array2insert('customers_system_info', $customer_system_info, true);
    $salesman_info = cw_query_first("select * from {$tables['customers_salesman_info']} where customer_id = '{$customer_id}'");
    $salesman_info['parent_customer_id'] = $userinfo['salesman_info']['parent_customer_id'];
    cw_array2insert('customers_salesman_info', $salesman_info, true);
}
    foreach ($app_config_file as $app_config_section => $app_config) {
        if (isset($_app_config_file[$app_config_section])) {
            $app_config_file[$app_config_section] = array_merge((array) $app_config, (array) $_app_config_file[$app_config_section]);
        }
    }
}
unset($_app_config_file, $app_config, $app_config_section);
$area = isset($_REQUEST['area']) ? $_REQUEST['area'] : 'customer';
$target = isset($_REQUEST['target']) ? $_REQUEST['target'] : 'index';
define('APP_START', 1);
$request_prepared = array();
define('APP_AREA', $area);
include_once $app_main_dir . '/init.php';
cw_include($area . '/auth.php');
cw_event('on_before_' . $target);
cw_event('on_before_' . $target . '_' . $action);
cw_include($area . '/' . $target . '.php');
if (defined('IS_AJAX') && !defined('PREVENT_XML_OUT')) {
    cw_include($area . '/ajax.php');
    exit(0);
}
$__script_microtime = microtime(true) - $__start_mictotime;
$__bech_display_id = cw_bench_open_tag('DISPLAY', 'POINT', '');
cw_display($area . '/index.tpl', $smarty, true);
cw_bench_close_tag($__bech_display_id);
$__smarty_microtime = microtime(true) - $__start_mictotime - $__script_microtime;
// Time end
if (!defined('IS_AJAX')) {
    // Time end
    $__output_microtime = 'Runtime: ' . sprintf("%.4f", $__smarty_microtime + $__script_microtime) . ' (SCRIPT: ' . sprintf("%.4f", $__script_microtime) . '; SMARTY: ' . sprintf("%.4f", $__smarty_microtime) . ')';
    if (!$app_config_file['debug']['development_mode']) {
            // 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'];
        }
    }
}
 if (count($fill_error)) {
     $fill_error = array(cw_get_langvar_by_name('lbl_fill_in_required_fields'));
 }
 // artem, TODO: add fields validation
 if ($register['email']) {
     // artem, TODO: no direct SQL, only api calls
     $is_user = cw_query_first_cell("select count(*) from {$tables['customers']} where email='{$register['email']}'");
     if ($is_user) {
         $fill_error['email'] = cw_get_langvar_by_name('lbl_email_already_used');
     }
 }
 if ($register['password'] != $register['password2']) {
     $fill_error['password'] = cw_get_langvar_by_name('lbl_password_confirmation_wrong');
 }
 // Handlers of on_register_validate should return array('field'=>'message') if field is failed
 $validation = cw_event('on_register_validate', array($register, $usertype), array());
 foreach ($validation as $res) {
     if (is_array($res)) {
         $fill_error = cw_array_merge_assoc($fill_error, $res);
     }
 }
 if (count($fill_error)) {
     $prefilled_info = $register;
     $top_message = array('content' => join('<br/>', $fill_error), 'type' => 'E');
 } else {
     $usertype = 'C';
     if ($action == 'register_reseller') {
         $usertype = 'R';
     }
     $register['usertype'] = $usertype;
     $register['membership_id'] = $partner_membership;