function cw_config_process_options($options)
{
    global $tables;
    if ($options) {
        foreach ($options as $k => $v) {
            switch ($v['name']) {
                case 'cmpi_currency':
                    $currs = cw_query_hash("SELECT code, name FROM {$tables['currencies']}", "code", false, true);
                    if (empty($currs)) {
                        unset($options[$k]);
                        continue;
                    }
                    $v['variants'] = "";
                    foreach ($currs as $ek => $ev) {
                        $v['variants'] .= $ek . ":({$ek}) " . $ev . "\n";
                    }
                    break;
            }
            if (in_array($v['type'], array("selector", "multiselector"))) {
                if (empty($v['variants'])) {
                    unset($options[$k]);
                    continue;
                }
                $vars = cw_parse_str(trim($v['variants']), "\n", ":");
                $vars = cw_array_map("trim", $vars);
                if ($v['type'] == "multiselector") {
                    $v['value'] = explode(";", $v['value']);
                    foreach ($v['value'] as $vk => $vv) {
                        if (!isset($vars[$vv])) {
                            unset($v['value'][$vk]);
                        }
                    }
                    $options[$k]['value'] = $v['value'] = array_values($v['value']);
                }
                $options[$k]['variants'] = array();
                foreach ($vars as $vk => $vv) {
                    $options[$k]['variants'][$vk] = array("name" => $vv);
                    if (strpos($vv, " ") === false) {
                        $name = cw_get_langvar_by_name($vv, NULL, false, true);
                        if (!empty($name)) {
                            $options[$k]['variants'][$vk] = array("name" => $name);
                        }
                    }
                    if ($v['type'] == "selector") {
                        $options[$k]['variants'][$vk]['selected'] = $v['value'] == $vk;
                    } else {
                        $options[$k]['variants'][$vk]['selected'] = in_array($vk, $v['value']);
                    }
                }
            }
            if (in_array($v['type'], array('shipping', 'memberships', 'doc_status'))) {
                $options[$k]['value'] = unserialize($v['value']);
            }
        }
    }
    return $options;
}
<?php

cw_load('profile_fields', 'map', 'check_user_field');
$fill_error =& cw_session_register('fill_error');
$prefilled_contact_list =& cw_session_register('prefilled_contact_list');
$area = cw_profile_fields_get_area($user);
list($profile_sections, $profile_fields) = cw_profile_fields_get_sections('U', true, $area);
$smarty->assign('profile_fields', $profile_fields);
if ($action == 'update_contact_list') {
    $fill_error = array();
    cw_array_map('trim', $contact_list);
    foreach ($profile_fields['contact_list'] as $k => $v) {
        if ($v['type'] == 'D' && empty($contact_list[$k]) && $v['is_avail'] && $v['is_required']) {
            $fill_error[$k] = true;
        } elseif ($v['type'] != 'D' && empty($contact_list['custom_fields'][$k]) && $v['is_avail'] && $v['is_required']) {
            $fill_error[$k] = true;
        }
    }
    $prefilled_contact_list = array();
    if (count($fill_error)) {
        $top_message = array('type' => 'E', 'content' => cw_check_user_get_error($fill_error));
        $prefilled_contact_list = $contact_list;
        cw_header_location("index.php?target={$target}&mode={$mode}&user={$user}&contact_list_id={$contact_list_id}");
    } else {
        cw_user_update_contact_list($user, $contact_list_id, $contact_list);
        cw_header_location("index.php?target={$target}&mode={$mode}&user={$user}");
    }
}
if ($action == 'delete' && is_array($del)) {
    foreach ($del as $contact_list_id => $val) {
        cw_user_delete_contact_list($user, $contact_list_id);
예제 #3
0
        db_query("DELETE FROM {$tables['newsletter_countries']} WHERE list_id='{$k}'");
    }
    $top_message['content'] = cw_get_langvar_by_name('msg_adm_newslists_del');
    cw_header_location("index.php?target={$target}");
}
// Update newslists on list page
if ($action == 'update' && AREA_TYPE != 'B' && is_array($posted_data)) {
    foreach ($posted_data as $list_id => $v) {
        cw_array2update('newslists', array('subscribe' => $v['subscribe'], 'show_as_news' => $v['show_as_news'], 'avail' => $v['avail']), "list_id='{$list_id}' {$salesman_condition}");
    }
    $top_message['content'] = cw_get_langvar_by_name('msg_adm_newslists_upd');
    cw_header_location("index.php?target={$target}");
}
// Modify certain newslist by list_id
if ($action == 'modify') {
    $list = cw_array_map('trim', $list);
    $fill_error = array();
    foreach (array('name', 'descr') as $key) {
        if (empty($list[$key])) {
            $fill_error[$key] = true;
        }
    }
    if (!count($fill_error)) {
        $list_values = $list;
        $list_values['salesman_customer_id'] = '';
        if (AREA_TYPE == 'B') {
            $list['salesman_customer_id'] = $customer_id;
            if ($list['list_id']) {
                $def_val = cw_query_first("select * from {$tables['newslists']} where list_id='" . $list['list_id'] . "'");
                $list_values['avail'] = $def_val['avail'];
            } else {
예제 #4
0
 } elseif ($action == "messages") {
     #
     # Manage messages of newslist
     #
     if (is_array($message)) {
         $message['subject'] = @trim($message['subject']);
         $message = cw_array_map('stripslashes', $message);
         $smarty->assign('action', 'modify');
         $smarty->assign('message', $message);
         $error = array();
         $err = false;
         foreach (array("subject", "body") as $key) {
             $err = $err || ($error[$key] = empty($message[$key]));
         }
         if (!$err) {
             $message = cw_array_map('addslashes', $message);
             $mode = "";
             $message['show_as_news'] = $flag_show_as_news ? 'Y' : 'N';
             if (!empty($message['newsid'])) {
                 db_query("UPDATE {$tables['newsletter']} SET subject='{$message['subject']}', body='{$message['body']}', allow_html='{$message['allow_html']}'" . (AREA_TYPE == 'B' ? "" : ", show_as_news='{$message['show_as_news']}'") . ", email1='{$message['email1']}', email2='{$message['email2']}', email3='{$message['email3']}' WHERE newsid='{$message['newsid']}'");
                 $top_message['content'] = cw_get_langvar_by_name("msg_adm_news_message_upd");
             } else {
                 if (AREA_TYPE == 'B') {
                     $message['show_as_news'] = 'N';
                 }
                 db_query("INSERT INTO {$tables['newsletter']} (list_id, send_date, subject, body, allow_html, show_as_news, email1, email2, email3) VALUES ('{$targetlist}','" . time() . "','{$message['subject']}', '{$message['body']}', '{$message['allow_html']}', '{$message['show_as_news']}', '{$message['email1']}', '{$message['email2']}', '{$message['email3']}')");
                 $message['newsid'] = db_insert_id();
                 $top_message['content'] = cw_get_langvar_by_name("msg_adm_news_message_add");
             }
             db_query("delete from {$tables['newsletter_countries']} where newsid='" . $message['newsid'] . "'");
             if (is_array($countries)) {
예제 #5
0
function db_prepare_query($query, $params)
{
    static $prepared = array();
    if (!empty($prepared[$query])) {
        $info = $prepared[$query];
        $tokens = $info['tokens'];
    } else {
        $tokens = preg_split('/((?<!\\\\)\\?)/S', $query, -1, PREG_SPLIT_DELIM_CAPTURE);
        $count = 0;
        foreach ($tokens as $k => $v) {
            if ($v === '?') {
                $count++;
            }
        }
        $info = array('tokens' => $tokens, 'param_count' => $count);
        $prepared[$query] = $info;
    }
    if (count($params) != $info['param_count']) {
        return array('info' => 'mismatch', 'expected' => $info['param_count'], 'actual' => count($params));
    }
    $pos = 0;
    foreach ($tokens as $k => $val) {
        if ($val !== '?') {
            continue;
        }
        if (!isset($params[$pos])) {
            return array('info' => 'missing', 'param' => $pos, 'expected' => $info['param_count'], 'actual' => count($params));
        }
        $val = $params[$pos];
        if (is_array($val)) {
            $val = cw_array_map('addslashes', $val);
            $val = implode("','", $val);
        } else {
            $val = addslashes($val);
        }
        $tokens[$k] = "'" . $val . "'";
        $pos++;
    }
    return implode('', $tokens);
}
                    cw_array2insert("products_detailed_images", $data);
                }
            }
        }
    }
    $top_message = array('content' => cw_get_langvar_by_name('msg_adm_product_images_add'), 'type' => 'I');
    cw_dpi_refresh($product_id, 'dpi');
}
$image = $_POST['image'];
if ($action == 'update_availability' && !empty($image)) {
    foreach ($image as $key => $value) {
        cw_array2update("products_detailed_images", $value, "image_id = '{$key}'");
        if ($ge_id && $fields['d_image'][$key]) {
            $data = cw_query_first("select * from {$tables['products_detailed_images']} where image_id = '{$key}'");
            unset($data['image_id']);
            $data = cw_array_map("addslashes", $data);
            while ($pid = cw_group_edit_each($ge_id, 1, $product_id)) {
                $id = cw_query_first_cell("SELECT image_id FROM {$tables['products_detailed_images']} WHERE id = '{$pid}' AND md5 = '{$data['md5']}'");
                if (!empty($id)) {
                    cw_image_delete($id, "D", true);
                }
                $data['id'] = $pid;
                cw_array2insert("products_detailed_images", $data);
            }
        }
    }
    $top_message = array('content' => cw_get_langvar_by_name('msg_adm_product_images_upd'), 'type' => 'I');
    cw_dpi_refresh($product_id, 'dpi');
}
if ($action == 'product_images_delete' && is_array($iids)) {
    foreach ($iids as $image_id => $tmp) {
function cw_gift_add2wishlist($product_id, $amount, $product_options = null)
{
    global $addons, $tables;
    global $user_account, $customer_id;
    if (is_array($amount)) {
        $amount = array_sum($amount);
    }
    $_options = array();
    if ($addons['product_options']) {
        if (is_array($product_options) && cw_check_product_options($product_id, $product_options)) {
            $product_options = cw_array_map('stripslashes', $product_options);
        } else {
            $product_options = cw_get_default_options($product_id, $amount, $user_account['membership_id']);
        }
        if (!is_array($product_options)) {
            unset($product_options);
        } else {
            $_options = addslashes(serialize($product_options));
        }
    }
    $added_product = cw_func_call('cw_product_get', array('id' => $product_id, 'user_account' => $user_account, 'info_type' => 3));
    $oamount = 0;
    $wlid = FALSE;
    $object = '';
    // Save to session for not loggin in customers
    if (empty($customer_id)) {
        $customer_wishlist =& cw_session_register('customer_wishlist');
        if ((empty($added_product['distribution']) || !$addons['egoods']) && !empty($customer_wishlist)) {
            $wlid = cw_gift_get_session_wishlist_id($product_id, $_options);
            if ($wlid !== FALSE) {
                $oamount = $customer_wishlist[$wlid]['amount'];
            }
        }
        if ($wlid !== FALSE) {
            $customer_wishlist[$wlid]['amount'] = $amount + $oamount;
        } else {
            $customer_wishlist[] = array('product_id' => $product_id, 'amount' => $amount, 'amount_purchased' => 0, 'options' => $_options, 'object' => $object, 'event_id' => 0);
            $index = count($customer_wishlist) - 1;
            $customer_wishlist[$index]['wishlist_id'] = $index;
        }
    } else {
        if (empty($added_product['distribution']) || !$addons['egoods']) {
            $oamount = cw_query_first_cell("SELECT amount FROM {$tables['wishlist']} WHERE customer_id='{$customer_id}' AND product_id='{$product_id}' AND options='{$_options}' AND event_id='0'");
        }
        $wlid = cw_query_first_cell("SELECT wishlist_id FROM {$tables['wishlist']} WHERE customer_id='{$customer_id}' AND product_id='{$product_id}' AND options='{$_options}' AND event_id='0'");
        if (!empty($wlid)) {
            cw_array2update('wishlist', array('amount' => $amount + $oamount), "wishlist_id='{$wlid}'");
        } else {
            cw_array2insert('wishlist', array('customer_id' => $customer_id, 'product_id' => $product_id, 'amount' => $amount, 'options' => $_options, 'object' => $object));
        }
    }
}
예제 #8
0
    $event_data = cw_query_first("select * from {$tables['giftreg_events']} where customer_id='{$customer_id}' AND event_id='{$event_id}'");
    $event_data['allow_to_send'] = cw_query_first_cell("select count(*) from {$tables['giftreg_maillist']} where event_id='{$event_id}' AND status=1");
    $smarty->assign('event_id', $event_id);
    $search_condition = "event_id='{$event_id}'";
    $total_items_in_search = cw_query_first_cell("select count(*) from {$tables['giftreg_guestbooks']} where {$search_condition}");
    $navigation = cw_core_get_navigation($target, $total_items_in_search, $page);
    $navigation['script'] = "index.php?target=gifts&mode=events&event_id={$event_id}&js_tab=guestbook";
    $smarty->assign('navigation', $navigation);
    $guestbook = cw_query("select * from {$tables['giftreg_guestbooks']} where {$search_condition} order by date DESC LIMIT {$navigation['first_page']}, {$navigation['objects_per_page']}");
    $smarty->assign('guestbook', $guestbook);
    $mailing_list = cw_query("select * from {$tables['giftreg_maillist']} where event_id='{$event_id}' order by recipient_name, recipient_email");
    $recipients_count = cw_query_first_cell("select count(*) from {$tables['giftreg_maillist']} where event_id='{$event_id}'");
    if ($recipients_count >= $config['estore_gift']['recipients_limit']) {
        $smarty->assign('recipients_limit_reached', 1);
    }
    $smarty->assign('mailing_list', $mailing_list);
    $wl_products = cw_gift_get_giftreg_wishlist($customer_id, $event_id);
    $smarty->assign('wl_products', $wl_products);
    $location[] = array($event_data['title'], '');
} else {
    $location[] = array(cw_get_langvar_by_name('lbl_giftreg_new_event', ''));
}
$event_details_sess =& cw_session_register('event_details_sess');
if ($event_details_sess) {
    $event_data = cw_array_map('stripslashes', $event_details_sess);
    cw_session_unregister('event_details_sess');
}
$smarty->assign('event_data', $event_data);
$smarty->assign('allow_edit', 1);
$smarty->assign('js_tab', $js_tab);
$smarty->assign('main', 'event');
function cw_check_surveys_events($event, $data = array(), $user_customer_id = false)
{
    global $survey_events, $customer_id, $config, $tables, $allowed_surveys;
    if (!in_array($event, $survey_events)) {
        return false;
    }
    if (empty($user_customer_id)) {
        $user_customer_id = $customer_id;
    }
    # Get survey's IDs
    $now = time();
    $ids = cw_query_hash("SELECT {$tables['surveys']}.survey_id, {$tables['survey_events']}.param, {$tables['survey_events']}.id FROM {$tables['surveys']} LEFT JOIN {$tables['survey_events']} ON {$tables['surveys']}.survey_id = {$tables['survey_events']}.survey_id WHERE {$tables['surveys']}.event_type = '{$event}' AND {$tables['surveys']}.survey_type != 'D' AND {$tables['surveys']}.valid_from_date < {$now} AND {$tables['surveys']}.expires_data > {$now}", "survey_id");
    if (empty($ids)) {
        return false;
    }
    $i = 0;
    foreach ($ids as $id => $params) {
        if (!empty($params) && !empty($params[0]['param'])) {
            # Check by event conditions
            $is_or = cw_query_first_cell("SELECT event_logic FROM {$tables['surveys']} WHERE survey_id = '{$id}'") == 'O';
            $params_count = count(cw_query_column("SELECT COUNT(*) FROM {$tables['survey_events']} WHERE survey_id = '{$id}' GROUP BY param"));
            $avail = array();
            foreach ($params as $p) {
                if (empty($p['id'])) {
                    continue;
                }
                switch ($p['param']) {
                    case "T":
                        if ($data['order']['total'] > $p['id']) {
                            $avail[$p['param']]++;
                        }
                        break;
                    case "P":
                        foreach ($data['products'] as $product) {
                            if ($product['product_id'] == $p['id']) {
                                $avail[$p['param']]++;
                                break;
                            }
                        }
                        break;
                    case "D":
                        foreach ($data['products'] as $product) {
                            if (cw_query_first_cell("SELECT COUNT(*) FROM {$tables['products_categories']} WHERE product_id = '{$product['product_id']}' AND category_id = '{$p['id']}'") > 0) {
                                $avail[$p['param']]++;
                                break;
                            }
                        }
                        break;
                }
            }
            if (count($avail) == 0 || count($avail) < $params_count && !$is_or) {
                continue;
            }
        }
        # Check survey availability
        list($valid, $tmp) = cw_check_survey($id);
        if (!$valid) {
            continue;
        }
        # Get user email
        $email = cw_query_first_cell("SELECT email FROM {$tables['customers']} WHERE BINARY customer_id='" . addslashes($user_customer_id) . "'");
        if (empty($email)) {
            continue;
        }
        # Check login and email
        $mail_logins = cw_query_column("SELECT customer_id FROM {$tables['customers']} WHERE email = '" . addslashes($email) . "'");
        $login_exists = false;
        if (!empty($mail_logins)) {
            $login_exists = cw_query_first_cell("SELECT COUNT(*) FROM {$tables['survey_results']} WHERE customer_id IN ('" . implode("','", cw_array_map("addslashes", $mail_logins)) . "') AND survey_id = '{$id}'") > 0;
        }
        if (cw_check_unique_email($email, $id) && !$login_exists) {
            $as_result = '';
            if (in_array($event, array("OPL", "OPC", "OPP", "OPB"))) {
                $as_result = $event . $data['order']['doc_id'];
            }
            # Add unique email
            $query_data = array("email" => addslashes($email), "customer_id" => addslashes($user_customer_id), "survey_id" => $id, "as_result" => $as_result, "date" => time());
            cw_array2insert("survey_maillist", $query_data);
            if ($config['survey']['survey_send_after_event'] == 'Y') {
                if ($config['survey']['survey_event_sent_delay'] > 0) {
                    cw_array2update("survey_maillist", array("delay_date" => time() + $config['survey']['survey_event_sent_delay'] * 3600), "email = '" . addslashes($email) . "' AND survey_id = '{$id}'");
                } else {
                    cw_send_survey_invitation($id, $email, $user_customer_id);
                }
            }
        }
        $allowed_surveys[$id] = $id;
        $i++;
    }
    return $i;
}
function cw_product_search($params, $return = null)
{
    extract($params);
    global $tables, $addons, $current_language, $config, $app_config_file;
    global $cart;
    global $smarty;
    global $target;
    $fields = $from_tbls = $query_joins = $where = $groupbys = $having = $orderbys = array();
    $from_tbls[] = 'products';
    # kornev, merge standart and additional variables
    if ($return) {
        foreach ($return as $saname => $sadata) {
            if (isset(${$saname}) && is_array(${$saname}) && empty(${$saname})) {
                ${$saname} = $sadata;
            }
        }
    }
    if ($data['where']) {
        $where[] = $data['where'];
    }
    $query_joins['products_stats'] = array('on' => "{$tables['products_stats']}.product_id = {$tables['products']}.product_id", 'only_select' => 1);
    # kornev, all of the inner joins are replaced by left join && not null
    # it works fastly because mylsq do not optimize the tables order is query and we are able to play with it.
    $memberships = array(0);
    if ($user_account['membership_id'] > 0) {
        $memberships[] = intval($user_account['membership_id']);
    }
    $query_joins['products_flat'] = array('on' => "{$tables['products_flat']}.product_id = {$tables['products']}.product_id", 'only_select' => 1);
    $fields[] = "{$tables['products_flat']}.*";
    $fields[] = "{$tables['products']}.*";
    if (!is_array($data['warehouse_customer_id'])) {
        $data['warehouse_customer_id'] = array($data['warehouse_customer_id'] => 1);
    }
    $query_joins['products_warehouses_amount'] = array('parent' => 'products', 'on' => "{$tables['products_warehouses_amount']}.product_id = {$tables['products']}.product_id and {$tables['products_warehouses_amount']}.warehouse_customer_id = 0 and {$tables['products_warehouses_amount']}.variant_id=0");
    $fields[] = "{$tables['products_warehouses_amount']}.avail";
    if ($current_area == 'A') {
        $fields[] = "{$tables['products_prices']}.variant_id";
        $fields[] = "{$tables['products_prices']}.price";
        # kornev, TOFIX
        if ($addons['product_options']) {
            $fields[] = "if({$tables['product_variants']}.product_id IS NULL, '', 'Y') as is_variants";
        }
        $query_joins['products_prices'] = array('on' => "{$tables['products_prices']}.product_id = {$tables['products']}.product_id", 'is_inner' => 1);
    } else {
        $fields[] = "min({$tables['products_prices']}.price) as price";
        $fields[] = "{$tables['products_prices']}.variant_id";
        $fields[] = "{$tables['products_prices']}.list_price";
        //        $fields[] = "min($tables[products_prices].list_price) as list_price";
        $query_joins['products_prices'] = array('parent' => 'products', 'on' => "{$tables['products_prices']}.product_id = {$tables['products']}.product_id and {$tables['products_prices']}.quantity=1 and {$tables['products_prices']}.membership_id in (" . join(',', $memberships) . ")", 'is_inner' => 1);
        if ($config['Appearance']['show_views_on_product_page'] == 'Y') {
            $fields[] = "{$tables['products_stats']}.views_stats";
        }
    }
    if ($config['Appearance']['categories_in_products'] == '1') {
        $query_joins['products_categories'] = array('on' => "{$tables['products_categories']}.product_id = {$tables['products']}.product_id", 'pos' => '0', 'is_inner' => 1);
    }
    # kornev, we should add filter by attributes names
    if ($data['attribute_names']) {
        $att_ids = cw_call('cw_attributes_get_attribute_by_field', array('field' => array_keys($data['attribute_names'])));
        if ($att_ids) {
            foreach ($att_ids as $k => $v) {
                $data['attributes'][$v] = $data['attribute_names'][$k];
            }
        }
    }
    # kornev, filter by attributes
    if ($data['attributes']) {
        if ($data['attributes'][PRICE_ATTRIBUTE_ID]) {
            $data['price_min'] = $data['attributes'][PRICE_ATTRIBUTE_ID]['min'];
            $data['price_max'] = $data['attributes'][PRICE_ATTRIBUTE_ID]['max'];
        }
        if ($data['attributes']['substring']) {
            $data['substring'] = $data['attributes']['substring'];
        }
        foreach ($data['attributes'] as $k => $v) {
            $a = cw_call('cw_attributes_filter', array(array('attribute_id' => $k), true));
            // If attr is number and presented in filter as predefined ranges,
            // then range attribute_value_id is passed as criteria, not real value or real range
            if (in_array($a['type'], array('decimal', 'integer'), true) && in_array($a['pf_display_type'], array('P', 'W', 'E', 'G')) && !isset($v['min'])) {
                $result = cw_product_filter_get_price_range_values($v[0]);
                if ($result) {
                    $v['min'] = $result[0];
                    $v['max'] = $result[1];
                }
                if ($k == PRICE_ATTRIBUTE_ID) {
                    $data['price_min'] = $v['min'];
                    $data['price_max'] = $v['max'];
                    $data['attributes']['price'] = $v;
                    continue;
                }
            }
            if (in_array($k, array('price', 'substring', PRICE_ATTRIBUTE_ID))) {
                continue;
            }
            if (!is_numeric($k)) {
                continue;
            }
            // Only real attributes must e converted into JOIN sql statement
            if (!is_array($v)) {
                $data['attributes'][$k] = $v = array($v);
            }
            $query_joins['atv_' . $k] = array('tblname' => 'attributes_values', 'on' => "{$tables['products']}.product_id=atv_{$k}.item_id and atv_{$k}.attribute_id = '{$k}' and atv_{$k}.code in ('{$current_language}', '') and " . (isset($v['min']) ? "atv_{$k}.value >= " . floatval($v['min']) . " and atv_{$k}.value <= " . floatval($v['max']) : "atv_{$k}.value in ('" . implode("', '", $v) . "')"), 'is_inner' => 1);
        }
    }
    if (!empty($data['by_pf_s_attr']) && !empty($data['substring'])) {
        $attr_pf_s_where = array();
        foreach ($data['by_pf_s_attr'] as $attr_id => $digit_flag) {
            $is_def_values = cw_query_first_cell("select count(*) from {$tables['attributes_default']} where attribute_id='{$attr_id}'");
            $attr_type = cw_query_first_cell("select type from {$tables['attributes']} where attribute_id='{$attr_id}'");
            if ($is_def_values && !in_array($attr_type, array('textarea', 'text'))) {
                if ($data['including'] == 'all' || $data['including'] == 'any') {
                    $search_words = array_filter(explode(" ", $data['substring']));
                    $search_words_arr = array();
                    foreach ($search_words as $word) {
                        $word = addslashes($word);
                        $search_words_arr[] = "atd_pf_s_{$attr_id}.value like '%{$word}%'";
                    }
                }
                if ($data['including'] == 'all') {
                    $value_eq_sql = " (" . implode(" and ", $search_words_arr) . ") ";
                } elseif ($data['including'] == 'any') {
                    $value_eq_sql = " (" . implode(" or ", $search_words_arr) . ") ";
                } else {
                    $value_eq_sql = "atd_pf_s_{$attr_id}.value like '%" . addslashes($data['substring']) . "%'";
                }
                $attr_value_ids = cw_query_column("select attribute_value_id from {$tables['attributes_default']} atd_pf_s_{$attr_id} where atd_pf_s_{$attr_id}.attribute_id='{$attr_id}' and {$value_eq_sql}");
                if (!empty($attr_value_ids)) {
                    $query_joins['atv_pf_s_' . $attr_id] = array('tblname' => 'attributes_values', 'on' => "{$tables['products']}.product_id=atv_pf_s_{$attr_id}.item_id and atv_pf_s_{$attr_id}.item_type='P' and atv_pf_s_{$attr_id}.attribute_id = '{$attr_id}' and atv_pf_s_{$attr_id}.code in ('{$current_language}', '') and cast(atv_pf_s_{$attr_id}.value as SIGNED) in ('" . implode("','", $attr_value_ids) . "')");
                    $attr_pf_s_where[] = "atv_pf_s_{$attr_id}.item_id is not null";
                }
            } else {
                if ($data['including'] == 'all' || $data['including'] == 'any') {
                    $search_words = array_filter(explode(" ", $data['substring']));
                    $search_words_arr = array();
                    foreach ($search_words as $word) {
                        $word = addslashes($word);
                        $search_words_arr[] = "atv_pf_s_{$attr_id}.value like '%{$word}%'";
                    }
                }
                if ($data['including'] == 'all') {
                    $value_eq_sql = " (" . implode(" and ", $search_words_arr) . ") ";
                } elseif ($data['including'] == 'any') {
                    $value_eq_sql = " (" . implode(" or ", $search_words_arr) . ") ";
                } else {
                    $value_eq_sql = "atv_pf_s_{$attr_id}.value like '%" . addslashes($data['substring']) . "%'";
                }
                $query_joins['atv_pf_s_' . $attr_id] = array('tblname' => 'attributes_values', 'on' => "{$tables['products']}.product_id=atv_pf_s_{$attr_id}.item_id and atv_pf_s_{$attr_id}.item_type='P' and atv_pf_s_{$attr_id}.attribute_id = '{$attr_id}' and atv_pf_s_{$attr_id}.code in ('{$current_language}', '') and {$value_eq_sql}");
                $attr_pf_s_where[] = "atv_pf_s_{$attr_id}.item_id is not null";
            }
            $return['substring_search_alternative'] = true;
        }
        if (!empty($attr_pf_s_where)) {
            $where[] = "(" . implode(" or ", $attr_pf_s_where) . ")";
        }
    }
    if (!empty($data['by_pf_attr_numeric'])) {
        $cast_types = array('decimal' => 'DECIMAL', 'integer' => 'SIGNED', 'yes_no' => 'SIGNED');
        foreach ($data['by_pf_attr_numeric'] as $attr_id => $attr_limits) {
            if (empty($attr_limits['min']) && empty($attr_limits['max'])) {
                continue;
            }
            $attr_type = cw_query_first_cell("select type from {$tables['attributes']} where attribute_id='{$attr_id}'");
            $_cast_type = $cast_types[$attr_type];
            if (empty($_cast_type)) {
                continue;
            }
            $ps_numeric_val_limits = array();
            $_min_limit = min($attr_limits['min'], $attr_limits['max']);
            $_max_limit = max($attr_limits['min'], $attr_limits['max']);
            $ps_num_table_alias = "ps_num_" . $attr_id;
            if (!empty($_min_limit)) {
                $ps_numeric_val_limits[] = "cast(" . $ps_num_table_alias . ".value as {$_cast_type}) >= '{$_min_limit}'";
            }
            if (!empty($_max_limit)) {
                $ps_numeric_val_limits[] = "cast(" . $ps_num_table_alias . ".value as {$_cast_type}) <= '{$_max_limit}'";
            }
            if (!empty($ps_numeric_val_limits)) {
                $query_joins[$ps_num_table_alias] = array('tblname' => 'attributes_values', 'on' => "{$tables['products']}.product_id={$ps_num_table_alias}.item_id and {$ps_num_table_alias}.item_type='P' and {$ps_num_table_alias}.attribute_id='{$attr_id}' and " . implode(" and ", $ps_numeric_val_limits), 'is_inner' => 1);
            }
        }
    }
    if (isset($data['by_pf_attr_multi'])) {
        foreach ($data['by_pf_attr_multi'] as $attr_id => $attr_value_ids) {
            if (empty($attr_value_ids)) {
                continue;
            }
            $ps_multi_table_alias = 'atv_pf_multi_' . $attr_id;
            $query_joins[$ps_multi_table_alias] = array('tblname' => 'attributes_values', 'on' => "{$tables['products']}.product_id={$ps_multi_table_alias}.item_id and {$ps_multi_table_alias}.item_type='P' and {$ps_multi_table_alias}.attribute_id = '{$attr_id}' and {$ps_multi_table_alias}.code in ('{$current_language}', '') and (cast({$ps_multi_table_alias}.value as SIGNED) in ('" . implode("','", $attr_value_ids) . "'))", 'is_inner' => 1);
        }
    }
    if (!$data['substring_exact']) {
        $data['substring'] = trim($data['substring']);
        $data['substring_prepared'] = '%' . $data['substring'] . '%';
    } else {
        $data['substring_prepared'] = $data['substring'];
    }
    $search_by_variants = false;
    if (($data['search_sections']['tab_basic_search'] || $data['flat_search'] || $data['attributes']['substring']) && $data['substring']) {
        $condition = array();
        $search_string_fields = array();
        if (empty($data['by_title']) && empty($data['by_shortdescr']) && empty($data['by_fulldescr']) && empty($data['by_sku']) && empty($return['substring_search_alternative'])) {
            $search_data['products'][$use_search_conditions]['by_title'] = $data['by_title'] = 1;
            // TOFIX: both $search_data and $use_search_conditions is undefinde
            $flag_save = true;
        }
        if ($data['by_title']) {
            $search_string_fields[] = "product";
        }
        if ($data['by_manufacturer']) {
            $search_string_fields[] = 'manufacturer_code';
        }
        if ($data['by_productcode']) {
            $search_string_fields[] = 'productcode';
        }
        if ($data['by_ean']) {
            $search_string_fields[] = 'eancode';
        }
        if ($data['by_shortdescr']) {
            $search_string_fields[] = "descr";
        }
        if ($data['by_fulldescr']) {
            $search_string_fields[] = "fulldescr";
        }
        if ($data['by_ean'] && !empty($addons['product_options'])) {
            $search_by_variants = true;
            $condition[] = "search_variants.eancode LIKE '" . $data['substring_prepared'] . "'";
        }
        if ($data['by_manufacturer'] && !empty($addons['product_options'])) {
            $search_by_variants = true;
            $condition[] = "search_variants.mpn LIKE '" . $data['substring_prepared'] . "'";
        }
        $search_words = array();
        if ($config['General']['allow_search_by_words'] == 'Y' && in_array($data['including'], array("all", "any"))) {
            $tmp = stripslashes(trim($data['substring']));
            if (preg_match_all('/"([^"]+)"/', $tmp, $match)) {
                $search_words = $match[1];
                $tmp = str_replace($match[0], '', $tmp);
            }
            $tmp = explode(' ', $tmp);
            $tmp = cw_array_map("trim", $tmp);
            $search_words = array_merge($search_words, $tmp);
            unset($tmp);
            # Check word length limit
            if ($search_word_length_limit > 0) {
                $search_words = preg_grep("/^..+\$/", $search_words);
            }
            $stopwords = cw_get_stopwords();
            if (!empty($stopwords) && is_array($stopwords)) {
                $tmp = preg_grep("/^(" . implode("|", $stopwords) . ")\$/i", $search_words);
                if (!empty($tmp) && is_array($tmp)) {
                    $search_words = array_diff($search_words, $tmp);
                    $search_words = array_values($search_words);
                }
                unset($tmp);
            }
            # Check word count limit
            if ($search_word_limit > 0 && count($search_words) > $search_word_limit) {
                $search_words = array_splice($search_words, $search_word_limit - 1);
            }
        }
        $search_words = array_filter($search_words);
        $search_words = cw_addslashes($search_words);
        foreach ($search_string_fields as $ssf) {
            if ($config['General']['allow_search_by_words'] == 'Y' && !empty($search_words) && in_array($data['including'], array("all", "any"))) {
                if ($data['including'] == 'all') {
                    $tmp = array();
                    foreach ($search_words as $sw) {
                        if ($current_area == 'C' || $current_area == 'B') {
                            if (in_array($ssf, array('productcode', 'manufacturer_code', 'eancode'))) {
                                $tmp[] = "{$tables['products']}.{$ssf} LIKE '%" . $sw . "%'";
                            } else {
                                $tmp[] = "IF({$tables['products_lng']}.product_id != '', {$tables['products_lng']}.{$ssf}, {$tables['products']}.{$ssf}) LIKE '%" . $sw . "%'";
                            }
                        } else {
                            $tmp[] = "{$tables['products']}.{$ssf} LIKE '%" . $sw . "%'";
                        }
                    }
                    if (!empty($tmp)) {
                        $condition[] = "(" . implode(" AND ", $tmp) . ")";
                    }
                    unset($tmp);
                } else {
                    if ($current_area == 'C' || $current_area == 'B') {
                        if (in_array($ssf, array('productcode', 'manufacturer_code', 'eancode'))) {
                            $condition[] = "{$tables['products']}.{$ssf} REGEXP '" . implode("|", $search_words) . "'";
                        } else {
                            $condition[] = "IF({$tables['products_lng']}.product_id != '', {$tables['products_lng']}.{$ssf}, {$tables['products']}.{$ssf}) REGEXP '" . implode("|", $search_words) . "'";
                        }
                    } else {
                        $condition[] = "{$tables['products']}.{$ssf} REGEXP '" . implode("|", $search_words) . "'";
                    }
                }
            } elseif ($current_area == 'C' || $current_area == 'B') {
                if (in_array($ssf, array('productcode', 'manufacturer_code', 'eancode'))) {
                    $condition[] = "{$tables['products']}.{$ssf} LIKE '" . $data['substring_prepared'] . "'";
                } else {
                    $condition[] = "IF({$tables['products_lng']}.product_id != '', {$tables['products_lng']}.{$ssf}, {$tables['products']}.{$ssf}) LIKE '" . $data['substring_prepared'] . "'";
                }
            } else {
                $condition[] = "{$tables['products']}.{$ssf} LIKE '" . $data['substring_prepared'] . "'";
            }
        }
        if ($data['by_sku']) {
            $search_by_variants = true;
            # kornev, TOFIX
            $condition[] = (empty($addons['product_options']) ? "({$tables['products']}.productcode)" : "(IFNULL(search_variants.productcode, {$tables['products']}.productcode)") . " LIKE '" . $data['substring_prepared'] . "' OR {$tables['products']}.eancode like '" . $data['substring_prepared'] . "')";
        }
        if ($data['by_tags'] || $data['by_shortdescr'] || $data['by_fulldescr']) {
            if (!empty($search_words) && in_array($data['including'], array("all", "any"))) {
                $tags_condition = "name REGEXP '" . implode("|", $search_words) . "'";
            } else {
                $tags_condition = "name LIKE '" . $data['substring_prepared'] . "'";
            }
            $tag_ids = cw_query_column("SELECT tag_id FROM {$tables['tags']} WHERE {$tags_condition}");
            $query_joins['tags_substr'] = array('tblname' => 'tags_products', 'on' => "tags_substr.product_id = {$tables['products']}.product_id", 'only_select' => 0);
            $condition[] = "tags_substr.tag_id IN ('" . join("','", $tag_ids) . "')";
            unset($tag_ids, $tags_condition);
        }
        if (!empty($condition)) {
            $where[] = "(" . implode(" OR ", $condition) . ")";
        }
        unset($condition);
    }
    if ($data['search_sections']['tab_add_search'] || $data['flat_search'] || $data['product_types']) {
        if (!$data['status']) {
            $data['status'] = cw_core_get_required_status($current_area);
        }
        if ($data['status']) {
            $where[] = "{$tables['products']}.status in (" . implode(", ", $data['status']) . ")";
        }
        if ($config['Appearance']['categories_in_products'] == '1') {
            if ($data['category_id']) {
                $data['categories'] = array($data['category_id'] => 1);
                $data['categories_orig'] = array($data['category_id']);
            }
            if ($data['category_ids']) {
                $_categories = array();
                $_categories_orig = array();
                foreach ($data['category_ids'] as $c_id) {
                    $_categories[$c_id] = 1;
                    $_categories_orig[] = $c_id;
                }
                $data['categories'] = $_categories;
                $data['categories_orig'] = $_categories_orig;
            }
            if ($data['categories'] && is_array($data['categories'])) {
                if ($data['search_in_subcategories']) {
                    $categories_to_search = cw_category_get_subcategory_ids($data['categories_orig']);
                    if (count($categories_to_search)) {
                        $where[] = "{$tables['products_categories']}.category_id IN (" . implode(",", $categories_to_search) . ")";
                    }
                } else {
                    $where[] = "{$tables['products_categories']}.category_id IN (" . implode(",", $data['categories_orig']) . ")";
                }
                $condition = array();
                if ($data['category_main']) {
                    $condition[] = "{$tables['products_categories']}.main = 1";
                }
                if ($data['category_extra']) {
                    $condition[] = "{$tables['products_categories']}.main = 0";
                }
                if (count($condition)) {
                    $where[] = "(" . implode(" OR ", $condition) . ")";
                }
            }
        }
        if ($data['productcode']) {
            $search_by_variants = true;
            # kornev, TOFIX
            $productcode_cond_string = empty($addons['product_options']) ? "{$tables['products']}.productcode" : "IFNULL(search_variants.productcode, {$tables['products']}.productcode)";
            $where[] = "({$productcode_cond_string} LIKE '%" . $data['productcode'] . "%')";
        }
        if ($data['manufacturer_code']) {
            $where[] = "({$tables['products']}.manufacturer_code like '%" . $data['manufacturer_code'] . "%')";
        }
        if ($data['eancode']) {
            $search_by_variants = true;
            # kornev, TOFIX
            $productcode_cond_string = empty($addons['product_options']) ? "{$tables['products']}.eancode" : "IFNULL(search_variants.eancode, {$tables['products']}.eancode)";
            $where[] = "({$productcode_cond_string} LIKE '%" . $data['eancode'] . "%')";
        }
        if ($data['product_id']) {
            $where[] = "{$tables['products']}.product_id " . (is_array($data['product_id']) ? " IN ('" . implode("','", $data['product_id']) . "')" : "= '" . $data['product_id'] . "'");
        }
        if (!empty($data['serial_number'])) {
            $warehouse_condition = AREA_TYPE == 'P' ? "and {$tables['serial_numbers']}.warehouse_customer_id='{$user_account['warehouse_customer_id']}'" : "";
            $where[] = "{$tables['serial_numbers']}.sn LIKE '%" . $data['serial_number'] . "%' {$warehouse_condition}";
            $query_joins['serial_numbers'] = array("on" => "{$tables['serial_numbers']}.product_id = {$tables['products']}.product_id", 'is_inner' => 1);
        }
        /* kornev, removed - the manufacturer is attribute now and search is going to be done in another way
                if ($addons['manufacturers']) {
        /*
        # kornev, attribute should be selected in another way
                    $fields[] = "$tables[manufacturers].manufacturer";
                    $query_joins['manufacturers'] = array(
                        'on' => "$tables[products].manufacturer_id = $tables[manufacturers].manufacturer_id",
                        'only_select' => 1,
                    );
        */
        /*
                    if ($data['manufacturers']) {
                        $where['manuf_condition'] = "$tables[products].manufacturer_id IN ('".implode("', '", array_keys($data['manufacturers']))."')";
                        $query_joins['manufacturers']['only_select'] = 0;
                        $query_joins['manufacturers']['is_inner'] = 1;
                    }
                    if ($data['manufacturers_substring']) {
                        $substring = $data['manufacturers_substring'];
                        if (!$data['manufacturers_substring_exact']) $substring = '%'.trim($substring).'%';
                        $where['manuf_condition'] .= "$tables[manufacturers].manufacturer like '$substring'";
                        $query_joins['manufacturers']['only_select'] = 0;
                        $query_joins['manufacturers']['is_inner'] = 1;
                    }
                }
        */
        if ($data['avail_types']) {
            if ($data['avail_types'][1]) {
                $where[] = "{$tables['products_warehouses_amount']}.avail > 0";
            }
            if ($data['avail_types'][2]) {
                $where[] = "{$tables['products_warehouses_amount']}.avail_ordered > 0";
            }
            if ($data['avail_types'][3]) {
                $where[] = "{$tables['products_warehouses_amount']}.avail_sold > 0";
            }
            if ($data['avail_types'][4]) {
                $where[] = "{$tables['products_warehouses_amount']}.avail_reserved > 0";
            }
            if ($data['avail_types'][5]) {
                $where[] = "{$tables['products_warehouses_amount']}.avail < 0";
            }
            if ($data['avail_types'][6]) {
                $where[] = "{$tables['products_warehouses_amount']}.avail = 0";
            }
        }
        if ($data['product_types']) {
            $where[] = "{$tables['products']}.product_type in ('" . implode("', '", array_keys($data['product_types'])) . "')";
        }
    }
    if (($current_area == "C" || $current_area == "B") && $config['General']['disable_outofstock_products'] == "Y") {
        $where[] = "{$tables['products_warehouses_amount']}.avail > 0";
    }
    if ($data['search_sections']['tab_prices'] || $data['flat_search']) {
        $query_joins['products_prices'] = array('parent' => 'products', 'on' => "{$tables['products_prices']}.product_id = {$tables['products']}.product_id and {$tables['products_prices']}.quantity=1 and {$tables['products_prices']}.membership_id in (" . join(',', $memberships) . ")", 'is_inner' => 1);
        if ($data['price_min']) {
            $where['price_min'] = "{$tables['products_prices']}.price >= '{$data['price_min']}'";
        }
        if ($data['price_max']) {
            $where['price_max'] = "{$tables['products_prices']}.price <= '{$data['price_max']}'";
        }
        if ($data['weight_min']) {
            $where['weight_min'] = "{$tables['products']}.weight >= '{$data['weight_min']}'";
        }
        if ($data['weight_max']) {
            $where['weight_max'] = "{$tables['products']}.weight <= '{$data['weight_max']}'";
        }
        /*
                if ($data['list_price_min'])
                    $where[] = "$tables[products_prices].list_price >= '$data[list_price_min]'";
                if ($data['list_price_min'])
                    $where[] = "$tables[products_prices].list_price <= '$data[list_price_max]'";
        */
        if ($data['list_price_min']) {
            $where[] = "{$tables['products']}.list_price >= '{$data['list_price_min']}'";
        }
        if ($data['list_price_min']) {
            $where[] = "{$tables['products']}.list_price <= '{$data['list_price_max']}'";
        }
    }
    if ($data['search_sections']['tab_additional_options'] || $data['flat_search']) {
        if ($data['flag_free_ship']) {
            $where[] = "{$tables['products']}.free_shipping = '" . $data['flag_free_ship'] . "'";
        }
        if ($data['flag_ship_freight']) {
            $where[] = "{$tables['products']}.shipping_freight " . ($data['flag_ship_freight'] == 'Y' ? '>0' : '=0');
        }
        if ($data['flag_global_disc']) {
            $where[] = "{$tables['products']}.discount_avail = '" . $data['flag_global_disc'] . "'";
        }
        if ($data['flag_free_tax']) {
            $where[] = "{$tables['products']}.free_tax = '" . $data['flag_free_tax'] . "'";
        }
        if ($data['flag_min_amount']) {
            if ($data['flag_min_amount'] == "Y") {
                $where[] = "{$tables['products']}.min_amount <= 1";
            } else {
                $where[] = "{$tables['products']}.min_amount = 1";
            }
        }
        if ($data['flag_low_avail_limit']) {
            if ($data['flag_low_avail_limit'] == 'Y') {
                $where[] = "{$tables['products']}.low_avail_limit <= 1";
            } else {
                $where[] = "{$tables['products']}.low_avail_limit > 1";
            }
        }
    }
    if ($data['search_sections']['tab_anagraphic'] || $data['flat_search']) {
        if ($data['blank_descr']) {
            $where[] = "{$tables['products']}.descr = ''";
        }
        if ($data['code']) {
            $search_by_variants = true;
            # kornev, TOFIX
            $productcode_cond_string = empty($addons['product_options']) ? "{$tables['products']}.eancode" : "IFNULL(search_variants.eancode, {$tables['products']}.eancode)";
            $where[] = "({$productcode_cond_string} != '')";
        }
        if ($data['without_code']) {
            $search_by_variants = true;
            # kornev, TOFIX
            $where[] = !$addons['product_options'] ? "({$tables['products']}.productcode = '' or {$tables['products']}.eancode = '')" : "(IFNULL(search_variants.productcode, {$tables['products']}.productcode) = '' OR IFNULL(search_variants.eancode, {$tables['products']}.eancode) = '')";
        }
        $query_joins['products_system_info'] = array('parent' => 'products', 'on' => "{$tables['products_system_info']}.product_id = {$tables['products']}.product_id", 'is_inner' => 1);
        if ($data['creation_date_start']) {
            $where[] = "{$tables['products_system_info']}.creation_date >= '{$data['creation_date_start']}'";
        }
        if ($data['creation_date_end']) {
            $where[] = "{$tables['products_system_info']}.creation_date <= '{$data['creation_date_end']}'";
        }
        if ($data['modify_date_start']) {
            $where[] = "{$tables['products_system_info']}.modification_date >= '{$data['modify_date_start']}'";
        }
        if ($data['modify_date_end']) {
            $where[] = "{$tables['products_system_info']}.modification_date <= '{$data['modify_date_end']}'";
        }
        if ($data['created_by']) {
            $where[] = "{$tables['products_system_info']}.creation_customer_id = '{$data['created_by']}'";
        }
        if ($data['supplier']) {
            $where[] = "{$tables['products_system_info']}.supplier_customer_id = '{$data['supplier']}'";
        }
        if ($data['sold_date_start'] || $data['sold_date_end']) {
            $query_joins['docs_items'] = array('on' => "{$tables['docs_items']}.product_id = {$tables['products']}.product_id", 'is_inner' => 1);
            $query_joins['docs'] = array('on' => "{$tables['docs']}.doc_id = {$tables['docs_items']}.doc_id", 'is_inner' => 1);
            if ($data['sold_date_start']) {
                $where[] = "{$tables['docs']}.date >= '{$data['sold_date_start']}'";
            }
            if ($data['sold_date_end']) {
                $where[] = "{$tables['docs']}.date <= '{$data['sold_date_end']}'";
            }
        }
    }
    if ($data['tag']) {
        $query_joins['tags_products'] = array('on' => "{$tables['tags_products']}.product_id = {$tables['products']}.product_id", 'only_select' => 0);
        $query_joins['tags'] = array('on' => "{$tables['tags']}.tag_id = {$tables['tags_products']}.tag_id", 'only_select' => 0);
        $where[] = "{$tables['tags']}.name = '{$data['tag']}'";
    }
    //   if (in_array($current_area, array('B', 'G'))) {
    $fields[] = "IF({$tables['products_lng']}.product_id != '', {$tables['products_lng']}.product, {$tables['products']}.product) as product";
    $fields[] = "IF({$tables['products_lng']}.product_id != '', {$tables['products_lng']}.descr, {$tables['products']}.descr) as descr";
    $fields[] = "IF({$tables['products_lng']}.product_id != '', {$tables['products_lng']}.fulldescr, {$tables['products']}.fulldescr) as fulldescr";
    $query_joins['products_lng'] = array('on' => "{$tables['products_lng']}.product_id = {$tables['products']}.product_id AND {$tables['products_lng']}.code = '{$current_language}'", 'only_select' => 1);
    if ($data['by_title'] || $data['by_shortdescr'] || $data['by_fulldescr']) {
        $query_joins['products_lng']['only_select'] = 0;
    }
    //    }
    if (in_array($current_area, array('C', 'R', 'G'))) {
        if ($config['Appearance']['categories_in_products'] == '1') {
            $query_joins['categories_memberships'] = array('on' => "{$tables['categories_memberships']}.category_id = {$tables['products_categories']}.category_id", 'parent' => 'products_categories', 'is_inner' => 1);
        }
        $query_joins['products_memberships'] = array('parent' => 'products', 'on' => "{$tables['products_memberships']}.product_id = {$tables['products']}.product_id", 'is_inner' => 1);
    }
    if ($current_area == 'C') {
        if ($config['Appearance']['categories_in_products'] == '1') {
            $where[] = "{$tables['categories_memberships']}.membership_id IN (" . join(',', $memberships) . ")";
            $where[] = "{$tables['categories']}.status = 1";
            $query_joins['categories_memberships']['only_select'] = 0;
            $query_joins['categories'] = array('parent' => 'products_categories', 'on' => "{$tables['categories']}.category_id = {$tables['products_categories']}.category_id", 'is_inner' => 1);
        }
        $where[] = "{$tables['products_memberships']}.membership_id IN (" . join(',', $memberships) . ")";
        $query_joins['products_memberships']['only_select'] = 0;
    } elseif ($config['Appearance']['categories_in_products'] == '1' && $current_area == 'B') {
        $where[] = "{$tables['categories']}.status = 1";
        $query_joins['categories'] = array('parent' => 'products_categories', 'on' => "{$tables['categories']}.category_id = {$tables['products_categories']}.category_id", 'is_inner' => 1);
    }
    if ($config['Appearance']['categories_in_products'] == '1' && $data['get_category'] == 'Y') {
        $query_joins['categories'] = array('parent' => 'products_categories', 'on' => "{$tables['categories']}.category_id = {$tables['products_categories']}.category_id");
        $query_joins['categories_lng'] = array("on" => "{$tables['categories_lng']}.category_id = {$tables['categories']}.category_id and {$tables['categories_lng']}.code='{$current_language}'", "parent" => "categories");
        $fields[] = "IF({$tables['categories_lng']}.category_id IS NOT NULL AND {$tables['categories_lng']}.category != '', {$tables['categories_lng']}.category, {$tables['categories']}.category) as category";
    }
    if (isset($data['avail_min'])) {
        $where[] = "{$tables['products_warehouses_amount']}.avail >= '" . $data['avail_min'] . "'";
    }
    if (isset($data['avail_max'])) {
        $where[] = "{$tables['products_warehouses_amount']}.avail <= '" . $data['avail_max'] . "'";
    }
    # kornev, TOFIX
    if ($addons['product_options']) {
        if ($search_by_variants) {
            $query_joins['search_variants'] = array('tblname' => 'product_variants', 'on' => "search_variants.product_id = {$tables['products']}.product_id", 'only_select' => 0);
        }
        if ($current_area == 'A') {
            # kornev, TOFIX
            $query_joins['product_variants'] = array('on' => "{$tables['product_variants']}.product_id = {$tables['products']}.product_id AND {$tables['product_variants']}.variant_id = {$tables['products_prices']}.variant_id", 'parent' => 'products_prices', 'only_select' => 1);
        } else {
            $query_joins['product_variants'] = array('on' => "{$tables['product_variants']}.product_id = {$tables['products']}.product_id AND {$tables['product_variants']}.variant_id = {$tables['products_prices']}.variant_id", 'parent' => 'products_prices', 'only_select' => 1);
        }
        foreach (array('weight', 'productcode') as $property) {
            $fields[] = "ifnull({$tables['product_variants']}.{$property}, {$tables['products']}.{$property}) as " . $property;
        }
    }
    foreach (array('products_images_thumb', 'products_images_det') as $products_images_type) {
        if ($data['has_' . $products_images_type]) {
            global $available_images;
            $exclude_names_products_images = array($available_images[$products_images_type]['default_image'], '');
            if (is_array($data['exclude_filenames_' . $products_images_type])) {
                $exclude_names_products_images = array_merge($exclude_names_products_images, $data['exclude_filenames_' . $products_images_type]);
            }
            $query_joins[$products_images_type] = array('on' => $tables[$products_images_type] . ".id = {$tables['products']}.product_id AND (" . $tables[$products_images_type] . ".filename NOT IN ('" . implode("', '", $exclude_names_products_images) . "') OR " . $tables[$products_images_type] . ".image_path like 'http://%')", 'is_inner' => 1);
        }
    }
    global $allowed_products_sort_fields;
    if (!isset($allowed_products_sort_fields)) {
        $allowed_products_sort_fields = array();
    }
    if (!in_array($data['sort_field'], array('rand', 'productcode', 'title', 'orderby', 'quantity', 'price', 'product_id')) && !in_array($data['sort_field'], $allowed_products_sort_fields)) {
        $data['sort_field'] = $config['Appearance']['products_order'];
    }
    if (!empty($data['sort_field'])) {
        $direction = $data['sort_direction'] ? 'DESC' : 'ASC';
        if ($config['Appearance']['display_productcode_in_list'] != "Y" && ($current_area == 'C' || $current_area == 'B') && $data['sort_field'] == 'productcode') {
            $data['sort_field'] = 'orderby';
        }
        switch ($data['sort_field']) {
            case 'rand':
                $sort_string = 'RAND()';
                break;
            case "productcode":
                $sort_string = "{$tables['products']}.productcode {$direction}";
                break;
            case "title":
                $sort_string = "{$tables['products']}.product {$direction}";
                break;
            case "orderby":
                if ($config['Appearance']['categories_in_products'] == '1') {
                    $sort_string = "{$tables['products_categories']}.orderby {$direction}";
                } else {
                    $sort_string = "{$tables['products']}.productcode {$direction}";
                }
                break;
            case "quantity":
                $sort_string = "{$tables['products_warehouses_amount']}.avail {$direction}";
                break;
            case "price":
                $sort_string = "price {$direction}";
                break;
            case "product_id":
                $sort_string = "{$tables['products']}.product_id {$direction}";
                break;
            default:
                $sort_string = $data['sort_field'] . ' ' . $direction;
                // special case to order by rand(seed) field or custom field
        }
        global $custom_products_sort_string;
        if (!empty($custom_products_sort_string)) {
            $sort_string = $custom_products_sort_string;
        }
    } else {
        $sort_string = "{$tables['products']}.product";
    }
    if (!empty($data['sort_condition'])) {
        $sort_string = $data['sort_condition'];
    }
    /*
        if (($current_area == "C" || $current_area == "B") && $config['General']['disable_outofstock_products'] == "Y") {
            $query_joins['products_warehouses_amount'] = array(
                'tblname' => 'products_warehouses_amount',
                'on' => "$tables[products_warehouses_amount].product_id = $tables[products].product_id and $tables[products_warehouses_amount].variant_id=$tables[product_variants].variant_id and $tables[products_warehouses_amount.avail > 0",
                'only_select' => 0,
            );
        }
    */
    $groupbys[] = "{$tables['products']}.product_id";
    $orderbys[] = $sort_string;
    $orderbys[] = "{$tables['products']}.product ASC";
    if (isset($params['product_id_only']) && $params['product_id_only'] == true) {
        $fields = array($tables['products'] . '.product_id');
    }
    $search_query_count = cw_db_generate_query('count(*)', $from_tbls, $query_joins, $where, $groupbys, $having, array(), 0);
    $search_query = cw_db_generate_query($fields, $from_tbls, $query_joins, $where, $groupbys, $having, $orderbys);
    //var_dump($search_query); die();
    if (!$data['limit'] && !$data['all']) {
        $_res = db_query($search_query_count);
        $total_items = db_num_rows($_res);
        db_free_result($_res);
    }
    # kornev, optimization, we don't need to pre-calculate the amount in some cases
    $page = $data['page'];
    if ($data['count']) {
        return $total_items;
    } elseif ($data['limit']) {
        $limit_str = " LIMIT {$data['limit']}";
    } elseif ($data['all']) {
        $limit_str = '';
    } else {
        $navigation = cw_core_get_navigation($target, $total_items, $page);
        $_objects2load = $navigation['objects_per_page'];
        $_first_object_on_page = $navigation['first_page'];
        if (isset($navigation['preload_objects'])) {
            $_objects2load += $navigation['preload_objects'];
            $_first_object_on_page = max($_first_object_on_page - $navigation['preload_objects'], 0);
        }
        $limit_str = " LIMIT {$_first_object_on_page}, {$_objects2load}";
    }
    $products = $pfr = array();
    if ($params['count_only']) {
        return array($products, $navigation, $pfr);
    }
    if ($total_items > 0 || $data['limit'] || $data['all'] || $data['attributes']) {
        $products = cw_query($search_query . $limit_str);
        if ($data['limit'] || $data['all']) {
            $items_per_page = 20;
            if (!empty($objects_per_page)) {
                $items_per_page = $objects_per_page;
            }
            $navigation = cw_core_get_navigation($target, count($products), $page, $items_per_page);
        }
        /* kornev, not used now
                if ($data['query_manufacturers'] == 'Y') {
                    $query_joins['manufacturers'] = array(
                        'on' => "$tables[products].manufacturer_id=$tables[manufacturers].manufacturer_id",
                        'is_inner' => 1,
                    );
        
                    unset($where['manuf_condition']);
                    $manuf_query = cw_db_generate_query(array("$tables[manufacturers].manufacturer", "$tables[manufacturers].manufacturer_id"), $from_tbls, $query_joins, $where, array("$tables[manufacturers].manufacturer"), $having, array("$tables[manufacturers].orderby"));
        
                    $p_manufacturers = cw_query($manuf_query);
                    if (is_array($p_manufacturers) && is_array($data['manufacturers']))
                    foreach($p_manufacturers as $k=>$v)
                        $p_manufacturers[$k]['selected'] = in_array($v['manufacturer_id'], array_keys($data['manufacturers']));
                    $smarty->assign('product_manufacturers', $p_manufacturers);
                }
        */
        # kornev, query features for the additional product filter
        if ($info_type & 1024 && !($pfr = cw_cache_get(array($search_query . $limit_str), 'PF_search'))) {
            $pfr = array();
            # kornev, we need that for the breadcrumbs
            if ($data['attributes']['substring']) {
                $pfr[] = array('attribute_id' => 'substring', 'name' => cw_get_langvar_by_name('lbl_substring'), 'type' => '', 'is_selected' => 1, 'selected' => array($data['attributes']['substring']), 'values' => array());
            }
            # kornev, firstly select all of the attributes to build the filter - without products count
            $attributes = cw_call('cw_attributes_filter', array(array('item_type' => 'P', 'pf_is_use' => 1, 'active' => 1)));
            uasort($attributes, '_sort_pf_by_pf_orderby');
            if ($attributes) {
                $att_ids = $ss_att = array();
                foreach ($attributes as $k => $v) {
                    $att_ids[] = $v['attribute_id'];
                    // Mark price attribute with special flag is_price
                    if ($v['field'] == 'price') {
                        //$attributes[$k]['attribute_id'] = $v['attribute_id'] = 'price';
                        $attributes[$k]['is_price'] = 1;
                    }
                    // If slider attr is passed in data, then prefill special array for sliders
                    if ($v['pf_display_type'] == 'S' && isset($data['attributes'][$v['attribute_id']])) {
                        $ss_att[] = $v;
                    }
                }
                $query_joins['atv'] = array('tblname' => 'attributes_values', 'on' => "{$tables['products']}.product_id=atv.item_id and atv.attribute_id in ('" . implode("', '", $att_ids) . "') and atv.code in ('{$current_language}', '') and atv.value != ''");
                # kornev, we have to select all of the slider attributes separatelly
                // general selection of all attributes, values, prices for all products according to search query
                $attribute_query = cw_db_generate_query(array("atv.attribute_id", "atv.value", 'atv.item_id', $tables['products_prices'] . '.price'), $from_tbls, $query_joins, $where, null, null, null);
                //$atv = cw_query($attribute_query); // It takes a lot of memory and don't want return back even after unset()
                $tmp = $prices = array();
                if ($p_result = db_query($attribute_query, null)) {
                    while ($v = db_fetch_array($p_result)) {
                        if ($v['item_id']) {
                            $tmp[$v['attribute_id']][$v['value']][$v['item_id']] = $v['price'];
                            // Use price (to calculate min_price later) instead of dummy flag "1"
                        }
                        if ($v['price']) {
                            $tmp[PRICE_ATTRIBUTE_ID][$v['price']][$v['item_id']] = 1;
                        }
                    }
                    db_free_result($p_result);
                }
                # kornev, for the sliders we should select all of the values - so without the appropriate condition for the attribute;
                if ($ss_att && $config['product_filter']['is_slow_mode']) {
                    foreach ($ss_att as $id => $v) {
                        $__query_joins = $query_joins;
                        $__where = $where;
                        if ($id == 'price') {
                            unset($__where['price_min']);
                            unset($__where['price_max']);
                            $flds = array($tables['products_prices'] . '.price', $tables['products_prices'] . '.product_id');
                        } else {
                            unset($__query_joins['atv_' . $v['id']]);
                            $flds = array('atv.attribute_id', 'atv.value', 'atv.item_id');
                            //                        $__where[] = "atv_$v[id]. "
                        }
                        $attribute_query = cw_db_generate_query($flds, $from_tbls, $__query_joins, $__where, null, null, null);
                        if ($p_result = db_query($attribute_query, null)) {
                            while ($v = db_fetch_array($p_result)) {
                                if ($v['item_id']) {
                                    $tmp[$v['attribute_id']][$v['value']][$v['item_id']] = $v['price'];
                                    // Use price (to calculate min_price later) instead of dummy flag "1"
                                }
                                if ($v['price']) {
                                    $tmp[PRICE_ATTRIBUTE_ID][$v['price']][$v['item_id']] = 1;
                                }
                            }
                            db_free_result($p_result);
                        }
                    }
                }
                $atv = null;
                unset($atv, $ss_att);
                # kornev, for now the fake price attribute is used - we should move it to the attributes array
                # kornev, TOFIX - move price to attributes
                //                array_unshift($attributes, array('attribute_id' => 'price', 'name' => cw_get_langvar_by_name('lbl_price'), 'type' => 'decimal', 'field' => 'price', 'pf_display_type' => 'S', 'is_price' => 1));
                foreach ($attributes as $ka => $v) {
                    $images = array();
                    if (!$tmp[$v['attribute_id']]) {
                        continue;
                    }
                    # kornev, array_multisort problem with numbers
                    # kornev, name will be replaced for selectors
                    foreach ($tmp[$v['attribute_id']] as $k => $pids) {
                        $v['values'][$k] = array('name' => $k, 'id' => $k, 'counter' => count($pids));
                        if ($config['product_filter']['show_from_price'] == 'Y') {
                            $v['values'][$k]['min_price'] = cw_func_call('cw_product_filter_get_slider_value', array('value' => min($pids), 'is_price' => true, 'current_area' => $current_area, 'user_account' => $user_account));
                        }
                    }
                    if (isset($data['attributes'][$v['attribute_id']])) {
                        $v['is_selected'] = true;
                        $v['selected'] = $data['attributes'][$v['attribute_id']];
                    }
                    # kornev, we need to apply some order by to the fields
                    # kornev, also we have to add the images for the selectboxes and multi-selectboxes
                    $dfv = cw_call('cw_attributes_get_attribute_default_value', array('attribute_id' => $v['attribute_id']));
                    if (in_array($v['type'], array('multiple_selectbox', 'selectbox'))) {
                        $sort = $images = array();
                        if ($dfv) {
                            $prepared_dfv = array();
                            foreach ($dfv as $k => $d) {
                                $prepared_dfv[$d['attribute_value_id']] = $d;
                            }
                            foreach ($v['values'] as $k => $d) {
                                if (!$prepared_dfv[$k]) {
                                    unset($v['values'][$k]);
                                    continue;
                                }
                                $sort[$k] = $prepared_dfv[$k]['counter'];
                                $v['values'][$k]['name'] = $prepared_dfv[$k]['value'];
                                $v['values'][$k]['description'] = $prepared_dfv[$k]['description'];
                                $v['values'][$k]['facet'] = $prepared_dfv[$k]['facet'];
                                $v['values'][$k]['orderby'] = $prepared_dfv[$k]['orderby'];
                                // if the type includes swatch - find the images
                                if (in_array($v['pf_display_type'], array('W', 'E', 'G'))) {
                                    $images[$k] = $prepared_dfv[$k]['pf_image_id'];
                                }
                            }
                            # kornev, some problems with values - TOFIX - move to attributes
                            /* doesn't work
                                                        if (count($sort) != count($v['values']))
                                                        foreach($v['values'] as $k=>$d)
                                                            if (!isset($sort[$k]))
                                                                db_query("delete from $tables[attributes_values] where attribute_id='$v[attribute_id]' and value='".addslashes($k)."'");
                            */
                        }
                    } else {
                        if (isset($dfv[0]) && $dfv[0]) {
                            foreach ($v['values'] as $k => $d) {
                                $v['values'][$k]['description'] = $dfv[0]['description'];
                                $v['values'][$k]['facet'] = $dfv[0]['facet'];
                            }
                        }
                    }
                    uasort($v['values'], '_sort_pf_by_counter');
                    # kornev, if slider is used - limit the number of chunks to 50
                    if (in_array($v['pf_display_type'], array('S', 'R'))) {
                        # kornev, slider should be sorted in another way - as the deciaml/integer numbers (sql sorted it as a string)
                        ksort($v['values']);
                        $min = array_shift($v['values']);
                        $max = array_pop($v['values']);
                        if (!$max) {
                            $max = $min;
                        }
                        # kornev, slider with one value is not possible
                        if (!$max && !$v['selected']) {
                            continue;
                        }
                        $v['min_name'] = $v['min'] = $min['name'];
                        $v['max_name'] = $v['max'] = $max['name'];
                        if ($v['pf_display_type'] == 'S' && is_numeric($min['name']) && is_numeric($max['name'])) {
                            $approx_range = ($max['name'] - $min['name']) / 50;
                            $start = $min['name'];
                            $is_price = $v['is_price'] && in_array($current_area, array('G', 'C')) && $info_type & 8;
                            $values = array();
                            $values[$min['id']] = cw_func_call('cw_product_filter_get_slider_value', array('field' => $v['field'], 'value' => $min['id'], 'is_price' => $is_price, 'current_area' => $current_area, 'user_account' => $user_account));
                            $current = null;
                            while ($v['values'] || $current) {
                                if (!$current) {
                                    $current = array_shift($v['values']);
                                    $current['name'] = $v['type'] == 'integer' ? intval($current['name']) : floatval($current['name']);
                                    // Foolproof if numeric fields contain text
                                } else {
                                    $start_prev = $start;
                                    $start += $approx_range;
                                }
                                if ($start >= $current['name']) {
                                    if ($current['name'] > $start_prev) {
                                        # kornev, we need calculate the taxes for the price;
                                        $values[$current['id']] = cw_func_call('cw_product_filter_get_slider_value', array('field' => $v['field'], 'value' => $current['id'], 'is_price' => $is_price, 'current_area' => $current_area, 'user_account' => $user_account));
                                        $start_prev = $start;
                                        $start += $approx_range;
                                    }
                                    $current = null;
                                }
                            }
                            $values[$max['id']] = cw_func_call('cw_product_filter_get_slider_value', array('field' => $v['field'], 'value' => $max['id'], 'is_price' => $is_price, 'current_area' => $current_area, 'user_account' => $user_account));
                            $v['values'] = $values;
                            $v['values_counter'] = count($values);
                            //                            if ($is_price) {
                            $v['min_name'] = cw_func_call('cw_product_filter_get_slider_value', array('field' => $v['field'], 'value' => $v['min'], 'is_price' => $is_price, 'current_area' => $current_area, 'user_account' => $user_account));
                            $v['max_name'] = cw_func_call('cw_product_filter_get_slider_value', array('field' => $v['field'], 'value' => $v['max'], 'is_price' => $is_price, 'current_area' => $current_area, 'user_account' => $user_account));
                            if ($v['selected']) {
                                foreach ($v['selected'] as $sk => $sv) {
                                    $v['selected'][$sk . '_name'] = cw_func_call('cw_product_filter_get_slider_value', array('field' => $v['field'], 'value' => $sv, 'is_price' => $is_price, 'current_area' => $current_area, 'user_account' => $user_account));
                                }
                            }
                            //                            }
                        }
                    } elseif (in_array($v['type'], array('integer', 'decimal')) && in_array($v['pf_display_type'], array('P', 'E', 'W', 'G'))) {
                        $v['values'] = cw_call('cw_product_filter_get_price_ranges', array('attribute_id' => $v['attribute_id'], $v['values']));
                        // Images collection
                        if (in_array($v['pf_display_type'], array('W', 'E', 'G'))) {
                            foreach ($v['values'] as $kk => $vv) {
                                $images[$kk] = $dfv[$kk]['pf_image_id'];
                            }
                        }
                        if (isset($data['attributes'][$v['attribute_id']])) {
                            $v['is_selected'] = true;
                            $v['selected'] = $data['attributes'][$v['attribute_id']];
                        }
                    }
                    # kornev, assign the images....
                    # kornev, TOFIX speed up is possible here
                    if ($images) {
                        foreach ($images as $kk => $dd) {
                            $v['values'][$kk]['image'] = cw_image_get('attributes_images', $dd);
                        }
                    }
                    $pfr[] = $v;
                }
                // foreach $attributes
            }
            unset($attributes, $tmp, $dfv, $prepared_dfv, $values, $images);
            cw_cache_save($pfr, array($search_query . $limit_str), 'PF_search');
        }
    }
    if ($products) {
        $cart =& cw_session_register('cart', array());
        cw_load('taxes', 'warehouse', 'cart');
        global $accl;
        cw_call('on_prepare_products_found', array(&$products, $data, $user_account, $info_type));
        $ids = array();
        $ids_options = array();
        foreach ($products as $k => $v) {
            $ids[] = $v['product_id'];
            $ids_options[$v['product_id']] = doubleval($v['price']);
        }
        # kornev, TOFIX
        if ($addons['product_options']) {
            $options_markups = array();
            if ($ids_options) {
                $options_markups = cw_get_default_options_markup_list($ids_options);
            }
            unset($ids_options);
        }
        //        $is_assigned = ($user_account['customer_id'] && cw_warehouse_is_warehouse_assigned($user_account['customer_id']));
        foreach ($products as $k => $v) {
            //            if($current_area == 'C' && $is_assigned)
            if ($current_area == 'C') {
                $products[$k]['avail'] = cw_warehouse_get_avail_for_customer($v['product_id'], $v['variant_id']);
            } elseif ($current_area == 'A') {
                $products[$k]['avails'] = cw_warehouse_get_avails($v['product_id']);
            }
            $products[$k]['display_price'] = $v['display_price'] = $v['price'];
            # kornev, TOFIX
            if ($addons['product-Options'] && !empty($v['is_product_options']) && !empty($options_markups[$v['product_id']])) {
                $products[$k]['price'] += $options_markups[$v['product_id']];
                $products[$k]['display_price'] = $products[$k]['price'];
                $v = $products[$k];
            }
            $in_cart = 0;
            if (in_array($current_area, array('C', 'G')) && !empty($cart['products']) && is_array($cart['products'])) {
                foreach ($cart['products'] as $cv) {
                    if ($cv['product_id'] == $v['product_id'] && intval($v['variant_id']) == intval($cv['variant_id'])) {
                        $in_cart += $cv['amount'];
                    }
                }
                $products[$k]['in_cart'] = $in_cart;
                $products[$k]['avail'] -= $in_cart;
                if ($products[$k]['avail'] < 0) {
                    $products[$k]['avail'] = 0;
                }
            }
            if ($info_type & 128) {
                $products[$k]['image_thumb'] = cw_image_get('products_images_thumb', $v['product_id']);
            }
            if (in_array($current_area, array('G', 'C')) && $info_type & 8) {
                $_tmp_price = $products[$k]['price'];
                $products[$k]['price'] = $products[$k]['list_price'];
                cw_get_products_taxes($products[$k], $user_account, false, '', $current_area == 'G' && $user_account['usertype'] != 'R');
                $products[$k]['list_price'] = $products[$k]['display_price'];
                $products[$k]['price'] = $_tmp_price;
                $products[$k]['taxes'] = cw_get_products_taxes($products[$k], $user_account, false, '', $current_area == 'G' && $user_account['usertype'] != 'R');
            }
            if ($products[$k]['descr'] == strip_tags($products[$k]['descr'])) {
                $products[$k]['descr'] = str_replace("\n", "<br />", $products[$k]['descr']);
            }
            if ($products[$k]['fulldescr'] == strip_tags($products[$k]['fulldescr'])) {
                $products[$k]['fulldescr'] = str_replace("\n", "<br />", $products[$k]['fulldescr']);
            }
        }
    }
    return array($products, $navigation, $pfr);
}
예제 #11
0
    $signature_template = "mail/newsletter_signature.tpl";
    $sign_delim = "\n\n";
    $message['headers'] = array("Content-Type" => "text/html");
    $sign_delim = "<br /><br />";
    $signature = cw_display($signature_template, $smarty, false);
    $extra = array("Content-Type" => "text/html");
    foreach ($recipients as $recipient) {
        cw_send_simple_mail($config['news']['newsletter_email'], $recipient, $message['subject'], $message['body'] . $sign_delim . preg_replace("/{$email_spec}/S", $recipient, $signature), $extra);
    }
    $current_language = $saved_language;
}
$do_not_update_status = false;
$recipients = array();
$limit = '';
if (is_array($message)) {
    $message = cw_array_map('stripslashes', $message);
    foreach (array("email1", "email2", "email3") as $f) {
        if (!empty($message[$f])) {
            $recipients[] = $message[$f];
        }
    }
    $do_not_update_status = true;
    $list_lng = cw_query_first_cell("SELECT lngcode FROM {$tables['newslists']} WHERE list_id='{$list_id}'");
} else {
    $list = cw_query_first("SELECT * FROM {$tables['newslists']} WHERE list_id='{$list_id}'");
    if (empty($list)) {
        return;
    }
    $list_lng = $list['lngcode'];
    $fields = array();
    $from_tbls = array();
    $result = db_query($query);
    $total_labels_in_search = db_num_rows($result);
    $navigation = cw_core_get_navigation($target, $total_labels_in_search, $page);
    $navigation['script'] = "index.php?target={$target}&language={$language}";
    $smarty->assign('navigation', $navigation);
    if ($total_labels_in_search > 0) {
        $smarty->assign("data", cw_query("{$query} LIMIT {$navigation['first_page']}, {$navigation['objects_per_page']}"));
    }
}
$smarty->assign("upload_max_filesize", ini_get("upload_max_filesize"));
$smarty->assign("my_files_location", cw_user_get_files_location());
if (!empty($serverfile)) {
    $smarty->assign("localfile", $serverfile);
    $serverfile = false;
} else {
    $smarty->assign("localfile", cw_user_get_files_location() . "/lng_file.csv");
}
if ($language) {
    $smarty->assign('topics', $topics);
    $smarty->assign('search_prefilled', cw_array_map('stripslashes', $search_data['languages']));
    $smarty->assign('language', $language);
    $location[] = array(cw_get_langvar_by_name('lbl_edit_languages'), 'index.php?target=' . $target);
    $location[] = array(cw_get_langvar_by_name('lbl_edit_language'), '');
    $smarty->assign('main', 'language');
} else {
    $new_languages = cw_query("SELECT {$tables['map_countries']}.*, IFNULL(lng1c.value, lng2c.value) as country, IFNULL(lng1l.value, lng2l.value) as language FROM {$tables['map_countries']} LEFT JOIN {$tables['languages']} as lng1c ON lng1c.name = CONCAT('country_', {$tables['map_countries']}.code) AND lng1c.code = '{$current_language}' LEFT JOIN {$tables['languages']} as lng2c ON lng2c.name = CONCAT('country_', {$tables['map_countries']}.code) AND lng2c.code = '{$config['default_admin_language']}' LEFT JOIN {$tables['languages']} as lng1l ON lng1l.name = CONCAT('language_', {$tables['map_countries']}.code) AND lng1l.code = '{$current_language}' LEFT JOIN {$tables['languages']} as lng2l ON lng2l.name = CONCAT('language_', {$tables['map_countries']}.code) AND lng2l.code = '{$config['default_admin_language']}' WHERE (lng1l.value != '' OR lng2l.value != '') GROUP BY language ORDER BY language");
    $smarty->assign("new_languages", $new_languages);
    $smarty->assign('languages', $languages);
    $location[] = array(cw_get_langvar_by_name('lbl_edit_languages'), '');
    $smarty->assign('main', 'languages');
}
function cw_get_variant_id($options, $product_id = false)
{
    global $tables;
    if (empty($options) || !is_array($options)) {
        return false;
    }
    $ids = cw_array_map("intval", array_keys($options));
    $vids = cw_query_column("SELECT product_option_id FROM {$tables['product_options']} WHERE type != '' AND product_option_id IN ('" . implode("','", $ids) . "')");
    if (!empty($vids)) {
        foreach ($vids as $v) {
            unset($options[$v]);
        }
    }
    if (empty($options)) {
        return false;
    }
    if ($product_id === false) {
        $ids = cw_array_map("intval", array_keys($options));
        $product_id = cw_query_first_cell("SELECT product_id FROM {$tables['product_options']} WHERE product_option_id IN ('" . implode("','", $ids) . "') LIMIT 1");
    }
    $cnt = 0;
    $res = db_query("SELECT {$tables['product_options']}.product_option_id FROM {$tables['product_options']}, {$tables['product_options_values']} WHERE {$tables['product_options']}.type = '' AND {$tables['product_options']}.avail = 1 AND {$tables['product_options']}.product_id = '" . intval($product_id) . "' AND {$tables['product_options']}.product_option_id = {$tables['product_options_values']}.product_option_id AND {$tables['product_options_values']}.avail = 1 GROUP BY {$tables['product_options']}.product_option_id");
    if ($res) {
        $cnt = db_num_rows($res);
        db_free_result($res);
    }
    if ($cnt != count($options)) {
        return false;
    }
    $options = cw_array_map("intval", $options);
    return cw_query_first_cell("SELECT variant_id, COUNT(variant_id) as cnt FROM {$tables['product_variant_items']} WHERE {$tables['product_variant_items']}.option_id IN ('" . implode("','", $options) . "') GROUP BY variant_id HAVING cnt = " . $cnt . " LIMIT 1");
}
        $pp_signature_txt = '';
        $pp_final_action = 'Sale';
    }
    if (!empty($do_return) && !empty($paypal_token)) {
        $str_token = "<Token>{$paypal_token}</Token>";
    }
    $pp_locale_code = "US";
    if (in_array($shop_language, $pp_locale_codes)) {
        $pp_locale_code = $shop_language;
    }
    $address = '';
    $address_override = '';
    if ($customer_id) {
        $userinfo = cw_user_get_info($customer_id, 65535);
        if (!empty($userinfo)) {
            $userinfo = cw_array_map("cw_xml_escape", $userinfo);
            $state = $userinfo['current_address']['country'] == 'US' || $userinfo['current_address']['country'] == 'CA' || $userinfo['current_address']['state'] != '' ? $userinfo['current_address']['state'] : 'Other';
            $address = <<<ADDR
<Address>
\t<Name>{$userinfo['current_address']['firstname']} {$userinfo['current_address']['lastname']}</Name>
\t<Street1>{$userinfo['current_address']['address']}</Street1>
\t<Street2>{$userinfo['current_address']['address_2']}</Street2>
\t<CityName>{$userinfo['current_address']['city']}</CityName>
\t<StateOrProvince>{$state}</StateOrProvince>
\t<PostalCode>{$userinfo['current_address']['zipcode']}</PostalCode>
\t<Country>{$userinfo['current_address']['country']}</Country>
\t<Phone>{$userinfo['current_address']['phone']}</Phone>
</Address>
ADDR;
            $address_override = "<AddressOverride>1</AddressOverride>";
        }
예제 #15
0
    $config['Company']['start_year'] = date('Y', cw_core_get_time());
}
$config['Company']['end_year'] = date('Y', cw_core_get_time());
if (empty($config['Appearance']['date_format'])) {
    $config['Appearance']['date_format'] = "%d-%m-%Y";
}
$config['Appearance']['datetime_format'] = $config['Appearance']['date_format'] . " " . $config['Appearance']['time_format'];
if ($HTTPS) {
    $config['General']['list_available_cdn_servers'] = '';
}
// Top message - simple way to pass message from page to page
// TODO: Wrap top message mechanism to functions to avoid direct variable usage
global $top_message;
$top_message =& cw_session_register('top_message', array());
if (!empty($top_message)) {
    $smarty->assign('top_message', cw_array_map('nl2br', $top_message));
    $top_message = array();
}
cw_include('init/numbers.php');
$taxes_units = array('ST' => 'lbl_subtotal', 'DST' => 'lbl_discounted_subtotal', 'SH' => 'lbl_shipping_cost', 'PM' => 'lbl_payment_method');
if ($config['card_types']) {
    $config['card_types'] = unserialize($config['card_types']);
}
//filter card types by active flag in customer area
if (APP_AREA == 'customer') {
    $_card_types = array();
    foreach ($config['card_types'] as $card_type) {
        if (!isset($card_type['active']) || $card_type['active'] == 1) {
            $_card_types[] = $card_type;
        }
    }