<?php


if (!defined('IN_ECS'))
{
    die('Hacking attempt');
}

/**
 * 获得所有模块的名称以及链接地址
 *
 * @access      public
 * @param       string      $directory      插件存放的目录
 * @return      array
 */
function read_modules($directory = '.')
{
    global $_LANG;

    $dir         = @opendir($directory);
    $set_modules = true;
    $modules     = array();

    while (false !== ($file = @readdir($dir)))
    {
        if (preg_match("/^.*?\.php$/", $file))
        {
            include_once($directory. '/' .$file);
        }
    }
    @closedir($dir);
    unset($set_modules);

    foreach ($modules AS $key => $value)
    {
        ksort($modules[$key]);
    }
    ksort($modules);

    return $modules;
}

/**
 * 系统提示信息
 *
 * @access      public
 * @param       string      msg_detail      消息内容
 * @param       int         msg_type        消息类型， 0消息，1错误，2询问
 * @param       array       links           可选的链接
 * @param       boolen      $auto_redirect  是否需要自动跳转
 * @return      void
 */
function sys_msg($msg_detail, $msg_type = 0, $links = array(), $auto_redirect = true)
{
    if (count($links) == 0)
    {
        $links[0]['text'] = $GLOBALS['_LANG']['go_back'];
        $links[0]['href'] = 'javascript:history.go(-1)';
    }
    assign_menu_info();
    assign_query_info();

    $GLOBALS['smarty']->assign('ur_here',     $GLOBALS['_LANG']['system_message']);
    $GLOBALS['smarty']->assign('msg_detail',  $msg_detail);
    $GLOBALS['smarty']->assign('msg_type',    $msg_type);
    $GLOBALS['smarty']->assign('links',       $links);
    $GLOBALS['smarty']->assign('default_url', $links[0]['href']);
    $GLOBALS['smarty']->assign('auto_redirect', $auto_redirect);

    $GLOBALS['smarty']->display('message.htm');

    exit;
}

/**
 * 记录管理员的操作内容
 *
 * @access  public
 * @param   string      $sn         数据的唯一值
 * @param   string      $action     操作的类型
 * @param   string      $content    操作的内容
 * @return  void
 */
function admin_log($sn = '', $action, $content)
{
    $log_info = $GLOBALS['_LANG']['log_action'][$action] . $GLOBALS['_LANG']['log_action'][$content] .': '. addslashes($sn);

    $sql = 'INSERT INTO ' . $GLOBALS['ecs']->table('admin_log') . ' (log_time, user_id, log_info, ip_address) ' .
            " VALUES ('" . gmtime() . "', $_SESSION[admin_id], '" . stripslashes($log_info) . "', '" . real_ip() . "')";
    $GLOBALS['db']->query($sql);
}

/**
 * 将通过表单提交过来的年月日变量合成为"2004-05-10"的格式。
 *
 * 此函数适用于通过smarty函数html_select_date生成的下拉日期。
 *
 * @param  string $prefix      年月日变量的共同的前缀。
 * @return date                日期变量。
 */
function sys_joindate($prefix)
{
    /* 返回年-月-日的日期格式 */
    $year  = empty($_POST[$prefix . 'Year']) ? '0' :  $_POST[$prefix . 'Year'];
    $month = empty($_POST[$prefix . 'Month']) ? '0' : $_POST[$prefix . 'Month'];
    $day   = empty($_POST[$prefix . 'Day']) ? '0' : $_POST[$prefix . 'Day'];

    return $year . '-' . $month . '-' . $day;
}

/**
 * 设置管理员的session内容
 *
 * @access  public
 * @param   integer $user_id        管理员编号
 * @param   string  $username       管理员姓名
 * @param   string  $action_list    权限列表
 * @param   string  $last_time      最后登录时间
 * @return  void
 */
function set_admin_session($user_id, $username, $action_list, $last_time)
{
    $_SESSION['admin_id']    = $user_id;
    $_SESSION['admin_name']  = $username;
    $_SESSION['action_list'] = $action_list;
    $_SESSION['last_check']  = $last_time; // 用于保存最后一次检查订单的时间
}

/**
 * 插入一个配置信息
 *
 * @access  public
 * @param   string      $parent     分组的code
 * @param   string      $code       该配置信息的唯一标识
 * @param   string      $value      该配置信息值
 * @return  void
 */
function insert_config($parent, $code, $value)
{
    global $ecs, $db, $_LANG;

    $sql = 'SELECT id FROM ' . $ecs->table('shop_config') . " WHERE code = '$parent' AND type = 1";
    $parent_id = $db->getOne($sql);

    $sql = 'INSERT INTO ' . $ecs->table('shop_config') . ' (parent_id, code, value) ' .
            "VALUES('$parent_id', '$code', '$value')";
    $db->query($sql);
}

/**
 * 判断管理员对某一个操作是否有权限。
 *
 * 根据当前对应的action_code，然后再和用户session里面的action_list做匹配，以此来决定是否可以继续执行。
 * @param     string    $priv_str    操作对应的priv_str
 * @param     string    $msg_type       返回的类型
 * @return true/false
 */
function admin_priv($priv_str, $msg_type = '' , $msg_output = true)
{
    global $_LANG;

    if ($_SESSION['supplier_action_list'] == 'all')
    {
        return true;
    }

    if (strpos(',' . $_SESSION['supplier_action_list'] . ',', ',' . $priv_str . ',') === false)
    {
        $link[] = array('text' => $_LANG['go_back'], 'href' => 'javascript:history.back(-1)');
        if ( $msg_output)
        {
            sys_msg($_LANG['priv_error'], 0, $link);
        }
        return false;
    }
    else
    {
        return true;
    }
}

/**
 * 检查管理员权限
 *
 * @access  public
 * @param   string  $authz
 * @return  boolean
 */
function check_authz($authz)
{
    return (preg_match('/,*'.$authz.',*/', $_SESSION['supplier_action_list']) || $_SESSION['supplier_action_list'] == 'all');
}

/**
 * 检查管理员权限，返回JSON格式数剧
 *
 * @access  public
 * @param   string  $authz
 * @return  void
 */
function check_authz_json($authz)
{
    if (!check_authz($authz))
    {
        make_json_error($GLOBALS['_LANG']['priv_error']);
    }
}

/**
 * 取得红包类型数组（用于生成下拉列表）
 *
 * @return  array       分类数组 bonus_typeid => bonus_type_name
 */
function get_bonus_type()
{
    $bonus = array();
    $sql = 'SELECT type_id, type_name, type_money FROM ' . $GLOBALS['ecs']->table('bonus_type') .
           ' WHERE send_type = 3 AND supplier_id='.$_SESSION['supplier_id'];
    $res = $GLOBALS['db']->query($sql);

    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $bonus[$row['type_id']] = $row['type_name'].' [' .sprintf($GLOBALS['_CFG']['currency_format'], $row['type_money']).']';
    }

    return $bonus;
}

/**
 * 取得用户等级数组,按用户级别排序
 * @param   bool      $is_special      是否只显示特殊会员组
 * @return  array     rank_id=>rank_name
 */
function get_rank_list($is_special = false)
{
    $rank_list = array();
    $sql = 'SELECT rank_id, rank_name, min_points FROM ' . $GLOBALS['ecs']->table('user_rank');
    if ($is_special)
    {
        $sql .= ' WHERE special_rank = 1';
    }
    $sql .= ' ORDER BY min_points';

    $res = $GLOBALS['db']->query($sql);

    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $rank_list[$row['rank_id']] = $row['rank_name'];
    }

    return $rank_list;
}

/**
 * 按等级取得用户列表（用于生成下拉列表）
 *
 * @return  array       分类数组 user_id => user_name
 */
function get_user_rank($rankid, $where)
{
    $user_list = array();
    $sql = 'SELECT user_id, user_name FROM ' . $GLOBALS['ecs']->table('users') . $where.
           ' ORDER BY user_id DESC';
    $res = $GLOBALS['db']->query($sql);

    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $user_list[$row['user_id']] = $row['user_name'];
    }

    return $user_list;
}

/**
 * 取得广告位置数组（用于生成下拉列表）
 *
 * @return  array       分类数组 position_id => position_name
 */
function get_position_list()
{
    $position_list = array();
    $sql = 'SELECT position_id, position_name, ad_width, ad_height '.
           'FROM ' . $GLOBALS['ecs']->table('ad_position');
    $res = $GLOBALS['db']->query($sql);

    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $position_list[$row['position_id']] = addslashes($row['position_name']). ' [' .$row['ad_width']. 'x' .$row['ad_height']. ']';
    }

    return $position_list;
}

/**
 * 生成编辑器
 * @param   string  input_name  输入框名称
 * @param   string  input_value 输入框值
 */
function create_html_editor($input_name, $input_value = '')
{
    global $smarty;
    /* 修改 by www.68ecshop.com 百度编辑器 begin */
    $HTML='
    <script type="text/javascript" charset="utf-8" src="../includes/ueditor/ueditor.config.js"></script>
    <script type="text/javascript" charset="utf-8" src="../includes/ueditor/ueditor.all.js"></script>
    <textarea name="'.$input_name.'" id="'.$input_name.'" style="width:100%;">'.$input_value.'</textarea>
    <script type="text/javascript">
    UE.getEditor("'.$input_name.'",{
    theme:"default", //皮肤
    lang:"zh-cn",    //语言
    initialFrameWidth:900,  //初始化编辑器宽度,默认650
    initialFrameHeight:330  //初始化编辑器高度,默认180
    });
    </script>';
    $smarty->assign('FCKeditor', $HTML);
    /* 修改 by www.68ecshop.com 百度编辑器 end */
}


/**
 * 取得商品列表：用于把商品添加到组合、关联类、赠品类
 * @param   object  $filters    过滤条件
 */
function get_goods_list($filter)
{
    $filter->keyword = json_str_iconv($filter->keyword);
    $where = get_where_sql($filter); // 取得过滤条件
    
    $suppid = (isset($_GET['suppId']) && intval($_GET['suppId'])>0) ? intval($_GET['suppId']) : $_SESSION['supplier_id'];
    
    $where .= ' AND sgc.supplier_id='.$suppid.' group by g.goods_id ';

    /* 取得数据 */
   // $sql = 'SELECT goods_id, goods_name, shop_price '.
     //      'FROM ' . $GLOBALS['ecs']->table('goods') . ' AS g ' . $where .
      //     'LIMIT 50';
    
    $sql = 'select g.goods_id,g.goods_name,g.shop_price '.
           'from ' . $GLOBALS['ecs']->table('supplier_goods_cat') . 'as sgc '.
           'left join ' . $GLOBALS['ecs']->table('goods') . 'as g on sgc.goods_id = g.goods_id' . $where.
           'LIMIT 50';

    $row = $GLOBALS['db']->getAll($sql);
    return $row;
}

/**
 * 取得文章列表：用于商品关联文章
 * @param   object  $filters    过滤条件
 */
function get_article_list($filter)
{
    /* 创建数据容器对象 */
    $ol = new OptionList();

    /* 取得过滤条件 */
    $where = ' WHERE a.cat_id = c.cat_id AND c.cat_type = 1 ';
    $where .= isset($filter->title) ? " AND a.title LIKE '%" . mysql_like_quote($filter->title) . "%'" : '';

    /* 取得数据 */
    $sql = 'SELECT a.article_id, a.title '.
           'FROM ' .$GLOBALS['ecs']->table('article'). ' AS a, ' .$GLOBALS['ecs']->table('article_cat'). ' AS c ' . $where;
    $res = $GLOBALS['db']->query($sql);

    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $ol->add_option($row['article_id'], $row['title']);
    }

    /* 生成列表 */
    $ol->build_select();
}

/**
 * 返回是否
 * @param   int     $var    变量 1, 0
 */
function get_yes_no($var)
{
    return empty($var) ? '<img src="images/no.gif" border="0" />' : '<img src="images/yes.gif" border="0" />';
}

/**
 * 生成过滤条件：用于 get_goodslist 和 get_goods_list
 * @param   object  $filter
 * @return  string
 */
function get_where_sql($filter)
{
	
    $time = date('Y-m-d');

    $where  = isset($filter->is_delete) && $filter->is_delete == '1' ?
        ' WHERE is_delete = 1 ' : ' WHERE is_delete = 0 ';
    $where .= (isset($filter->real_goods) && ($filter->real_goods > -1)) ? ' AND is_real = ' . intval($filter->real_goods) : '';
    $where .= isset($filter->cat_id) && $filter->cat_id > 0 ? ' AND ' . get_children_supplier($filter->cat_id) : '';
    $where .= isset($filter->brand_id) && $filter->brand_id > 0 ? " AND brand_id = '" . $filter->brand_id . "'" : '';
    $where .= isset($filter->intro_type) && $filter->intro_type != '0' ? ' AND ' . $filter->intro_type . " = '1'" : '';
    $where .= isset($filter->intro_type) && $filter->intro_type == 'is_promote' ?
        " AND promote_start_date <= '$time' AND promote_end_date >= '$time' " : '';
    $where .= isset($filter->keyword) && trim($filter->keyword) != '' ?
        " AND (goods_name LIKE '%" . mysql_like_quote($filter->keyword) . "%' OR goods_sn LIKE '%" . mysql_like_quote($filter->keyword) . "%' OR g.goods_id LIKE '%" . mysql_like_quote($filter->keyword) . "%') " : '';
    $where .= isset($filter->suppliers_id) && trim($filter->suppliers_id) != '' ?
        " AND (g.suppliers_id = '" . $filter->suppliers_id . "') " : '';

    $where .= isset($filter->in_ids) ? ' AND goods_id ' . db_create_in($filter->in_ids) : '';
    $where .= isset($filter->exclude) ? ' AND goods_id NOT ' . db_create_in($filter->exclude) : '';
    $where .= isset($filter->stock_warning) ? ' AND goods_number <= warn_number' : '';

    return $where;
}

/**
 * 获取地区列表的函数。
 *
 * @access  public
 * @param   int     $region_id  上级地区id
 * @return  void
 */
function area_list($region_id)
{
    $area_arr = array();

    $sql = 'SELECT * FROM ' . $GLOBALS['ecs']->table('region').
           " WHERE parent_id = '$region_id' ORDER BY region_id";
    $res = $GLOBALS['db']->query($sql);
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $row['type']  = ($row['region_type'] == 0) ? $GLOBALS['_LANG']['country']  : '';
        $row['type'] .= ($row['region_type'] == 1) ? $GLOBALS['_LANG']['province'] : '';
        $row['type'] .= ($row['region_type'] == 2) ? $GLOBALS['_LANG']['city']     : '';
        $row['type'] .= ($row['region_type'] == 3) ? $GLOBALS['_LANG']['cantonal'] : '';

        $area_arr[] = $row;
    }

    return $area_arr;
}

/**
 * 取得图表颜色
 *
 * @access  public
 * @param   integer $n  颜色顺序
 * @return  void
 */
function chart_color($n)
{
    /* 随机显示颜色代码 */
    $arr = array('33FF66', 'FF6600', '3399FF', '009966', 'CC3399', 'FFCC33', '6699CC', 'CC3366', '33FF66', 'FF6600', '3399FF');

    if ($n > 8)
    {
        $n = $n % 8;
    }

    return $arr[$n];
}

/**
 * 获得商品类型的列表
 *
 * @access  public
 * @param   integer     $selected   选定的类型编号
 * @return  string
 */
function goods_type_list($selected)
{
    $sql = 'SELECT cat_id, cat_name FROM ' . $GLOBALS['ecs']->table('goods_type') . ' WHERE enabled = 1';
    $res = $GLOBALS['db']->query($sql);

    $lst = '';
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        $lst .= "<option value='$row[cat_id]'";
        $lst .= ($selected == $row['cat_id']) ? ' selected="true"' : '';
        $lst .= '>' . htmlspecialchars($row['cat_name']). '</option>';
    }

    return $lst;
}


/**
 * 清空表数据
 * @param   string  $table_name 表名称
 */
function truncate_table($table_name)
{
    $sql = 'TRUNCATE TABLE ' .$GLOBALS['ecs']->table($table_name);

    return $GLOBALS['db']->query($sql);
}

/**
 *  返回字符集列表数组
 *
 * @access  public
 * @param
 *
 * @return void
 */
function get_charset_list()
{
    return array(
        'UTF8'   => 'UTF-8',
        'GB2312' => 'GB2312/GBK',
        'BIG5'   => 'BIG5',
    );
}


/**
 * 创建一个JSON格式的数据
 *
 * @access  public
 * @param   string      $content
 * @param   integer     $error
 * @param   string      $message
 * @param   array       $append
 * @return  void
 */
function make_json_response($content='', $error="0", $message='', $append=array())
{
    include_once(ROOT_PATH . 'includes/cls_json.php');

    $json = new JSON;

    $res = array('error' => $error, 'message' => $message, 'content' => $content);

    if (!empty($append))
    {
        foreach ($append AS $key => $val)
        {
            $res[$key] = $val;
        }
    }

    $val = $json->encode($res);

    exit($val);
}

/**
 *
 *
 * @access  public
 * @param
 * @return  void
 */
function make_json_result($content, $message='', $append=array())
{
    make_json_response($content, 0, $message, $append);
}

/**
 * 创建一个JSON格式的错误信息
 *
 * @access  public
 * @param   string  $msg
 * @return  void
 */
function make_json_error($msg)
{
    make_json_response('', 1, $msg);
}

/**
 * 根据过滤条件获得排序的标记
 *
 * @access  public
 * @param   array   $filter
 * @return  array
 */
function sort_flag($filter)
{
    $flag['tag']    = 'sort_' . preg_replace('/^.*\./', '', $filter['sort_by']);
    $flag['img']    = '<img src="images/' . ($filter['sort_order'] == "DESC" ? 'sort_desc.gif' : 'sort_asc.gif') . '"/>';

    return $flag;
}

/**
 * 分页的信息加入条件的数组
 *
 * @access  public
 * @return  array
 */
function page_and_size($filter)
{
    if (isset($_REQUEST['page_size']) && intval($_REQUEST['page_size']) > 0)
    {
        $filter['page_size'] = intval($_REQUEST['page_size']);
    }
    elseif (isset($_COOKIE['ECSCP']['page_size']) && intval($_COOKIE['ECSCP']['page_size']) > 0)
    {
        $filter['page_size'] = intval($_COOKIE['ECSCP']['page_size']);
    }
    else
    {
        $filter['page_size'] = 15;
    }

    /* 每页显示 */
    $filter['page'] = (empty($_REQUEST['page']) || intval($_REQUEST['page']) <= 0) ? 1 : intval($_REQUEST['page']);

    /* page 总数 */
    $filter['page_count'] = (!empty($filter['record_count']) && $filter['record_count'] > 0) ? ceil($filter['record_count'] / $filter['page_size']) : 1;

    /* 边界处理 */
    if ($filter['page'] > $filter['page_count'])
    {
        $filter['page'] = $filter['page_count'];
    }

    $filter['start'] = ($filter['page'] - 1) * $filter['page_size'];

    return $filter;
}

/**
 *  将含有单位的数字转成字节
 *
 * @access  public
 * @param   string      $val        带单位的数字
 *
 * @return  int         $val
 */
function return_bytes($val)
{
    $val = trim($val);
    $last = strtolower($val{strlen($val)-1});
    switch($last)
    {
        case 'g':
            $val *= 1024;
        case 'm':
            $val *= 1024;
        case 'k':
            $val *= 1024;
    }

    return $val;
}

/**
 * 获得指定的商品类型下所有的属性分组
 *
 * @param   integer     $cat_id     商品类型ID
 *
 * @return  array
 */
function get_attr_groups($cat_id)
{
    $sql = "SELECT attr_group FROM " . $GLOBALS['ecs']->table('goods_type') . " WHERE cat_id='$cat_id'";
    $grp = str_replace("\r", '', $GLOBALS['db']->getOne($sql));

    if ($grp)
    {
        return explode("\n", $grp);
    }
    else
    {
        return array();
    }
}

/**
 * 生成链接后缀
 */
function list_link_postfix()
{
    return 'uselastfilter=1';
}

/**
 * 保存过滤条件
 * @param   array   $filter     过滤条件
 * @param   string  $sql        查询语句
 * @param   string  $param_str  参数字符串，由list函数的参数组成
 */
function set_filter($filter, $sql, $param_str = '')
{
    $filterfile = basename(PHP_SELF, '.php');
    if ($param_str)
    {
        $filterfile .= $param_str;
    }
    setcookie('ECSCP[lastfilterfile]', sprintf('%X', crc32($filterfile)), time() + 600);
    setcookie('ECSCP[lastfilter]',     urlencode(serialize($filter)), time() + 600);
    setcookie('ECSCP[lastfiltersql]',  base64_encode($sql), time() + 600);
}

/**
 * 取得上次的过滤条件
 * @param   string  $param_str  参数字符串，由list函数的参数组成
 * @return  如果有，返回array('filter' => $filter, 'sql' => $sql)；否则返回false
 */
function get_filter($param_str = '')
{
    $filterfile = basename(PHP_SELF, '.php');
    if ($param_str)
    {
        $filterfile .= $param_str;
    }
    if (isset($_GET['uselastfilter']) && isset($_COOKIE['ECSCP']['lastfilterfile'])
        && $_COOKIE['ECSCP']['lastfilterfile'] == sprintf('%X', crc32($filterfile)))
    {
        return array(
            'filter' => unserialize(urldecode($_COOKIE['ECSCP']['lastfilter'])),
            'sql'    => base64_decode($_COOKIE['ECSCP']['lastfiltersql'])
        );
    }
    else
    {
        return false;
    }
}

/**
 * URL过滤
 * @param   string  $url  参数字符串，一个urld地址,对url地址进行校正
 * @return  返回校正过的url;
 */
function sanitize_url($url , $check = 'http://')
{
    if (strpos( $url, $check ) === false)
    {
        $url = $check . $url;
    }
    return $url;
}

/**
 * 检查分类是否已经存在
 *
 * @param   string      $cat_name       分类名称
 * @param   integer     $parent_cat     上级分类
 * @param   integer     $exclude        排除的分类ID
 *
 * @return  boolean
 */
function cat_exists($cat_name, $parent_cat, $exclude = 0)
{
    $sql = "SELECT COUNT(*) FROM " .$GLOBALS['ecs']->table('category').
    " WHERE parent_id = '$parent_cat' AND cat_name = '$cat_name' AND cat_id<>'$exclude'";
    return ($GLOBALS['db']->getOne($sql) > 0) ? true : false;
}

function brand_exists($brand_name)
{
    $sql = "SELECT COUNT(*) FROM " .$GLOBALS['ecs']->table('brand').
    " WHERE brand_name = '" . $brand_name . "'";
    return ($GLOBALS['db']->getOne($sql) > 0) ? true : false;
}

/**
 * 获取当前管理员信息
 *
 * @access  public
 * @param
 *
 * @return  Array
 */
function admin_info()
{
    $sql = "SELECT * FROM ". $GLOBALS['ecs']->table('admin_user')."
            WHERE user_id = '$_SESSION[admin_id]'
            LIMIT 0, 1";
    $admin_info = $GLOBALS['db']->getRow($sql);

    if (empty($admin_info))
    {
        return $admin_info = array();
    }

    return $admin_info;
}

/**
 * 供货商列表信息
 *
 * @param       string      $conditions
 * @return      array
 */
function suppliers_list_info($conditions = '')
{
    $where = '';
    if (!empty($conditions))
    {
        $where .= 'WHERE ';
        $where .= $conditions;
    }

    /* 查询 */
    $sql = "SELECT suppliers_id, suppliers_name, suppliers_desc
            FROM " . $GLOBALS['ecs']->table("suppliers") . "
            $where";

    return $GLOBALS['db']->getAll($sql);
}

/**
 * 供货商名
 *
 * @return  array
 */
function suppliers_list_name()
{
    /* 查询 */
    $suppliers_list = suppliers_list_info(' is_check = 1 ');

    /* 供货商名字 */
    $suppliers_name = array();
    if (count($suppliers_list) > 0)
    {
        foreach ($suppliers_list as $suppliers)
        {
            $suppliers_name[$suppliers['suppliers_id']] = $suppliers['suppliers_name'];
        }
    }

    return $suppliers_name;
}

/**
 * 获得指定分类下的子分类的数组
 *
 * @access  public
 * @param   int     $cat_id     分类的ID
 * @param   int     $selected   当前选中分类的ID
 * @param   boolean $re_type    返回的类型: 值为真时返回下拉列表,否则返回数组
 * @param   int     $level      限定返回的级数。为0时返回所有级数
 * @param   int     $is_show_all 如果为true显示所有分类，如果为false隐藏不可见分类。
 * @return  mix
 */
function cat_list_2($cat_id = 0, $selected = 0, $re_type = true, $level = 0, $is_show_all = true)
{
    static $res = NULL;

    if ($res === NULL)
    {
        
            $sql = "SELECT c.cat_id, c.cat_name, c.measure_unit, c.parent_id, c.is_show, c.show_in_nav, c.grade, c.sort_order, COUNT(s.cat_id) AS has_children ".
                'FROM ' . $GLOBALS['ecs']->table('supplier_category') . " AS c ".
                "LEFT JOIN " . $GLOBALS['ecs']->table('supplier_category') . " AS s ON s.parent_id=c.cat_id  where c.supplier_id = ".$_SESSION['supplier_id'].
                " GROUP BY c.cat_id ".
                'ORDER BY c.parent_id, c.sort_order ASC';
            $res = $GLOBALS['db']->getAll($sql);

            /*$sql = "SELECT cat_id, COUNT(*) AS goods_num " .
                    " FROM " . $GLOBALS['ecs']->table('goods') .
                    " WHERE supplier_id = ".$_SESSION['supplier_id']." AND is_delete = 0 AND is_on_sale = 1 " .
                    " GROUP BY cat_id";
            $res2 = $GLOBALS['db']->getAll($sql);*/

            $sql = "SELECT gc.cat_id, COUNT(*) AS goods_num " .
                    " FROM " . $GLOBALS['ecs']->table('supplier_goods_cat') . " AS gc , " . $GLOBALS['ecs']->table('goods') . " AS g " .
                    " WHERE gc.supplier_id = ".$_SESSION['supplier_id']." AND g.goods_id = gc.goods_id AND g.is_delete = 0 AND g.is_on_sale = 1 " .
                    " GROUP BY gc.cat_id";
            $res3 = $GLOBALS['db']->getAll($sql);

            $newres = array();
            //foreach($res2 as $k=>$v)
            //{
                //$newres[$v['cat_id']] = $v['goods_num'];
                foreach($res3 as $ks=>$vs)
                {
                	$newres[$vs['cat_id']] = $vs['goods_num'];
                   // if($v['cat_id'] == $vs['cat_id'])
                    //{
                    //$newres[$v['cat_id']] = $v['goods_num'] + $vs['goods_num'];
                   // }
                }
            //}

            foreach($res as $k=>$v)
            {
                $res[$k]['goods_num'] = !empty($newres[$v['cat_id']]) ? $newres[$v['cat_id']] : 0;
            }
        
    }

    if (empty($res) == true)
    {
        return $re_type ? '' : array();
    }

    $options = cat_options_2($cat_id, $res); // 获得指定分类下的子分类的数组

    $children_level = 99999; //大于这个分类的将被删除
    if ($is_show_all == false)
    {
        foreach ($options as $key => $val)
        {
            if ($val['level'] > $children_level)
            {
                unset($options[$key]);
            }
            else
            {
                if ($val['is_show'] == 0)
                {
                    unset($options[$key]);
                    if ($children_level > $val['level'])
                    {
                        $children_level = $val['level']; //标记一下，这样子分类也能删除
                    }
                }
                else
                {
                    $children_level = 99999; //恢复初始值
                }
            }
        }
    }

    /* 截取到指定的缩减级别 */
    if ($level > 0)
    {
        if ($cat_id == 0)
        {
            $end_level = $level;
        }
        else
        {
            $first_item = reset($options); // 获取第一个元素
            $end_level  = $first_item['level'] + $level;
        }

        /* 保留level小于end_level的部分 */
        foreach ($options AS $key => $val)
        {
            if ($val['level'] >= $end_level)
            {
                unset($options[$key]);
            }
        }
    }

    if ($re_type == true)
    {
        $select = '';
        foreach ($options AS $var)
        {
            $select .= '<option value="' . $var['cat_id'] . '" ';
            $select .= ($selected == $var['cat_id']) ? "selected='ture'" : '';
            $select .= '>';
            if ($var['level'] > 0)
            {
                $select .= str_repeat('&nbsp;', $var['level'] * 4);
            }
            $select .= htmlspecialchars(addslashes($var['cat_name']), ENT_QUOTES) . '</option>';
        }

        return $select;
    }
    else
    {
        foreach ($options AS $key => $value)
        {
            $options[$key]['url'] = build_uri('supplier', array('go'=>'category','suppid'=>$_SESSION['supplier_id'],'cid' => $value['cat_id']), $value['cat_name']);
        }

        return $options;
    }
}

/**
 * 过滤和排序所有分类，返回一个带有缩进级别的数组
 *
 * @access  private
 * @param   int     $cat_id     上级分类ID
 * @param   array   $arr        含有所有分类的数组
 * @param   int     $level      级别
 * @return  void
 */
function cat_options_2($spec_cat_id, $arr)
{
    static $cat_options = array();

    if (isset($cat_options[$spec_cat_id]))
    {
        return $cat_options[$spec_cat_id];
    }

    if (!isset($cat_options[0]))
    {
        $level = $last_cat_id = 0;
        $options = $cat_id_array = $level_array = array();
        
            while (!empty($arr))
            {
                foreach ($arr AS $key => $value)
                {
                    $cat_id = $value['cat_id'];
                    if ($level == 0 && $last_cat_id == 0)
                    {
                        if ($value['parent_id'] > 0)
                        {
                            break;
                        }

                        $options[$cat_id]          = $value;
                        $options[$cat_id]['level'] = $level;
                        $options[$cat_id]['id']    = $cat_id;
                        $options[$cat_id]['name']  = $value['cat_name'];
                        unset($arr[$key]);

                        if ($value['has_children'] == 0)
                        {
                            continue;
                        }
                        $last_cat_id  = $cat_id;
                        $cat_id_array = array($cat_id);
                        $level_array[$last_cat_id] = ++$level;
                        continue;
                    }

                    if ($value['parent_id'] == $last_cat_id)
                    {
                        $options[$cat_id]          = $value;
                        $options[$cat_id]['level'] = $level;
                        $options[$cat_id]['id']    = $cat_id;
                        $options[$cat_id]['name']  = $value['cat_name'];
                        unset($arr[$key]);

                        if ($value['has_children'] > 0)
                        {
                            if (end($cat_id_array) != $last_cat_id)
                            {
                                $cat_id_array[] = $last_cat_id;
                            }
                            $last_cat_id    = $cat_id;
                            $cat_id_array[] = $cat_id;
                            $level_array[$last_cat_id] = ++$level;
                        }
                    }
                    elseif ($value['parent_id'] > $last_cat_id)
                    {
                        break;
                    }
                }

                $count = count($cat_id_array);
                if ($count > 1)
                {
                    $last_cat_id = array_pop($cat_id_array);
                }
                elseif ($count == 1)
                {
                    if ($last_cat_id != end($cat_id_array))
                    {
                        $last_cat_id = end($cat_id_array);
                    }
                    else
                    {
                        $level = 0;
                        $last_cat_id = 0;
                        $cat_id_array = array();
                        continue;
                    }
                }

                if ($last_cat_id && isset($level_array[$last_cat_id]))
                {
                    $level = $level_array[$last_cat_id];
                }
                else
                {
                    $level = 0;
                }
            }
            
        $cat_options[0] = $options;
    }
    else
    {
        $options = $cat_options[0];
    }

    if (!$spec_cat_id)
    {
        return $options;
    }
    else
    {
        if (empty($options[$spec_cat_id]))
        {
            return array();
        }

        $spec_cat_id_level = $options[$spec_cat_id]['level'];

        foreach ($options AS $key => $value)
        {
            if ($key != $spec_cat_id)
            {
                unset($options[$key]);
            }
            else
            {
                break;
            }
        }

        $spec_cat_id_array = array();
        foreach ($options AS $key => $value)
        {
            if (($spec_cat_id_level == $value['level'] && $value['cat_id'] != $spec_cat_id) ||
                ($spec_cat_id_level > $value['level']))
            {
                break;
            }
            else
            {
                $spec_cat_id_array[$key] = $value;
            }
        }
        $cat_options[$spec_cat_id] = $spec_cat_id_array;

        return $spec_cat_id_array;
    }
}

/**
* 为每一个创建店铺的商家创建基本信息的保存记录，如果之前没有创建过
* 
*/
function create_shop_settiongs()
{
	global $db, $ecs, $_LANG;
	
	if(!isset($_SESSION['supplier_id']) || intval($_SESSION['supplier_id'])<=0){
		return;
	}
	
	$sql = "SELECT count(id) FROM " . $ecs->table('supplier_shop_config') ." WHERE supplier_id=".$_SESSION['supplier_id'];
	$num = $db->getOne($sql);
	if($num>0){
		return;
	}else{
		$insql = "INSERT INTO ". $ecs->table('supplier_shop_config') ." (`id`, `parent_id`, `code`, `type`, `store_range`, `store_dir`, `value`, `sort_order`, `supplier_id`) VALUES
				(1, 0, 'shop_info', 'group', '', '', '', 1, ".$_SESSION['supplier_id']."),
				(2, 0, 'hidden', 'hidden', '', '', '', 1, ".$_SESSION['supplier_id']."),
				(8, 0, 'sms', 'group', '', '', '', 1, ".$_SESSION['supplier_id']."),
				(101, 1, 'shop_name', 'text', '', '', '商家店铺名称', 1, ".$_SESSION['supplier_id']."),
				(102, 1, 'shop_title', 'text', '', '', '商家店铺标题', 1, ".$_SESSION['supplier_id']."),
				(103, 1, 'shop_desc', 'hidden', '', '', '商家店铺描述', 1, ".$_SESSION['supplier_id']."),
				(104, 1, 'shop_keywords', 'text', '', '', '商家店铺关键字', 1, ".$_SESSION['supplier_id']."),
				(105, 1, 'shop_country', 'manual', '', '', '1', 1, ".$_SESSION['supplier_id']."),
				(106, 1, 'shop_province', 'manual', '', '', '0', 2, ".$_SESSION['supplier_id']."),
				(107, 1, 'shop_city', 'manual', '', '', '0', 52, ".$_SESSION['supplier_id']."),
				(108, 1, 'shop_address', 'text', '', '', '', 1, ".$_SESSION['supplier_id']."),
				(109, 1, 'qq', 'text', '', '', '', 1, ".$_SESSION['supplier_id']."),
				(110, 1, 'ww', 'text', '', '', '', 1, ".$_SESSION['supplier_id']."),
				(111, 1, 'skype', 'hidden', '', '', '', 1, ".$_SESSION['supplier_id']."),
				(112, 1, 'ym', 'hidden', '', '', '', 1, ".$_SESSION['supplier_id']."),
				(113, 1, 'msn', 'hidden', '', '', '', 1, ".$_SESSION['supplier_id']."),
				(114, 1, 'service_email', 'text', '', '', '', 1, ".$_SESSION['supplier_id']."),
				(115, 1, 'service_phone', 'text', '', '', '', 1, ".$_SESSION['supplier_id']."),
				(116, 1, 'shop_closed', 'select', '0,1', '', '0', 1, ".$_SESSION['supplier_id']."),
				(117, 1, 'close_comment', 'hidden', '', '', '', 1, ".$_SESSION['supplier_id']."),
				(118, 1, 'shop_logo', 'file', '', '../themes/".'{$template}'."/images/', '', 1, ".$_SESSION['supplier_id']."),
				(119, 1, 'licensed', 'hidden', '0,1', '', '1', 1, ".$_SESSION['supplier_id']."),
				(120, 1, 'user_notice', 'hidden', '', '', '用户中心公告！', 1, ".$_SESSION['supplier_id']."),
				(121, 1, 'shop_notice', 'textarea', '', '', '商家店铺介绍:欢迎光临手机网,我们的宗旨：诚信经营、服务客户！\r\n<MARQUEE onmouseover=this.stop() onmouseout=this.start() \r\nscrollAmount=3><U><FONT color=red>\r\n<P>咨询电话010-10124444  010-21252454 8465544</P></FONT></U></MARQUEE>', 1, ".$_SESSION['supplier_id']."),
				(122, 1, 'shop_reg_closed', 'hidden', '1,0', '', '0', 1, ".$_SESSION['supplier_id']."),
				(123, 1, 'shop_index_num', 'textarea', '', '', '8\r\n6\r\n4', 1, ".$_SESSION['supplier_id']."),
				(124, 1, 'shop_search_price', 'textarea', '', '', '0-1000元\r\n1000-2000元\r\n2000-4000元', 1, ".$_SESSION['supplier_id']."),
				(125, 1, 'close_comment', 'textarea', '', '', '该店铺正在装修', 1, ".$_SESSION['supplier_id']."),
				(201, 2, 'shop_header_color', 'hidden', '', '', '#E4368F', 1, ".$_SESSION['supplier_id']."),
				(202, 2, 'shop_header_text', 'hidden', '', '', '请上传logo和banner', 1, ".$_SESSION['supplier_id']."),
				(203, 2, 'template', 'hidden', '', '', 'dianpu', 1, ".$_SESSION['supplier_id']."),
				(204, 2, 'stylename', 'hidden', '', '', '', 1, ".$_SESSION['supplier_id']."),
				(205, 2, 'flash_theme', 'hidden', '', '', '".$_SESSION['supplier_name'].$_SESSION['supplier_id']."', 1, ".$_SESSION['supplier_id']."),
				(801, 8, 'sms_shop_mobile', 'text', '', '', '', 1, ".$_SESSION['supplier_id']."),
				(802, 8, 'sms_order_placed', 'select', '1,0', '', '0', 1, ".$_SESSION['supplier_id']."),
				(803, 8, 'sms_order_payed', 'hidden', '1,0', '', '0', 1, ".$_SESSION['supplier_id']."),
				(804, 8, 'sms_order_shipped', 'hidden', '1,0', '', '0', 1, ".$_SESSION['supplier_id'].");";
		if($db->query($insql) === false){
			$links[] = array('text' => $_LANG['navigator'], 'href' => 'navigator.php?act=list');
        	sys_msg('店铺设置信息创建失败！', 1);
		}
		return;
	}
}

/* 代码增加_start    By   morestock_morecity */
function get_ssid_list($sid)
{
		$sql="select store_id from ". $GLOBALS['ecs']->table('store_main') ." where supplier_id=".$_REQUEST['storetypeid']." and parent_id = '$sid' ";
		$ssid_res = $GLOBALS['db']->query($sql);
		$arr=array();
		while ($ssid_row=$GLOBALS['db']->fetchRow($ssid_res))
		{
		   $arr[]=$ssid_row['store_id'];
		}
		if (count($arr))
	    {
				return "(".implode(',', $arr).")";		
		}
		else
	   	{
			return "(0)";
		}
}

/* 获取库房完整名称（两级） */
function get_store_fullname($store_id)
{
		if(!$store_id){return '';}
		$store_row = $GLOBALS['db']->getRow("select parent_id, store_name from ". $GLOBALS['ecs']->table('store_main') ." where store_id='$store_id' ");
		$store_name = $store_row['store_name'];
		if($store_row['parent_id'])
		{
			$store_name_p = $GLOBALS['db']->getOne("select store_name from ". $GLOBALS['ecs']->table('store_main') ." where store_id='$store_row[parent_id]' ");
			$store_name  = $store_name_p ?  $store_name_p."<br>".$store_name :  $store_name;
		}
		return $store_name;
}
function get_inout_type_name($typeid)
{
	if (empty($typeid))
	{
		return '';
	}
	else
	{
		$return = $GLOBALS['db']->getOne("select type_name from ". $GLOBALS['ecs']->table('store_inout_type') ." where type_id='$typeid' ");
		return $return;
	}
}
function get_attr_name($attr_list)
{

	if(trim($attr_list))
	{
		$attr_list = str_replace("|", ",", $attr_list );
		$sql= "select attr_value from ". $GLOBALS['ecs']->table('goods_attr') ." where goods_attr_id in ($attr_list) ORDER BY  FIND_IN_SET(goods_attr_id,'$attr_list') ";
		$attr_name_arr = $GLOBALS['db']->query($sql);
		while ($row_attr_name = $GLOBALS['db']->fetchRow($attr_name_arr ))
		{
			$attr_name_list .=  $row_attr_name['attr_value']." ";
		}
		return $attr_name_list;
	}
	else
	{
		return '';	
	}
}

function get_goods_attr_id($goods_id, $attr_str)
{
	if (empty($attr_str))
	{
		return '';
	}
	else
	{
		$attr_str =str_replace("\r", "", $attr_str);
	    $attr_array = explode("\n", $attr_str);
		if (!is_array($attr_array)){return '';}
		$attr_array = array_filter($attr_array);
		$return = "";
		foreach($attr_array  AS $attr_temp)
		{
			$attr_temp = preg_replace("/\[.+\]/", "", $attr_temp);
			if($attr_temp)
			{
			$attr_arr = explode(":", $attr_temp);
			$sql="SELECT  a.attr_id  FROM ". $GLOBALS['ecs']->table('goods') ." AS g left join ". $GLOBALS['ecs']->table('attribute') ."  AS a on g.goods_type=a.cat_id WHERE g.goods_id='$goods_id' and a.attr_name='$attr_arr[0]' ";
			$attr_id = $GLOBALS['db']->getOne($sql);
			$sql="SELECT goods_attr_id  FROM ". $GLOBALS['ecs']->table('goods_attr') ." WHERE goods_id='$goods_id' and attr_id='$attr_id' and attr_value='$attr_arr[1]' ";
			$goods_attr_id = $GLOBALS['db']->getOne($sql);

			$return .= $return ? "|" : "";
			$return .= $goods_attr_id;
			}
		}

		if($return)
		{
			$goods_attr =explode("|", $return);
			$goods_attr = sort_goods_attr_id_array($goods_attr);
			$goods_attr = implode('|', $goods_attr['sort']);
			$return = $goods_attr;
		}
		return $return;
	}
}

/* 更新库存表（出库） */
function update_stock_out($rec_id, $store_id)
{
	$sql = "select goods_id, attr_value, number_shishou, supplier_id, store_type_id from ". $GLOBALS['ecs']->table('store_inout_goods') ." where inout_rec_id='$rec_id' ";
	$res = $GLOBALS['db']->query($sql);
	$no_jian=0;
	$no_jian_item="商品ID：";
	$update_arr =array();
	while ($row= $GLOBALS['db']->fetchRow($res))
	{
			$sql = "select stock_id, goods_id, goods_attr, store_number from ". $GLOBALS['ecs']->table('store_goods_stock') ." where supplier_id=".$row['supplier_id']." and goods_id='$row[goods_id]' and store_id='$store_id' and goods_attr='$row[attr_value]' limit 0,1";
			$row_stock = $GLOBALS['db']->getRow($sql);
			if ($row_stock['store_number'] < $row['number_shishou'])
			{
				$no_jian++;
				$no_jian_item .= $row['goods_id']."&nbsp;";
			}
			else
			{
				$update_arr[]=array(
						'stock_id'=>$row_stock['stock_id'], 
						'number_shishou'=>$row['number_shishou'],
						'goods_id'=>$row_stock['goods_id'],						
						'attr_value'=>$row_stock['goods_attr'],
						'store_number'=>$row_stock['store_number']
						);
			}
	}

	if (!$no_jian)
	{
		foreach($update_arr AS $upd)
		{
				$sql = "update ". $GLOBALS['ecs']->table('store_goods_stock') ." set store_number=store_number-".$upd['number_shishou']." where stock_id='$upd[stock_id]' ";
				$GLOBALS['db']->query($sql);

				//序时簿
				$number_stock= $upd['store_number']- $upd['number_shishou'];
				$sql = "insert into  ".$GLOBALS['ecs']->table('store_inout_xushibu')."(inout_rec_id, goods_id, attr_value, inout_mode, number_shishou, number_stock, supplier_id, store_type_id) ".
						" values('$rec_id', '$upd[goods_id]',  '$upd[attr_value]', '1', '$upd[number_shishou]', '$number_stock', '$_SESSION[supplier_id]', '$_REQUEST[storetypeid]' )";	
				$GLOBALS['db']->query($sql);
				update_old_stock($upd['goods_id'], $upd['attr_value']);
		}
	}

	 return array('error'=>$no_jian, 'error_item'=>$no_jian_item.' 库存不足！');
}


/* 更新库存表（入库） */
function update_stock_in($rec_id, $store_id)
{
	$sql = "select goods_id, attr_value, number_shishou, supplier_id, store_type_id from ". $GLOBALS['ecs']->table('store_inout_goods') ." where inout_rec_id='$rec_id' ";
	$res = $GLOBALS['db']->query($sql);
	while ($row= $GLOBALS['db']->fetchRow($res))
	{
		$sql = "select stock_id, store_number from ". $GLOBALS['ecs']->table('store_goods_stock') ." where supplier_id=".$row['supplier_id']." and goods_id='$row[goods_id]' and store_id='$store_id' and goods_attr='$row[attr_value]' limit 0,1";
		$stock_row = $GLOBALS['db']->getRow($sql);
		if ($stock_row['stock_id'])
		{
			$sql = "update ".$GLOBALS['ecs']->table('store_goods_stock')." set store_number=store_number+".$row['number_shishou']." where stock_id='$stock_row[stock_id]' ";			
		}
		else
		{
			$sql = "insert into  ".$GLOBALS['ecs']->table('store_goods_stock')."(goods_id, store_id, goods_attr, store_number, supplier_id, store_type_id) ".
						" values('$row[goods_id]', '$store_id', '$row[attr_value]', '$row[number_shishou]', '$row[supplier_id]', '$row[store_type_id]')";	
		}
		$GLOBALS['db']->query($sql);

		//序时簿
		$number_stock= $stock_row['store_number']+ $row['number_shishou'];
		$sql = "insert into  ".$GLOBALS['ecs']->table('store_inout_xushibu')."(inout_rec_id, goods_id, attr_value, inout_mode, number_shishou, number_stock, supplier_id, store_type_id) ".
						" values('$rec_id', '$row[goods_id]',  '$row[attr_value]', '2', '$row[number_shishou]', '$number_stock', '$_SESSION[supplier_id]', '$_REQUEST[storetypeid]' )";	
		$GLOBALS['db']->query($sql);
		update_old_stock($row['goods_id'], $row['attr_value']);
	}
}

function update_old_stock($goods_id, $attr_id)
{
	$sql="select sum(store_number) from ". $GLOBALS['ecs']->table('store_goods_stock') ." where goods_id='$goods_id'";
	$all_count  = $GLOBALS['db']->getOne($sql);
	$sql="update ". $GLOBALS['ecs']->table('goods') ." set goods_number='$all_count'  where goods_id='$goods_id'";
	$GLOBALS['db']->query($sql);

    if($attr_id)
	{
		$sql="select sum(store_number) from ". $GLOBALS['ecs']->table('store_goods_stock') ." where goods_attr = '$attr_id' and goods_id='$goods_id'";
		$attr_count  = $GLOBALS['db']->getOne($sql);
		$sql="select product_id from ". $GLOBALS['ecs']->table('products') ." where goods_attr = '$attr_id' and goods_id='$goods_id' ";
		$product_id = $GLOBALS['db']->getOne($sql);
		if($product_id)
		{
			$sql="update ". $GLOBALS['ecs']->table('products') ." set product_number='$attr_count'  where product_id='$product_id' ";
		}
		else
		{
			$sql="insert into ". $GLOBALS['ecs']->table('products') ."(goods_id, goods_attr, product_number) values('$goods_id', '$attr_id', '$attr_count' ) ";
		}
		$GLOBALS['db']->query($sql);
	}
}

/* 代码增加_end    By   morestock_morecity */
/* 姓名遮罩 */
function name_cut($user_name){
    $strlen     = mb_strlen($user_name, 'utf-8');
    $firstStr     = mb_substr($user_name, 0, 1, 'utf-8');
    $lastStr     = mb_substr($user_name, -1, 1, 'utf-8');

    return $strlen == 2 ? $firstStr . str_repeat('*', mb_strlen($user_name, 'utf-8') - 1) : $firstStr . str_repeat("*", $strlen - 2) . $lastStr;
}

function id_cut($user_id){
    $strlen       = mb_strlen($user_id, 'utf-8');
    $firstStr     = mb_substr($user_id, 0, 2, 'utf-8');
    $middleStr    = mb_substr($user_id, 4, 2, 'utf-8');
    $lastStr      = mb_substr($user_id, -1, 1, 'utf-8');

	if($strlen<5){
		return 	$firstStr . "**";	
	}elseif($strlen>=5 && $strlen<7){
		return 	$firstStr . "**" .$middleStr;			
	}elseif($strlen==7 ){
		return  $firstStr . "**" . $middleStr .str_repeat("*", $strlen - 6) . $lastStr;
	}elseif($strlen>7){
		return  $firstStr . "**" . $middleStr ."*";				
	}
}

function phone_cut($phone){
    $strlen       = strlen($phone);
    $firstStr     = substr($phone, 0, 5);
    $middleStr    = substr($phone, 7, 1);
    $lastStr      = substr($phone, 9, 1);

    return $firstStr . "**" . $middleStr . "*" . $lastStr;
}

function get_agent_tree($id){
	if($id>0){
		$c_id="(";
		$c_id.=build_agent_tree($id); 	
		$c_id.="'".$id."')";
		
	}elseif($id==0){
		$c_id="('0')";
	}
	
	return $c_id;		
}

function build_agent_tree($id){
	$p_rs = $GLOBALS['db']->query("SELECT user_id FROM ".$GLOBALS['ecs']->table('agent_user')." WHERE parent_id= ".$id);
	$c_id='';
	while ($row = $GLOBALS['db']->FetchRow($p_rs)){
		   $c_id.="'".$row['user_id']."',";
			 $c_id.=build_agent_tree($row['user_id']);
			 
	}
	
	return $c_id;
}
?>