<?php
	require_once('htmlfilter.php');

	/**
	 * Filters text messages for various uses
	 *
	 * @package core
	 */
	class filter
	{
		/**
		 * Create script-safe HTML from raw HTML
		 *
		 * @param string $html The HTML text
		 * @return string safe html
		 */
		function safeHTML($html)
		{
			// Save all "<" symbols
			$html = preg_replace("/<(?=[^a-zA-Z\/\!\?\%])/", "&lt;", $html); 

			if(!DISABLE_HTMLBODY_FILTER){
				// Filter '<script>'
				$html = $this->filterScripts($html);
			}

			return $html;
		} 

		/**
		 * Filter scripts from HTML
		 *
		 * @access private
		 * @param string $str string which should be filtered
		 * @return string string without any script tags		
		 */
		function filterScripts($str)
		{
			return magicHTML($str, 0);
		} 
	
		/**
		 * Convert HTML to text
		 *
		 * @param string $str the html which should be converted to text
		 * @return string plain text version of the given $str				
		 */
		function html2text($str)
		{
			return $this->unhtmlentities(preg_replace(
					Array("'<(HEAD|SCRIPT|STYLE|TITLE)[^>]*?>.*?</(HEAD|SCRIPT|STYLE|TITLE)[^>]*?>'si",
						"'(\r|\n)'",
						"'<BR[^>]*?>'i",
						"'<P[^>]*?>'i",
						"'<\/?\w+[^>]*>'e",
						"'<![^>]*>'s"
						),
					Array("",
						"",
						"\r\n",
						"\r\n\r\n",
						"",
						""),
					$str));
		} 

		/**
		 * Remove HTML entities and convert them to single characters where possible
		 *
		 * @access private
		 * @param string $str string which should be converted
		 * @return string converted string
		 */
		function unhtmlentities ($string)
		{
			$trans_tbl = get_html_translation_table(HTML_ENTITIES);
			$trans_tbl = array_flip($trans_tbl);
			return strtr($string, $trans_tbl);
		} 

		/**
		 * Remove script tags from HTML source
		 *
		 * @access private
		 * @param string $str the html which the events should be filtered
		 * @return string html with no 'on' events
		 */
		function _filter_tag($str)
		{
			// fix $str when called by preg_replace_callback
			if (is_array($str)) $str = $str[0];

			// fix unicode
			$str = preg_replace_callback("|(%[0-9A-Z]{2})|i", create_function('$str', 'return chr(hexdec($str[0]));'), $str);

			$matches = Array(
				// (\bON\w+(?!.)) - matches string beginning with 'on' only if the string is not followed by '.'	for example 'online.nl' will not be matched, whereas 'onmouse' will be.
				"'(\bON\w+(?!.))'i", // events
				"'(HREF)( *= *[\"\']?\w+SCRIPT *:[^\"\' >]+)'i", // links
				"'\n'",
				"'\r'"
				);
			$replaces = Array(
				"\\1_filtered",
				"\\1_filtered\\2",
				" ",
				" ",
				);
			return preg_replace($matches, $replaces, $str);
		}
	} 
?>
