<?php

/**
 * 获取和设置配置参数 支持批量定义
 * @param string|array $name 配置变量
 * @param mixed $value 配置值
 * @param mixed $default 默认值
 * @return mixed
 */
function C($name = null, $value = null, $default = null)
{
    static $_config = array();
    // 无参数时获取所有
    if (empty($name)) {
        return $_config;
    }
    // 优先执行设置获取或赋值
    if (is_string($name)) {
        if (! strpos($name, '.')) {
            $name = strtoupper($name);
            if (is_null($value))
                return isset($_config[$name]) ? $_config[$name] : $default;
            $_config[$name] = $value;
            return;
        }
        // 二维数组设置和获取支持
        $name = explode('.', $name);
        $name[0] = strtoupper($name[0]);
        if (is_null($value))
            return isset($_config[$name[0]][$name[1]]) ? $_config[$name[0]][$name[1]] : $default;
        $_config[$name[0]][$name[1]] = $value;
        return;
    }
    // 批量设置
    if (is_array($name)) {
        $_config = array_merge($_config, array_change_key_case($name, CASE_UPPER));
        return;
    }
    return null; // 避免非法参数
}

function I($k = false)
{
    if ($k == 'server.REQUEST_TIME') {
        return $_SERVER['REQUEST_TIME'];
    }
    static $request = null;
    if ($request === null) {
        $data = $_REQUEST['data'];
        if (! $data) {
            $request = array();
            return $request;
        }
        $data = str_replace(' ', '+', $data);
        $data = base64_decode($data);
        if (! $data) {
            $request = array();
            return $request;
        }
        parse_str($data, $request);
    }
    if ($k === false) {
        return $request;
    }
    return $request[$k];
}

/**
 *
 * @author 验证用户授权操作
 * @param string $info
 *            是否返回用户基本信息
 * @return mixed
 */
function user_auth_check($check_role = false)
{
    $auth = I('auth');
    $U = Module::getInstance('User');
    $result = $U->parseAuth($auth);
    if ($result['err'] > 0) {
        echo_json($result);
    }
    $user = $U->getBaseCache($result['user']['uid']);
    if (! $user) {
        echo_error(2003);
    } elseif ($user['status'] == 2) {
        echo_error(2072);
    }
    $user['uid'] = $result['user']['uid'];
    return $user;
}

function parseAuth($info = false)
{
    $auth = I('auth');
    $U = Module::getInstance('User');
    $result = $U->parseAuth($auth);
    if ($result['err'] > 0) {
        return false;
    }
    $user = $U->getBaseCache($result['user']['uid']);
    if (! $user) {
        return false;
    } elseif ($user['status'] == 2) {
        return false;
    }
    if ($user['login_t'] == $result['user']['t']) {
        $user['rid'] = intval($result['user']['rid']);
    } else {
        return false; // 账号在别处登陆
    }
    return $user;
}

function get_user_info($uid)
{
    return Module::getInstance('User')->getUserByUid($uid);
}

function is_register($uid)
{
    if (! $uid) {
        return ER(2017, array(
            'info' => array()
        ));
    }
    $user = Module::getInstance('User')->getUserByUid($uid);
    if (! $user) {
        return ER(2003, array(
            'info' => array()
        ));
    }
    return array(
        'err' => 0,
        'info' => $user
    );
}

function show_star_name($str, $itype = 1, $iarray = array())
{
    // 显示星号名字
    $i = 0;
    $count = 0;
    $len = strlen($str);
    $temp = array();
    $pre_i = 0;
    while ($i < $len) {
        $chr = ord($str[$i]);
        if ($i > 0) {
            $temp[] = substr($str, $pre_i, $i - $pre_i);
            $pre_i = $i;
        }
        $count ++;
        $i ++;
        if ($i >= $len)
            break;
        if ($chr & 0x80) {
            $chr <<= 1;
            while ($chr & 0x80) {
                $i ++;
                $chr <<= 1;
            }
        }
    }
    if ($pre_i != $i) {
        $temp[] = substr($str, $pre_i, $i - $pre_i);
    }
    if ($itype == 1) {
        $cnt = count($temp);
        if ($cnt < 3 && $cnt > 1) {
            $temp[1] = '*';
            return implode('', $temp);
        } elseif ($temp < 2) {
            return $str;
        } elseif ($cnt >= 3) {
            $i = intval($cnt / 3);
            $l = $i * 2;
            $y = $cnt % 3;
            if ($y > 0) {
                $l ++;
            }
            for ($i; $i < $l; $i ++) {
                if (! isset($temp[$i]))
                    break;
                $temp[$i] = '*';
            }
            return implode('', $temp);
        }
    } elseif ($itype == 2) {
        foreach ($iarray as $i) {
            $temp[$i] = '*';
        }
        return implode('', $temp);
    } elseif ($itype == 3) { // 显示索引
        $cnt = count($temp);
        $before = $iarray['before'];
        $after = $cnt - $iarray['after'];
        foreach ($temp as $i => $v) {
            if ($i >= $before && $i < $after) {
                $temp[$i] = '*';
            }
        }
        return implode('', $temp);
    } elseif ($itype == 4) { // 显示索引
        $cnt = count($temp);
        $before = $iarray['before'];
        $after = $cnt - $iarray['after'];
        foreach ($temp as $i => $v) {
            if ($i < $before || $i >= $after) {
                $temp[$i] = '*';
            }
        }
        return implode('', $temp);
    }
}

function parse_url_param($url)
{
    $pos = strpos($url, '?');
    if (! $pos) {
        $url_path = $url;
        $param = array();
    } else {
        $url_path = substr($url, 0, $pos);
        parse_str(substr($url, $pos + 1), $param);
    }
    return array(
        'url' => $url_path,
        'param' => $param
    );
}

function fitter_url_param($url, $fitter = array())
{
    $result = parse_url_param($url);
    foreach ($fitter as $v) {
        if (isset($result['param'][$v])) {
            unset($result['param'][$v]);
        }
    }
    return $result['url'] . '?' . http_build_query($result['param']);
}

function make_index($table)
{
    $table_index = array(
        'out_status' => 'index_out',
        'pay_status' => 'index_pay',
        'ft_orders' => 'index_order'
    );
    if (! isset($table_index[$table])) {
        return 0;
    } else {
        $_table = $table_index[$table];
    }
    if (! $_table)
        return 0;
    $t = time();
    $db = GObject::getDBO();
    $sql = "insert into `{$_table}` (`ctime`) values({$t})";
    if ($db->query($sql)) {
        return intval($db->insert_id());
    } else {
        return 0;
    }
}

function getIp()
{
    $ip = false;
    if (! empty($_SERVER["HTTP_CLIENT_IP"])) {
        $ip = $_SERVER["HTTP_CLIENT_IP"];
    }
    if (! empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ips = explode(", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
        if ($ip) {
            array_unshift($ips, $ip);
            $ip = FALSE;
        }
        for ($i = 0; $i < count($ips); $i ++) {
            if (! eregi("^(10|172\.16|192\.168)\.", $ips[$i])) {
                $ip = $ips[$i];
                break;
            }
        }
    }
    return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
}

function make_dir($dir)
{
    if (! file_exists($dir)) {
        @make_dir(dirname($dir), 0775);
        @mkdir($dir, 0775);
    }
}

function getRandCode()
{
    $code = 'QWERTYUIOPLKJHGFDSAZXCVBNM0123456789';
    $d = date('y-m-d-H-i-s', time());
    list ($y, $m, $d, $i, $s) = explode('-', $d);
    $r = mt_rand(0, 17);
    $y = intval($y);
    $m = intval($m);
    $d = intval($d);
    $i = intval($i);
    $s = intval($s);
    $y -= 12;
    $m -= 1;
    if ($i > 35 && $s <= 35) {
        $i -= 35;
        $m += 12;
    } elseif ($i <= 35 && $s > 35) {
        $s -= 35;
        $m += 24; // 最大35
    } elseif ($i > 35 && $s > 35) {
        $i -= 35;
        $s -= 35;
        $r += 18; // 最大35
    }
    if ($m > 35)
        $m = 35;
    
    $invite_code = $code[mt_rand(0, 35)] . $code[mt_rand(0, 35)] . $code[mt_rand(0, 35)] . $code[mt_rand(0, 35)] . $code[mt_rand(0, 35)] . $code[$r] . $code[$y] . $code[$m] . $code[$d] . $code[$i] . $code[$s] . $code[mt_rand(0, 35)];
    return $invite_code;
}

function deldir($dir)
{
    // 先删除目录下的文件:
    $dh = opendir($dir);
    while ($file = readdir($dh)) {
        if ($file != "." && $file != "..") {
            $fullpath = $dir . "/" . $file;
            if (! is_dir($fullpath)) {
                unlink($fullpath);
            } else {
                deldir($fullpath);
            }
        }
    }
    closedir($dh);
    // 删除当前文件夹:
    if (rmdir($dir)) {
        return true;
    } else {
        return false;
    }
}

function get_url($url, $param)
{
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($param));
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_TIMEOUT, 20);
    $response = curl_exec($ch);
    curl_close($ch);
    // echo $url.'?'.http_build_query($param);
    // print_r($response);
    return $response;
}

function get_ssl_url($url, $param = null)
{
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    // https 不验证证书和hosts
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    if (is_array($param)) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($param));
    } elseif (is_string($param)) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
    }
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_TIMEOUT, 20);
    $response = curl_exec($ch);
    curl_close($ch);
    return $response;
}

function echo_json($data, $exit = true)
{
    if (! __DEBUG__ && is_array($data) && key_exists('debug', $data)) {
        unset($data['debug']);
    }
    if (defined('ECHO_ENCRYPT') && ECHO_ENCRYPT === false) {
        if (is_array($data)) {
            echo json_encode($data, true);
        } else {
            echo $data;
        }
        if ($exit === true)
            exit();
    }
    
    if (is_array($data)) {
        echo base64_encode(json_encode($data, true));
    } else {
        echo base64_encode($data);
    }
    if ($exit === true)
        exit();
}

function echo_json_apix($data, $exit = true)
{
    if (! __DEBUG__ && is_array($data) && key_exists('debug', $data)) {
        unset($data['debug']);
    }
    if (defined('ECHO_ENCRYPT') && ECHO_ENCRYPT === false) {
        if (is_array($data)) {
            echo json_encode($data);
        } else {
            echo $data;
        }
        if ($exit === true)
            exit();
    }
    
    if (is_array($data)) {
        echo base64_encode(json_encode($data, true));
    } else {
        echo base64_encode($data);
    }
    if ($exit === true)
        exit();
}

function echo_djson($data, $exit = true)
{
    if (! __DEBUG__ && is_array($data) && key_exists('debug', $data)) {
        unset($data['debug']);
    }
    
    if (is_array($data)) {
        echo json_encode($data);
    } else {
        echo $data;
    }
    if ($exit === true)
        exit();
}

/**
 * 3DES加密php程式
 *
 * @param string $data
 *            需要加密字符串
 * @param string $key
 *            运营商应用密钥
 * @return string $res 加密后的字符串
 */
function do_encrypt($data, $key, $iv = '', $algorithm = 'ecb')
{
    if ($data === '' || ! extension_loaded('mcrypt')) {
        return $data;
    }
    if (! defined('_3DES_')) {
        include C('COMMON_LIB_DIR') . '3des.php';
        if (! defined('_3DES_')) {
            define('_3DES_', 1);
        }
    }
    $des = new Crypt3Des($key, $iv);
    if ($algorithm == 'ecb') {
        return $des->encrypt($data);
    } else {
        return $des->do_encrypt_x($data);
    }
}

/**
 * 3DES解密php程式
 *
 * @param string $data
 *            需要加密字符串
 * @param string $key
 *            运营商应用密钥
 * @return string $res 解密后的字符串
 */
function do_decrypt($data, $key, $iv = '', $algorithm = 'ecb')
{
    if ($data === '' || ! extension_loaded('mcrypt')) {
        return $data;
    }
    if (! defined('_3DES_')) {
        include C('COMMON_LIB_DIR') . '3des.php';
        if (! defined('_3DES_')) {
            define('_3DES_', 1);
        }
    }
    $des = new Crypt3Des($key, $iv);
    if ($algorithm == 'ecb') {
        return $des->decrypt($data);
    } else {
        return $des->do_decrypt_x($data);
    }
}

function ER($code, $data = false, $replace = false)
{
    static $error = null;
    if ($error === null) {
        $error = include C('COMMON_CFG_DIR') . '/err_code.php';
    }
    if ($error[$code] && isset($error[$code])) {
        if ($data) {
            if (! $replace) {
                return array_merge(array(
                    'err' => $code,
                    'msg' => $error[$code]
                ), $data);
            } else {
                $error[$code] = $data['msg'];
                return array_merge(array(
                    'err' => $code,
                    'msg' => $error[$code]
                ), $data);
            }
        }
        return array(
            'err' => $code,
            'msg' => $error[$code]
        );
    } else {
        if ($data) {
            if (! $replace) {
                return array_merge(array(
                    'err' => $code,
                    'msg' => ''
                ), $data);
            } else {
                $error[$code] = $data['msg'];
                return array_merge(array(
                    'err' => $code
                ), $data);
            }
        }
        return array(
            'err' => $code,
            'msg' => ''
        );
    }
}

function echo_error($code, $data = array())
{
    echo_json(array_merge(ER($code), $data));
}

function upload_file($file, $save_file, $filename, $upload_type = false, $max_size = false)
{
    $fileName = pathinfo($file['name']);
    $fileName['extension'] = strtolower($fileName['extension']);
    
    if ($upload_type !== false) {
        if (! is_array($upload_type))
            $upload_type = array(
                $upload_type
            );
        if (! in_array($fileName['extension'], $upload_type)) {
            return array(
                'err' => 1,
                'msg' => '上传类型不对'
            );
        }
    }
    $save_file = rtrim($save_file, '/') . '/';
    make_dir($save_file);
    
    if (! is_writeable($save_file)) {
        return array(
            'err' => 1,
            'msg' => '上传失败'
        );
    }
    $filename .= '.' . $fileName['extension'];
    $save_file = $save_file . $filename;
    
    if ($max_size !== false) {
        if (filesize($file['tmp_name']) > $max_size) {
            return array(
                'err' => 1,
                'msg' => '上传太大了'
            );
        }
    }
    if (is_uploaded_file($file['tmp_name'])) {
        if (! move_uploaded_file($file['tmp_name'], $save_file)) {
            return array(
                'err' => 1,
                'msg' => '上传失败'
            );
        } else {
            return array(
                'err' => 0,
                'file' => $save_file,
                'file_name' => $filename
            );
        }
    }
    return array(
        'err' => 1,
        'msg' => '上传失败'
    );
}

function write_upload($data, $save_path, $file_name = false)
{
    if ($data) {
        $data = str_replace(' ', '+', $data);
        $arr_data = explode('.', $data);
        $ext = $arr_data[1];
        $file = base64_decode($arr_data[0]);
        $re_write_file = true;
        if ($file) {
            make_dir($save_path);
            if ($file_name == false) {
                $re_write_file = false;
                if ($ext) {
                    $file_name = md5($arr_data[0]) . '.' . $ext;
                } else {
                    $file_name = md5($arr_data[0]);
                }
            } else {
                if (strpos($file_name, '.') === false && $ext) {
                    $file_name = $file_name . '.' . $ext;
                }
            }
            $save_file = $save_path . '/' . $file_name;
            if ($re_write_file || ! file_exists($save_file)) {
                file_put_contents($save_file, $file);
            }
            
            return array(
                'err' => 0,
                'file' => $save_file,
                'file_name' => $file_name
            );
        } else {
            return ER(4005);
        }
    }
    return ER(4006);
}

function getOS()
{
    $agent = $_SERVER['HTTP_USER_AGENT'];
    
    static $os = null;
    if ($os !== null)
        return $os;
    
    if (strpos($agent, 'Mac OS') !== false || strpos($agent, 'iPhone') !== false || strpos($agent, 'iPod') !== false || strpos($agent, 'iPad') !== false) {
        if (strpos($agent, 'iPhone') !== false) {
            $os = 'iphone';
        } elseif (strpos($agent, 'iPod') !== false) {
            $os = 'ipod';
        } elseif (strpos($agent, 'iPad') !== false) {
            $os = 'ipad';
        } else {
            $os = 'apple';
        }
    } else
        if (strpos($agent, 'Windows Phone') !== false) {
            $os = 'wphone';
        } else
            if (strpos($agent, 'Android') !== false || strpos($agent, 'Adr') !== false) {
                $os = 'android';
            } elseif (strpos($agent, 'Windows') !== false) {
                $os = 'windows';
            } elseif (strpos($agent, 'Linux') !== false) {
                $os = 'linux';
            } else {
                $os = 'android';
            }
    return $os;
}

function alertMsg($msg, $url = "")
{
    header("Content-Type: text/html; charset=utf-8");
    if ($url == 'back') {
        $redirectStr = 'window.history.go(-1);';
    } elseif ($url) {
        $redirectStr = 'location.href="' . $url . '";';
    }
    echo '<script>';
    if ($msg) {
        echo 'alert("' . $msg . '");';
    }
    echo $redirectStr;
    echo '</script> ';
    exit();
    // location.href="'.$url.'";
}

/**
 * 返回页面级别的HTML代码 返回信息
 * $status 返回状态
 * $msg 返回的具体内容
 */
function system_push($data, $arrary = false)
{
    if (! $data['txt']) {
        return 1003;
    }
    if (! $data['to']) {
        return 1004;
    }
    $setting = C('sys_push');
    if (! $data['from']) {
        $data['from'] = $setting['default']['from_id'];
    }
    
    if (! isset($data['ct'])) {
        $data['ct'] = $setting['default']['ct'];
    }
    if (! isset($data['mt'])) {
        $data['mt'] = $setting['default']['mt'];
    }
    if (! isset($data['app'])) {
        $data['app'] = $setting['default']['app'];
    }
    $key = $setting['from'][$data['from']]['sign'];
    if (is_array($data['txt'])) {
        $data['txt'] = json_encode($data['txt']);
    }
    $data['txt'] = urlencode($data['txt']);
    $data['t'] = time();
    $data['sign'] = md5($key . '#' . $data['from'] . '#' . $data['to'] . '#' . $data['ct'] . '#' . $data['app'] . '#' . $data['t']);
    $result = get_url($setting['url'], $data);
    
    $result = json_decode($result, true);
    if (isset($result['err']) && $result['err'] == 0) {
        return 0;
    } else {
        if ($arrary) {
            return $result;
        }
        return 1005;
    }
}

function str_to_array($str, $num_or_str = 1, $fiter = false)
{
    $arr = explode(',', $str);
    return array_to_array($arr, $num_or_str, $fiter);
}

function array_to_str($arr, $num_or_str = 1, $fiter = false)
{
    return implode(',', array_to_array($arr, $num_or_str, $fiter));
}

function str_to_str($str, $num_or_str = 1, $fiter = false)
{
    $arr = str_to_array($str, $num_or_str, $fiter);
    if ($arr) {
        return implode(',', $arr);
    }
    return '';
}

// 新用户注册
function write_reg($uid, $plat, $net_p_id = 0, $net_id = 0)
{
    $db = &GObject::getDBO('log');
    $t = time();
    $d = date('Ymd', $t);
    $res = $db->query("update `stplace` set cnt=cnt+1 where bid='{$net_id}' and comid='{$net_p_id}' and d='{$d}' and plat='{$plat}'");
    if ($db->affected_rows() == 0) {
        $data = $db->query_first("select * from  `stplace`  where  bid='{$net_id}' and comid='{$net_p_id}' and d='{$d}' and plat='{$plat}'");
        if (! $data) {
            $res = $db->query("insert into `stplace` (comid,bid,cnt,plat,t,d) values ('{$net_p_id}','{$net_id}',1,'{$plat}','{$t}','{$d}')");
        } else {
            $res = $db->query("update `stplace` set cnt=cnt+1 where bid='{$net_id}' and comid='{$net_p_id}' and d='{$d}' and plat='{$plat}'");
        }
    }
}

/**
 * 获取机构列表
 * @acyid
 * @p 如果$p为1,就是查询的是顶级结构数据,如果不是 只是查询acyid下级的机构数据
 *
 * @return 返回查询的机构列表
 */
// 新用户注册
function getTagencyList($acyid = '1', $p = '1')
{
    $db = &GObject::getDBO('com');
    if ($p == "1") {
        $sql = "select * from  `tagency`  where  p='{$p}'";
    } else {
        $sql = "select * from  `tagency`  where acyid like '{$acyid}%' and p='{$p}'";
    }
    
    $result = $db->getRecords($sql);
    return $result;
}

/**
 * 数据统计分析记录 end----------
 */
function z_map($mac, $type = 'make')
{
    $map = array(
        '0' => 'P',
        '1' => 'O',
        '2' => 'A',
        '3' => '7',
        '4' => 'L',
        '5' => 'G',
        '6' => 'F',
        '7' => '2',
        '8' => 'W',
        '9' => 'Q',
        'a' => 'C',
        'b' => 'M',
        'c' => 'B',
        'd' => 'N',
        'e' => '9',
        'f' => 'X'
    );
    $l = strlen($mac);
    $newmac = '';
    if ($type == 'make') {
        for ($i = 0; $i < $l; $i ++) {
            $newmac .= $map[strtolower($mac[$i])];
        }
    } elseif ($type == 'parse') {
        $map = array_flip($map);
        for ($i = 0; $i < $l; $i ++) {
            $newmac .= $map[$mac[$i]];
        }
    }
    
    return $newmac;
}

/**
 * 订单号生成函数
 */
function build_order_no()
{
    return 's' . date('md') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 12);
}

/**
 * 订单号生成函数
 */
function build_order_no_n()
{
    return 'a' . date('md') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 12);
}

/**
 * 充值订单生成函数
 */
function build_pay_order_no()
{
    return 'upay' . date('md') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 12);
}

/**
 * 排号机接口 记录日志
 */
function write_logs_p($arr)
{
    error_log(json_encode($arr) . "\r\n", 3, "/var/www/jubao/did/Log/paihao.log");
}

/**
 * 对排号机取号码 进行格式化
 */
function cut_string_4($string)
{
    $tempString = "";
    $tempString .= substr($string, 0, 4) . " ";
    $tempString .= substr($string, 4, 4) . " ";
    $tempString .= substr($string, 8, 4);
    return $tempString;
}

/**
 * 对排号号码不够三位的 填充0
 */
function fillZeroThree($num)
{
    $return = "";
    $len = strlen($num);
    if ($len == 1) {
        $return = "00" . $num;
    } else
        if ($len == 2) {
            $return = "0" . $num;
        } else {
            $return = $num;
        }
    return $return;
}

/**
 * 根据两点间的经纬度计算距离
 *
 * @param float $lat
 *            纬度值
 * @param float $lng
 *            经度值
 */
function getDistanceTwoPoint($lat1, $lng1, $lat2, $lng2)
{
    $earthRadius = 6367000; // approximate radius of earth in meters
    $lat1 = ($lat1 * pi()) / 180;
    $lng1 = ($lng1 * pi()) / 180;
    $lat2 = ($lat2 * pi()) / 180;
    $lng2 = ($lng2 * pi()) / 180;
    $calcLongitude = $lng2 - $lng1;
    $calcLatitude = $lat2 - $lat1;
    $stepOne = pow(sin($calcLatitude / 2), 2) + cos($lat1) * cos($lat2) * pow(sin($calcLongitude / 2), 2);
    $stepTwo = 2 * asin(min(1, sqrt($stepOne)));
    $calculatedDistance = $earthRadius * $stepTwo;
    return round($calculatedDistance);
}

function characet_my($data)
{
    if (! empty($data)) {
        
        $filetype = mb_detect_encoding($data, array(
            'utf-8',
            'gbk',
            'latin1',
            'big5'
        ));
        
        if ($filetype != 'utf-8') {
            
            $data = mb_convert_encoding($data, 'utf-8', $filetype);
        }
    }
    
    return $data;
}

/**
 * 获取系统相关参数
 */
function getParamFromRequest()
{
    $imei = trim($_REQUEST['_imei']); // 设备唯一标示
    $os = trim($_REQUEST['_os']); // 设备类型 0:android 1:苹果 2:终端
    $ver = trim($_REQUEST['_ver']); // 软件版本号(短版本)
    $vers = trim($_REQUEST['_vers']); // 软件版本号(长版本)
    if ($os == '0') {
        $os = 0;
    } else
        if ($os == '1') {
            $os = 1;
        } else
            if ($os == '2') {
                $os = 2;
            } else {
                $os = - 1;
            }
    return array(
        'imei' => $imei,
        'os' => $os,
        'ver' => $ver,
        'vers' => $vers
    );
}

/**
 * 添加模块消息
 *
 * @param unknown $sendUid
 *            发送者uid
 * @param unknown $accepterUid
 *            接受者uid 以逗号分隔
 * @param int $loc
 *            村镇id
 * @param
 *            string mid 类型 10 村圈 11 档案
 * @param string $msg
 *            消息内容
 * @param
 *            string sid 数据id
 * @param number $md
 *            提示模式: 0标准方式 1 弹出
 */
function insertModuleMsg($sendUid, $accepterUid, $loc = "0", $mid = "0", $msg = "", $sid = '0', $md = 0)
{
    if (! empty($accepterUid)) {
        $accepterArr = array();
        if (! empty($accepterUid)) {
            $accepterArr = explode(",", $accepterUid);
        }
        
        if (! empty($accepterArr)) {
            
            $len = count($accepterArr);
            for ($i = 0; $i < $len; $i ++) {
                if ($accepterArr[$i] > 0) {
                    $MsgData = array(
                        'f' => $sendUid,
                        'tp' => 1,
                        'mid' => $mid,
                        'msg' => $msg,
                        'sid' => $sid,
                        't' => time(),
                        'md' => $md
                    );
                    $MsgData = json_encode($MsgData, true);
                    $insertData = array(
                        "sender" => $sendUid,
                        'accepter' => $accepterArr[$i],
                        'loc' => $loc,
                        'types' => 1,
                        'ctime' => time(),
                        'msg' => $MsgData
                    );
                    $re = Module::getInstance("Msgnew")->addMsg($insertData);
                }
            }
        }
    } else {
        $UserList = Module::getInstance("Users")->getUserByComid($loc);
        if (! empty($UserList)) {
            foreach ($UserList as $key => $val) {
                $MsgData = array(
                    'f' => $sendUid,
                    'tp' => 1,
                    'mid' => $mid,
                    'msg' => $msg,
                    'sid' => $sid,
                    't' => time(),
                    'md' => $md
                );
                $MsgData = json_encode($MsgData, true);
                $insertData = array(
                    "sender" => $sendUid,
                    'accepter' => $val['id'],
                    'loc' => $loc,
                    'types' => 1,
                    'ctime' => time(),
                    'msg' => $MsgData
                );
                $re = Module::getInstance("Msgnew")->addMsg($insertData);
            }
        }
    }
}

function write_upload_new($data, $save_path)
{
    file_put_contents($save_path, $data);
    return array(
        'err' => 0,
        'msg' => "上传成功"
    );
}

/**
 * 请求小包谷接口
 */
function send_botot($msg)
{
    $url = "http://capi.nids.com.cn/znzd/voice";
    $data = base64_encode($msg);
    $data = base64_encode("txt=" . $data);
    $param = array(
        'data' => $data
    );
    return get_url($url, $param);
}

/**
 *
 * @param unknown $data            
 * @param
 *            string 发送附件地址
 * @return mixed
 */
function pushMessage($data, $files = "")
{
    // $data = Array
    // (
    // "mt" => 1,//发送方式:1即时消息,2异步消息
    // "o" => 1,//全部 还是 指定发送人,1指定 2全部
    // "to" => $sendUidString,//接收人id
    // "ct" => 0,//0文字,1图片,2声音,3html,4内部消息json格式
    // "txt" => $strtemp,//消息内容 需要进行urlencode($txt)
    // 'app'=>$app,//发送消息的app
    // 'ty' => "",
    // );
    if (! isset($data['from'])) {
        $data['from'] = 1;
    }
    if (empty($data['app'])) {
        $data['app'] = 'anxinsong';
    }
    $key = 'uuyyyxxxxllkjyyerereggg';
    $data['t'] = time();
    $data['sign'] = md5($key . '#' . $data['from'] . '#' . $data['to'] . '#' . $data['ct'] . '#' . $data['app'] . '#' . $data['t']);
    if ($files) {
        $path_info = pathinfo($files);
        $data['source'][] = base64_encode(file_get_contents($files)) . '.' . $path_info['extension'];
    }
    if (! isset($data['xt']))
        $data['xt'] = 0;
    if (! isset($data['ex']))
        $data['ex'] = 0;
    return get_url("http://push.cdanyida.com/msg/system_sent", $data);
}

/**
 * 实现图片等比例不失真缩放
 *
 * @param unknown $oldpic
 *            要缩放的原始图片
 * @param unknown $maxwidth
 *            生成图片的最大宽度(单位:像素)
 * @param unknown $maxheight
 *            生成图片的最大高度(单位:像素)
 * @param unknown $name
 *            生成的新图片名 如(1.jpg/1.png/1.gif)
 */
function resizeImage($oldpic, $maxwidth, $maxheight, $name)
{
    $oldFileType = end(explode('.', $oldpic));
    $im = "";
    if ($oldFileType == "jpeg" || $oldFileType == "jpg") {
        $im = imagecreatefromjpeg($oldpic);
    } else
        if ($oldFileType == "png") {
            
            $im = imagecreatefrompng($oldpic);
        } else
            if ($oldFileType == "gif") {
                $im = imagecreatefromgif($oldpic);
                require_once ROOT_DIR . "Common/Library/gifresizer.php";
                
                $gr = new gifresizer();
                
                $gr->temp_dir = ROOT_DIR . "Public/temp";
                
                $gr->resize($oldpic, $name, $maxwidth, $maxheight);
                return;
            }
    if (! $im) {
        $tempContents = file_get_contents($oldpic);
        file_put_contents($name, $tempContents);
        return;
    }
    $pic_width = imagesx($im);
    
    $pic_height = imagesy($im);
    
    if (($maxwidth && $pic_width > $maxwidth) || ($maxheight && $pic_height > $maxheight)) {
        if ($maxwidth && $pic_width > $maxwidth) {
            $widthratio = $maxwidth / $pic_width;
            $resizewidth_tag = true;
        }
        
        if ($maxheight && $pic_height > $maxheight) {
            $heightratio = $maxheight / $pic_height;
            $resizeheight_tag = true;
        }
        
        if ($resizewidth_tag && $resizeheight_tag) {
            if ($widthratio < $heightratio)
                $ratio = $widthratio;
            else
                $ratio = $heightratio;
        }
        
        if ($resizewidth_tag && ! $resizeheight_tag)
            $ratio = $widthratio;
        if ($resizeheight_tag && ! $resizewidth_tag)
            $ratio = $heightratio;
        
        $newwidth = $pic_width * $ratio;
        $newheight = $pic_height * $ratio;
        
        if (function_exists("imagecopyresampled")) {
            $newim = imagecreatetruecolor($newwidth, $newheight);
            imagecopyresampled($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $pic_width, $pic_height);
        } else {
            $newim = imagecreate($newwidth, $newheight);
            imagecopyresized($newim, $im, 0, 0, 0, 0, $newwidth, $newheight, $pic_width, $pic_height);
        }
        
        if ($oldFileType == "jpeg" || $oldFileType == "jpg") {
            imagejpeg($newim, $name);
        } else
            if ($oldFileType == "png") {
                imagepng($newim, $name);
            }
        imagedestroy($newim);
    } else {
        if ($oldFileType == "jpeg" || $oldFileType == "jpg") {
            imagejpeg($im, $name);
        } else
            if ($oldFileType == "png") {
                imagepng($im, $name);
            }
    }
}

/**
 * 自定义图片裁剪功能
 *
 * @param unknown $sourcePic
 *            裁剪的原始图片
 * @param unknown $distPic
 *            裁剪后的生成图片
 * @param unknown $startX            
 * @param unknown $startY            
 * @param unknown $width
 *            生成的新图片宽度
 * @param unknown $height
 *            生成的新图片高度
 */
function ImageCut($sourcePic, $distPic, $startX = 0, $startY = 0, $width = 200, $height = 200, $isShow = false)
{
    require_once ROOT_DIR . "Common/Library/ThumbHandler.php";
    $t = new ThumbHandler();
    $t->setSrcImg($sourcePic);
    $t->setCutType(2); // 0 按比例放大缩小图片 ,1自动剪切,2:手工剪切图片
    $t->setSrcCutPosition($startX, $startY); // 设置切割起始位置
    $t->setRectangleCut($width, $height); // 设置切割图片 宽高
    $t->setDstImg($distPic); // 生成的图片路径
    $t->createImg($width, $height); // 指定固定宽高
    if ($isShow) {
        $t->dispalyImg($distPic, '', false); // false 保存生成的图片
    }
}

/**
 * 生成文字水印图片
 *
 * @param unknown $sourcePic
 *            原始图片
 * @param unknown $distPic
 *            目标图片
 * @param unknown $waterPic
 *            水印图片
 * @param number $width
 *            生成图片的宽度
 * @param number $height
 *            生成图片的高度
 * @param number $borderWidth
 *            生成图片的边框宽度
 * @param string $borderColor
 *            生成图片的边框颜色
 * @param number $pos
 *            水印位置
 * @param number $filter
 *            透明度
 * @param string $isShow
 *            是否直接显示图片
 */
function ImageWaterMark($sourcePic, $distPic, $waterPic, $width = 200, $height = 200, $borderWidth = 1, $borderColor = '#ffffff', $pos = 1, $filter = 80, $isShow = false)
{
    require_once ROOT_DIR . "Common/Library/ThumbHandler.php";
    $t = new ThumbHandler();
    $t->setSrcImg($sourcePic); // 原始图片路径
    $t->setMaskImg($waterPic); // 水印图片路径
    $t->setDstImg($distPic); // 生成的图片路径
    $t->setMaskPosition($pos); // 值为 1、2、3、4分别对应图片的4个角.
    { // 设置水印的位置通过坐标指定
          // $t->setMaskOffsetX($_GET['x']);
          // $t->setMaskOffsetY($_GET['y']);
    }
    $t->setMaskImgPct($filter); // 透明度 为不同程度的分辨率.
    $t->setDstImgBorder($borderWidth, $borderColor);
    $t->createImg($width, $height); // 指定缩放比例
    $t->setDstImgBorder($borderWidth, $borderColor); // 设置边框
    if ($isShow) {
        $t->dispalyImg($distPic, '', false);
    }
}

/**
 * 生成图片水印图片
 *
 * @param unknown $sourcePic
 *            原图片
 * @param unknown $distPic
 *            目标图片
 * @param unknown $text
 *            文字
 * @param string $font            
 * @param number $fontSize
 *            字体大小
 * @param string $fontColor
 *            字体颜色
 * @param number $bili
 *            生成图片是原来图片的比例
 * @param number $fontBorderWidth
 *            字体边框
 * @param string $fontBorderColor
 *            边框颜色
 * @param number $pos
 *            位置
 * @param string $isShow            
 */
function ImageWaterFontMark($sourcePic, $distPic, $text, $font = "", $fontSize = 12, $fontColor = "#FF80FF", $bili = 50, $fontBorderWidth = 10, $fontBorderColor = "#dddddd", $pos = 4, $isShow = false)
{
    // 使用方法一:在图片上输出文字 用于打水印
    require_once ROOT_DIR . "Common/Library/ThumbHandler.php";
    $t = new ThumbHandler();
    // 基本使用
    $t->setSrcImg($sourcePic);
    $t->setMaskWord($text); // 字的内容
    $t->setMaskFont($font); // 设置水印字体,网上下载字体库
    $t->setMaskFontSize($fontSize); // 设置水印字体大小
    $t->setMaskFontColor($fontColor); // 设置水印字体颜色
    $t->setMaskPosition($pos); // 字的位置 //值为 1、2、3、4分别对应图片的4个角.
    $t->setDstImgBorder($fontBorderWidth, $fontBorderColor); // 字体边框
    $t->setDstImg($distPic); // 生成的图片路径
                             
    // 指定缩放比例
    $t->createImg($bili);
    if ($isShow) {
        $t->dispalyImg($distPic, '', true);
    }
}

/**
 * mysqli方式连接数据库
 *
 * @param string $db            
 * @return unknown
 */
function conn_mysqli($db = "axs")
{
    $config = Config::getConfig("db", $db);
    $mysqli = mysqli_connect($config['host'], $config['username'], $config['password'], $config['db_name'], $config['port']);
    
    if (mysqli_connect_errno()) {
        $this->msg_error = mysqli_connect_error();
        printf("Connect failed:" . $this->msg_error);
        exit();
    }
    mysqli_query($mysqli, "SET NAMES " . $config['charset']);
    return $mysqli;
}

/**
 * mysqli 对象方式连接数据库
 *
 * @param string $db            
 * @return mysqli
 */
function conn_mysqli_obj($db = "axs")
{
    $config = Config::getConfig("db", $db);
    $mysqli = new mysqli($config['host'], $config['username'], $config['password'], $config['db_name'], $config['port']);
    if ($mysqli->connect_errno) {
        printf("Connect failed: %s\n", $mysqli->connect_error);
        exit();
    }
    $mysqli->query("SET NAMES " . $config['charset']);
    return $mysqli;
}

/**
 * mysql 方式连接数据库
 *
 * @param string $db            
 */
function conn_mysql($db = "cris")
{
    $config = Config::getConfig("db", $db);
    mysql_connect($config['host'], $config['username'], $config['password'], $config['port']);
    mysql_select_db($config['db_name']);
    mysql_query("set names " . $config['charset']);
}

function unicodeToUtf8($str)
{
    $os = strtoupper(substr(PHP_OS, 0, 3));
    if ($os == 'WIN') {
        $str = preg_replace("#\\\u([0-9a-f]+)#ie", "iconv('UCS-2','UTF-8', pack('H4', '\\1'))", $str);
    } else
        if ($os == 'LIN') {
            $str = preg_replace("#\\\u([0-9a-f]{4})#ie", "iconv('UCS-2BE', 'UTF-8', pack('H4', '\\1'))", $str);
        } else {
            $str = preg_replace("#\\\u([0-9a-f]+)#ie", "iconv('UCS-2','UTF-8', pack('H4', '\\1'))", $str);
        }
    return $str;
}

function sendTelMsg($tel, $msg)
{
    $url = "http://utf8.sms.webchinese.cn/";
    $param = array(
        "Uid" => "xgl2582069",
        "KeyMD5" => "f857fa2d30124fb9229d7c1f514b25af",
        "smsMob" => $tel,
        "smsText" => $msg
    );
    $res = get_url($url, $param);
    return $res;
}

/**
 * 优惠码生成函数
 *
 * @return string
 */
function coupon()
{
    return substr(uniqid(), 3, 13);
}

/**
 * 收件随机码生成函数
 *
 * @return string
 */
function receiveCode()
{
    return rand(1000, 9999);
}

/**
 * 用户的交易密码加密
 *
 * @param unknown $pwd            
 * @return string
 */
function user_pay_pwd($pwd)
{
    $salt = "anxingsong.";
    return md5($salt . $pwd);
}

function conn_cache($db = "common")
{
    $config = Config::getConfig("cache", $db);
    
    $redis = new Redis();
    $redis->connect($config['host'], $config['port']);
    return $redis;
}

/*
 * 调用百度地图api接口计算距离
 */
function BaiduPointDistance($startPoint, $endPoint)
{
    $ak = "kLRrTpynP3zWdNkByEMieI1RrjGrFTIt";
    $urlStartRegion = "http://api.map.baidu.com/geocoder/v2/?ak={$ak}&location={$startPoint['lat']},{$startPoint['lng']}&output=json&pois=1";
    $startRegionData = get_url($urlStartRegion);
    $startRegionData = json_decode($startRegionData, true);
    if ($startRegionData['status'] > 0) {
        return array(
            'err' => 1,
            'msg' => '寄件人位置解析错误'
        );
    }
    $origin_region = $startRegionData['result']['addressComponent']['city'];
    
    $urlEndRegion = "http://api.map.baidu.com/geocoder/v2/?ak={$ak}&location={$endPoint['lat']},{$endPoint['lng']}&output=json&pois=1";
    $endRegionData = get_url($urlEndRegion);
    $endRegionData = json_decode($endRegionData, true);
    if ($endRegionData['status'] > 0) {
        return array(
            'err' => 2,
            'msg' => '收件人位置解析错误'
        );
    }
    $destination_region = $endRegionData['result']['addressComponent']['city'];
    
    $distanceUrl = "http://api.map.baidu.com/direction/v1?mode=walking&origin={$startPoint['lat']},{$startPoint['lng']}&destination={$endPoint['lat']},{$endPoint['lng']}&origin_region={$origin_region}&destination_region={$destination_region}&output=json&ak={$ak}";
    $distanceData = get_url($distanceUrl);
    $distanceData = json_decode($distanceData, true);
    if ($distanceData['status'] > 0) {
        return array(
            'err' => 3,
            'msg' => '距离计算失败'
        );
    }
    $returnDistance = $distanceData['result']['routes'][0]['distance'];
    $returnDistance = round($returnDistance / 1000, 1);
    return array(
        'err' => 0,
        'msg' => '成功',
        'distance' => $returnDistance
    );
}

/**
 * 解析ini配置文件为数组
 * @param unknown $filename 读取的ini文件
 * eg:
 *  [user1]
 *       name=zhangshan1
 *       sex=nan1
 *  [user2]
 *       name=zhangshan2
 *       sex=nan2
 *
 *调用: parseInitFile("1.ini",true);
 * @param string $model true:表示兼容  false:表示覆盖
 * @return array  返回配置数组
 */
function parseInitFile($filename,$model=false)
{
    if($model==false)
    {
        return  parse_ini_file($filename);
    }
    $content = @file($filename);
    $ret = array();
    if($content)
    {
        $arr_key="";
        foreach ($content as $val)
        {
            $val = trim($val);
            if($val)
            {
                if(strpos ( $val , "=") == false)
                {
                    $arr_key = substr($val, 1,strlen($val)-2);
                    $ret[$arr_key]=array();
                    continue;
                }
                if($arr_key)
                {
                    $temp = explode("=", $val);
                    $temp_key = trim($temp[0]);
                    $temp_val = trim($temp[1]);
                    $ret[$arr_key][$temp_key]=$temp_val;
                }
                 
            }
        }
    }
    return $ret;
}