<?php

if(!defined('ONYX')) exit;

$bbcode_config = $OPT;

function bbcode($var,$level=0)
	{
		global $bbcode_config;
		
		switch($level)
			{
				case 1:
				$pattern[] = '#\\[code\\](.+?)\\[/code\\]#us';
				$replace[] = '<pre>$1</pre>';
				
				$pattern[] = '#\\[size=([1-3][0-9])\\](.+?)\\[/size\\]#us';
				$replace[] = '<span style="font-size: $1px;">$2</span>';
				
				$pattern[] = '#\\[color=(aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|purple|red|silver|teal|white|yellow|\\#[0-9A-Fa-f]{6})\\](.+?)\\[/color\\]#us';
				$replace[] = '<span style="color: $1;">$2</span>';
				
				$pattern[] = '#\\[img\\]http(s)?://([a-zA-Z0-9_/.%*+~,;:\\#-]+)\\[/img\\]#u';
				$replace[] = '<img src="http$1://$2" alt="$2" />';
				
				default:
				case 0:
				$pattern[] = '#\\[url=(?:http(s)?://)?([a-zA-Z0-9_/.%*+~,;:?&=\\#-]+)\\](.+?)\\[/url\\]#u';
				$replace[] = '<a href="http$1://$2">$3</a>';
				
				$pattern[] = '#\\[url\\](?:http(s)?://)?([a-zA-Z0-9_/.%*+~,;:?&=\\#-]+)\\[/url\\]#u';
				$replace[] = '<a href="http$1://$2">$2</a>';
				
				$pattern[] = '#\\[cite\\](.+?)\\[/cite\\]#us';
				$replace[] = '<q>$1</q>';
				
				$pattern[] = '#\\[u\\](.+?)\\[/u\\]#us';
				$replace[] = '<ins>$1</ins>';
				
				$pattern[] = '#\\[i\\](.+?)\\[/i\\]#us';
				$replace[] = '<em>$1</em>';
				
				$pattern[] = '#\\[b\\](.+?)\\[/b\\]#us';
				$replace[] = '<strong>$1</strong>';
				
				if(isset($bbcode_config['smiley']) && isset($bbcode_config['smiley_dir']))
                                    foreach($bbcode_config['smiley'] as $keys => $values)
					{
						$pattern[] = '#'.preg_quote($values).'#u';
						$replace[] = '<img src="'.$bbcode_config['smiley_dir'].'/'.htmlspecialchars($keys).'.gif" alt="'.htmlspecialchars($keys).'" />';
					}
			}
		
		$pattern = array_reverse($pattern);
		$replace = array_reverse($replace);
		
		$var = preg_replace($pattern,$replace,$var);
		return $var;
	}
?>