<?php
function objtoarr($obj){
	$ret = array();
	foreach($obj as $key =>$value){
		if(gettype($value) == 'array' || gettype($value) == 'object'){
			$ret[$key] = objtoarr($value);
		}
		else{
			$ret[$key] = $value;
		}
	}
	return $ret;
}
function fulldate($time) {
	$rtime = date("Y-m-d H:i:s",$time);
	 return $rtime;
}

function addslashes_deep($value) {
    $value = is_array($value) ? array_map('addslashes_deep', $value) : addslashes($value);
    return $value;
}
function utf_substr($str, $len)
{
    $str = preg_replace("@<script(.*?)</script>@is", "", $str);
    $str = preg_replace("@<iframe(.*?)</iframe>@is", "", $str);
    $str = preg_replace("@<style(.*?)</style>@is", "", $str);
    $str = preg_replace("@<(.*?)>@is", "", $str);
    $str = str_replace("&nbsp;", '', $str);
    $str = preg_replace("/<a[^>]+>/", "", $str);
    $str = preg_replace("/<\\/a>/", "", $str);
    $str = preg_replace("/<p[^>]+>/", "", $str);
    $str = preg_replace("/<\\/p>/", "", $str);
    for ($i = 0; $i < $len; $i++) {
        $temp_str = substr($str, 0, 1);
        if (ord($temp_str) > 127) {
            $i++;
            if ($i < $len) {
                $new_str[] = substr($str, 0, 3);
                $str = substr($str, 3);
            }
        } else {
            $new_str[] = substr($str, 0, 1);
            $str = substr($str, 1);
        }
    }
    return join($new_str) . '...';
}
function stripslashes_deep($value) {
    if (is_array($value)) {
        $value = array_map('stripslashes_deep', $value);
    } elseif (is_object($value)) {
        $vars = get_object_vars($value);
        foreach ($vars as $key => $data) {
            $value->{$key} = stripslashes_deep($data);
        }
    } else {
        $value = stripslashes($value);
    }

    return $value;
}

function filter_default(&$value){
    $value = htmlspecialchars($value);
}



function get_word($html,$star,$end){
	$pat = '/'.$star.'(.*?)'.$end.'/s';
	if(!preg_match_all($pat, $html, $mat)) {                
	}else{
		$wd= $mat[1][0];
	}
	return $wd;
}

 function getpinyin($content){
	    $list = mb_split_str($content,1);
		foreach($list as $val){ 
		    $py[]= getpyz($val);
		}
		$pinyin = implode(' ',$py);
		return $pinyin;
}
function getpyz($content){		
		$url = "https://hanyu.baidu.com/s?wd=".$content."&ptype=zici";
        $ch   = curl_init();   
		curl_setopt($ch, CURLOPT_URL, $url); 
		curl_setopt($ch, CURLOPT_REFERER, "https://hanyu.baidu.com");
		curl_setopt($ch, CURLOPT_TIMEOUT, 5);          
		curl_setopt($ch, CURLOPT_USERAGENT, $ua);      
		curl_setopt($ch ,CURLOPT_FOLLOWLOCATION,1);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
		$web = curl_exec($ch);   
		curl_close($ch); 
        if(mb_strlen($content) > 1){
               $ename = get_word($web,'<b class="pinyin-font">','<\/b>');
        }else{
            preg_match_all('/<div class="pronounce" id="pinyin".*>.*<b>(.*)<\/b>.*<\/div>/isU', $web, $pinyin);
            if(isset($pinyin[1][0])){
                $ename = $pinyin[1][0];
            }
        }
        return $ename; 
}
function mb_split_str($str, $count){
        $leng = strlen($str)/3;     
        $arr = array();
        for ($i=0; $i < $leng; $i+=$count) {			
            $arr[] = mb_substr($str, $i, $count);
        }
        return $arr;
}
/**
 * 友好时间
 */
function frienddate($time) {
    $rtime = date("m-d H:i",$time);
    $htime = date("H:i",$time);
    $timetime = time() - $time;

    if ($timetime < 60) {
       $str = '刚刚';
    }
    else if ($timetime < 60 * 60) {
       $min = floor($timetime/60);
       $str = $min.'分钟前';
    }
    else if ($timetime < 60 * 60 * 24) {
       $h = floor($timetime/(60*60));
       $str = $h.'小时前 ';
    }
    else if ($timetime < 60 * 60 * 24 * 3) {
       $d = floor($timetime/(60*60*24));
       if($d==1)
       $str = '昨天 '.$htime;
    else
       $str = '前天 '.$htime;
    }
    else {
       $str = $rtime;
    }
    return $str;
}

function getImgs($content, $order = 'ALL')
{
    $pattern = "/<img.*?src=[\\'|\"](.*?(?:[\\.gif|\\.jpg]))[\\'|\"].*?[\\/]?>/";
    preg_match_all($pattern, $content, $match);
    if (isset($match[1]) && !empty($match[1])) {
        if ($order === 'ALL') {
            return $match[1];
        }
        if (is_numeric($order) && isset($match[1][$order])) {
            $ps = $order - 1;
            return $match[1][$ps];
        }
    }
    return '';
}

function http( $url, $ua = "" ){
	$opts = array(
		"http" => array(
			"header" => "USER-AGENT: ".$ua)
	);
	$context = stream_context_create( $opts );
    $html = @file_get_contents( $url, FALSE, $context );
	if(!$html){
		$html = @file_get_contents( $url, FALSE, $context );
		if(!$html){
			$html = @file_get_contents( $url, FALSE, $context);
		}
	}
	for($i=0; $i < 10; $i++ ){
		if(!($html=== FALSE )){
			break;
		}
		$html = @file_get_contents( $url, FALSE, $context );
	}
	return $html;
}

function utf8( $string, $code = "" ){
	$code = mb_detect_encoding($string,array('GBK', 'UTF-8', 'UTF-16LE', 'UTF-16BE', 'ISO-8859-1'));
	return mb_convert_encoding( $string, "UTF-8", true );
}

function attach($attach, $type) {
    if (false === strpos($attach, 'http://') && false === strpos($attach, 'https://')) {
        //本地附件
        return __ROOT__ . '/' . C('ftx_attach_path') . $type . '/' . $attach;
        //远程附件
        //todo...
    } else {
        //URL链接
        return $attach;
    }
}
function get_id($url) {
        $id = 0;
        $parse = parse_url($url);
        if (isset($parse['query'])) {
            parse_str($parse['query'], $params);
            if (isset($params['id'])) {
                $id = $params['id'];
            } elseif (isset($params['item_id'])) {
                $id = $params['item_id'];
            } elseif (isset($params['default_item_id'])) {
                $id = $params['default_item_id'];
            } elseif (isset($params['amp;id'])) {
                $id = $params['amp;id'];
            } elseif (isset($params['amp;item_id'])) {
                $id = $params['amp;item_id'];
            } elseif (isset($params['amp;default_item_id'])) {
                $id = $params['amp;default_item_id'];
            }
        }
        return $id;
    }
/*
 * 获取缩略图
 */
function get_thumb($img, $suffix = '_thumb') {    
    if (strpos($img, 'data/upload') && false === strpos($img, 'https://') && false === strpos($img, 'http://')) { 
        $thumb = $img;
    } else {        			
		$thumb = $img;		
    }	
    return $thumb;
}

/*
 * 中文截取内容
 */
function gettt($description,$length){				
		$description = str_replace(PHP_EOL,'',$description);
		$description = strip_tags($description);  
        $description = trim($description);  
        $description = mb_substr($description,0,$length,'utf-8');      
		$description = str_replace("\t","",$description);  
		$description = str_replace("\r\n","",$description);  
		$description = str_replace("\r","",$description);  
		$description = str_replace("\n","",$description); 
		$description = str_replace(" ","",$description);  
		$description = preg_replace("/<strong[^>]+>/", "<strong>", $description);
		return $description;
	}

/**
 * 将数组键名变成大写或小写
 * @param array $arr 数组
 * @param int $type 转换方式 1大写   0小写
 * @return array
 */
function array_change_key_case_d($arr, $type = 0)
{
    $function = $type ? 'strtoupper' : 'strtolower';
    $newArr = array(); //格式化后的数组
    if (!is_array($arr) || empty($arr))
        return $newArr;
    foreach ($arr as $k => $v) {
        $k = $function($k);
        if (is_array($v)) {
            $newArr[$k] = array_change_key_case_d($v, $type);
        } else {
            $newArr[$k] = $v;
        }
    }
    return $newArr;
}
function getBaseDomain($url='',$type){
		if(!$url){
		return $url[$type];
		}  
		$state_domain = array(
		'al','dz','af','ar','ae','aw','om','az','eg','et','ie','ee','ad','ao','ai','ag','at','au','mo','bb','pg','bs','pk','py','ps','bh','pa','br','by','bm','bg','mp','bj','be','is','pr','ba','pl','bo','bz','bw','bt','bf','bi','bv','kp','gq','dk','de','tl','tp','tg','dm','do','ru','ec','er','fr','fo','pf','gf','tf','va','ph','fj','fi','cv','fk','gm','cg','cd','co','cr','gg','gd','gl','ge','cu','gp','gu','gy','kz','ht','kr','nl','an','hm','hn','ki','dj','kg','gn','gw','ca','gh','ga','kh','cz','zw','cm','qa','ky','km','ci','kw','cc','hr','ke','ck','lv','ls','la','lb','lt','lr','ly','li','re','lu','rw','ro','mg','im','mv','mt','mw','my','ml','mk','mh','mq','yt','mu','mr','us','um','as','vi','mn','ms','bd','pe','fm','mm','md','ma','mc','mz','mx','nr','np','ni','ne','ng','nu','no','nf','na','za','aq','gs','eu','pw','pn','pt','jp','se','ch','sv','ws','yu','sl','sn','cy','sc','sa','cx','st','sh','kn','lc','sm','pm','vc','lk','sk','si','sj','sz','sd','sr','sb','so','tj','tw','th','tz','to','tc','tt','tn','tv','tr','tm','tk','wf','vu','gt','ve','bn','ug','ua','uy','uz','es','eh','gr','hk','sg','nc','nz','hu','sy','jm','am','ac','ye','iq','ir','il','it','in','id','uk','vg','io','jo','vn','zm','je','td','gi','cl','cf','cn','yr','com','arpa','edu','gov','int','mil','net','org','biz','info','pro','name','museum','coop','aero','xxx','idv','me','mobi','asia','ax','bl','bq','cat','cw','gb','jobs','mf','rs','su','sx','tel','travel','accountant','app','art','auction','audio','auto','band','bar','beer','best','bid','bike','black','blog','blue','business','cab','cafe','camera','car','cards','cars','cash','center','ceo','chat','city','click','clothing','club','cn.com','coffee','com.co','com.hk','com.tw','company','cool','credit','cricket','date','design','dev','diet','dog','domains','download','email','equipment','estate','expert','faith','family','fans','feedback','fish','fit','flowers','fun','fund','fyi','game','games','gift','gives','gold','group','guru','haus','help','holiday','host','hosting','house','ink','kim','land','life','link','live','loan','lol','love','ltd','market','marketing','mba','media','men','mom','money','net.co','network','news','one','online','ooo','party','pet','photo','photography','photos','pics','pink','plus','press','property','pub','racing','red','ren','rent','review','rip','run','sale','school','science','services','sex','sexy','shop','show','site','social','software','solutions','space','store','studio','style','support','taipei','tax','team','tech','test','tips','today','tools','top','town','toys','trade','ventures','vet','video','vin','vip','wang','watch','webcam','website','wiki','win','wine','work','works','world','wtf','xin','xyz','yoga','zone','net.cn','org.cn'
  		);
    
		if(!preg_match("/^http/is", $url)){
		$url="http://".$url;
		}  
		$res = null;
		$res['domain'] = null;
		$res['host'] = null;
		$url_parse = parse_url(strtolower($url));
		$urlarr = explode(".", $url_parse['host']);
		$count = count($urlarr);    
		if($count <= 2){		
		$res['domain'] = $url_parse['host'];
		}elseif($count > 2){
		$last = array_pop($urlarr);
		$last_1 = array_pop($urlarr);
		$last_2 = array_pop($urlarr);      
		$res['domain'] = $last_1.'.'.$last;
		$res['host'] = $last_2;      
		if(in_array($last, $state_domain)){
		$res['domain']=$last_1.'.'.$last;
		$res['host']=implode('.', $urlarr);
		}      
		if(in_array($last_1, $state_domain)){
		$res['domain'] = $last_2.'.'.$last_1.'.'.$last;
		$res['host'] = implode('.', $urlarr);
		}    
		}
		return $res[$type];
    }     
    