<?php
include_once "./zoujingli/wechat-php-sdk/include.php";
// alert提示
function alertMsg($string = "", $url = "")
{
    if (!$url) {
        // if ($_SERVER['HTTP_REFERER']) {
        //     echo "<script>alert('$string');location.href='{$_SERVER['HTTP_REFERER']}';</script>";die;
        // } else {
            echo "<script>alert('$string');location.href=history.back();</script>";die;
        // }
    } else {
        echo "<script>alert('$string');location.href='$url';</script>";die;
    }
}


/************************************************************** 
 * 
 *  将数组转换为JSON字符串（兼容中文） 
 *  @param  array   $array      要转换的数组 
 *  @return string      转换得到的json字符串 
 *  @access public 
 * 
 *************************************************************/
function JSON($array) { 
    arrayRecursive($array, 'urlencode', true); 
    $json = json_encode($array); 
    return urldecode($json); 
} 
/************************************************************** 
 * 
 *  使用特定function对数组中所有元素做处理 
 *  @param  string  &amp;$array     要处理的字符串 
 *  @param  string  $function   要执行的函数 
 *  @return boolean $apply_to_keys_also     是否也应用到key上 
 *  @access public 
 * 
 *************************************************************/
function arrayRecursive(&$array, $function, $apply_to_keys_also = false){ 
    static $recursive_counter = 0; 
    if (++$recursive_counter > 1000) { 
        die('possible deep recursion attack'); 
    } 
    foreach ($array as $key => $value) { 
        if (is_array($value)) { 
            arrayRecursive($array[$key], $function, $apply_to_keys_also); 
        } else { 
            $array[$key] = $function($value); 
        }                                        
        if ($apply_to_keys_also && is_string($key)) { 
            $new_key = $function($key); 
            if ($new_key != $key) { 
                $array[$new_key] = $array[$key]; 
                unset($array[$key]); 
            } 
        } 
    } 
    $recursive_counter--; 
}

// API 返回数据
function apiReturn($data)
{
    echo json_encode($data);die;
}

//substr() 自定义
function my_substr($str, $index = '', $lenth = '')
{
    //起始位置
    if (!$index) {
        $index = 0;
    } elseif ($index < 0) {
        $index = strlen($str) + $index;
    }
    //截取长度
    if ($lenth) {
        if ($lenth < 0) {
            $len_cur = strlen($str) + $lenth;
        } else {
            $len_cur = $lenth + $index;
        }
    } else {
        $len_cur = strlen($str);
    }
    //编码判断
    $encoding = mb_detect_encoding($str, array('UTF-8', 'GBK'));
    if ($encoding == 'UTF-8') {
        header("Content-type:text/html;charset=UTF-8");
        $zifuji = "UTF-8";
        $step = 3;
    } else {
        header("Content-type:text/html;charset=GBK");
        $zifuji = "GBK";
        $step = 2;
    }
    //数组拼装
    $arr = array();
    if ($index < 0) {
        $index = 0;
    }
    if ($len_cur > strlen($str)) {
        $len_cur = strlen($str);
    }
    for ($i=0; $i < $len_cur; $i++) { 
        $ascii = ord($str{$i});
        if ($ascii < 128) {
            if (($index > 0) && ($i >= $index)) {
                $arr[] = $str[$i];
            } elseif ($index == 0) {
                $arr[] = $str[$i];
            }
        } else {
            if (($index > 0) && ($i >= $index)) {
                $arr[] = $str_now = substr($str, $i, $step);
            } elseif ($index == 0) {
                $arr[] = $str_now = substr($str, $i, $step);
            }
            $i = $i + $step - 1;
        }
    }
    //提示当前字符集
    // echo '<script type="text/javascript">alert("当前字符集为 '.$zifuji.'");</script>';
    //字符串组装
    return implode("", $arr);
}

/**
 * Get 请求 模拟登陆
 * @param  string $url 访问链接
 * @return mix
 */
function curlGet($url)
{
    // 使用 curl_init()函数初始化一个CURL会话，初始化成功后返回一个句柄供curl_setopt(), curl_exec(),和 curl_close() 函数使用
    $curl = curl_init();
    // 使用curl_setopt()设置要获取的URL地址
    curl_setopt($curl, CURLOPT_URL, $url);
    // 设置是否输出header 设为0 否则影响输出
    curl_setopt($curl, CURLOPT_HEADER, 0);
    // 设置是否输出结果
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    // 设置是否输出结果
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    // 设置是否检查服务器端的证书
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    // 使用curl_exec()将CURL返回的结果转换成正常数据并保存到一个变量
    $data = curl_exec($curl);
    // 使用 curl_close() 关闭CURL会话
    curl_close($curl);
    return $data;
}

/**
 * Post 请求 模拟登陆
 * @param  string $url  访问链接
 * @param  array $data 请求参数
 * @return mix
 */
function curlPost($url, $data = array())
{
    // dump($data);die;
    $data = json_encode($data);
    $headers = array(
        // "Content-type: application/json",
        "Content-type: text/html; charset=UTF-8",
    );
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);// dump($data);// die;
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}


/**
 * [get_curl description]
 * @param  [type] $json   [传递的数据]
 * @param  [type] $url    [访问的接口地址]
 * @param  [type] $second [超时时间]
 * @return [type]         [正常返回结果错误返回false]
 */
function get_curl($json,$url,$second=30)
{
    $type = 'get';
    $arr = json_decode($json);
        
    //拼接字符串
    $url .= '?';
    foreach ($arr as $key => $value) {
        $url .= '&'.$key.'='.$value;
    }

    //执行并返回数据
    $ch = _curl($url,$second,$type);
    $ret = curl_exec($ch);
    if ($ret) {
        curl_close($ch);
        return $ret;
    }else{
        $error = curl_errno($ch);
        echo "curl出错，错误码:$error"."<br>"; 
        echo "<a href='http://curl.haxx.se/libcurl/c/libcurl-errors.html'>错误原因查询</a></br>";
        curl_close($ch);
        return FALSE;
    }
}

/**
 * POST方式
 * @param  [type]  $json   [传递的数据]
 * @param  [type]  $url    [访问的接口地址]
 * @param  integer $second [超时时间]
* @return [type]          [正常返回结果错误返回false]
 */
// function post_curl($json,$url,$second=30)
// {
//     //执行并返回数据
//     $ch = _curl($json,$url,$second);
//     $ret = curl_exec($ch);
//     if ($ret) {
//         curl_close($ch);
//         return $ret;
//     }else{
//         $error = curl_errno($ch);
//         echo "curl出错，错误码:$error"."<br>"; 
//         echo "<a href='http://curl.haxx.se/libcurl/c/libcurl-errors.html'>错误原因查询</a></br>";
//         curl_close($ch);
//         return FALSE;
//     }
// }

function post_curl($url = '', $post_data = array(), $timeout = 30)
{
        if (empty($url) || empty($post_data)) {
            return false;
        }

        header("Content-type: text/html; charset=UTF-8");
        $ch = curl_init();//初始化curl
        $timeout = 5;
        curl_setopt($ch, CURLOPT_URL,$url);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        $data = curl_exec($ch);//运行curl
        curl_close($ch);
        return $data;
    }

/**
 * curl
 * @param  string  $json   [传递的数据]
 * @param  [type]  $url    [访问的接口地址]
 * @param  integer $second [超时时间]
 * @param  string  $type   [调用类型-post/get]
 * @return [type]          [curl权柄]
 */
function _curl($json='',$url,$second=30,$type='post')
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_TIMEOUT, $second);//设置超时
    curl_setopt($ch,CURLOPT_URL, $url);
    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
    curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
    //设置header
    curl_setopt($ch, CURLOPT_HEADER, FALSE);
    //要求结果为字符串且输出到屏幕上
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

    if ($type==='post') {
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    }

    return $ch;
}


/** 
* @desc 根据两点间的经纬度计算距离 
* @param float $lat 纬度值 
* @param float $lng 经度值 
*/
function getDistance($lng1, $lat1, $lng2, $lat2) 
{ 
    // 将角度转为狐度
    $radLat1 = deg2rad($lat1); //deg2rad()函数将角度转换为弧度
    $radLat2 = deg2rad($lat2);
    $radLng1 = deg2rad($lng1);
    $radLng2 = deg2rad($lng2);
    $a = $radLat1 - $radLat2;
    $b = $radLng1 - $radLng2;
    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137 * 1000;
    return $s;
}

/**
 * 获取微信操作对象
 * @staticvar array $wechat
 * @param type $type
 * @return WechatReceive
 */
function & load_wechat($type = '',$admin_id) {
    !class_exists('Wechat\Loader', FALSE) && Vendor('Wechat.Loader');
    static $wechat = array();
    $index = md5(strtolower($type));
    if (!isset($wechat[$index])) {
        // 从数据库查询配置参数
        $config = M('wechat_config')->where('admin_id='.$admin_id)->field('token,mch_id,appid,appsecret,partnerkey,ssl_cer,ssl_key')->find();
        // 设置SDK的缓存路径
        $config['cachepath'] = CACHE_PATH . 'Data/';
        $wechat[$index] = \Wechat\Loader::get_instance($type, $config);
    }
    return $wechat[$index];
}

/**
 * [create_xls 导出excel表格]
 * @param  array  $data     [表的数据]
 * @param  string $filename [文件名]
 */
function create_xls($data,$filename='simple.xls'){
    ini_set('max_execution_time', '0');
    Vendor('PHPExcel');
    $filename = str_replace('.xls', '', $filename).'.xls';
    $phpexcel = new PHPExcel();
    $phpexcel->getProperties()
        ->setCreator("Maarten Balliauw")
        ->setLastModifiedBy("Maarten Balliauw")
        ->setTitle("Office 2007 XLSX Test Document")
        ->setSubject("Office 2007 XLSX Test Document")
        ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
        ->setKeywords("office 2007 openxml php")
        ->setCategory("Test result file");
    $phpexcel->getActiveSheet()->fromArray($data);
    $phpexcel->getActiveSheet()->setTitle('Sheet1');
    $phpexcel->setActiveSheetIndex(0);
    header('Content-Type: application/vnd.ms-excel');
    header("Content-Disposition: attachment;filename=$filename");
    header('Cache-Control: max-age=0');
    header('Cache-Control: max-age=1');
    header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
    header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
    header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
    header ('Pragma: public'); // HTTP/1.0
    $objwriter = PHPExcel_IOFactory::createWriter($phpexcel, 'Excel5');
    $objwriter->save('php://output');
    exit;
}

/**
 * 系统邮件发送函数
 * @param string $tomail 接收邮件者邮箱
 * @param string $name 接收邮件者名称
 * @param string $subject 邮件主题
 * @param string $body 邮件内容
 * @param string $attachment 附件列表
 * @return boolean
 * @author static7 <static7@qq.com>
 */
function send_mail($tomail, $name, $subject = '', $body = '', $attachment = null) {
    vendor('PHPMailer.PHPMailerAutoload');
    $mail = new PHPMailer();           //实例化PHPMailer对象
    $mail->CharSet = 'UTF-8';           //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码
    $mail->IsSMTP();                    // 设定使用SMTP服务
    $mail->SMTPDebug = 0;               // SMTP调试功能 0=关闭 1 = 错误和消息 2 = 消息
    $mail->SMTPAuth = true;             // 启用 SMTP 验证功能
    $mail->SMTPSecure = 'ssl';          // 使用安全协议
    $mail->Host = "smtp.qq.com"; // SMTP 服务器
    $mail->Port = 465;                  // SMTP服务器的端口号
    $mail->Username = '32241931@qq.com';    // SMTP服务器用户名
    $mail->Password = 'jgwkqdgokrpycaij';     // SMTP服务器密码
    $mail->SetFrom('32241931@qq.com', '极速上线');
    $replyEmail = '';                   //留空则为发件人EMAIL
    $replyName = '';                    //回复名称（留空则为发件人名称）
    $mail->AddReplyTo($replyEmail, $replyName);
    $mail->Subject = $subject;
    $mail->MsgHTML($body);
    $mail->AddAddress($tomail, $name);
    if (is_array($attachment)) { // 添加附件
        foreach ($attachment as $file) {
            is_file($file) && $mail->AddAttachment($file);
        }
    }
    return $mail->Send() ? true : $mail->ErrorInfo;
}