<?php
/*
* Copyright (c) 2009-2010 ATMAIL. All rights reserved
* See http://atmail.com/license.php for license agreement
*/

class Atmail_Filter_HTMLPurifier implements Zend_Filter_Interface
{
	private $_htmlPurifier;

	public function __construct($options = null)
	{
		if( extension_loaded('dom') )
		{
			if( !is_array($options) && is_a($options, 'HTMLPurifier_Config') )
			{
				$config = &$option;
			}
			else
			{
				$config = HTMLPurifier_Config::createDefault();
				$config->set('HTML.Allowed', null);
				//$config->set('Filter.ExtractStyleBlocks', true); //Needs CSSTidy
				$config->set('Core.Encoding', 'UTF-8'); 
				$config->set('HTML.Doctype', 'HTML 4.01 Transitional');
				if( is_array($options) )
				{
					foreach( $options as $option )
					{
						$config->set($option[0], $option[1]);
					}
				}
			}
			$this->_htmlPurifier = new HTMLPurifier($config);
		}
	}

    public function filter($text)
    {
		//reason for cleaning up first is some email clients generate illegal dom structure causing symptom of missing inline images once HTMLPurifier done
		//start by stripping off depreciated and not allowed tage (pre can mess up layout)
		//replace any line breaks inside pre with <br/>
		$text = preg_replace_callback('@<pre[^>]*?>(.*?)</pre>@siu', create_function('$matches', 'return preg_replace("@\n@siu","<br />\n",$matches[0]);'),$text);
		
		//strip pre tags
		$text = preg_replace('@</?pre[^>]*>@siu','',$text);

		//strip off outer html and anything in head
		//$text = preg_replace('@(</?html[^>]*
		//? >|</?body[^>]*? >|<head[^>]*? >.*?</head>)@siu','',$text);

		try
		{
			if( extension_loaded('dom') )
			{
				$text = $this->_htmlPurifier->purify( $text );
			}
			else
			{
				$text = preg_replace(
			        array(
						'@</?[a-z]+:[a-z]+>@siu',
						'@<!.*>@siu',
						'@<script.*</script>@siu',
						'@<object.*</object>@siu',
						'@<embed.*</embed>@siu',
						'@<applet.*</applet>@siu',
						'@<noframes.*</noframes>@siu',
						'@<noscript.*</noscript>@siu',
						'@<noembed.*</noembed>@siu',
						'@(?<=[\'"])javascript:@siu',
						'@</?(form|button|input:select|option)@iu',
						'@(on(abort|blue|change|click|dblclick|error|focus|key(down|up)|load|mouse(down|move|over|up)|re(set|size)|select|submitunload))=@siu',
			            
			        ),
			        array(
			            '',  ' ', ' ', 
						' ', ' ', ' ', 
						' ', ' ', ' ', 
						' ', ' ', 'blockedEvent=' 
			        ),
			        $text );
	
	    	}
		}
		catch ( Exception $e ) 
		{
			// oh crap !
			return false;	
		}
		return $text;

    }

}