<?php
	function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true){
		if(function_exists("mb_substr")) {
		  if($suffix){
			 if($str==mb_substr($str, $start, $length, $charset)){ 
			 
				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){
		
			 if($str==iconv_substr($str,$start,$length,$charset)){ 
			 
				return iconv_substr($str,$start,$length,$charset); 
			 }
			 else{
			 
				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;
	}
	function delhtml($html){
	$search = array ("'<script[^>]*?>.*?</script>'si",  // 去掉 javascript
					  "'<[\/\!]*?[^<>]*?>'si",          // 去掉 HTML 标记
					  "'([\r\n])[\s]+'",                // 去掉空白字符
					  "'&(quot|#34);'i",                // 替换 HTML 实体
					  "'&(amp|#38);'i",
					  "'&(lt|#60);'i",
					  "'&(gt|#62);'i",
					  "'&(nbsp|#160);'i"
					  );                    // 作为 PHP 代码运行
					  $replace = array ("","","\\1","\"","&","<",">"," ");
					  $html = preg_replace($search, $replace, $html);
					  return $html;
	}
	//批量过滤post,get敏感数据  
	function stripslashes_array(&$array) {  
	
	while(list($key,$var) = each($array)) {  
	
	 if ($key != 'argc' && $key != 'argv' && (strtoupper($key) != $key || ''.intval($key) == "$key")) {  
	
	if (is_string($var)) {  
	
	 $array[$key] = stripslashes($var);  
	
	}  
	
	 if (is_array($var))  {  
	
	 $array[$key] = stripslashes_array($var);  
	
	 }  
	
	 }  
	
	 }  
	
	 return $array;  
	
	 }  
	
	//防止SQL注入
	function lib_replace_end_tag($str){   
	 if (empty($str)) return false;  
	
		 $str = htmlspecialchars($str);  
		
		 $str = str_replace( '/', "", $str);  
		
		 $str = str_replace("\\", "", $str);  
		
		 $str = str_replace("&gt", "", $str);  
		
		 $str = str_replace("&lt", "", $str);  
		
		 $str = str_replace("<SCRIPT>", "", $str);  
		
		 $str = str_replace("</SCRIPT>", "", $str);  
		
		 $str = str_replace("<script>", "", $str);  
		
		 $str = str_replace("</script>", "", $str);  
		
		 $str=str_replace("select","select",$str);  
		
		 $str=str_replace("join","join",$str);  
		
		 $str=str_replace("union","union",$str);  
		
		 $str=str_replace("where","where",$str);  
		
		 $str=str_replace("insert","insert",$str);  
		
		 $str=str_replace("delete","delete",$str);  
		
		 $str=str_replace("update","update",$str);  
		
		 $str=str_replace("like","like",$str);  
		
		$str=str_replace("drop","drop",$str);  
		
		 $str=str_replace("create","create",$str);  
		
		 $str=str_replace("modify","modify",$str);  
		
		 $str=str_replace("rename","rename",$str);  
		
		 $str=str_replace("alter","alter",$str);  
		
		 $str=str_replace("cas","cast",$str);  
		
		 $str=str_replace("&","&",$str);  
		
		 $str=str_replace(">",">",$str);  
		
		 $str=str_replace("<","<",$str);  
		
		 $str=str_replace(" ",chr(32),$str);  
		
		 $str=str_replace(" ",chr(9),$str);  
		
		 $str=str_replace("    ",chr(9),$str);  
		
		 $str=str_replace("&",chr(34),$str);  
		
		 $str=str_replace("'",chr(39),$str);  
		
		 $str=str_replace("<br />",chr(13),$str);  
		
		 $str=str_replace("''","'",$str);  
		
		 $str=str_replace("css","'",$str);  
		
		 $str=str_replace("CSS","'",$str);  
		
		 return $str;  
	
	 } 
	
	function blogTags($tags){
	
		$tags = explode(' ',$tags);
		$str = '';
		foreach($tags as $key=>$val) {
			$tag =  trim($val);
			$str  .= ' <a href="'.__APP__.'/Blog/tag/name/'.urlencode($tag).'">'.$tag.'</a>  ';
			
		}
		return $str;
	}
	function webTags($tags){
	
		$tags = explode(' ',$tags);
		$str = '';
		foreach($tags as $key=>$val) {
			$tag =  trim($val);
			$str  .= ' <a href="'.__APP__.'/Web/tag/name/'.urlencode($tag).'">'.$tag.'</a>  ';
			
		}
		return $str;
	}		
	/**
	* 产生随机字符串
	*/
	function random() {
		$hash = '';
		$chars = 'abcdef0123';
		$max = strlen($chars) - 1;
		for($i = 0; $i < 2; $i++) {
			$hash .= $chars[mt_rand(0, $max)];
		}
		return $hash;
	}
	function tourl($url) {
		$url= str_replace("//","#",$url);
		$url=str_replace(":","%",$url);
		$url=str_replace(".","@",$url);
		
		for ($i=0;$i<strlen($url);$i++){ 
			$urls.= $url[$i].random();
		}
		return $urls;
	
		
		}
	function sizecount($filesize) {
		if ($filesize >= 1073741824) {
			$filesize = round($filesize / 1073741824 * 100) / 100 .' GB';
		} elseif ($filesize >= 1048576) {
			$filesize = round($filesize / 1048576 * 100) / 100 .' MB';
		} elseif($filesize >= 1024) {
			$filesize = round($filesize / 1024 * 100) / 100 . ' KB';
		} else {
			$filesize = $filesize.' Bytes';
		}
		return $filesize;
	}
	function color_txt($str){
	
		if(function_exists('iconv_strlen')) {
			$len  = iconv_strlen($str);
		}else if(function_exists('mb_strlen')) {
			$len = mb_strlen($str);
		}
		$colorTxt = '';
		for($i=0; $i<$len; $i++) {
				   $colorTxt .=  '<span style="color:'.rand_color().'">'.msubstr($str,$i,1,'utf-8','').'</span>';
		 }
	
		return $colorTxt;
	}
	function rcolor() {
	$rand = rand(0,255);
	return sprintf("%02X","$rand");
	}
	function rand_color(){
	
		return '#'.rcolor().rcolor().rcolor();
	}
	function getTitleSize($count){
	
		$size = (ceil($count/10)+11).'px';
		return $size;
	}
	function showExt($ext,$pic=true) {
		static $_extPic = array(
			'dir'=>"folder.gif",
			'doc'=>'msoffice.gif',
			'rar'=>'rar.gif',
			'zip'=>'zip.gif',
			'txt'=>'text.gif',
			'pdf'=>'pdf.gif',
			'html'=>'html.gif',
			'png'=>'image.gif',
			'gif'=>'image.gif',
			'jpg'=>'image.gif',
			'php'=>'text.gif',
		);
		static $_extTxt = array(
			'dir'=>'文件夹',
			'jpg'=>'JPEG图象',
			);
		if($pic) {
			if(array_key_exists(strtolower($ext),$_extPic)) {
				$show = "<IMG SRC='__PUBLIC__/wblog/extension/".$_extPic[strtolower($ext)]."' BORDER='0' alt='' align='absmiddle'>";
			}else{
				$show = "<IMG SRC='__PUBLIC__/wblog/extension/common.gif' WIDTH='16' HEIGHT='16' BORDER='0' alt='文件' align='absmiddle'>";
			}
		}else{
			if(array_key_exists(strtolower($ext),$_extTxt)) {
				$show = $_extTxt[strtolower($ext)];
			}else{
				$show = $ext?$ext:'文件夹';
			}
		}
	
		return $show;
	}
	function byte_format($input, $dec=0){
	
	  $prefix_arr = array("B", "K", "M", "G", "T");
	  $value = round($input, $dec);
	  $i=0;
	  while ($value>1024){
	
		 $value /= 1024;
		 $i++;
	  }
	  $return_str = round($value, $dec).$prefix_arr[$i];
	  return $return_str;
	}
	/**
     +----------------------------------------------------------
     * 输出安全的html，用于过滤危险代码
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @param string $text 要处理的字符串
     * @param mixed $allowTags 允许的标签列表，如 table|td|th|td
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     */
    function safeHtml($text, $allowTags = null) {
		$htmlTags = array(
        'allow' => 'table|td|th|tr|i|b|u|strong|img|p|br|div|strong|em|ul|ol|li|dl|dd|dt|a',
        'ban' => 'html|head|meta|link|base|basefont|body|bgsound|title|style|script|form|iframe|frame|frameset|applet|id|ilayer|layer|name|script|style|xml',
    );
        $text =  trim($text);
        //完全过滤注释
        $text = preg_replace('/<!--?.*-->/','',$text);
        //完全过滤动态代码
        $text =  preg_replace('/<\?|\?'.'>/','',$text);
        //完全过滤js
        $text = preg_replace('/<script?.*\/script>/','',$text);

        $text =  str_replace('[','&#091;',$text);
        $text = str_replace(']','&#093;',$text);
        $text =  str_replace('|','&#124;',$text);
        //过滤换行符
        $text = preg_replace('/\r?\n/','',$text);
        //br
        $text =  preg_replace('/<br(\s\/)?'.'>/i','[br]',$text);
        $text = preg_replace('/(\[br\]\s*){10,}/i','[br]',$text);
        //过滤危险的属性，如：过滤on事件lang js
        while(preg_match('/(<[^><]+)(lang|on|action|background|codebase|dynsrc|lowsrc)[^><]+/i',$text,$mat)){
            $text=str_replace($mat[0],$mat[1],$text);
        }
        while(preg_match('/(<[^><]+)(window\.|javascript:|js:|about:|file:|document\.|vbs:|cookie)([^><]*)/i',$text,$mat)){
            $text=str_replace($mat[0],$mat[1].$mat[3],$text);
        }
        if( empty($allowTags) ) { $allowTags = $htmlTags['allow']; }
        //允许的HTML标签
        $text =  preg_replace('/<('.$allowTags.')( [^><\[\]]*)>/i','[\1\2]',$text);
        //过滤多余html
        if ( empty($banTag) ) { $banTag = $htmlTags['ban']; }
        $text =  preg_replace('/<\/?('.$banTag.')[^><]*>/i','',$text);
        //过滤合法的html标签
        while(preg_match('/<([a-z]+)[^><\[\]]*>[^><]*<\/\1>/i',$text,$mat)){
            $text=str_replace($mat[0],str_replace('>',']',str_replace('<','[',$mat[0])),$text);
        }
        //转换引号
        while(preg_match('/(\[[^\[\]]*=\s*)(\"|\')([^\2=\[\]]+)\2([^\[\]]*\])/i',$text,$mat)){
            $text=str_replace($mat[0],$mat[1].'|'.$mat[3].'|'.$mat[4],$text);
        }
        //空属性转换
        $text =  str_replace('\'\'','||',$text);
        $text = str_replace('""','||',$text);
        //过滤错误的单个引号
        while(preg_match('/\[[^\[\]]*(\"|\')[^\[\]]*\]/i',$text,$mat)){
            $text=str_replace($mat[0],str_replace($mat[1],'',$mat[0]),$text);
        }
        //转换其它所有不合法的 < >
        $text =  str_replace('<','&lt;',$text);
        $text = str_replace('>','&gt;',$text);
        $text = str_replace('"','&quot;',$text);
        //反转换
        $text =  str_replace('[','<',$text);
        $text =  str_replace(']','>',$text);
        $text =  str_replace('|','"',$text);
        //过滤多余空格
        $text =  str_replace('  ',' ',$text);
        return $text;
    }

    /**已调试，可用
     +----------------------------------------------------------
     * 删除html标签，得到纯文本。可以处理嵌套的标签
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @param string $string 要处理的html
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     */
      function deleteHtmlTags($string) {
        while(strstr($string, '>')) {
            $currentBeg = strpos($string, '<');
            $currentEnd = strpos($string, '>');
            $tmpStringBeg = @substr($string, 0, $currentBeg);
            $tmpStringEnd = @substr($string, $currentEnd + 1, strlen($string));
            $string = $tmpStringBeg.$tmpStringEnd;
        }
        return $string;
    }
?>