/**
 * Get video by product
 * 
 * @param int $product_id
 * @return array of rows from table cw_product_video
 */
function get_product_video($product_id)
{
    global $tables;
    $product_id = intval($product_id);
    $video = cw_query("SELECT * FROM {$tables['product_video']} WHERE product_id='{$product_id}' order by pos, title");
    return $video;
}
function cw_speed_bar_search($params, $return = null)
{
    extract($params);
    global $tables, $current_language;
    $fields = $from_tbls = $query_joins = $where = $groupbys = $having = $orderbys = array();
    $orderbys[] = "{$tables['speed_bar']}.orderby";
    $from_tbls[] = 'speed_bar';
    $fields[] = "{$tables['speed_bar']}.*";
    # kornev, merge standart and additional variables
    if ($return) {
        foreach ($return as $saname => $sadata) {
            if (isset(${$saname}) && is_array(${$saname}) && empty(${$saname})) {
                ${$saname} = $sadata;
            }
        }
    }
    $language = $language ? $language : $current_language;
    $query_joins['speed_bar_lng'] = array('on' => "{$tables['speed_bar_lng']}.item_id = {$tables['speed_bar']}.item_id AND {$tables['speed_bar_lng']}.code = '{$language}'", 'only_select' => 1);
    $fields[] = "IFNULL({$tables['speed_bar_lng']}.title, {$tables['speed_bar']}.title) as title";
    if (isset($data['active'])) {
        $where[] = "{$tables['speed_bar']}.active='{$data['active']}'";
    }
    $search_query = cw_db_generate_query($fields, $from_tbls, $query_joins, $where, $groupbys, $having, $orderbys);
    return cw_query($search_query);
}
function cw_sections_get($section, $data = array(), $where = '', $info_type = 264)
{
    global $tables, $current_area, $user_account;
    //    extract($params);
    $table = $tables[$section];
    if (!$info_type) {
        $info_type = 264;
    }
    if ($current_area == 'C') {
        $where .= ($where ? ' and ' : ' ') . $table . '.active=1 ';
        if (in_array($section, array('arrivals', 'hot_deals', 'clearance', 'super_deals'))) {
            $current_time = time();
            $where .= " and ({$table}.from_time <= {$current_time} or {$table}.from_time = 0) and ({$table}.to_time >={$current_time} or {$table}.to_time = 0) and ({$table}.min_amount <= {$tables['products_warehouses_amount']}.avail or {$table}.min_amount = 0)";
        }
        $add_data['query_joins'][$section] = array('on' => "{$tables['products']}.product_id={$table}.product_id", 'is_inner' => 1);
        $data['where'] = $where;
        if ($data['sort_field'] == 'orderby' || empty($data['sort_field'])) {
            $data['sort_field'] = "{$table}.pos";
        }
        $return = cw_func_call('cw_product_search', array('data' => $data, 'user_account' => $user_account, 'current_area' => $current_area, 'info_type' => $info_type), $add_data);
        if ($data['all']) {
            $return = $return[0];
        }
    } else {
        $return = cw_query("select {$table}.*, {$tables['products']}.product_id, {$tables['products']}.product from {$table}, {$tables['products']}, {$tables['products_warehouses_amount']} where {$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 and {$tables['products']}.product_id={$table}.product_id {$where} order by {$table}.pos, {$tables['products']}.product");
    }
    return $return;
}
function product_stages_view()
{
    global $smarty, $product_id, $tables;
    $product_stages = cw_call('cw\\' . addon_name . '\\cw_product_stages_get_product_settings', array($product_id));
    $lib_stages = cw_query("select * from {$tables['product_stages_library']} order by title");
    $smarty->assign('product_stages', $product_stages);
    $smarty->assign('lib_stages', $lib_stages);
}
function cw_get_serial_numbers($customer_id, $product_id, $full_info = false)
{
    global $tables, $current_area;
    $serials = cw_query($sql = "select * from {$tables['serial_numbers']} where doc_id=0 and product_id='{$product_id}'" . ($customer_id ? " and warehouse_customer_id='{$customer_id}'" : "") . " order by warehouse_customer_id");
    if (!$serials) {
        $serials = array();
    }
    return $serials;
}
function cw_breadcrumbs_get_management_breadcrumbs($where = "", $orderby = "", $limit = "", $count_query = FALSE)
{
    global $tables;
    $result = cw_query("\n        SELECT " . ($count_query ? "count(b1.breadcrumb_id) as c" : "b1.*, b2.link as parent_link, b2.title as parent_title") . "\n        FROM {$tables['breadcrumbs']} b1\n        LEFT JOIN {$tables['breadcrumbs']} b2 ON b2.breadcrumb_id = b1.parent_id\n        LEFT JOIN {$tables['addons']} as a ON a.addon = b1.addon\n        WHERE (a.active OR a.addon IS NULL) {$where}\n        " . ($count_query ? "" : $orderby) . "\n        {$limit}\n    ");
    if ($count_query) {
        return $result[0]['c'];
    }
    return $result;
}
function cw_flexible_import_get_profiles($params)
{
    global $tables;
    extract($params);
    $sort_field = $sort_field && $sort_field != "" ? " ORDER BY " . $sort_field . " " : "";
    $sort_direction = $sort_direction != 0 ? " DESC " : " ASC ";
    $limit .= 'LIMIT ' . ($items_per_page * $page - $items_per_page) . ', ' . $items_per_page;
    $profiles = cw_query("SELECT * FROM {$tables['flexible_import_profiles']} {$sort_field} {$sort_direction}  {$limit}");
    return $profiles;
}
function cw_system_messages($type, $with_hidden = false)
{
    global $tables;
    $type = intval($type);
    $sign = '=';
    if ($with_hidden) {
        $sign = '>=';
    }
    return cw_query("SELECT * FROM {$tables['system_messages']} WHERE type='{$type}' AND hidden {$sign} 0 \n        ORDER BY (severity = 'C') DESC, date DESC");
}
function cw_ab_check_clean_url($url, $attr_ids)
{
    global $tables;
    $data = cw_query("SELECT item_id FROM {$tables['attributes_values']} WHERE value = '{$url}' AND attribute_id IN (" . implode(", ", $attr_ids) . ") ");
    if (!$data) {
        return 0;
    } else {
        return 1;
    }
}
function cw_file_area_get_list($type, $customer_id, $where = '')
{
    global $tables;
    $files = cw_query("select * from " . $tables[$type] . " where customer_id='{$customer_id}' {$where} order by orderby, file_id");
    if ($files) {
        foreach ($files as $k => $val) {
            $files[$k] = cw_file_get_info($type, $val);
        }
    }
    return $files;
}
function cw_get_salesman_pending_orders($salesman = '')
{
    global $tables;
    $data = cw_query("select * from {$tables['salesman_orders']} where status=0" . ($salesman ? " and salesman_customer_id='{$salesman}'" : ""));
    if (is_array($data)) {
        foreach ($data as $k => $v) {
            $data[$k]['products'] = unserialize($v['cart']);
            unset($data[$k]['cart']);
        }
    }
    return $data;
}
function get($product_id = null, $category_id = null, $main = null)
{
    global $tables;
    $where = (!is_null($product_id) ? ' AND product_id = "' . intval($product_id) . '"' : '') . (!is_null($category_id) ? ' AND category_id = "' . intval($category_id) . '"' : '') . (!is_null($main) ? ' AND category_id = "' . intval($main) . '"' : '');
    $result = cw_query('SELECT * FROM ' . $tables['products_categories'] . ' WHERE 1 ' . $where);
    // if certain prod<=>cat link requested, then return only this row
    if (!is_null($product_id) && (!is_null($category_id) || !is_null($main)) && count($result) == 1) {
        return array_pop($result);
    }
    // otherwise return array of rows
    return $result;
}
function cw_objects_get_list_ids($type = 'P')
{
    global $tables, $customer_id;
    $objects = array();
    $result = cw_query("SELECT object_id \r\n\t\t\t\t\t\t\tFROM {$tables['objects_set']} \r\n\t\t\t\t\t\t\tWHERE customer_id = {$customer_id} \r\n\t\t\t\t\t\t\t\tAND set_type = '{$type}'");
    if (is_array($result) && count($result)) {
        foreach ($result as $object) {
            $objects[] = $object['object_id'];
        }
    }
    return $objects;
}
function cw_cron_invoice_check_params($time, $prev_time)
{
    global $tables, $config, $smarty;
    $expired_invoices = array();
    $notify_invoices = array();
    $days_notify = intval($config['General']['days_notify_expiration_invoice']);
    $result = cw_query("SELECT d.doc_id, d.display_id, ui.customer_id, di.expiration_date\n\t\t\t\t\t\t\tFROM {$tables['docs']} d\n\t\t\t\t\t\t\tLEFT JOIN {$tables['docs_info']} di ON di.doc_info_id = d.doc_info_id\n\t\t\t\t\t\t\tLEFT JOIN {$tables['docs_user_info']} ui ON ui.doc_info_id = d.doc_info_id\n\t\t\t\t\t\t\tWHERE di.expiration_date <> 0 AND d.type = 'I' AND status <> 'C' AND status <> 'F'");
    if (!empty($result)) {
        foreach ($result as $value) {
            if (!empty($value['customer_id'])) {
                $expiration_date = $value['expiration_date'];
                $days_left = floor(($expiration_date - $time) / SECONDS_PER_DAY);
                // invoice is expired
                if ($days_left <= 0) {
                    cw_load('mail', 'doc');
                    $doc_id = $value['doc_id'];
                    $status = 'F';
                    $expired_invoices[] = "ID:" . $doc_id . " NUMBER:" . $value['display_id'];
                    cw_call('cw_doc_change_status', array($doc_id, $status));
                } elseif ($days_notify > 0 && $days_left == $days_notify) {
                    cw_load('mail', 'doc', 'web');
                    $doc_id = $value['doc_id'];
                    $doc_data = cw_call('cw_doc_get', array($doc_id, 8192));
                    $notify_invoices[] = "ID:" . $doc_id . " NUMBER:" . $value['display_id'];
                    if (empty($doc_data)) {
                        continue;
                    }
                    if ($doc_data['info']['layout_id']) {
                        $layout = cw_web_get_layout_by_id($doc_data['info']['layout_id']);
                    } else {
                        $layout = cw_web_get_layout('docs_' . $doc_data['type']);
                    }
                    $smarty->assign('layout_data', $layout);
                    $smarty->assign('info', $doc_data['info']);
                    $smarty->assign('products', $doc_data['products']);
                    $smarty->assign('order', $doc_data);
                    $smarty->assign('doc', $doc_data);
                    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));
                }
            }
        }
    }
    $message = "";
    if (count($expired_invoices)) {
        $message = "\n Expired invoices: '" . implode(", ", $expired_invoices) . "'";
    }
    if (count($notify_invoices)) {
        $message .= "\n Notify invoices: '" . implode(", ", $notify_invoices) . "'";
    }
    return $message;
}
function ab_show($product_id)
{
    global $smarty, $tables, $config;
    global $current_language;
    $product_id = (int) $product_id;
    if (empty($product_id)) {
        return;
    }
    if ($_SERVER['REQUEST_METHOD'] != 'GET') {
        ab_redirect($product_id);
    }
    $contentsections = cw_query("SELECT ab.contentsection_id, ab.service_code, ab.name, ab.type, abp.object_id as selected FROM {$tables['cms']} ab\n            LEFT JOIN {$tables['cms_restrictions']} abp ON ab.contentsection_id = abp.contentsection_id AND abp.object_id='{$product_id}' AND abp.object_type='P'\n            ORDER BY ab.service_code");
    $smarty->assign('contentsections', $contentsections);
}
function get_messages($membership_id, $lngcode, $only_first = false, $limit = null)
{
    global $tables, $customer_id;
    # kornev
    $query = "\nselect\n\t{$tables['newsletter']}.*\nfrom\n\t{$tables['newsletter']}, {$tables['newslists']}\nleft join\n    {$tables['newslists_memberships']} on {$tables['newslists']}.list_id = {$tables['newslists_memberships']}.list_id\nwhere\n    ({$tables['newslists_memberships']}.membership_id IS NULL or {$tables['newslists_memberships']}.membership_id = '{$membership_id}') AND\n\t{$tables['newslists']}.avail=1 AND\n\t{$tables['newslists']}.show_as_news=1 AND\n\t{$tables['newslists']}.lngcode='{$lngcode}' AND\n\t{$tables['newslists']}.list_id={$tables['newsletter']}.list_id AND\n\t{$tables['newsletter']}.show_as_news=1\norder by {$tables['newsletter']}.send_date DESC";
    if ($limit) {
        $query .= " LIMIT {$limit}";
    } elseif ($only_first) {
        $query .= " LIMIT 1";
    }
    $result = cw_query($query);
    if (!is_array($result) || empty($result)) {
        return false;
    }
    return $only_first ? $result[0] : $result;
}
function view()
{
    global $tables, $smarty;
    $library_stages = cw_query("select {$tables['product_stages_library']}.* from {$tables['product_stages_library']} order by {$tables['product_stages_library']}.pos");
    if (!empty($library_stages)) {
        foreach ($library_stages as $ls_k => $ls_v) {
            if (!empty($ls_v['default_status'])) {
                $library_stages[$ls_k]['default_status'] = unserialize($ls_v['default_status']);
            }
        }
        $smarty->assign('library_stages', $library_stages);
    }
    //    print("cw_product_stages_send_emails ".function_exists('cw\\'.addon_name.'\\cw_product_stages_send_emails'));
    //    cw_call('cw\\'.addon_name.'\\cw_product_stages_send_emails');
    return $library_stages;
}
function cw_ebay_get_categories_list()
{
    global $tables;
    $ebay_categories[] = array("id" => "", "name" => "Not specified");
    $attribute_id = cw_query_first_cell("SELECT attribute_id FROM {$tables['attributes']} WHERE field = 'ebay_category' AND addon = 'ebay'");
    if (!empty($attribute_id)) {
        $categories = cw_query("SELECT value_key, value FROM {$tables['attributes_default']} WHERE attribute_id = {$attribute_id} ORDER BY value");
        if (!empty($categories)) {
            $ebay_categories = array();
            foreach ($categories as $category) {
                $_cats = explode("|", $category['value']);
                $ebay_categories[] = array("id" => $category['value_key'], "name" => $_cats[0]);
            }
        }
    }
    return $ebay_categories;
}
function cw_group_edit_copy_category($product_id, $is_main = true)
{
    global $ge_id, $tables;
    if (!$ge_id) {
        return;
    }
    $main = $is_main ? 1 : 0;
    $current_records = cw_query("select * from " . $tables['products_categories'] . " where product_id='{$product_id}' and main={$main}");
    if (is_array($current_records)) {
        while ($pid = cw_group_edit_each($ge_id, 1, $product_id)) {
            db_query("delete from {$tables['products_categories']} where product_id='{$pid}' and main={$main}");
            foreach ($current_records as $current_record) {
                $current_record['product_id'] = $pid;
                cw_array2insert('products_categories', $current_record, true);
            }
        }
    }
}
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_top_menu_make_sql_query()
{
    global $tables, $app_web_dir;
    cw_load('category');
    $pcats_ = cw_func_call('cw_category_search', array('data' => array('active' => 1, 'all' => 1)));
    $pcats_ = $pcats_[0];
    foreach ($pcats_ as $v) {
        extract($v);
        $mid = 'p' . $category_id;
        $pmid = $parent_id;
        if ($pmid != 0) {
            $pmid = 'p' . $pmid;
        }
        $title = $category;
        $pcount = $product_count_web;
        //$link="$app_web_dir/?target=index&cat=$category_id";
        $link = cw_call('cw_core_get_html_page_url', array(array('var' => 'index', 'cat' => $category_id)));
        $pos = $tm_pos;
        $active = $tm_active;
        $title2 = $tm_title;
        $type = 'pcat';
        if (APP_AREA != 'customer' || $active != 0) {
            $pcats[] = compact('mid', 'pmid', 'title', 'pcount', 'link', 'pos', 'active', 'title2', 'type');
        }
    }
    unset($pcats_);
    $fields = "CONCAT('u',category_id) as mid, CONCAT(parent_id_tag,parent_id) as pmid, category as title,\n";
    $fields .= "0 as pcount, link, pos, active, '' as title2, 'ucat' as type\n";
    if (APP_AREA == 'customer') {
        $where = "where active=1";
    } else {
        $where = "";
    }
    $sql = "select {$fields} from {$tables['top_menu_user_categories']} {$where};";
    $ucats = cw_query($sql);
    $cats = array_merge($pcats, $ucats);
    foreach ($cats as $k => $v) {
        $sorter[$k] = $v['pos'];
    }
    array_multisort($sorter, $cats);
    return $cats;
}
function cw_copy_class($product_option_id, $product_id = false)
{
    global $tables, $ge_id;
    $data['class'] = cw_query_first("SELECT * FROM {$tables['product_options']} WHERE product_option_id = '{$product_option_id}'");
    $data['product_options_values'] = cw_query("SELECT * FROM {$tables['product_options_values']} WHERE product_option_id = '{$product_option_id}'");
    $data['product_options_lng'] = cw_query("select * from {$tables['product_options_lng']} where product_option_id = '{$product_option_id}'");
    $data['product_options_values_lng'] = cw_query("SELECT {$tables['product_options_values_lng']}.* FROM {$tables['product_options_values_lng']}, {$tables['product_options_values']} WHERE {$tables['product_options_values_lng']}.option_id = {$tables['product_options_values']}.option_id AND {$tables['product_options_values']}.product_option_id = '{$product_option_id}'");
    if (empty($product_id)) {
        while ($pid = cw_group_edit_each($ge_id, 1, $product_id)) {
            cw_add_class_data($data, $pid);
        }
    } else {
        if (!is_array($product_id)) {
            $product_id = array($product_id);
        }
        foreach ($product_id as $pid) {
            cw_add_class_data($data, $pid);
        }
    }
}
function ppd_filetype_show()
{
    global $available_fields, $smarty, $tables, $config, $target;
    global $app_catalogs;
    global $page;
    if (!isset($page)) {
        $page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
    }
    $page = (int) $page;
    if ($_SERVER['REQUEST_METHOD'] != 'GET') {
        ppd_filetype_redirect();
    }
    $_new_types =& cw_session_register('_new_types');
    if (!empty($_new_types)) {
        $smarty->assign('_new_types', $_new_types);
        cw_session_unregister('_new_types');
    }
    $limit_types = null;
    $number_types = cw_query_first_cell('SELECT COUNT(type_id) FROM ' . $tables['ppd_types']);
    $navigation = cw_core_get_navigation($target, $number_types, $page);
    $navigation['script'] = "{$app_catalogs['admin']}/index.php?target={$target}";
    $smarty->assign('navigation', $navigation);
    if (isset($navigation['first_page']) && isset($navigation['objects_per_page'])) {
        $limit_types = " LIMIT {$navigation['first_page']}, {$navigation['objects_per_page']}";
    }
    $types = array();
    if (!empty($number_types)) {
        $types = cw_query('SELECT `' . implode('`, `', array_keys($available_fields)) . '` FROM ' . $tables['ppd_types'] . $limit_types);
    }
    if (empty($types) || !is_array($types)) {
        return;
    }
    foreach ($types as $key => $file) {
        $types[$key]['fileicon_exists'] = true;
        $types[$key]['fileicon_url'] = ppd_get_url_fileicon($types[$key]['fileicon']);
        if (empty($types[$key]['fileicon_url'])) {
            $types[$key]['fileicon_exists'] = false;
        }
    }
    $smarty->assign('ppd_types', $types);
}
function tabs_show($tab_type = 'product', $product_id = 0)
{
    global $available_tab_fields, $optional_tab_fields, $tables, $smarty, $top_message;
    global $_pt_addon_tables;
    $product_tabs = array();
    $product_id = (int) $product_id;
    $product_id_condition = null;
    if ($tab_type == 'product') {
        if (empty($product_id)) {
            return;
        }
        $product_id_condition = ' WHERE product_id = \'' . $product_id . '\'';
    }
    $table = $_pt_addon_tables[$tab_type];
    $number_tabs = cw_query_first_cell('SELECT COUNT(tab_id) FROM ' . $tables[$table] . $product_id_condition);
    if (!empty($number_tabs)) {
        $product_tabs = cw_query('
            SELECT `' . implode('`, `', array_keys($available_tab_fields)) . '`
            FROM ' . $tables[$table] . $product_id_condition . '
            ORDER BY `number`' . $limit_tabs);
    }
    if ($tab_type == 'product') {
        $global_tabs = cw_query('
            SELECT `' . implode('`, `', array_keys($available_tab_fields)) . '`, 1=1 as global
            FROM ' . $tables[$_pt_addon_tables['global']] . '
            ORDER BY `number`
        ');
        if (!empty($global_tabs) && is_array($global_tabs)) {
            $product_tabs = array_merge($global_tabs, $product_tabs);
            usort($product_tabs, 'cw_pt_tabs_comparison');
        }
    }
    $_new_tab =& cw_session_register('_new_tab');
    if (!empty($_new_tab)) {
        $smarty->assign('_new_tab', $_new_tab);
        cw_session_unregister('_new_tab');
    }
    $smarty->assign('product_tabs', $product_tabs);
}
function cw_addons_get($parent_addon = '')
{
    global $current_language, $tables;
    $addons = cw_query("select m.*, IFNULL(lng1.value, m.addon) as addon_lng, IFNULL(lng2.value, m.descr) as addon_descr_lng from {$tables['addons']} as m left join {$tables['languages']} as lng1 ON lng1.code = '{$current_language}' and lng1.name = CONCAT('addon_name_', m.addon) left join {$tables['languages']} as lng2 ON lng2.code = '{$current_language}' and lng2.name = CONCAT('addon_descr_', m.addon) where m.parent='{$parent_addon}' order by addon_lng");
    $mod_options = cw_query_column("select {$tables['addons']}.addon from {$tables['addons']}, {$tables['config_categories']} where {$tables['addons']}.addon={$tables['config_categories']}.category group by {$tables['addons']}.addon", "addon");
    foreach ($addons as $k => $v) {
        // cw_get_langvar_by_name provides name and descr including tooltip
        if ($v['addon'] != $v['addon_lng']) {
            $addons[$k]['addon_lng'] = cw_get_langvar_by_name('addon_name_' . $v['addon']);
        }
        if ($v['descr'] != $v['addon_descr_lng']) {
            $addons[$k]['addon_descr_lng'] = cw_get_langvar_by_name('addon_descr_' . $v['addon']);
        }
        if ($parent_id == 0) {
            $addons[$k]['subaddons'] = cw_addons_get($v['addon']);
        }
        if (in_array($v['addon'], $mod_options)) {
            $addons[$k]['options_url'] = true;
        }
    }
    return $addons;
}
function cw_product_shipping_get_options($product_id)
{
    global $tables;
    $shipping_values = cw_query("select * from {$tables['product_shipping_options_values']} where product_id='{$product_id}' order by price asc");
    global $current_area;
    if ($current_area == 'C') {
        if (!empty($shipping_values)) {
            foreach ($shipping_values as $shv_k => $shv_v) {
                $shipping_values[$shv_k]['shipping'] = cw_call('cw_shipping_get', array($shv_v['shipping_id']));
            }
        }
    } else {
        $carriers = cw_shipping_get_carriers(true);
        if (!empty($carriers)) {
            foreach ($carriers as $k => $v) {
                //            $carriers[$k]['total_methods'] = cw_query_first_cell("select count(*) from $tables[shipping] where carrier_id='$v[carrier_id]'");
                //            $carriers[$k]['total_enabled'] = cw_query_first_cell("select count(*) from $tables[shipping] where carrier_id='$v[carrier_id]' and active=1");
                $carriers[$k]['shipping'] = cw_func_call('cw_shipping_search', array('data' => array('carrier_id' => $v['carrier_id'])));
            }
        }
    }
    return array('shipping_options' => $carriers, 'shipping_values' => $shipping_values);
}
function cw_seller_doc_place_order($params, $return)
{
    global $tables, $config, $current_location;
    if (empty($return)) {
        return array();
    }
    if (!empty($return)) {
        foreach ($return as $doc_id) {
            $result = cw_query("\n                SELECT c.warehouse_customer_id, di.product_id, di.amount\n                FROM {$tables['docs']} d\n                LEFT JOIN {$tables['docs_items']} di ON di.doc_id = d.doc_id\n                LEFT JOIN {$tables['docs_info']} c ON c.doc_info_id = d.doc_info_id\n                WHERE d.doc_id = '{$doc_id}'\n            ");
            if (!empty($result)) {
                $seller_products = array();
                foreach ($result as $data) {
                    $seller_products[$data['warehouse_customer_id']][] = array('product_id' => $data['product_id'], 'amount' => $data['amount']);
                }
                foreach ($seller_products as $customer_id => $products) {
                    // send notification email to seller
                    cw_call('cw_seller_doc_place_order_seller_email', array($doc_id, $customer_id, $products));
                }
            }
        }
    }
    return $return;
}
    cw_header_location('index.php?target=logging');
}
$total_items = cw_query_first_cell("select count(*) from {$tables['logged_data']} as ld {$where_string_qry}");
$navigation = cw_core_get_navigation($target, $total_items, $page);
$navigation['script'] = 'index.php?target=' . $target;
$smarty->assign('navigation', $navigation);
$smarty->assign('page', $page);
$limit_qry = " LIMIT {$navigation['first_page']}, {$navigation['objects_per_page']}";
$logged_data = cw_query($s = "select ld.*, IF(ld.customer_id>0,1,0) as is_logged from {$tables['logged_data']} as ld {$where_string_qry} {$orderby_qry} {$limit_qry}");
$session_ids = array();
foreach ($logged_data as $ld_k => $ld_v) {
    $session_ids[$ld_v['cwsid']] = 1;
    $logged_data[$ld_k]['GET_POST'] = unserialize($ld_v['GET_POST']);
}
$smarty->assign('logged_data', $logged_data);
$_sess_data = cw_query("select * from {$tables['logged_data_sessions']} where cwsid in ('" . implode("', '", array_keys($session_ids)) . "')");
$sess_data = array();
foreach ($_sess_data as $s_data) {
    $s_data['SERVER'] = unserialize($s_data['SERVER']);
    $s_data['user_account'] = unserialize($s_data['user_account']);
    $_cwsid = $s_data['cwsid'];
    unset($s_data['cwsid']);
    $sess_data[$_cwsid] = $s_data;
}
$smarty->assign('sess_data', $sess_data);
$unq_target_code = cw_query_column("select distinct target_code from {$tables['logged_data']} as ld", 'target_code');
$smarty->assign('unq_target_code', $unq_target_code);
$_all_arch_files = cw_files_get_dir($var_dirs['logs_archive'], 1, true);
$all_arch_files = array();
foreach ($_all_arch_files as $f_name) {
    if (is_file($f_name)) {
function cw_tabs_get_menu($area)
{
    global $tables, $customer_id, $config;
    $where = '';
    if ($config['Appearance']['categories_in_products'] == '0') {
        $where = " AND nm.link <> 'index.php?target=categories'";
    }
    $items = cw_query("select nm.parent_menu_id, nm.title, nm.link, nm.menu_id from {$tables['navigation_menu']} as nm left join {$tables['addons']} as m on m.addon=nm.addon where (m.active or (m.addon is null and nm.addon='')) and area='{$area}' and is_loggedin & " . ($customer_id ? 1 : 2) . "{$where} order by nm.orderby");
    $menu = cw_tabs_build_tree($items, 0);
    # kornev, some lost items - move it to the top
    # kornev, think here, TOFIX
    //    if ($items) $menu = array_merge($menu, $items);
    return $menu;
}
function cw_get_affiliates_flat($user, $keys_only = false)
{
    global $tables, $config;
    if (!$user) {
        return false;
    }
    $ret = array();
    $childs = cw_query("SELECT * FROM {$tables['customers']} WHERE parent = '{$user}'");
    if ($childs) {
        foreach ($childs as $val) {
            $ret[$val['customer_id']] = $keys_only ? $val['customer_id'] : $val;
            $tmp = cw_get_affiliates($val['customer_id']);
            if ($tmp) {
                foreach ($tmp as $val) {
                    $ret[$val['customer_id']] = $keys_only ? $val['customer_id'] : $val;
                }
            }
        }
    }
    return $ret;
}