<?php
/**
 * 字符截取 支持UTF8/GBK
 * @param $string
 * @param $length
 * @param $dot
 */
function str_cut($string, $length, $dot = '...') {
	$strlen = strlen($string);
	if($strlen <= $length) return $string;
	$string = str_replace(array(' ','&nbsp;', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), array('∵',' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), $string);
	$strcut = '';
	if(strtolower(CHARSET) == 'utf-8') {
		$length = intval($length-strlen($dot)-$length/3);
		$n = $tn = $noc = 0;
		while($n < strlen($string)) {
			$t = ord($string[$n]);
			if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
				$tn = 1; $n++; $noc++;
			} elseif(194 <= $t && $t <= 223) {
				$tn = 2; $n += 2; $noc += 2;
			} elseif(224 <= $t && $t <= 239) {
				$tn = 3; $n += 3; $noc += 2;
			} elseif(240 <= $t && $t <= 247) {
				$tn = 4; $n += 4; $noc += 2;
			} elseif(248 <= $t && $t <= 251) {
				$tn = 5; $n += 5; $noc += 2;
			} elseif($t == 252 || $t == 253) {
				$tn = 6; $n += 6; $noc += 2;
			} else {
				$n++;
			}
			if($noc >= $length) {
				break;
			}
		}
		if($noc > $length) {
			$n -= $tn;
		}
		$strcut = substr($string, 0, $n);
		$strcut = str_replace(array('∵', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), array(' ', '&amp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;'), $strcut);
	} else {
		$dotlen = strlen($dot);
		$maxi = $length - $dotlen - 1;
		$current_str = '';
		$search_arr = array('&',' ', '"', "'", '“', '”', '—', '<', '>', '·', '…','∵');
		$replace_arr = array('&amp;','&nbsp;', '&quot;', '&#039;', '&ldquo;', '&rdquo;', '&mdash;', '&lt;', '&gt;', '&middot;', '&hellip;',' ');
		$search_flip = array_flip($search_arr);
		for ($i = 0; $i < $maxi; $i++) {
			$current_str = ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
			if (in_array($current_str, $search_arr)) {
				$key = $search_flip[$current_str];
				$current_str = str_replace($search_arr[$key], $replace_arr[$key], $current_str);
			}
			$strcut .= $current_str;
		}
	}
	return $strcut.$dot;
}
function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true){  
  if(function_exists("mb_substr")){
              if($suffix)
              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);  
         }  
         $re['utf-8']   = "/[x01-x7f]|[xc2-xdf][x80-xbf]|[xe0-xef]
                  [x80-xbf]{2}|[xf0-xff][x80-xbf]{3}/";  
         $re['gb2312'] = "/[x01-x7f]|[xb0-xf7][xa0-xfe]/";  
         $re['gbk']    = "/[x01-x7f]|[x81-xfe][x40-xfe]/";  
         $re['big5']   = "/[x01-x7f]|[x81-xfe]([x40-x7e]|xa1-xfe])/";  
         preg_match_all($re[$charset], $str, $match);  
         $slice = join("",array_slice($match[0], $start, $length));  
         if($suffix) return $slice."…";  
         return $slice;
    }
/*模型生成链接
$v= id或其它唯一值参数
$model = 模块 例如content
$app = action 例如list*/
function gurl($v,$model,$app){
	U($model.'/'.$app);
}
/*加密解密
$en = encrypt($data, $key);  加密
$de = decrypt($en, $key); 解密
*/
function encrypt($data, $key='feimao88.com') { 
	$prep_code = serialize($data); 
	$block = mcrypt_get_block_size('des', 'ecb'); 
	if (($pad = $block - (strlen($prep_code) % $block)) < $block) { 
	$prep_code .= str_repeat(chr($pad), $pad); 
	} 
	$encrypt = mcrypt_encrypt(MCRYPT_DES, $key, $prep_code, MCRYPT_MODE_ECB); 
	return base64_encode($encrypt); 
} 

function decrypt($str, $key='feimao88.com') { 
	$str = base64_decode($str); 
	$str = mcrypt_decrypt(MCRYPT_DES, $key, $str, MCRYPT_MODE_ECB); 
	$block = mcrypt_get_block_size('des', 'ecb'); 
	$pad = ord($str[($len = strlen($str)) - 1]); 
	if ($pad && $pad < $block && preg_match('/' . chr($pad) . '{' . $pad . '}$/', $str)) { 
	$str = substr($str, 0, strlen($str) - $pad); 
	} 
	return unserialize($str); 
} 
/*内容操作，$v=内容；$len=长度*/
function up_content($v,$len='10',$s){
	$v = str_replace('<br/>','\n',$v);
	$v = str_replace('&nbsp;',' ',$v);
	return msubstr($v,0,$len,"utf-8",false);
}
function convert_html_to_swf($url = '') 
{
    if(!is_string($url) || empty($url)) return ;
    if(strpos($url, 'swf')) return $url;
    
    preg_match_all('/http:\/\/(.*?)?\.(.*?)?\.com\/(.*)/', $url, $types);
    $type = $types[2][0];
    $domain = $types[1][0];
 
    switch ($type) {
        case 'youku' :
            preg_match_all('/http:\/\/v\.youku\.com\/v_show\/id_(.*)?\.html/', $url, $url_array);
            $swf = 'http://player.youku.com/player.php/sid/' . str_replace('/', '', $url_array[1][0]) . '/v.swf';
            break;
        
        case 'tudou' :
            $method = substr($types[3][0], 0, 1);
            $method = $method == 'p' ? 'v' : $method;
            preg_match_all('/http:\/\/www.tudou\.com\/(.*)?\/(.*)?/', $url, $url_array);
            $str_arr = explode('/', $url_array[1][0]);
            $count = count($str_arr);
            
            if ($count == 1) {
                $id = explode('.', $url_array[2][0]);
                $id = $id[0];
            } else if ($count == 2) {
                $id = $str_arr[1];
            } else if ($count == 3) {
                $id = $str_arr[2];
            }
            
            $swf = 'http://www.tudou.com/' . $method . '/' . $id . '/v.swf';
            break;
            
        case 'qq' :
            $url_array = parse_url($url);
            $swf = "http://static.video.qq.com/TPout.swf?{$url_array['query']}&auto=0";
            break;
 
        default :
            $swf = false;
            break;
    }
    return $swf;
}
/*@description    取得两个时间戳相差的年龄
 * @before         较小的时间戳
 * @after          较大的时间戳
 * @return str     返回相差年龄y岁m月d天*/
function datediffage($before, $after) {
 if ($before>$after) {
  $b = getdate($after);
  $a = getdate($before);
 }
 else {
  $b = getdate($before);
  $a = getdate($after);
 }
 $n = array(1=>31,2=>28,3=>31,4=>30,5=>31,6=>30,7=>31,8=>31,9=>30,10=>31,11=>30,12=>31);
 $y=$m=$d=0;
 if ($a['mday']>=$b['mday']) { //天相减为正
  if ($a['mon']>=$b['mon']) {//月相减为正
   $y=$a['year']-$b['year'];$m=$a['mon']-$b['mon'];
  }
  else { //月相减为负，借年
   $y=$a['year']-$b['year']-1;$m=$a['mon']-$b['mon']+12;
  }
  $d=$a['mday']-$b['mday'];
 }
 else {  //天相减为负，借月
  if ($a['mon']==1) { //1月，借年
   $y=$a['year']-$b['year']-1;$m=$a['mon']-$b['mon']+12;$d=$a['mday']-$b['mday']+$n[12];
  }
  else {
   if ($a['mon']==3) { //3月，判断闰年取得2月天数
    $d=$a['mday']-$b['mday']+($a['year']%4==0?29:28);
   }
   else {
    $d=$a['mday']-$b['mday']+$n[$a['mon']-1];
   }
   if ($a['mon']>=$b['mon']+1) { //借月后，月相减为正
    $y=$a['year']-$b['year'];$m=$a['mon']-$b['mon']-1;
   }
   else { //借月后，月相减为负，借年
    $y=$a['year']-$b['year']-1;$m=$a['mon']-$b['mon']+12-1;
   }
  }
 }
 return ($y==0?'':$y.'年').($m==0?'':$m.'月').($d==0?'':$d.'天');
}
/*判断手机版本*/
function isMobile()
{ 
    // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
    if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
    {
        return true;
    } 
    // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
    if (isset ($_SERVER['HTTP_VIA']))
    { 
        // 找不到为flase,否则为true
        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'
            ); 
        // 从HTTP_USER_AGENT中查找手机浏览器的关键字
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT'])))
        {
            return true;
        } 
    } 
    // 协议法，因为有可能不准确，放到最后判断
    if (isset ($_SERVER['HTTP_ACCEPT']))
    { 
        // 如果只支持wml并且不支持html那一定是移动设备
        // 如果支持wml和html但是wml在html之前则是移动设备
        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 GrabImage($url, $filename = "") {
 if ($url == ""):return false;
 endif;
 //如果$url地址为空，直接退出
 if ($filename == "") {
 //如果没有指定新的文件名
 $ext = strrchr($url, ".");
 //得到$url的图片格式
	 $ext = '.png';
 //如果图片格式不为.gif或者.jpg，直接退出
 $file_path = 'uploads/images/'.date("Y").date("m").date("d");
 if(!is_dir($file_path)){
	mkdir($file_path, 0777, true);
 }
 $filename = $file_path. '/' . rand(0,10).rand(0,10).rand(0,10).rand(0,10).rand(0,10).rand(0,10) . time() . $ext;
 //用天月面时分秒来命名新的文件名
 } 
 ob_start();//打开输出
 readfile($url);//输出图片文件
 $img = ob_get_contents();//得到浏览器输出
 ob_end_clean();//清除输出并关闭
 $size = strlen($img);//得到图片大小
 $fp2 = @fopen($filename, "a");
 fwrite($fp2, $img);//向当前目录写入图片文件，并重新命名
 fclose($fp2);
 return $filename;//返回新的文件名
}
function _safe($str){

    $html_string = array("&amp;", "&nbsp;", "'", '"', "<", ">", "\t", "\r");

    $html_clear = array("&", " ", "&#39;", "&quot;", "&lt;", "&gt;", "&nbsp; &nbsp; ", "");

    $js_string = array("/<script(.*)<\/script>/isU");

    $js_clear = array("");

    

    $frame_string = array("/<frame(.*)>/isU", "/<\/fram(.*)>/isU", "/<iframe(.*)>/isU", "/<\/ifram(.*)>/isU",);

    $frame_clear = array("", "", "", "");

    

    $style_string = array("/<style(.*)<\/style>/isU", "/<link(.*)>/isU", "/<\/link>/isU");

    $style_clear = array("", "", "");

    

    $str = trim($str);

    //过滤字符串

    // $str = str_replace($html_string, $html_clear, $str);

    //过滤JS

    $str = preg_replace($js_string, $js_clear, $str);

    //过滤ifram

    $str = preg_replace($frame_string, $frame_clear, $str);

    //过滤style

    $str = preg_replace($style_string, $style_clear, $str);

    return $str;

}
/*标签云，随机颜色*/
function randColor(){
    $colors = array();
    for($i = 0;$i<6;$i++){
        $colors[] = dechex(rand(0,15));
    }
    return implode('',$colors);
}

/*获取用户等级*/
function user_group($integral){
  $result = M('users_group')->where("min_integral <= ". $integral ."")->order("min_integral desc")->find();
  return $result;
}
function get_ad($id){
  $result = D('ad')->where("id='". $id ."'")->find();
  if($result['type'] == '1'){
    return '<a href="'. $result['url'] .'"><img src="'. $result['pic'] .'"></a>';
  }elseif($result['type'] == '2'){
    return $result['value'];
  }
}
?>