function cw_file_area_save($type, $for_customer_id, $data)
{
    global $tables, $customer_id, $var_dirs, $app_dir;
    $insert = array('customer_id' => $for_customer_id, 'by_customer_id' => $customer_id, 'filename' => $data['filename'], 'date' => cw_core_get_time(), 'md5' => md5(file_get_contents($data['file_path'])));
    if ($data['descr']) {
        $insert['descr'] = $data['descr'];
    }
    if ($data['id']) {
        $insert['id'] = $data['id'];
    }
    $file_id = cw_array2insert($type, $insert);
    if ($file_id) {
        $file_info = explode('.', $data['filename'], 2);
        $stored_file_name = $file_info[0] . '_' . $file_id . '.' . $file_info[1];
        $files_dir = $var_dirs['documents'] . '/' . $type;
        if (!is_dir($files_dir)) {
            @mkdir($files_dir);
        }
        $new_file_path = $files_dir . '/' . $stored_file_name;
        @copy($data['file_path'], $new_file_path);
        @unlink($data['file_path']);
        $new_file_path = cw_relative_path($new_file_path, $app_dir);
        db_query("update " . $tables[$type] . " set file_path='" . addslashes($new_file_path) . "' where file_id='{$file_id}'");
    }
    return $file_id;
}
function cw_system_messages_add($code, $msg, $type = SYSTEM_MESSAGE_COMMON, $severity = SYSTEM_MESSAGE_INFO)
{
    global $tables;
    $code = mysql_real_escape_string($code);
    $msg = mysql_real_escape_string($msg);
    $type = intval($type);
    $existing = cw_query_first("SELECT code, hidden FROM {$tables['system_messages']} WHERE code='{$code}'");
    $data = array('date' => cw_core_get_time(), 'message' => $msg, 'type' => $type, 'severity' => $severity);
    if ($existing) {
        $ret = cw_array2update('system_messages', $data, "code='{$code}'");
    } else {
        $data['code'] = $code;
        $data['hidden'] = 0;
        $ret = cw_array2insert('system_messages', $data);
    }
    return $ret;
}
function cw_aom_get_doc_storage($type, $info = array(), $prefix = '', $special_info = array())
{
    $display_id = cw_doc_get_display_id($type);
    $usertype = 'C';
    if (in_array($type, array('P', 'Q', 'R'))) {
        $usertype = 'S';
    } elseif ($type == 'D') {
        $usertype = 'D';
    }
    $ret = array('doc_id' => 0, 'display_id' => $prefix . $display_id, 'prefix' => $prefix, 'display_doc_id' => $display_id, 'type' => $type, 'date' => cw_core_get_time(), 'status' => 'Q', 'info' => array('total' => 0), 'userinfo' => array('customer_id' => 0, 'usertype' => $usertype, 'current_address' => array('same_as_main' => 1)));
    if ($info) {
        $ret['info'] = array_merge($ret['info'], $info);
    }
    foreach ($special_info as $tbl => $fields) {
        $ret[$tbl] = $fields;
    }
    return $ret;
}
function cw_ppd_doc_change_status_C($doc_data, $return)
{
    global $tables, $config;
    if (empty($doc_data) || !is_array($doc_data)) {
        return $return;
    }
    $doc_data['doc_id'] = (int) $doc_data['doc_id'];
    $_download_exists = cw_query_first_cell('SELECT download_id FROM ' . $tables['ppd_downloads'] . ' WHERE order_id = \'' . $doc_data['doc_id'] . '\'');
    if (!empty($_download_exists) || empty($doc_data['products'])) {
        return $return;
    }
    $values_for_ins = array();
    $data = array();
    $data['order_id'] = $doc_data['doc_id'];
    $data['customer_id'] = $doc_data['userinfo']['customer_id'];
    $data['allowed_number'] = (int) $config['ppd']['ppd_loading_attempts'];
    $data['counter'] = 0;
    $data['expiration_date'] = cw_core_get_time() + (int) $config['ppd']['ppd_link_lifetime'] * 60 * 60;
    foreach ($doc_data['products'] as $product) {
        $files = cw_query('SELECT file_id FROM ' . $tables['ppd_files'] . ' WHERE product_id = \'' . $product['product_id'] . '\' AND active = 1 AND perms_owner >= 4 AND perms_all = 0 ORDER BY number');
        if (empty($files) || !is_array($files)) {
            continue;
        }
        $data['product_id'] = $product['product_id'];
        foreach ($files as $file) {
            $data['file_id'] = $file['file_id'];
            $_replace_data = cw_query_first_cell('SELECT download_id FROM ' . $tables['ppd_downloads'] . ' WHERE product_id = \'' . $data['product_id'] . '\' AND file_id = \'' . $data['file_id'] . '\'');
            if (!empty($_replace_data)) {
                $data['download_id'] = $_replace_data;
                $query = 'REPLACE INTO ' . $tables['ppd_downloads'] . ' (`' . implode('`, `', array_keys($data)) . '`) VALUES ' . '(\'' . implode('\', \'', $data) . '\')';
                db_query($query);
                unset($data['download_id']);
                continue;
            }
            $values_for_ins[] = '(\'' . implode('\', \'', $data) . '\')';
        }
    }
    if (empty($values_for_ins)) {
        return $return;
    }
    $query = 'INSERT INTO ' . $tables['ppd_downloads'] . ' (`' . implode('`, `', array_keys($data)) . '`) VALUES ' . implode(', ', $values_for_ins);
    db_query($query);
    return $return;
}
function cw_sections_get_featured($featured_type, $cat = 0, $info_type = 128)
{
    global $tables, $smarty;
    global $user_account, $current_area;
    if (empty($featured_type)) {
        $featured_type = 'featured_products';
    }
    $data = array();
    $data['flat_search'] = 1;
    $data['all'] = 1;
    $data['status'] = array(1);
    $table = $tables[$featured_type];
    $data['sort_condition'] = $table . ".product_order";
    $current_time = cw_core_get_time();
    $add_params = array();
    $add_params['query_joins'][$featured_type] = array('on' => "{$tables['products']}.product_id=" . $table . ".product_id AND " . $table . ".avail=1 AND " . $table . ".category_id='" . $cat . "'" . ($featured_type == 'featured_products' ? " and ({$table}.from_time <= {$current_time} or {$table}.from_time = 0) and ({$table}.to_time >={$current_time} or {$table}.to_time = 0)" : ''), 'is_inner' => 1);
    $data['where'] = $featured_type == 'featured_products' ? "{$table}.min_amount <= {$tables['products_warehouses_amount']}.avail" : '';
    list($products, $navigation) = cw_func_call('cw_product_search', array('data' => $data, 'user_account' => $user_account, 'current_area' => $current_area, 'info_type' => $info_type), $add_params);
    return $products;
}
function cw_messages_create_new_message($customer_id, $sender_name, $recipient_id, $recipient_email, $subject, $body, $conversation_id)
{
    global $config, $current_location;
    cw_load('email');
    // sent message (incoming folder)
    $new_message_id = cw_array2insert('messages', array('subject' => $subject, 'body' => $body, 'sender_id' => $customer_id, 'recipient_id' => $recipient_id, 'sending_date' => cw_core_get_time(), 'conversation_id' => !empty($conversation_id) ? $conversation_id : 0, 'conversation_customer_id' => $recipient_id));
    // duplicate for sent folder
    $current_conversation_id = !empty($conversation_id) ? $conversation_id : $new_message_id;
    $duplicate_message_id = cw_array2insert('messages', array('subject' => $subject, 'body' => $body, 'sender_id' => $customer_id, 'recipient_id' => $recipient_id, 'sending_date' => cw_core_get_time(), 'read_status' => 1, 'conversation_id' => $current_conversation_id, 'conversation_customer_id' => $customer_id, 'type' => 2, 'link_id' => $new_message_id));
    // unite message if they have not been united
    $data = array('link_id' => $duplicate_message_id);
    if (empty($conversation_id)) {
        $data['conversation_id'] = $new_message_id;
    }
    cw_array2update('messages', $data, "message_id = '{$new_message_id}'");
    // send notification email to recipient
    // notification is sent from system email and says about new received message from Sender at <sitename>
    $from = $config['Company']['site_administrator'];
    /*
        $mail_subject = "The notification of a new message";
        $mail_body = '<b>You have received a new message from "' . $sender_name . '" at <a href="' . $current_location . '">';
        $mail_body .= $config['Company']['company_name'] . '</a></b><br />';
        $mail_body .= '<b>Subject:</b> ' . $subject . '<br />';
        $mail_body .= '<b>Body:</b> ' . nl2br($body) . '<br />';
        $mail_body .= '<a href="' . $current_location . '/index.php?target=message_box&mode=new';
        $mail_body .= '&contact_id=' . $customer_id . '&conversation_id=' . $current_conversation_id . '">Link to reply</a><br />';
        cw_send_simple_mail($from, $recipient_email, $mail_subject, $mail_body);
    */
    global $smarty;
    $smarty->assign('sender_name', $sender_name);
    $smarty->assign('current_location', $current_location);
    $smarty->assign('config', $config);
    $smarty->assign('subject', $subject);
    $smarty->assign('body', $body);
    $smarty->assign('customer_id', $customer_id);
    $smarty->assign('recipient_id', $recipient_id);
    $smarty->assign('current_conversation_id', $current_conversation_id);
    $smarty->assign('new_message_id', $new_message_id);
    cw_call('cw_send_mail', array($from, $recipient_email, 'addons/messaging_system/mail/new_message_subj.tpl', 'addons/messaging_system/mail/new_message.tpl'));
    return $new_message_id;
}
function cw_commit_sitemap()
{
    global $site_map_counter;
    global $file_counter;
    global $smarty, $tables;
    global $app_catalogs, $var_dirs;
    # kornev, commit google sitemap
    $site_map_name = $smarty->compile_dir . '/sitemap.xml';
    $files = array();
    for ($i = 1; $i <= $file_counter; $i++) {
        $tmp_filename = $smarty->compile_dir . '/sitemap' . $i . '.xml';
        $sitemap_file = $var_dirs['sitemap'] . '/sitemap' . $i . '.xml.gz';
        if (is_file($tmp_filename)) {
            @unlink($sitemap_file);
            @rename($tmp_filename, $site_map_name);
            exec($sql = "gzip -c " . $site_map_name . " > " . $sitemap_file);
            //        @unlink($site_map_name);
            $files[] = $sitemap_file;
        }
    }
    $tmp_filename = $smarty->compile_dir . '/sitemap_index.xml';
    $fp = fopen($tmp_filename, "w+");
    $str = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<sitemapindex xmlns=\"http://www.google.com/schemas/sitemap/0.84\">\n";
    fwrite($fp, $str);
    $date = date("Y-m-d", cw_core_get_time());
    foreach ($files as $file) {
        $str = "<sitemap>\n<loc>" . $app_catalogs['customer'] . "/" . basename($file) . "</loc>\n<lastmod>" . $date . "</lastmod>\n</sitemap>\n";
        fwrite($fp, $str);
    }
    $str = "</sitemapindex>";
    fwrite($fp, $str);
    @rename($tmp_filename, $var_dirs['sitemap'] . '/sitemap_index.xml');
    # kornev, commit yahoo sitemap
    $tmp_filename_yahoo = $smarty->compile_dir . '/urllist.txt';
    @rename($tmp_filename_yahoo, $var_dirs['sitemap'] . '/urllist.txt');
    db_query("UPDATE {$tables['config']} SET value='" . time() . "' WHERE name='google_sitemap_date'");
}
     switch ($data['basic']['created']) {
         case 'this_month':
             $start = mktime(0, 0, 0, date("n"), 1, date("Y"));
             $end = cw_core_get_time();
             $where[] = "{$tables['docs']}.date >= '" . $start . "'";
             $where[] = "{$tables['docs']}.date <= '" . $end . "'";
             break;
         case 'this_week':
             $start = mktime(0, 0, 0, date("n"), date("j") - date("w"), date("Y"));
             $end = cw_core_get_time();
             $where[] = "{$tables['docs']}.date >= '" . $start . "'";
             $where[] = "{$tables['docs']}.date <= '" . $end . "'";
             break;
         case 'today':
             $start = mktime(0, 0, 0, date("n"), date("j"), date("Y"));
             $end = cw_core_get_time();
             $where[] = "{$tables['docs']}.date >= '" . $start . "'";
             $where[] = "{$tables['docs']}.date <= '" . $end . "'";
             break;
     }
 }
 if (!empty($data['basic']['status'])) {
     if (is_array($data['basic']['status'])) {
         $where[] = "{$tables['docs']}.status in ('" . implode("','", $data['basic']['status']) . "')";
     } else {
         $where[] = "{$tables['docs']}.status = '" . $data['basic']['status'] . "'";
     }
 }
 if (!empty($data['basic']['doc_id_start'])) {
     $where[] = "{$tables['docs']}.display_doc_id >= '" . $data['basic']['doc_id_start'] . "'";
 }
function cw_accounting_create_supplier_amount($doc_id, $product, $variant_id, $warehouse_customer_id, $supplier_customer_id, $source_pwa_id = 0)
{
    global $tables;
    $supplier_type = cw_query_first_cell("select customer_id from {$tables['customers']} where customer_id='{$supplier_customer_id}' and usertype='S'");
    if (!$supplier_customer_id || $supplier_customer_id != $supplier_type) {
        $supplier_customer_id = cw_query_first_cell("select supplier_customer_id from {$tables['products_supplied_amount']} where productcode='" . $product['productcode'] . "' and product_id='{$product['product_id']}'");
    }
    if ($source_pwa_id) {
        $record = cw_query_first("select * from {$tables['products_supplied_amount']} where pwa_id='{$source_pwa_id}'");
        unset($record['pwa_id']);
    }
    if (!$record) {
        $record = array('product_id' => $product['product_id'], 'productcode' => $product['productcode'], 'supplier_price' => $product['net_price'], 'discount' => $product['discount_formula'] ? $product['discount_formula'] : $product['discount'], 'price' => $product['price'], 'variant_id' => $variant_id);
    }
    $record = array_merge($record, array('doc_id' => $doc_id, 'item_id' => $product['item_id'], 'warehouse_customer_id' => $warehouse_customer_id, 'supplier_customer_id' => $supplier_customer_id, 'avail' => 0, 'avail_ordered' => 0, 'avail_ordered' => 0, 'avail_sold' => 0, 'avail_reserved' => 0, 'is_auto_calc' => $product['is_auto_calc'], 'date' => cw_core_get_time()));
    return cw_array2insert('products_supplied_amount', $record);
}
         $antibot_err = true;
     }
     if ($antibot_err) {
         $top_message['type'] = "E";
         $top_message['content'] = cw_get_langvar_by_name("msg_err_antibot");
         cw_header_location("index.php?target={$target}&survey_id=" . $survey_id);
     }
 }
 # Check if survey results is empty
 if (cw_is_survey_result_empty($data) || !is_array($data)) {
     $top_message['type'] = 'W';
     $top_message['content'] = cw_get_langvar_by_name("txt_survey_is_empty_message");
     cw_header_location("index.php?target={$target}&survey_id={$survey_id}");
 }
 # Save common data
 $query_data = array('survey_id' => $survey_id, 'date' => cw_core_get_time(), 'ip' => $CLIENT_IP, 'customer_id' => $fill_customer_id, 'code' => $current_language, 'from_mail' => empty($fill_user) ? "N" : "Y", 'as_result' => empty($fill_user) ? "" : $fill_user['as_result']);
 $survey_result_id = cw_array2insert("survey_results", $query_data);
 $quids = cw_query_hash("SELECT question_id, answers_type FROM {$tables['survey_questions']} WHERE survey_id = '{$survey_id}'", 'question_id', false);
 foreach ($data as $qid => $v) {
     $question = $quids[$qid];
     if (!$question) {
         continue;
     }
     $query_data = array('survey_result_id' => $survey_result_id, 'question_id' => $qid);
     if ($question['answers_type'] == 'N') {
         $query_data['comment'] = $v['comment'];
         cw_array2insert('survey_result_answers', $query_data);
     } else {
         $answers = cw_query_hash("SELECT answer_id, textbox_type FROM {$tables['survey_answers']} WHERE question_id = '{$qid}'", 'answer_id', false);
         if (empty($v['answers'])) {
             continue;
function cw_faq_create_rubrik($title, $parent_id, $ars_id = 0, $ars_type = '')
{
    global $tables;
    $to_insert = array();
    $to_insert['title'] = $title;
    $to_insert['date'] = cw_core_get_time();
    $to_insert['parent_id'] = $parent_id;
    $to_insert['ars_id'] = $ars_id;
    $to_insert['ars_type'] = $ars_type;
    $rubrik_id = cw_array2insert('faq_rubrik', $to_insert);
    cw_faq_update_path($rubrik_id);
    cw_faq_recalc_counters($rubrik_id);
    return $rubrik_id;
}
function cw_discount_coupons_is_valid($coupon, $products)
{
    global $tables, $customer_id, $config;
    $my_coupon = cw_query_first("select * from {$tables['discount_coupons']} where coupon='{$coupon}' and status=1 AND expire>" . cw_core_get_time());
    # kornev, may be it's salesman discount
    $salesman_discount = false;
    if (!$my_coupon) {
        $my_coupon = cw_query_first("select * from {$tables['discount_coupons']} where coupon='{$coupon}' and status=1 and salesman_customer_id='{$customer_id}'");
        $salesman_discount = true;
    }
    if (!$my_coupon) {
        return 1;
    }
    if ($my_coupon['per_user']) {
        if (empty($cutomer_id)) {
            return 1;
        }
        $_times_used = cw_query_first_cell("select times_used from {$tables['discount_coupons_cutomer_id']} where coupon='{$coupon}' and cutomer_id='{$cutomer_id}'");
        if ($_times_used >= $my_coupon['times']) {
            return 5;
        }
    }
    if ($my_coupon['coupon_type'] == "percent" && $my_coupon['discount'] > 100) {
        return 1;
    }
    if ($my_coupon['product_id'] > 0) {
        $found = false;
        foreach ($products as $value) {
            if ($value['product_id'] == $my_coupon['product_id']) {
                $found = true;
            }
        }
        return $found ? 0 : 4;
    } elseif ($my_coupon['category_id'] > 0) {
        $found = false;
        $category_ids[] = $my_coupon['category_id'];
        if ($my_coupon['recursive']) {
            $category_ids[] = cw_category_get_path($my_coupon['category_id']);
        }
        if (!is_array($products)) {
            return 4;
        }
        if ($config['Appearance']['categories_in_products'] == '1') {
            foreach ($products as $value) {
                $product_categories = cw_query("SELECT category_id FROM {$tables['products_categories']} WHERE product_id='{$value['product_id']}'");
                $is_valid_product = false;
                foreach ($product_categories as $k => $v) {
                    if (in_array($v['category_id'], $category_ids)) {
                        $is_valid_product = true;
                        break;
                    }
                }
                if ($is_valid_product) {
                    $found = true;
                    break;
                }
            }
        }
        return $found ? 0 : 4;
    } else {
        $total = 0;
        if (!empty($products) && is_array($products)) {
            foreach ($products as $value) {
                $total += $value['price'] * $value['amount'];
            }
        }
        if ($total < $my_coupon['minimum']) {
            return 3;
        } else {
            return 0;
        }
    }
    return 0;
}
function cw_ps_get_customer_offers(&$cart, &$products, $_user_info = array())
{
    global $tables, $domain_attributes, $addons, $smarty;
    static $offers_hash;
    if (empty($cart) || empty($products)) {
        return array();
    }
    global $customer_id, $user_info;
    $customer_zone = null;
    if (isset($customer_id) && !empty($customer_id)) {
        if (!isset($user_info) || empty($user_info)) {
            $user_info = cw_user_get_info($customer_id, 1);
        }
    } else {
        $user_info = $_user_info;
        if (empty($_user_info)) {
            $user_info = $cart['userinfo'];
        }
    }
    $customer_zone = cw_func_call('cw_cart_get_zone_ship', array('address' => $user_info['current_address'], 'type' => 'D'));
    list($_products, $_categories, $_manufacturers) = cw_ps_normalize_products($products);
    if (empty($_products) || empty($_categories)) {
        return array();
    }
    //$hash_key = md5(serialize($_products) . serialize($user_info));
    $shipping_address = array();
    $shipping_address_fields = array('country', 'state', 'zipcode', 'city', 'address');
    if (!isset($user_info) || empty($user_info)) {
        foreach ($shipping_address_fields as $field) {
            if (isset($user_info['current_address'][$field])) {
                $shipping_address[] = $user_info['current_address'][$field];
            }
        }
    }
    $hash_key = md5(serialize($_products) . serialize($shipping_address));
    if (!isset($offers_hash[$hash_key])) {
        $offers_hash[$hash_key] = array();
    } else {
        return $offers_hash[$hash_key];
    }
    $fields = $from_tbls = $query_joins = $where = $groupbys = $having = $orderbys = array();
    $fields = array("{$tables['ps_offers']}.offer_id");
    $offers = array();
    $from_tbls[] = 'ps_offers';
    if (isset($addons['multi_domains'])) {
        $conditions = cw_md_get_available_domains();
        if ($conditions !== false) {
            $query_joins['attributes_values'] = array('on' => "{$tables['ps_offers']}.offer_id = {$tables['attributes_values']}.item_id and {$tables['attributes_values']}.item_type = '" . PS_ATTR_ITEM_TYPE . "' and {$tables['attributes_values']}.attribute_id='" . $domain_attributes[PS_ATTR_ITEM_TYPE] . "' and {$tables['attributes_values']}.value in " . $conditions, 'is_inner' => 1);
        }
    }
    $query_joins['ps_bonuses'] = array('on' => "{$tables['ps_offers']}.offer_id = {$tables['ps_bonuses']}.offer_id", 'is_inner' => 1);
    $query_joins['ps_conditions'] = array('on' => "{$tables['ps_offers']}.offer_id = {$tables['ps_conditions']}.offer_id", 'is_inner' => 1);
    $where[] = "{$tables['ps_offers']}.enddate >= '" . cw_core_get_time() . "'";
    $where[] = "{$tables['ps_offers']}.active = '1'";
    $having[] = "COUNT({$tables['ps_bonuses']}.bonus_id) > 0";
    $having[] = "COUNT({$tables['ps_conditions']}.cond_id) > 0";
    $groupbys[] = "{$tables['ps_offers']}.offer_id";
    $orderbys[] = 'priority DESC';
    $orderbys[] = 'position';
    $_query_joins = $query_joins;
    $_where = $where;
    $_having = $having;
    $_groupbys = $groupbys;
    $_fields = $fields;
    // let's take offers suitable by date and domain
    $search_query = cw_db_generate_query($fields, $from_tbls, $query_joins, $where, $groupbys, $having, $orderbys);
    $offers = cw_query_hash($search_query, 'offer_id', false);
    if (empty($offers) || !is_array($offers)) {
        return array();
    }
    // let's take offers with the subtotal condition defined
    $offers_condition = "{$tables['ps_cond_details']}.offer_id IN ('" . implode("', '", array_keys($offers)) . "')";
    $fields = $from_tbls = $query_joins = $where = $groupbys = $having = $orderbys = array();
    $fields = array('offer_id');
    $from_tbls[] = 'ps_conditions';
    //TODO: update the code below
    //echo '<pre>', print_r($tmp_cart), '</pre>';
    $discounted_subtotal = 0;
    //if (!isset($cart['info']['discounted_subtotal'])) {
    //$cart['discounted_subtotal'] = 10;
    $tmp_cart = array();
    $products_warehouses = cw_cart_get_products_warehouses($products);
    if (!empty($products_warehouses) && is_array($products_warehouses)) {
        foreach ($products_warehouses as $warehouse_id) {
            $tmp_products = cw_get_products_by_warehouse($products, $warehouse_id);
            $result = cw_func_call('cw_cart_calc_single', array('cart' => $cart, 'products' => $tmp_products, 'userinfo' => $user_info, 'warehouse_id' => $warehouse_id));
            //echo '<pre>result: ', print_r($result), '</pre>';
            $tmp_cart = cw_func_call('cw_cart_summarize', array('res' => $result, 'warehouse_id' => $warehouse_id), $tmp_cart);
        }
        unset($tmp_products);
    } else {
        $warehouse_id = 0;
        $result = cw_func_call('cw_cart_calc_single', array('cart' => $cart, 'products' => $products, 'userinfo' => $user_info, 'warehouse_id' => $warehouse_id));
        $tmp_cart = cw_func_call('cw_cart_summarize', array('res' => $result, 'warehouse_id' => $warehouse_id), $tmp_cart);
    }
    if (!empty($tmp_cart) && is_array($tmp_cart)) {
        if (isset($tmp_cart['info']['discounted_subtotal'])) {
            $discounted_subtotal = $tmp_cart['info']['discounted_subtotal'];
            if ($tmp_cart['info']['discounted_subtotal'] > $tmp_cart['info']['subtotal']) {
                $discounted_subtotal = $tmp_cart['info']['subtotal'];
            }
        }
    }
    unset($tmp_cart);
    //}
    //echo '<pre>', "discounted_subtotal: $discounted_subtotal", '</pre>';
    //echo '<pre>tmp_cart: ', print_r($tmp_cart), '</pre>';
    //die;
    $where[] = "type = '" . PS_TOTAL . "'";
    $where[] = "total > {$discounted_subtotal}";
    $where[] = "offer_id IN ('" . implode("', '", array_keys($offers)) . "')";
    $search_query = cw_db_generate_query($fields, $from_tbls, $query_joins, $where, $groupbys, $having, $orderbys);
    $not_allowed_offers = cw_query_hash($search_query, 'offer_id', false);
    //echo '<pre>1 ', print_r($offers), '</pre>';
    //echo '<pre>2 ', print_r($not_allowed_offers), '</pre>';
    if (!empty($not_allowed_offers) && is_array($not_allowed_offers)) {
        $offers = array_diff_key($offers, $not_allowed_offers);
    }
    //echo '<pre>3 ', print_r($offers), '</pre>';
    //die;
    if (empty($offers) || !is_array($offers)) {
        return array();
    }
    // let's take offers with the destination zone defined
    $fields = $from_tbls = $query_joins = $where = $groupbys = $having = $orderbys = array();
    $fields = array('offer_id');
    $from_tbls[] = 'ps_cond_details';
    if (!empty($customer_zone)) {
        $where[] = "object_type = '" . PS_OBJ_TYPE_ZONES . "'";
        $where[] = "object_id != '" . $customer_zone . "'";
        $where[] = "offer_id IN ('" . implode("', '", array_keys($offers)) . "')";
        $search_query = cw_db_generate_query($fields, $from_tbls, $query_joins, $where, $groupbys, $having, $orderbys);
        $not_allowed_offers = cw_query_hash($search_query, 'offer_id', false);
        //die(var_dump($offers, $customer_zone, $not_allowed_offers));
        if (!empty($not_allowed_offers) && is_array($not_allowed_offers)) {
            $offers = array_diff_key($offers, $not_allowed_offers);
        }
    } else {
        $where[] = "object_type = '" . PS_OBJ_TYPE_ZONES . "'";
        $where[] = "offer_id IN ('" . implode("', '", array_keys($offers)) . "')";
        $search_query = cw_db_generate_query($fields, $from_tbls, $query_joins, $where, $groupbys, $having, $orderbys);
        $not_allowed_offers = cw_query_hash($search_query, 'offer_id', false);
        if (!empty($not_allowed_offers) && is_array($not_allowed_offers)) {
            $offers = array_diff_key($offers, $not_allowed_offers);
        }
    }
    if (empty($offers) || !is_array($offers)) {
        return array();
    }
    //let's take offers with suitable products
    //list($_products, $_categories, $_manufacturers) = cw_ps_normalize_products($products);
    foreach ($offers as $offer_id => $trash) {
        $checking_result = cw_ps_check_offer($offer_id, $_products);
        if ($checking_result == false) {
            unset($offers[$offer_id]);
        }
    }
    //let's delete offers which cannot be applied after the application of the first ones by priority
    //die(var_dump($offers, $customer_zone));
    $first_offer = null;
    foreach ($offers as $offer_id => $trash) {
        if (empty($first_offer)) {
            $first_offer = $offer_id;
            cw_ps_update_conditions($offer_id, $_products, $_categories, $_manufacturers);
            continue;
        }
        $checking_result = false;
        if (!empty($_products)) {
            $checking_result = cw_ps_check_offer($offer_id, $_products);
        }
        if ($checking_result == false) {
            unset($offers[$offer_id]);
        } else {
            cw_ps_update_conditions($offer_id, $_products, $_categories, $_manufacturers);
        }
    }
    //var_dump($offers, $_categories, $_manufacturers, $_products);
    //die('end');
    $offers_hash[$hash_key] = $offers;
    unset($offers);
    return $offers_hash[$hash_key];
}
            }
        }
        if ($message) {
            $message['products1'] = cw_query("\n\t\t\t\tSELECT product_id as id, product as name FROM {$tables['newsletter_products']}\n\t\t\t\tWHERE list_id = '{$list_id}' AND product_num = 1\n\t\t\t");
            $message['products2'] = cw_query("\n\t\t\t\tSELECT product_id as id, product as name FROM {$tables['newsletter_products']}\n\t\t\t\tWHERE list_id = '{$list_id}' AND product_num = 2\n\t\t\t");
            $smarty->assign('message', $message);
            $smarty->assign('messageid', $message['news_id']);
        }
        $smarty->assign('main', 'management');
    } else {
        $smarty->assign('main', 'details');
    }
} else {
    if (!isset($vertical_response_data['news']) || empty($vertical_response_data['news'])) {
        if (empty($vertical_response_data['time'])) {
            $vertical_response_data['time'] = cw_core_get_time();
            // lifetime
        }
        $result = cw_vertical_response_get_newslists();
        $vertical_response_data['news'] = true;
        if ($result) {
            $exist_list_id = array();
            foreach ($result as $item) {
                $exist_list_id[] = $item['id'];
                // if list exist
                if (cw_query_first_cell("SELECT list_id FROM {$tables['newslists']} WHERE list_id = '" . $item['id'] . "'")) {
                    // update it
                    cw_array2update('newslists', array('name' => $item['name'], 'descr' => $item['descr']), "list_id = '" . $item['id'] . "'");
                } else {
                    // add new list
                    $data = array();
 $target = cw_salesman_get_target($customer_id);
 $smarty->assign('current_level', $current_level);
 $smarty->assign('salesman_target', $target);
 $smarty->assign('salesman_reach', $target['target'] - $current_level);
 $smarty->assign('salesman_reached', cw_salesman_is_reached($customer_id));
 $premiums_selected = cw_salesman_is_selected($customer_id);
 $smarty->assign('salesman_selected', $premiums_selected);
 $smarty->assign('salesman_premiums', cw_salesman_get_premiums($customer_id, $current_language, " and active=1" . ($premiums_selected ? " and selected=1" : "")));
 if ($action == 'premiums' && !$premiums_selected && is_array($choosed_premium)) {
     foreach ($choosed_premium as $id => $val) {
         db_query("update {$tables['salesman_premiums']} set selected=1 where id='{$id}' and customer_id='{$customer_id}'");
     }
 }
 # kornev, select orders
 $previous_customer_id_date =& cw_session_register('previous_customer_id_date');
 $curtime = cw_core_get_time();
 $start_dates[] = $previous_customer_id_date;
 # Since last customer_id
 $start_dates[] = mktime(0, 0, 0, date("m", $curtime), date("d", $curtime), date("Y", $curtime));
 $start_week = $curtime - date("w", $curtime) * 24 * 3600;
 # Week starts since Sunday
 $start_dates[] = mktime(0, 0, 0, date("m", $start_week), date("d", $start_week), date("Y", $start_week));
 $start_dates[] = mktime(0, 0, 0, date("m", $curtime), 1, date("Y", $curtime));
 foreach ($start_dates as $start_date) {
     $date_condition = "and d.doc_info_id=di.doc_info_id and d.date>='{$start_date}' and d.date<='{$curtime}' and di.salesman_customer_id='{$customer_id}'";
     $orders['P'][] = cw_query_first_cell("select count(*) from {$tables['docs']} as d, {$tables['docs_info']} as di where d.type='O' and d.status='P' {$date_condition}");
     $orders['F'][] = cw_query_first_cell("select count(*) from {$tables['docs']} as d, {$tables['docs_info']} as di where d.type='O' and (d.status='F' OR d.status='D') {$date_condition}");
     $orders['I'][] = cw_query_first_cell("select count(*) from {$tables['docs']} as d, {$tables['docs_info']} as di where d.type='O' and d.status='I' {$date_condition}");
     $orders['Q'][] = cw_query_first_cell("select count(*) from {$tables['docs']} as d, {$tables['docs_info']} as di where d.type='O' and d.status='Q' {$date_condition}");
     $gross_total[] = price_format(cw_query_first_cell("select sum(total) from {$tables['docs']} as d, {$tables['docs_info']} as di where 1 {$date_condition}"));
     $total_paid[] = price_format(cw_query_first_cell("select sum(total) from {$tables['docs']} as d, {$tables['docs_info']} as di where (status='P' OR status='C') {$date_condition}"));
<?php

$ctime = cw_core_get_time();
$start_date = mktime(0, 0, 0, date("m", $ctime), 1, date("Y", $ctime));
$end_date = $ctime;
if ($action == "go") {
    $salesman_condition = $salesman ? " AND {$tables['salesman_payment']}.customer_id='{$salesman}'" : "";
    if ($StartMonth) {
        $start_date = mktime(0, 0, 0, $StartMonth, $StartDay, $StartYear);
        $end_date = mktime(23, 59, 59, $EndMonth, $EndDay, $EndYear);
    }
    $query = "SELECT {$tables['salesman_payment']}.*, {$tables['customers']}.* FROM {$tables['salesman_payment']}, {$tables['customers']} WHERE {$tables['salesman_payment']}.paid='Y' AND {$tables['salesman_payment']}.customer_id={$tables['customers']}.customer_id AND {$tables['salesman_payment']}.add_date>='{$start_date}' AND {$tables['salesman_payment']}.add_date<='{$end_date}' {$salesman_condition} ORDER BY {$tables['salesman_payment']}.add_date desc";
    $total_history = count(cw_query($query));
    $navigation = cw_core_get_navigation($target, $total_history, $page);
    $navigation['script'] = "index.php?target=payment_history&StartMonth={$StartMonth}&StartDay={$StartDay}&StartYear={$StartYear}&EndMonth={$EndMonth}&EndDay={$EndDay}&EndYear={$EndYear}&salesman={$salesman}&mode=go";
    $smarty->assign('navigation', $navigation);
    $smarty->assign("history", cw_query("{$query} LIMIT {$navigation['first_page']}, {$navigation['objects_per_page']}"));
}
$salesmans = cw_query("SELECT * FROM {$tables['customers']} WHERE usertype='B' ORDER BY lastname");
$smarty->assign("salesmans", $salesmans);
$smarty->assign('history', $history);
$smarty->assign('salesman', $salesman);
$smarty->assign('start_date', $start_date);
$smarty->assign('end_date', $end_date);
$smarty->assign('main', 'payment_history');
function cw_doc_change_status_inner(&$doc_data, $status, $advinfo)
{
    global $tables, $config, $smarty, $current_area;
    global $current_language;
    $doc_id = $doc_data['doc_id'];
    if ($advinfo) {
        $info = addslashes(cw_crypt_text($doc_data['info']['details'] . "\n--- Advanced info ---\n" . $advinfo));
        db_query("update {$tables['docs_info']} set details='" . $info . "' where doc_info_id='" . $doc_data['info']['doc_info_id'] . "'");
    }
    db_query("update {$tables['docs']} set status='{$status}', status_change='" . cw_core_get_time() . "' where doc_id='{$doc_id}'");
    if ($status != $doc_data['status']) {
        cw_event('on_doc_change_status', array($doc_data, $status));
        cw_load('web', 'email', 'accounting');
        cw_accounting_generate_movement($doc_data, 0, $doc_data['status'], $status);
        if ($current_area == 'C') {
            $session_failed_transaction++;
        }
        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['products']);
        $smarty->assign('new_status', $status);
        $smarty->assign('old_status', $doc_data['status']);
        $doc_data['status'] = $status;
        $smarty->assign('order', $doc_data);
        $smarty->assign('doc', $doc_data);
        if (cw_doc_order_status_email_enabled($status, 'admin')) {
            $to_customer = $config['default_admin_language'];
            $current_language = $to_customer;
            $smarty->assign('usertype_layout', 'A');
            $smarty->assign('is_email_invoice', 'Y');
            cw_call('cw_send_mail', array($config['Company']['orders_department'], $config['Company']['orders_department'], 'mail/docs/status_changed_admin_subj.tpl', 'mail/docs/status_changed_admin.tpl', $config['default_admin_language'], true));
            $extra_admin_email = cw_doc_order_status_extra_admin_email($status);
            if (!empty($extra_admin_email)) {
                cw_call('cw_send_mail', array($config['Company']['orders_department'], $extra_admin_email, 'mail/docs/status_changed_admin_subj.tpl', 'mail/docs/status_changed_admin.tpl', $config['default_admin_language'], true));
            }
            $smarty->assign('is_email_invoice', 'N');
            $smarty->assign('usertype_layout', '');
        }
        if (cw_doc_order_status_email_enabled($status, 'customer')) {
            $to_customer = cw_query_first_cell("SELECT language FROM {$tables['customers']} WHERE customer_id='{$doc_data['userinfo']}[customer_id]'");
            if (empty($to_customer)) {
                $to_customer = $config['default_customer_language'];
            }
            $doc_data['products'] = cw_doc_translate_products($doc_data['products'], $to_customer);
            $smarty->assign('order', $doc_data);
            $current_language = $to_customer;
            $smarty->assign('is_email_invoice', 'Y');
            cw_call('cw_send_mail', array($config['Company']['orders_department'], $doc_data['userinfo']['email'], 'mail/docs/status_changed_customer_subj.tpl', 'mail/docs/status_changed_customer.tpl', null, false, true));
            $smarty->assign('is_email_invoice', 'N');
        }
        $func = 'cw_doc_change_status_' . $status;
        if (function_exists($func)) {
            cw_func_call($func, $doc_data);
        }
        // invoice approved
        if ($status == 'P' && $doc_data['type'] == 'I') {
            $smarty->assign('is_email_invoice', 'Y');
            cw_call('cw_send_mail', array($config['Company']['orders_department'], $doc_data['userinfo']['email'], 'mail/docs/customer_subj.tpl', 'mail/docs/customer_invoice_approved.tpl', null, false, true));
            $smarty->assign('is_email_invoice', 'N');
        }
        // invoice expired
        if ($status == 'F' && $doc_data['type'] == 'I') {
            $smarty->assign('is_email_invoice', 'Y');
            cw_call('cw_send_mail', array($config['Company']['orders_department'], $doc_data['userinfo']['email'], 'mail/docs/customer_subj.tpl', 'mail/docs/customer.tpl', null, false, true));
            $smarty->assign('is_email_invoice', 'N');
        }
    }
}
function cw_session_save()
{
    global $APP_SESS_ID;
    global $APP_SESSION_VARS, $APP_SESSION_UNPACKED_VARS;
    global $tables, $bench_max_session;
    global $customer_id, $config;
    $varnames = func_get_args();
    if (!empty($varnames)) {
        foreach ($varnames as $varname) {
            if (isset($GLOBALS[$varname])) {
                $APP_SESSION_VARS[$varname] = $GLOBALS[$varname];
            }
        }
    } elseif (is_array($APP_SESSION_UNPACKED_VARS)) {
        foreach ($APP_SESSION_UNPACKED_VARS as $varname => $value) {
            if (isset($GLOBALS[$varname])) {
                $APP_SESSION_VARS[$varname] = $GLOBALS[$varname];
            }
        }
    }
    $curtime = cw_core_get_time();
    $expiry_time = $curtime + USE_SESSION_LENGTH;
    if (!defined('PREVENT_SESSION_SAVE') && (!defined('IS_ROBOT') || constant('IS_ROBOT') == 'N' || constant('IS_ROBOT') == '')) {
        db_query("update {$tables['sessions_data']} set data='" . addslashes(serialize($APP_SESSION_VARS)) . "', customer_id='" . intval($customer_id) . "', usertype='" . ($customer_id ? AREA_TYPE : 'C') . "', ip='" . $_SERVER['REMOTE_ADDR'] . "', expiry='{$expiry_time}' where sess_id='{$APP_SESS_ID}'");
    }
}
        db_query("UPDATE {$tables['giftreg_maillist']} SET status='S', status_date='{$time}' WHERE reg_id='{$k}' AND event_id='{$event_id}'");
    }
    cw_header_location("index.php?target={$target}&mode=events&event_id={$event_id}&js_tab=recipients");
}
if ($action == 'maillist' && is_array($recipient_details)) {
    foreach ($recipient_details as $k => $v) {
        if (!$k && (!$v['recipient_name'] || !$v['recipient_email'])) {
            continue;
        }
        if (!$k) {
            $recipients_count = cw_query_first_cell("select count(*) from {$tables['giftreg_maillist']} where event_id='{$event_id}'");
            $is_exists = cw_query_first_cell("select count(*) from {$tables['giftreg_maillist']} where event_id='{$event_id}' and recipient_email='{$v['recipient_email']}'");
            if ($is_exists || $recipients_count > $config['estore_gift']['recipients_limit']) {
                continue;
            }
            $k = cw_array2insert('giftreg_maillist', array('event_id' => $event_id, 'date' => cw_core_get_time(), 'confirmation_code' => cw_gift_get_confirmation_code(), 'recipient_email' => $v['recipient_email']));
        }
        cw_array2update('giftreg_maillist', $v, "reg_id='{$k}'", array('recipient_name', 'recipient_email'));
    }
    cw_header_location("index.php?target={$target}&mode=events&event_id={$event_id}&js_tab=recipients");
}
if ($action == 'delete') {
    $event_id = cw_query_first_cell("select event_id from {$tables['giftreg_events']} where event_id='{$event_id}' and customer_id='{$customer_id}'");
    db_query("delete from {$tables['giftreg_events']} where event_id='{$event_id}' AND customer_id='{$customer_id}'");
    db_query("delete from {$tables['giftreg_maillist']} where event_id='{$event_id}'");
    db_query("delete from {$tables['giftreg_guestbooks']} where event_id='{$event_id}'");
    cw_header_location("index.php?target={$target}&mode=events");
}
$location[] = array(cw_get_langvar_by_name('lbl_giftreg_events_list', 'index.php?target=gifts&mode=events'));
if ($event_id) {
    $event_data = cw_query_first("select * from {$tables['giftreg_events']} where customer_id='{$customer_id}' AND event_id='{$event_id}'");
function cw_product_update_system_info($product_id, $data)
{
    global $tables, $customer_id;
    $time = cw_core_get_time();
    $update = array('modification_customer_id' => $customer_id, 'modification_date' => $time);
    if (!is_array($data) && is_numeric($data)) {
        // $data contains single customer_id
        $data = array('modification_customer_id' => intval($data), 'modification_date' => $time);
    }
    $update = array_merge($update, $data);
    if (!cw_query_first_cell("select count(*) from {$tables['products_system_info']} where product_id='{$product_id}'")) {
        cw_array2insert('products_system_info', array('product_id' => $product_id, 'creation_customer_id' => intval($update['modification_customer_id']), 'creation_date' => $time), true);
    }
    cw_array2update('products_system_info', $update, "product_id='{$product_id}'");
}
     $record['customer_id'] = $user;
 }
 if ($action == 'update_transation') {
     $record_data['customer_id'] = $user;
     $rules = array('accounting_category_id' => '', 'date_ref' => '', 'customer_id' => '');
     if (!$record_id || !$record['reference']) {
         $rules['total'] = '';
     }
     $fillerror = cw_error_check($record_data, $rules);
     if ($fillerror) {
         $record_saved_data = $record_data;
         $top_message = array('content' => $fillerror, 'type' => 'E');
         cw_header_location("index.php?target={$target}&mode={$mode}&user={$user}&record_id={$record_id}");
     }
     if (!$record_id) {
         $record_id = cw_array2insert('accounting_records', array('date' => cw_core_get_time()));
     }
     $to_update = array('customer_id' => $record_data['customer_id'], 'accounting_category_id' => $record_data['accounting_category_id'], 'descr' => $record_data['descr'], 'date_ref' => cw_core_strtotime($record_data['date_ref']), 'bank_code' => $record_data['bank_code'], 'payment_code' => $record_data['payment_code'], 'status' => $record_data['status']);
     if (!$record['reference']) {
         $to_update['total'] = $record_data['total'];
     }
     cw_array2update('accounting_records', $to_update, "accounting_record_id='{$record_id}'");
     cw_accounting_category_recalc_subcat_count($record_data['accounting_category_id']);
     if (count($_FILES)) {
         foreach ($_FILES['enfiles']['name'] as $index => $name) {
             $data = array();
             $data['file_path'] = cw_move_uploaded_file('enfiles', '', $index);
             $data['filename'] = basename($name);
             if ($data['file_path']) {
                 cw_file_area_save('accounting_records_files', $record_id, $data);
             }
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;
}
             continue;
         }
         list($val['file_size'], $val['image_x'], $val['image_y'], $val['image_type']) = cw_get_image_size($val['file_path']);
         if ($val['file_size'] == 0) {
             if ($data['is_copied']) {
                 unlink($val['file_path']);
             }
             unset($data[$k]);
             continue;
         }
         if (!isset($val['filename'])) {
             $val['filename'] = basename($val['file_path']);
         }
         $val['id'] = $id;
         $val['type'] = $type;
         $val['date'] = cw_core_get_time();
         if ($available_images[$type]['multiple'] == 2) {
             $file_upload_data[$type][] = $val;
         } elseif ($available_images[$type]['multiple'] == 1) {
             $file_upload_data[$type][$id] = $val;
         } else {
             $file_upload_data[$type] = $val;
         }
     }
 }
 cw_session_save();
 $smarty->assign('type', $type);
 $smarty->assign('imgid', $imgid);
 $smarty->assign('id', $id);
 $smarty->assign('multiple', $available_images[$type]['multiple']);
 $smarty->assign('file_upload_data', $file_upload_data[$type]);
<?php

$adv_campaign_id =& cw_session_register('adv_campaign_id');
if (empty($adv_campaign_id) && !empty($_COOKIE['adv_campaign_id']) && !empty($_COOKIE['adv_campaign_id_time'])) {
    if ($_COOKIE['adv_campaign_id_time'] >= cw_core_get_time()) {
        $adv_campaign_id = 'Y';
    } else {
        setcookie('adv_campaign_id', '', 0, '/', $app_config_file['web']['http_host'], 0);
        setcookie('adv_campaign_id_time', '', 0, '/', $app_config_file['web']['http_host'], 0);
    }
}
#
# For type 'G' (use GET parameter(s))
#
if ($REQUEST_METHOD == 'GET' && empty($adv_campaign_id)) {
    $gets = cw_query("SELECT campaign_id, data, type FROM {$tables['salesman_adv_campaigns']} WHERE type = 'G'");
    $_campaign_id = 0;
    if ($gets) {
        foreach ($gets as $v) {
            $tmp = cw_parse_str($v['data']);
            if (!empty($tmp)) {
                $cnt = 0;
                foreach ($tmp as $key => $value) {
                    if ($_GET[$key] == $value && isset($_GET[$key])) {
                        $cnt++;
                    }
                }
                if ($cnt == count($tmp)) {
                    $QUERY_STRING = implode("&", array_diff(explode("&", $QUERY_STRING), explode("&", $v['data'])));
                    $_campaign_id = $v['campaign_id'];
                    $_type = $v['type'];
<?php

cw_load('profile_fields');
$fill_error =& cw_session_register('fill_error');
$prefilled_transaction =& cw_session_register('prefilled_transaction');
if ($action == 'update_contacts') {
    if ($content) {
        $to_insert = array('customer_id' => $user, 'date' => $date ? cw_core_strtotime($date) : cw_core_get_time(), 'content' => $content);
        cw_array2insert('customers_contacts', $to_insert);
    }
    cw_header_location("index.php?target={$target}&mode={$mode}&user={$user}");
}
if ($action == 'delete_contacts' && is_array($del)) {
    foreach ($del as $contact_id => $val) {
        db_query("delete from {$tables['customers_contacts']} where contact_id='{$contact_id}' and customer_id='{$user}'");
    }
    cw_header_location("index.php?target={$target}&mode={$mode}&user={$user}");
}
$smarty->assign('contact_dates', cw_query("select * from {$tables['customers_contacts']} where customer_id='{$user}' order by date desc limit 10"));
$smarty->assign('main', 'contact_dates');
$smarty->assign('user', $user);
$smarty->assign('current_section', '');
$smarty->assign('home_style', 'iframe');
function cw_review_send_order_review_reminder_email($customer_products)
{
    global $tables, $config, $smarty, $current_location;
    cw_load('email', 'user');
    if (!empty($customer_products) && is_array($customer_products)) {
        foreach ($customer_products as $customer_id => $product_ids) {
            $user_info = cw_user_get_info($customer_id);
            if (empty($user_info['email']) || empty($product_ids)) {
                continue;
            }
            $key = md5('rps' . $customer_id);
            $link = $current_location . "/index.php?target=product";
            $link .= "&action=review_product&review_key={$key}&review_object={$customer_id}";
            $alinks = array();
            foreach ($product_ids as $product_id) {
                $product_name = cw_query_first_cell("SELECT product FROM {$tables['products']} WHERE product_id = {$product_id}");
                if (empty($product_name)) {
                    continue;
                }
                $alinks[] = array('link' => $link . "&product_id={$product_id}", 'product_name' => $product_name);
                cw_array2insert('products_reviews_reminder', array('product_id' => $product_id, 'customer_id' => $customer_id, 'ctime' => cw_core_get_time()), TRUE);
            }
            if (!empty($alinks)) {
                $smarty->assign('reminders', $alinks);
                cw_call('cw_send_mail', array($config['Company']['site_administrator'], $user_info['email'], 'addons/estore_products_review/mail/reminder_subj.tpl', 'addons/estore_products_review/mail/reminder_body.tpl', $config['default_admin_language']));
            }
        }
    }
    return TRUE;
}
function cw_user_create_profile($fields)
{
    global $tables, $customer_id, $current_language;
    cw_load('crypt');
    // Defaults
    // password
    if (empty($fields['password'])) {
        $fields['password'] = cw_user_generate_password();
    }
    // membership
    if (empty($fields['membership_id'])) {
        $fields['membership_id'] = cw_query_first_cell("select membership_id from {$tables['memberships']} where default_membership='Y' and area='{$usertype}' ");
    }
    // usertype
    if (empty($fields['usertype'])) {
        $fields['usertype'] = 'C';
    }
    // status
    if (empty($fields['status'])) {
        $fields['status'] = 'Y';
    }
    // language
    if (empty($fields['language'])) {
        $fields['language'] = $current_language;
    }
    // Create profile
    $profile_create = array('password' => cw_call('cw_user_get_hashed_password', array($fields['password'])), 'email' => $fields['email'], 'membership_id' => $fields['membership_id'], 'status' => $fields['status'], 'usertype' => $fields['usertype']);
    $user = cw_array2insert('customers', $profile_create);
    $customers_customer_info = array('customer_id' => $user, 'web_user' => 1);
    cw_array2insert('customers_customer_info', $customers_customer_info);
    if (empty($customer_id)) {
        $customer_id = $user;
    }
    $customer_system_info = array('customer_id' => $customer_id, 'creation_customer_id' => $user, 'creation_date' => cw_core_get_time());
    cw_array2insert('customers_system_info', $customer_system_info, true);
    cw_array2insert('customers_settings', array('customer_id' => $user), true);
    return $user;
}
function cw_core_get_time_frame($str1, $str2 = '')
{
    $time = cw_core_get_time();
    return array(strtotime($str1, $time), $str2 ? strtotime($str2, $time) : $time);
}
 if ($usertype == 'R') {
     $usertype = 'C';
     $product_list_template =& cw_session_register("product_list_template");
     $product_list_template = 2;
 }
 $identifiers[$current_area == 'R' ? 'C' : $current_area] = array('customer_id' => $user_data['customer_id']);
 $customer_id = $user_data['customer_id'];
 if (in_array($current_area, array("C", "R"))) {
     cw_session_register("login_redirect");
     $login_redirect = 1;
 }
 // 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='" . cw_core_get_time() . "' 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);
function cw_error_handler($errno, $errstr, $errfile, $errline)
{
    static $hash_errors = array();
    if (!(ini_get("error_reporting") & $errno)) {
        return;
    }
    if (ini_get("display_errors") == 0 && ini_get("log_errors") == 0) {
        return;
    }
    if (ini_get("ignore_repeated_errors") == 1 && isset($hash_errors[$errno]) && isset($hash_errors[$errno][$errfile . ":" . $errline])) {
        return;
    }
    $date = date('d-M-Y H:i:s', cw_core_get_time());
    $errortypes = array(E_ERROR => "Error", E_WARNING => "Warning", E_PARSE => "Parsing Error", E_NOTICE => "Notice", E_CORE_ERROR => "Error", E_CORE_WARNING => "Warning", E_COMPILE_ERROR => "Error", E_COMPILE_WARNING => "Warning", E_USER_ERROR => "Error", E_USER_WARNING => "Warning", E_USER_NOTICE => "Notice", E_STRICT => "Runtime Notice");
    $errortype = isset($errortypes[$errno]) ? $errortypes[$errno] : "Unknown Error";
    if (ini_get("display_errors") != 0) {
        # Display error
        global $REQUEST_METHOD;
        if (empty($REQUEST_METHOD)) {
            echo "{$errortype}: {$errstr} in {$errfile} on line {$errline}\n";
        } else {
            echo "<b>{$errortype}</b>: {$errstr} in <b>{$errfile}</b> on line <b>{$errline}</b><br />\n";
        }
    }
    if (ini_get("log_errors") == 1 && ini_get("error_log") != '') {
        # Write error to file
        $bt = '';
        $bt = "\nREQUEST_URI: " . $_SERVER['REQUEST_URI'];
        $bt .= "\nBacktrace:\n\t" . implode("\n\t", cw_get_backtrace(1));
        error_log("[{$date}] {$errortype}: {$errstr} in {$errfile} on line {$errline} {$bt}\n", 3, ini_get("error_log"));
    }
    if (ini_get("ignore_repeated_errors") == 1) {
        if (!isset($hash_errors[$errno])) {
            $hash_errors[$errno] = array();
        }
        $hash_errors[$errno][$errfile . ":" . $errline] = true;
    }
}