<?php

/**
 *--------------------------------------
 * 过滤
 *--------------------------------------
 * @project		: pfa
 * @author		: cblee
 * @created		: 2012-11-23
 * @copyright	: (c)2012 AsThis
 *--------------------------------------
 */

class AFilter
{
	public static $allowTags = 'table|th|tr|td|div|p|ul|ol|li|dl|dt|dd|strong|em|i|b|u|a|span|img|br|object|param|embed|sup|sub|tbody';
	public static $banTags = 'html|head|meta|link|base|basefont|body|bgsound|title|style|script|form|iframe|frame|frameset|applet|id|ilayer|layer|name|xml';

	public static function safeHtml($text, $allowTags = '')
	{
		$text = str_replace('[', '&#091;', $text);
		$text = str_replace(']', '&#093;', $text);
		$text = str_replace('|', '&#124;', $text);
		/* br */
		$text = preg_replace('/<br(\s\/)?'.'>/i', '[br]', $text);
		$text = preg_replace('/(\[br\]\s*){1,}/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);
		} */

		/* 转换允许的html标签 */
		if(empty($allowTags))
		{
			$allowTags = self::$allowTags;
		}
		while(preg_match('/<('.$allowTags.')>/i', $text, $mat))
		{
			$text=str_replace($mat[0], str_replace(array('<', '>'), array('[', ']'), $mat[0]), $text);
		}
		while(preg_match('/<('.$allowTags.') [^><]*>/i', $text, $mat))
		{
			$text=str_replace($mat[0], str_replace(array('<', '>'), array('[', ']'), $mat[0]), $text);
		}
		while(preg_match('/<\/('.$allowTags.')>/i', $text, $mat))
		{
			$text=str_replace($mat[0], str_replace(array('<', '>'), array('[', ']'), $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(array('\'\'', '""'), '||', $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);
		return $text;
	}

	/* 检查word是否符合规定 */
	public static function is_word($word)
	{
		if(preg_match("/\W+/", $word)) /*\W:[^A-Za-z0-9_]*/
		{
			return false;
		}
		return true;
	}

	/* 检查userid是否符合规定, 同变量名 */
	public static function is_userid($string)
	{
		if(!preg_match("/^[a-zA-Z_][a-zA-Z0-9_]+$/", $string))
		{
			return false;
		}
		return true;
	}

	/* 检查username是否符合规定, 中文数字字母_ */
	public static function is_username($string)
	{
		if(!preg_match("/^[\x7f-\xff\w]+$/", $string))
		{
			return false;
		}
		return true;
	}

	/* 判断email格式是否正确*/
	public static function is_email($email)
	{
		return strlen($email) > 5 && preg_match("/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/", $email);
	}

	/* 处理搜索关键词 */
	public static function keyword($keyword)
	{
		if(MAGIC_QUOTES_GPC)
		{
			$keyword = stripslashes(trim($keyword));
		}
		$keyword = str_replace('\'', '', $keyword);
		$keyword = str_replace('"', '', $keyword);
		$keyword = preg_replace('/\s+/', ' ', $keyword);

		return $keyword;
	}

	/* 文本 */
	public static function text($string, $strlen = false)
	{
		$string = htmlspecialchars($string);
		if(0 < $strlen)
		{
			$string = AString::msubstr($string, 0, $strlen);
		}
		return $string;
	}

	/* 纯文本 */
	public static function plain_text($string, $strlen = false)
	{
		$string = preg_replace("/(\s|\&nbsp\;|　|\xc2\xa0)+/i", ' ', strip_tags($string));
		if(0 < $strlen)
		{
			$string = AString::msubstr($string, 0, $strlen);
		}
		return $string;
	}

	/* 转义 javascript 代码标记 */
	public static function trim_script($str)
	{
		$str = preg_replace ( '/\<([\/]?)script([^\>]*?)\>/si', '&lt;\\1script\\2&gt;', $str);
		$str = preg_replace ( '/\<([\/]?)iframe([^\>]*?)\>/si', '&lt;\\1iframe\\2&gt;', $str);
		$str = preg_replace ( '/\<([\/]?)frame([^\>]*?)\>/si', '&lt;\\1frame\\2&gt;', $str);
		$str = preg_replace ( '/]]\>/si', ']] >', $str);
		return $str;
	}

	/* 修复浏览器XSS hack的函数 */
	public static function remove_XSS($val)
	{
		$val = preg_replace('/([\x00-\x08\x0b-\x0c\x0e-\x19])/', '', $val);
		$search = 'abcdefghijklmnopqrstuvwxyz';
		$search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
		$search .= '1234567890!@#$%^&*()';
		$search .= '~`";:?+/={}[]-_|\'\\';
		for($i = 0; $i < strlen($search); $i++)
		{
			$val = preg_replace('/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i],	$val); // with a ;
			$val = preg_replace('/(&#0{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ;
		}
		$ra1 = array(
			'javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script',
			'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
		$ra2 = 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');
		$ra = array_merge($ra1, $ra2);

		$found = true;
		while($found == true)
		{
			$val_before = $val;
			for($i = 0; $i < sizeof($ra); $i++)
			{
				$pattern = '/';
				for($j = 0; $j < strlen($ra[$i]); $j++)
				{
					if($j > 0)
					{
						$pattern .= '(';
						$pattern .= '(&#[xX]0{0,8}([9ab]);)';
						$pattern .= '|';
						$pattern .= '|(&#0{0,8}([9|10|13]);)';
						$pattern .= ')*';
					}
					$pattern .= $ra[$i][$j];
				}
				$pattern .= '/i';
				$replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2);
				$val = preg_replace($pattern, $replacement, $val);
				if($val_before == $val)
				{
					$found = false;
				}
			}
		}
		return $val;
	}
}


?>