<?php

class vB5_Frontend_Controller_Bbcode extends vB5_Frontend_Controller
{

	function __construct()
	{
		parent::__construct();
	}

	public static function parse($text, $options = array(), $attachments = array(), $cacheInfo = array())
	{
		//if we have a nodeid, let's try to cache this.
		if (!empty($cacheInfo))
		{
			//TODO- Find a caching method that doesn't break collapsed mode.
			if (!empty($cacheInfo['nodeid']))
			{
				$cacheKey = 'vbNode' . $cacheInfo['nodeid'];
			}
			else if (!empty($cacheInfo['signatureid']))
			{
				$cacheKey = 'vbSig' . $cacheInfo['signatureid'];
			}
			if (!empty($cacheKey))
			{
				$cacheKey .= strval($options);
				$parsed = vB_Cache::instance()->read($cacheKey);

				if ($parsed)
				{
					return $parsed;
				}
			}
		}
		$result = self::parseInternal(new vB5_Template_BbCode(), $text, $options, $attachments);

		if (!empty($cacheKey))
		{
			if (!empty($cacheInfo['nodeid']))
			{
				$cacheEvent = 'nodeChg_' . $cacheInfo['nodeid'];
			}
			else if (!empty($cacheInfo['signatureid']))
			{
				$cacheEvent = 'userChg_' . $cacheInfo['signatureid'];
			}
			vB_Cache::instance()->write($cacheKey, $result, 86400, $cacheEvent);
		}
		return $result;
	}

	public static function parseWysiwyg($text, $options = array(), $attachments = array())
	{
		return self::parseInternal(new vB5_Template_BbCode_Wysiwyg(), $text, $options, $attachments);
	}

	private static function parseInternal(vB5_Template_BbCode $parser, $text, $options = array(), $attachments = array())
	{
		if (!isset($options['allowhtml']))
		{
			$options['allowhtml'] = false;
		}

		if (!isset($options['allowsmilies']))
		{
			$options['allowsmilies'] = true;
		}

		if (!isset($options['allowbbcode']))
		{
			$options['allowbbcode'] = true;
		}

		if (!isset($options['allowimagebbcode']))
		{
			$options['allowimagebbcode'] = true;
		}

		if (isset($options['userid'])){
			$parser->setParseUserinfo($options['userid']);
		}

		$parser->setAttachments($attachments);
		$result = $parser->doParse($text, $options['allowhtml'], $options['allowsmilies'], $options['allowbbcode'], $options['allowimagebbcode']);

		return $result;
	}

	function evalCode($code)
	{
		ob_start();
		eval($code);
		$output = ob_get_contents();
		ob_end_clean();
		
		return $output;
	}
	
	public function resolveIp($ip)
	{
		return @gethostbyaddr($ip);
	}
}
