<?php

/**
 * @package : PowerBBCode
 * @copyright : MaaSTaaR And abu Rakan >
 * @version : 1.1 Special verion for PowerBB
 * @start : 23/2/2006 , 3:46 PM (kuwait : GMT+3)
 * @end   : 23/2/2006 , 6:30 PM (kuwait : GMT+3)
 * @last update : 29/8/2010 02:41:55 AM
 */

class PowerBBCodeParse
{
 	/**
 	 * Search some text in $string and change it to other text
 	 *
 	 * @param :
 	 *				$string -> the text
 	 */
 	function replace($string)
 	{
 		global $PowerBB;

 		$brackets = (strpos($string,'[') !== false) and (strpos($string,']') !== false);

 		if ($brackets)
 		{
 			$string = htmlspecialchars($string);

 			$first_search = array();
 			$first_replace = array();

            $first_search['[code]'] = '#\[code\](.*)\[/code\]#esiU';
            $first_replace['[code]'] = "\$this->PowerCode_Code('\\1')";

            $first_search['[php]'] = '#\[php\](.*)\[/php\]#esiU';
            $first_replace['[php]'] = "\$this->PowerCode_Code('\\1')";

 			$string = preg_replace($first_search,$first_replace,$string);

 			$search_array = array();
 			$replace_array = array();

             //replace
		      $querybbcode = $PowerBB->DB->sql_query("SELECT  *   FROM " . $PowerBB->table['custom_bbcode'] . " ");
		       while ($getbbcode_row = $PowerBB->DB->sql_fetch_array($querybbcode))
		      {
		      	$bbcode_tag = $getbbcode_row['bbcode_tag'];
		      	$bbcode_replace = $getbbcode_row['bbcode_replace'];

				if ($getbbcode_row['bbcode_useoption'] == '1')
				{

		            $search_array['['.$bbcode_tag.'='] = '#\['.$bbcode_tag.'=(.*)\](.*)\[/'.$bbcode_tag.'\]#esiU';
		            $replace_array['['.$bbcode_tag.'='] = "\$this->PowerCode_BBcode('\\1', '\\2', $bbcode_tag)";


				}
				else
				{
							$search_array['['.$bbcode_tag.']'] = '#\['.$bbcode_tag.'\](.*)\[/'.$bbcode_tag.'\]#esiU';
							$replace_array['['.$bbcode_tag.']'] = "\$this->PowerCode_Tag_BBcode('$bbcode_replace','$bbcode_tag','\\1')";
				}

		      }
            $search_array['[img]'] = '#\[img\](.*)\[/img\]#esiU';
            $replace_array['[img]'] = "\$this->resize_image('\\1')";

            $search_array['[IMG]'] = '#\[IMG\]\s*(https?://([^<>*"]+|[a-z0-9/\\._\- !]+))\[/IMG\]#iUe';
            $replace_array['[IMG]'] = "\$this->resize_image('\\1', '\\1')";

            $search_array['[b]'] = '#\[b\](.*)\[/b\]#esiU';
            $replace_array['[b]'] = "\$this->PowerCode_Tag('b', '\\1')";

            $search_array['[u]'] = '#\[u\](.*)\[/u\]#esiU';
            $replace_array['[u]'] = "\$this->PowerCode_Tag('u', '\\1')";

            $search_array['[i]'] = '#\[i\](.*)\[/i\]#esiU';
            $replace_array['[i]'] = "\$this->PowerCode_Tag('i', '\\1')";

            $search_array['[blockquote]'] = '#\[blockquote\](.*)\[/blockquote\]#esiU';
            $replace_array['[blockquote]'] = "\$this->PowerCode_Tag('blockquote', '\\1')";

            $search_array['[indent]'] = '#\[indent\](.*)\[/indent\]#esiU';
            $replace_array['[indent]'] = "\$this->PowerCode_Tag('blockquote', '\\1')";

            $search_array['[right]'] = '#\[right\](.*)\[/right\]#esiU';
            $replace_array['[right]'] = "\$this->PowerCode_Tag('p', '\\1', ' align=\"right\"')";

            $search_array['[left]'] = '#\[left\](.*)\[/left\]#esiU';
            $replace_array['[left]'] = "\$this->PowerCode_Tag('p', '\\1', ' align=\"left\"')";

            $search_array['[justify]'] = '#\[justify\](.*)\[/justify\]#esiU';
            $replace_array['[justify]'] = "\$this->PowerCode_Tag('p', '\\1', ' align=\"justify\"')";

            $search_array['[JUSTIFY]'] = '#\[JUSTIFY\](.*)\[/JUSTIFY\]#esiU';
            $replace_array['[JUSTIFY]'] = "\$this->PowerCode_Tag('p', '\\1', ' align=\"justify\"')";

            $search_array['[h1]'] = '#\[h1\](.*)\[/h1\]#esiU';
            $replace_array['[h1]'] = "\$this->PowerCode_Tag('h1', '\\1')";

            $search_array['[h2]'] = '#\[h2\](.*)\[/h2\]#esiU';
            $replace_array['[h2]'] = "\$this->PowerCode_Tag('h2', '\\1')";

            $search_array['[h3]'] = '#\[h3\](.*)\[/h3\]#esiU';
            $replace_array['[h3]'] = "\$this->PowerCode_Tag('h3', '\\1')";

            $search_array['[h4]'] = '#\[h4\](.*)\[/h4\]#esiU';
            $replace_array['[h4]'] = "\$this->PowerCode_Tag('h4', '\\1')";

            $search_array['[h5]'] = '#\[h5\](.*)\[/h5\]#esiU';
            $replace_array['[h5]'] = "\$this->PowerCode_Tag('h5', '\\1')";

            $search_array['[h6]'] = '#\[h6\](.*)\[/h6\]#esiU';
            $replace_array['[h6]'] = "\$this->PowerCode_Tag('h6', '\\1')";

            $search_array['[highlight='] = '#\[highlight=(.*)\](.*)\[/highlight\]#esiU';
            $replace_array['[highlight='] = "\$this->PowerCode_Tag('span', '\\2',' style=\"background: \\1\"')";

            $search_array['[center]'] = '#\[center\](.*)\[/center\]#esiU';
            $replace_array['[center]'] = "\$this->PowerCode_Tag('p', '\\1', ' align=\"center\"')";

            $search_array['[-WEBKIT-CENTER]'] = '#\[-WEBKIT-CENTER\](.*)\[/-WEBKIT-CENTER\]#esiU';
            $replace_array['[-WEBKIT-CENTER]'] = "\$this->PowerCode_Tag('p', '\\1', ' align=\"center\"')";

            $search_array['[font='] = '#\[font=(.*)\](.*)\[/font\]#esiU';
            $replace_array['[font='] = "\$this->PowerCode_Tag('font', '\\2', ' face=\"\\1\"')";

            $search_array['[color='] = '#\[color=(.*)\](.*)\[/color\]#esiU';
            $replace_array['[color='] = "\$this->PowerCode_Tag('font', '\\2', ' color=\"\\1\"')";

            $search_array['[quote='] = '#\[quote=(.*)\](.*)\[/quote\]#esiU';
            $replace_array['[quote='] = "\$this->PowerCode_Quote('\\2', '\\1')";

            $search_array['[quote]'] = '#\[quote\](.*)\[/quote\]#esiU';
            $replace_array['[quote]'] = "\$this->PowerCode_Quote('\\1')";

            $search_array['[qu]'] = '#\[qu\](.*)\[/qu\]#esiU';
            $replace_array['[qu]'] = "\$this->PowerCode_Quote('\\1')";

            $search_array['[youtube]'] = '#\[youtube\](.*)\[/youtube\]#esiU';
            $replace_array['[youtube]'] = "\$this->PowerCode_Youtube('\\1', '\\1')";
            $search_array['[youtube='] = '#\[youtube=(.*)\](.*)\[/youtube\]#esiU';
            $replace_array['[youtube='] = "\$this->PowerCode_Youtube('\\1', '\\2')";

            $search_array['[media]'] = '#\[media\](.*)\[/media\]#esiU';
            $replace_array['[media]'] = "\$this->PowerCode_Media('\\1', '\\1')";
            $search_array['[media='] = '#\[media=(.*)\](.*)\[/media\]#esiU';
            $replace_array['[media='] = "\$this->PowerCode_Media('\\1', '\\2')";

            $search_array['[ram]'] = '#\[ram\](.*)\[/ram\]#esiU';
            $replace_array['[ram]'] = "\$this->PowerCode_Ram('\\1', '\\1')";
            $search_array['[ram='] = '#\[ram=(.*)\](.*)\[/ram\]#esiU';
            $replace_array['[ram='] = "\$this->PowerCode_Ram('\\1', '\\2')";

            $search_array['[Flash='] = '#\[flash=(&quot;|"|\'|)(.*)\\1\](height=)\\1([0-9]+)\\1[ ]+(width=)\\1([0-9]+)\\1\[/flash\]#esiU';
            $replace_array['[Flash='] = "\$this->PowerCode_Flash('\\2', '\\6','\\4', 'flash')";
            $search_array['[Flash='] = '#\[flash=(&quot;|"|\'|)(.*)\\1\]([w|W][i|I][d|D][t|T][h|H][=])\\1([0-9]+)\\1[ ]+([h|H][e|E][i|I][g|G][h|H][t|T][=])\\1([0-9]+)\\1\[/flash\]#esiU';
            $replace_array['[Flash='] = "\$this->PowerCode_Flash('\\2', '\\6','\\4', 'flash')";

            $search_array['[frame]'] = '#\[frame\](.*)\[/frame\]#esiU';
            $replace_array['[frame]'] = "\$this->PowerCode_frame('\\1', '\\1')";
            $search_array['[frame='] = '#\[frame=(.*)\](.*)\[/frame\]#esiU';
            $replace_array['[frame='] = "\$this->PowerCode_frame('\\1', '\\2')";

            $search_array['[gradient]'] = '#\[gradient\](.*)\[/gradient\]#esiU';
            $replace_array['[gradient]'] = "\$this->PowerCode_gradient('\\1', '\\1')";
            $search_array['[gradient='] = '#\[gradient=(.*)\](.*)\[/gradient\]#esiU';
            $replace_array['[gradient='] = "\$this->PowerCode_gradient('\\1', '\\2')";

            $search_array['[poem]'] = '#\[poem\](.*)\[/poem\]#esiU';
            $replace_array['[poem]'] = "\$this->PowerCode_poem('\\1', '\\1')";
            $search_array['[poem='] = '#\[poem=(.*)\](.*)\[/poem\]#esiU';
            $replace_array['[poem='] = "\$this->PowerCode_poem('\\1', '\\2')";

      	    $search_array['[s]'] = '#\[s\](.*)\[/s\]#esiU';
            $replace_array['[s]'] = "\$this->PowerCode_Tag('s', '\\1')";


            $search_array['[hr]'] = '#\[hr\](.*)\[/hr\]#esiU';
            $replace_array['[hr]'] = "\$this->PowerCode_Tag('span', '<HR id=null>')";

            $search_array['[sub]'] = '#\[sub\](.*)\[/sub\]#esiU';
            $replace_array['[sub]'] = "\$this->PowerCode_Tag('SUB', '\\1')";

            $search_array['[sup]'] = '#\[sup\](.*)\[/sup\]#esiU';
            $replace_array['[sup]'] = "\$this->PowerCode_Tag('SUP', '\\1')";

            $search_array['[table]'] = '#\[table\](.*)\[/table\]#esiU';
            $replace_array['[table]'] = "\$this->PowerCode_table('\\1')";

            $search_array['[tr]'] = '#\[tr\](.*)\[/tr\]#esiU';
            $replace_array['[tr]'] = "\$this->PowerCode_tr('\\1')";

            $search_array['[td]'] = '#\[td\](.*)\[/td\]#esiU';
            $replace_array['[td]'] = "\$this->PowerCode_td('\\1')";

            $search_array['[th]'] = '#\[th\](.*)\[/th\]#esiU';
            $replace_array['[th]'] = "\$this->PowerCode_th('\\1')";

            $search_array['[url]'] = '#\[url\](.*)\[/url\]#esiU';
            $replace_array['[url]'] = "\$this->PowerCode_Tag_Url('\\1', '\\1')";

            $search_array['[url='] = '#\[url=(.*)\](.*)\[/url\]#esiU';
            $replace_array['[url='] = "\$this->PowerCode_Tag_Url('\\1', '\\2')";

            $search_array['[size='] = '#\[size=(.*)\](.*)\[/size\]#esiU';
            $replace_array['[size='] = "\$this->PowerCode_Tag('font', '\\2', ' size=\"\\1\"')";

			$search_array['[list]'] = '#\[list\](.*)\[/list\]#esiU';
			$replace_array['[list]'] ="\$this->DoList('\\1','\\1')";

			$search_array['[list='] = '#\[list=(1|2)\](.*)\[/list\]#esiU';
			$replace_array['[list='] ="\$this->DoList('\\1','\\2')";

            $search_array['[guest_name]'] = '#\[guest_name\](.*)\[/guest_name\]#esiU';
            $replace_array['[guest_name]'] = "\$this->PowerCode_Tag('br', '\\1' )";


			foreach($search_array AS $tag => $regex)
			{
			  while (stristr($string, $tag) !== false)
			  {
			          $text = $string;
			          $string = preg_replace($regex, $replace_array["$tag"], $string);
			          if ($text == $string)
			          {
			                  break;
			          }
			  }
			}

	         $Guest_message = ($PowerBB->_CONF['info_row']['guest_message_for_haid_links']);
				if ($PowerBB->_CONF['info_row']['haid_links_for_guest'] == 0)
				{
				//start_replace_links_reply
				$search_array[] = ",([^]_a-z0-9-=\"'\/])((https?|ftp|gopher|news|telnet):\/\/)([^ \r\n\(\)\*\^\$!`\"'\|\[\]\{\}<>]*),i";
				$replace_array[] = '<a href="$2$4" target="_blank">$2$4</a>';
				$search_array[] = ",^((https?|ftp|gopher|news|telnet):\/\/|\.)([^ \r\n\(\)\*\^\$!`\"'\|\[\]\{\}<>]*),i";
				$replace_array[] = '<a href="$1$3" target="_blank">$1$3</a>';
				//$search_array[] = ",([^]_a-z0-9-=\"'\/])((ftp|gopher|news|telnet):\/\/|www\.)([^ \r\n\(\)\*\^\$!`\"'\|\[\]\{\}<>]*),i";
				//$replace_array[] = '<a href="http://$2$4" target="_blank">$2$4</a>';
				$search_array[] = "/^([\\._a-zA-Z0-9-]+(\.[\\._a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,3}))/i";
				$replace_array[] = '<a href="mailto:$1">$1</a>';
				$string = preg_replace($search_array,$replace_array ,$string);
				//end_replace_links_reply
				 }
				else
				{
	            $Guest_message = ($PowerBB->_CONF['info_row']['guest_message_for_haid_links']);
	            $register_link = ('index.php?page=register&index=1');
	                if ($PowerBB->_CONF['member_permission'])
					{
					//start_replace_links_reply
					$search_array[] = ",([^]_a-z0-9-=\"'\/])((https?|ftp|gopher|news|telnet):\/\/)([^ \r\n\(\)\*\^\$!`\"'\|\[\]\{\}<>]*),i";
					$replace_array[] = '<a href="$2$4" target="_blank">$2$4</a>';
					$search_array[] = ",^((https?|ftp|gopher|news|telnet):\/\/|\.)([^ \r\n\(\)\*\^\$!`\"'\|\[\]\{\}<>]*),i";
					$replace_array[] = '<a href="$1$3" target="_blank">$1$3</a>';
					//$search_array[] = ",([^]_a-z0-9-=\"'\/])((ftp|gopher|news|telnet):\/\/|www\.)([^ \r\n\(\)\*\^\$!`\"'\|\[\]\{\}<>]*),i";
					//$replace_array[] = '<a href="http://$2$4" target="_blank">$2$4</a>';
					$search_array[] = "/^([\\._a-zA-Z0-9-]+(\.[\\._a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,3}))/i";
					$replace_array[] = '<a href="mailto:$1">$1</a>';
	                $string = preg_replace($search_array,$replace_array ,$string);

					}
	                if (!$PowerBB->_CONF['member_permission'])
					{
				    //end_replace_links_reply
					$search_array[] = ",([^]_a-z0-9-=\"'\/])((https?|ftp|gopher|news|telnet):\/\/)([^ \r\n\(\)\*\^\$!`\"'\|\[\]\{\}<>]*),i";
					$replace_array[] = "<a href=\"$register_link\" target=\"_blank\">$Guest_message</a>";
					$search_array[] = ",^((https?|ftp|gopher|news|telnet):\/\/|\.)([^ \r\n\(\)\*\^\$!`\"'\|\[\]\{\}<>]*),i";
					$replace_array[] = "<a href=\"$register_link\" target=\"_blank\">$Guest_message</a>";
					//$search_array[] = ",([^]_a-z0-9-=\"'\/])((ftp|gopher|news|telnet):\/\/|www\.)([^ \r\n\(\)\*\^\$!`\"'\|\[\]\{\}<>]*),i";
					//$replace_array[] = "<a href=\"$register_link\" target=\"_blank\">$Guest_message</a>";
					$search_array[] = "/^([\\._a-zA-Z0-9-]+(\.[\\._a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,3}))/i";
					$replace_array[] = "<a href=\"$register_link\" target=\"_blank\">$Guest_message</a>";
					//end_replace_links_reply
					 $string = preg_replace($search_array,$replace_array ,$string);

				    }
	            }

         }
 		else
 		{
           $Guest_message = ($PowerBB->_CONF['info_row']['guest_message_for_haid_links']);
			if ($PowerBB->_CONF['info_row']['haid_links_for_guest'] == 0)
			{
			//start_replace_links_reply
			$search_array[] = ",([^]_a-z0-9-=\"'\/])((https?|ftp|gopher|news|telnet):\/\/)([^ \r\n\(\)\*\^\$!`\"'\|\[\]\{\}<>]*),i";
			$replace_array[] = '<a href="$2$4" target="_blank">$2$4</a>';
			$search_array[] = ",^((https?|ftp|gopher|news|telnet):\/\/|\.)([^ \r\n\(\)\*\^\$!`\"'\|\[\]\{\}<>]*),i";
			$replace_array[] = '<a href="$1$3" target="_blank">$1$3</a>';
			$search_array[] = ",([^]_a-z0-9-=\"'\/])((ftp|gopher|news|telnet):\/\/|www\.)([^ \r\n\(\)\*\^\$!`\"'\|\[\]\{\}<>]*),i";
			$replace_array[] = '<a href="http://$2$4" target="_blank">$2$4</a>';
			$search_array[] = "/^([\\._a-zA-Z0-9-]+(\.[\\._a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,3}))/i";
			$replace_array[] = '<a href="mailto:$1">$1</a>';
			//end_replace_links_reply

			 }
			else
			{
            $Guest_message = ($PowerBB->_CONF['info_row']['guest_message_for_haid_links']);
            $register_link = ('index.php?page=register&index=1');
                if ($PowerBB->_CONF['member_permission'])
				{
				//start_replace_links_reply
				$search_array[] = ",([^]_a-z0-9-=\"'\/])((https?|ftp|gopher|news|telnet):\/\/)([^ \r\n\(\)\*\^\$!`\"'\|\[\]\{\}<>]*),i";
				$replace_array[] = '<a href="$2$4" target="_blank">$2$4</a>';
				$search_array[] = ",^((https?|ftp|gopher|news|telnet):\/\/|\.)([^ \r\n\(\)\*\^\$!`\"'\|\[\]\{\}<>]*),i";
				$replace_array[] = '<a href="$1$3" target="_blank">$1$3</a>';
				$search_array[] = ",([^]_a-z0-9-=\"'\/])((ftp|gopher|news|telnet):\/\/|www\.)([^ \r\n\(\)\*\^\$!`\"'\|\[\]\{\}<>]*),i";
				$replace_array[] = '<a href="http://$2$4" target="_blank">$2$4</a>';
				$search_array[] = "/^([\\._a-zA-Z0-9-]+(\.[\\._a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,3}))/i";
				$replace_array[] = '<a href="mailto:$1">$1</a>';
				}
                if (!$PowerBB->_CONF['member_permission'])
				{
			    //end_replace_links_reply
				$search_array[] = ",([^]_a-z0-9-=\"'\/])((https?|ftp|gopher|news|telnet):\/\/)([^ \r\n\(\)\*\^\$!`\"'\|\[\]\{\}<>]*),i";
				$replace_array[] = "<a href=\"$register_link\" target=\"_blank\">$Guest_message</a>";
				$search_array[] = ",^((https?|ftp|gopher|news|telnet):\/\/|\.)([^ \r\n\(\)\*\^\$!`\"'\|\[\]\{\}<>]*),i";
				$replace_array[] = "<a href=\"$register_link\" target=\"_blank\">$Guest_message</a>";
				$search_array[] = ",([^]_a-z0-9-=\"'\/])((ftp|gopher|news|telnet):\/\/|www\.)([^ \r\n\(\)\*\^\$!`\"'\|\[\]\{\}<>]*),i";
				$replace_array[] = "<a href=\"$register_link\" target=\"_blank\">$Guest_message</a>";
				$search_array[] = "/^([\\._a-zA-Z0-9-]+(\.[\\._a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*(\.[a-zA-Z]{2,3}))/i";
				$replace_array[] = "<a href=\"$register_link\" target=\"_blank\">$Guest_message</a>";
				//end_replace_links_reply
			    }

            }

              $string = preg_replace($search_array,$replace_array ,$string);

 		}

         return nl2br($string);
 	}

 	/**
 	 * The PowerCode should be programmer paradise like Linux ;)
 	 *
 	 * @author : Jason Warner <jason@mercuryboard.com>
 	 *
 	 * @edited by : MaaSTaaR <MaaSTaaR@gmail.com>
 	 *
 	 * @param :
 	 * 	 			code 	-> the code
 	 *				is_php	->	if the code wrote in php this variable should value true to highlight the code
 	 */


 	    function PowerCode_Tag($tag, $message, $att = '')
        {

				if (count(explode('=',$att)) > 2)
                {
                        return $message;
                }

				if (trim($message) == '')
                {
                        return '';
                }

                $message = str_replace('\\"', '"', $message);
                if($tag == 'tag')
                {
                        return $message;
                }

                return "<$tag$att>$message</$tag>";
        }

         function PowerCode_Tag_BBcode($bbcode_replace,$bbcode_tag,$message)
        {
        	global $PowerBB;
				if (trim($message) == '')
                {
                        return '';
                }

                $message = str_replace('\\"', '"', $message);
                $bbcode_replace = str_replace("#", '', $bbcode_replace);
                $bbcode_replace = str_replace("{content}",$message, $bbcode_replace);
                $bbcode_replace = str_replace("{option}","", $bbcode_replace);

                return $bbcode_replace;
        }

 	  function PowerCode_Quote($message, $username = '')
        {
        	global $PowerBB;

                if (trim($message) == '')
                {
                        return '';
                }

                $message = str_replace('\\"', '"', $message);

                if($username)
                {
                        return '<div class="quotetop">' .$PowerBB->_CONF['template']['lang']['quote_username'] .' '. $username . ' </div><div class="quotemain">' . $message . '</div>';
                }
                return '<div class="quotetop">'.$PowerBB->_CONF['template']['lang']['quote'].'</div><div class="quotemain">' . $message . '</div>';
        }

 	  function PowerCode_table($txt)
        {
        	global $PowerBB;


                if (trim($txt) == '')
                {
                        return '';
                }

                $txt = str_replace('\\"', '"', $txt);

                return '<table align="center" border="0" cellspacing="1" class="Code_table" width="98%">' . $txt . '</table>';
        }

 	  function PowerCode_tr($txt)
        {
        	global $PowerBB;

                if (trim($txt) == '')
                {
                        return '';
                }

                $txt = str_replace('\\"', '"', $txt);

                return '<tr>' . $txt . '</tr>';
        }

 	  function PowerCode_td($txt)
        {
        	global $PowerBB;


                if (trim($txt) == '')
                {
                        return '';
                }

                $txt = str_replace('\\"', '"', $txt);
                return '<td class="Code_td">&nbsp;' . $txt . '</td>';
        }

 	  function PowerCode_th($txt)
        {
        	global $PowerBB;

                if (trim($txt) == '')
                {
                        return '';
                }

                $txt = str_replace('\\"', '"', $txt);

                return '<th style="font-size: 20px; border: none;border: 1px solid #789DB3; background-color: #F4F4F4;">&nbsp;' . $txt . '</th>';
        }

	function PowerCode_Code($txt)
	{
		global $PowerBB;

		$txt = preg_replace( "#&lt;#"   , "&#60;", $txt );
		$txt = preg_replace( "#&gt;#"   , "&#62;", $txt );
		$txt = preg_replace( "#&quot;#" , "&#34;", $txt );
		$txt = preg_replace( "#:#"      , "&#58;", $txt );
		$txt = preg_replace( "#\[#"     , "&#91;", $txt );
		$txt = preg_replace( "#\]#"     , "&#93;", $txt );
		$txt = preg_replace( "#\)#"     , "&#41;", $txt );
		$txt = preg_replace( "#\(#"     , "&#40;", $txt );

       return '<div class="codemain"><pre class="brush:php">'.$txt.'</pre></div>';
	}

        function PowerCode_Url($link, $message)
        {
                if (trim($message) == '')
                {
                        return '';
                }

                $message = str_replace('\\"', '"', $message);
                $link = str_replace(array('"', "'"), array('&quot;', '&#39;'), $link);
				if ($PowerBB->_CONF['info_row']['haid_links_for_guest'] == 0)
				{
				return "<a href=\"$link\" target=\"_blank\">$message</a>";
				}
				else
				{
				$Guest_message = ($PowerBB->_CONF['info_row']['guest_message_for_haid_links']);
				$register_link = ('index.php?page=register&index=1');
                if ($PowerBB->_CONF['member_permission'])
				{
				return "<a href=\"$link\" target=\"_blank\">$message</a>";
								}
                if ($PowerBB->_CONF['member_permission'])
				{
				return "<a href=\"$register_link\" target=\"_blank\">$Guest_message</a>";
                }
				}
        }

		function PowerCode_Email($link, $message)
        {
			if (preg_match('#^[a-z0-9.!\#$%&\'*+-/=?^_`{|}~]+@([0-9.]+|([^\s\'"<>@,;]+\.+[a-z]{2,6}))$#si', $link))
			{
                return "<a href=\"mailto:$link\" target=\"_blank\">$message</a>";
			}
			else
			{
                return '';
			}
        }

		function PowerCode_Youtube($linky, $messages)
        {
        	global $PowerBB;
                if (trim($messages) == '')
                {
                        return '';
                }
		// $bad_characters: All ASCII characters below ASCII 32 (except 9, 10 and 13 (tab, newline and carrige return)).
		$bad_characters = array_diff(range(chr(0), chr(31)), array(chr(9), chr(10), chr(13)));
		$messages = str_replace($bad_characters, "", $messages);
		$linky = str_replace($bad_characters, "", $linky);

                $messages = str_replace("youtube.com/embed/", "youtube.com/watch?v=", $messages);

                $messages = str_replace('\\"', '"', $messages);
                $messages = str_replace('&lt;br /&gt;"', "<br />", $messages);
                $messages = str_replace("&lt;", "<", $messages);
                $messages = str_replace("&quot;", '"', $messages);
                $messages = str_replace("&gt;", ">", $messages);

                $linky = str_replace("youtube.com/embed/", "youtube.com/watch?v=", $linky);
                $linky = str_replace('\\"', '"', $linky);
                $linky = str_replace('&lt;br /&gt;"', "<br />", $linky);
                $linky = str_replace("&lt;", "<", $linky);
                $linky = str_replace("&quot;", '"', $linky);
                $linky = str_replace("&gt;", ">", $linky);

                $linky = str_replace(array('"', "'"), array('&quot;', '&#39;'), $linky);
                $linky = str_replace(array('/watch?', "v="), array('/v', '/'), $linky);
                return "<span><object width='425' height='344'><param name='movie' value='$linky'></param><param name='allowFullScreen' value='true'></param><param name='allowscriptaccess' value='always'></param><embed src='$linky' type='application/x-shockwave-flash' allowscriptaccess='always' allowfullscreen='true' width='425' height='344'></embed></object></span>";
         }

		function PowerCode_BBcode($option, $content, $bbcode_tag)
        {
		      global $PowerBB;
                if (trim($content) == '')
                {
                        return '';
                }

                $content = str_replace('\\"', '"', $content);

                $querybbcode1 = $PowerBB->DB->sql_query("SELECT * FROM " . $PowerBB->table['custom_bbcode'] . " WHERE bbcode_tag = '$bbcode_tag' ");
				$bbcode_row1 = $PowerBB->DB->sql_fetch_array($querybbcode1);

				$bbcode_replace = $bbcode_row1['bbcode_replace'];

                $bbcode_replace = str_replace( "{option}",$option , $bbcode_replace );
                $bbcode_replace = str_replace("{content}", $content, $bbcode_replace);
                $bbcode_replace = str_replace("&#39;",'"',$bbcode_replace);

                return $bbcode_replace;

         }

		function PowerCode_Media($linky, $messages)
        {
		      global $PowerBB;

                if (trim($messages) == '')
                {
                        return '';
                }

		// $bad_characters: All ASCII characters below ASCII 32 (except 9, 10 and 13 (tab, newline and carrige return)).
		$bad_characters = array_diff(range(chr(0), chr(31)), array(chr(9), chr(10), chr(13)));
		$messages = str_replace($bad_characters, "", $messages);
		$linky = str_replace($bad_characters, "", $linky);

                $messages = str_replace('\\"', '"', $messages);
                $messages = str_replace('&lt;br /&gt;"', "<br />", $messages);
                $messages = str_replace("&lt;", "<", $messages);
                $messages = str_replace("&quot;", '"', $messages);
                $messages = str_replace("&gt;", ">", $messages);

                $linky = str_replace('\\"', '"', $linky);
                $linky = str_replace('&lt;br /&gt;"', "<br />", $linky);
                $linky = str_replace("&lt;", "<", $linky);
                $linky = str_replace("&quot;", '"', $linky);
                $linky = str_replace("&gt;", ">", $linky);
                $messages = str_replace('\\"', '"', $messages);
                $linky = str_replace(array('"', "'"), array('&quot;', '&#39;'), $linky);
                return "<span><object width='350' height='350'><param name='movie' value='$linky'><PARAM name='ShowControls' VALUE='true'><param name='ShowStatusBar' value='true'><PARAM name='ShowDisplay' VALUE='false'><PARAM name='autostart' VALUE='false'><embed src='$linky' type='application/x-mplayer2' ShowControls='1' ShowStatusBar='1' ShowDisplay='0' autostart='0' width='350' height='300'></embed></object></span>";
         }

		function PowerCode_Ram($linky, $messages)
        {
        			      global $PowerBB;

                if (trim($messages) == '')
                {
                        return '';
                }
		// $bad_characters: All ASCII characters below ASCII 32 (except 9, 10 and 13 (tab, newline and carrige return)).
		$bad_characters = array_diff(range(chr(0), chr(31)), array(chr(9), chr(10), chr(13)));
		$messages = str_replace($bad_characters, "", $messages);
		$linky = str_replace($bad_characters, "", $linky);

                $messages = str_replace('\\"', '"', $messages);
                $messages = str_replace('&lt;br /&gt;"', "<br />", $messages);
                $messages = str_replace("&lt;", "<", $messages);
                $messages = str_replace("&quot;", '"', $messages);
                $messages = str_replace("&gt;", ">", $messages);

                $linky = str_replace('\\"', '"', $linky);
                $linky = str_replace('&lt;br /&gt;"', "<br />", $linky);
                $linky = str_replace("&lt;", "<", $linky);
                $linky = str_replace("&quot;", '"', $linky);
                $linky = str_replace("&gt;", ">", $linky);

                $messages = str_replace('\\"', '"', $messages);
                $linky = str_replace(array('"', "'"), array('&quot;', '&#39;'), $linky);
                return "<span><object width='275' height='40'><param name='movie' value='$linky'></param><param name='autostart' value='true'></param><param name='allowscriptaccess' value='always'></param><embed src='$linky' type='audio/x-pn-realaudio-plugin' allowscriptaccess='always' allowfullscreen='true' width='275' height='40'></embed></object></span>";

         }


        function PowerCode_Flash ($message, $param1 = '', $param2 = '', $type = '' )
		{
		      global $PowerBB;

			if (trim($message) == '' || $type == '')
			{
			return '';
		    }

			if (!preg_match('#^[a-z]+://#si', $message)){
			return '';
			}

		// $bad_characters: All ASCII characters below ASCII 32 (except 9, 10 and 13 (tab, newline and carrige return)).
		$bad_characters = array_diff(range(chr(0), chr(31)), array(chr(9), chr(10), chr(13)));
		$param1 = str_replace($bad_characters, "", $param1);
		$param2 = str_replace($bad_characters, "", $param2);
		$message = str_replace($bad_characters, "", $message);
		$type = str_replace($bad_characters, "", $type);

                $param1 = str_replace('\\"', '"', $param1);
                $param1 = str_replace('&lt;br /&gt;"', "<br />", $param1);
                $param1 = str_replace("&lt;", "<", $param1);
                $param1 = str_replace("&quot;", '"', $param1);
                $param1 = str_replace("&gt;", ">", $param1);

                $param2 = str_replace('\\"', '"', $param2);
                $param2 = str_replace('&lt;br /&gt;"', "<br />", $param2);
                $param2 = str_replace("&lt;", "<", $param2);
                $param2 = str_replace("&quot;", '"', $param2);
                $param2 = str_replace("&gt;", ">", $param2);

                $messages = str_replace('\\"', '"', $messages);
                $messages = str_replace('&lt;br /&gt;"', "<br />", $messages);
                $messages = str_replace("&lt;", "<", $messages);
                $messages = str_replace("&quot;", '"', $messages);
                $messages = str_replace("&gt;", ">", $messages);

			$param1 = intval($param1);
			$param2 = intval($param2);
            $html = '<span><embed src="'.$message.'" width="'.$param2.'" height="'.$param1.'" quality=high wmode=transparent loop=true menu=false TYPE="application/x-shockwave-flash"></embed></span>';

			return $html;
	    }



       function PowerCode_frame($option_frame, $content_frame)
        {
		      global $PowerBB;
                if (trim($content_frame) == '')
                {
                        return '';
                }

                $content_frame = str_replace('\\"', '"', $content_frame);
                if ($PowerBB->_CONF['info_row']['content_dir'] == 'ltr')
                {
				$bbcode_replace_frame = '<br/><table border="0" width="98%" cellpadding="0" cellspacing="0"><tr><td width="1%"><img src="look/images/myframes/{option}_cul.gif" alt=""  border="0" /></td><td width="100%" style="background-image: url(look/images/myframes/{option}_u.gif)"></td><td width="1%"><img src="look/images/myframes/{option}_cur.gif" alt=""  border="0" /></td></tr><tr><td width="1%" style="background-image: url(look/images/myframes/{option}_l.gif)"></td><td align="center" width="100%" style="background-image: url(look/images/myframes/{option}.gif)">{content}</td><td width="1%" style="background-image: url(look/images/myframes/{option}_r.gif)"></td></tr><tr><td width="1%"><img src="look/images/myframes/{option}_cdl.gif" alt=""  border="0" /></td><td width="100%" style="background-image: url(look/images/myframes/{option}_d.gif)"></td><td width="1%"><img src="look/images/myframes/{option}_cdr.gif" alt=""  border="0" /></td></tr></table>';
                }
                else
                {
				$bbcode_replace_frame = '<br/><table border="0" width="98%" cellpadding="0" cellspacing="0"><tr><td width="1%"><img src="look/images/myframes/{option}_cur.gif" alt=""  border="0" /></td><td width="100%" style="background-image: url(look/images/myframes/{option}_u.gif)"></td><td width="1%"><img src="look/images/myframes/{option}_cul.gif" alt=""  border="0" /></td></tr><tr><td width="1%" style="background-image: url(look/images/myframes/{option}_r.gif)"></td><td align="center" width="100%" style="background-image: url(look/images/myframes/{option}.gif)">{content}</td><td width="1%" style="background-image: url(look/images/myframes/{option}_l.gif)"></td></tr><tr><td width="1%"><img src="look/images/myframes/{option}_cdr.gif" alt=""  border="0" /></td><td width="100%" style="background-image: url(look/images/myframes/{option}_d.gif)"></td><td width="1%"><img src="look/images/myframes/{option}_cdl.gif" alt=""  border="0" /></td></tr></table>';
                }
                $bbcode_replace_frame = str_replace("{option}",$option_frame ,  $bbcode_replace_frame);
                $bbcode_replace_frame = str_replace("{content}", $content_frame, $bbcode_replace_frame);
                $bbcode_replace_frame = str_replace("&#39;",'"',$bbcode_replace_frame);

                return $bbcode_replace_frame;

         }

       function PowerCode_gradient($option_gradient, $content_gradient)
        {
		      global $PowerBB;
                if (trim($content_gradient) == '')
                {
                        return '';
                }

                $content_gradient = str_replace('\\"', '"', $content_gradient);

				$bbcode_replace_gradient = '<div id="mygradient" title="{option}" style="display:none">{content}</div><script type="text/javascript">drawGradient()</script>';
                $bbcode_replace_gradient = str_replace("{option}",$option_gradient ,  $bbcode_replace_gradient);
                $bbcode_replace_gradient = str_replace("{content}", $content_gradient, $bbcode_replace_gradient);
                $bbcode_replace_gradient = str_replace("&#39;",'"',$bbcode_replace_gradient);

                return $bbcode_replace_gradient;

         }

      function PowerCode_poem($option_poem, $content_poem)
        {
		      global $PowerBB;
                if (trim($content_poem) == '')
                {
                        return '';
                }

                $content_poem = str_replace('\\"', '"', $content_poem);

				$bbcode_replace_poem = '<div tag="{option}">{content}</div><script type="text/javascript">doPoem(0)</script>';
                $bbcode_replace_poem = str_replace("{option}",$option_poem ,  $bbcode_replace_poem);
                $bbcode_replace_poem = str_replace("{content}", $content_poem, $bbcode_replace_poem);
                $bbcode_replace_poem = str_replace('\"','"',$bbcode_replace_poem);

                return $bbcode_replace_poem;
         }


        function DoList($mark,$item)
         {

                  if ($mark=="1")
                  {
                      $tag = "ol";
                  }
                  else
                  {
                      $tag = "ul";
                  }

                  $return = "<".$tag.">";

                  $new_item = explode("[*]" , $item);
                  $new_item = str_replace('\\"', '"', $new_item);
                  for ($i=1; $i <= count($new_item); $i++)
                  {
                       if ($new_item[$i]!="")
                       {
                           $return .= "<li>".$new_item[$i]."</li>";
                       }
                  }

                  $return .= "</".$tag.">";
                  return $return;
         }


 	function censor_words($text)
	{
		global $PowerBB;
       // feltr words
    	static $blanks = null;

         $text = str_replace("&amp;","&",$text);
         $text = str_replace('{39}',"'",$text);
         $text = str_replace('&#092;&#092;',"&#092;",$text);
         $text = str_replace("&amp;#39;","'",$text);
         $text = str_replace("&#39;","'",$text);
         $text = str_replace('<p align="left">','<p dir="ltr" align="left">',$text);
         $text = str_replace("&amp;#092;","\(:*:)",$text);
         $text = str_replace("(:*:)","",$text);

         //$text = str_replace("amp;lt;","&amp;&lt;",$text);

		if ($PowerBB->_GET['page'] != 'topic'
		and $PowerBB->_GET['operator'] != 'edit'
		and $PowerBB->_GET['page'] != 'new_reply'
		and $PowerBB->_GET['page'] != 'profile')
		{
		 $text = stripslashes($text);
		}

        $censorwords = preg_split('#[ \r\n\t]+#', $PowerBB->_CONF['info_row']['censorwords'], -1, PREG_SPLIT_NO_EMPTY);
        $text = str_ireplace($censorwords,'**', $text);

         $blankasciistrip ="160 173 u8205 u8204 u8237 u8238";

		if ($blanks === null AND trim($blankasciistrip) != '')
		{
			$blanks = array();

			$charset_unicode = (strtolower($PowerBB->_CONF['info_row']['charset']) == 'utf-8');

			$raw_blanks = preg_split('#\s+#', $blankasciistrip, -1, PREG_SPLIT_NO_EMPTY);
			foreach ($raw_blanks AS $code_point)
			{
				if ($code_point[0] == 'u')
				{
					// this is a unicode character to remove
					$code_point = intval(substr($code_point, 1));
					$force_unicode = true;
				}
				else
				{
					$code_point = intval($code_point);
					$force_unicode = false;
				}

				if ($code_point > 255 OR $force_unicode OR $charset_unicode)
				{
					// outside ASCII range or forced Unicode, so the chr function wouldn't work anyway
					$blanks[] = '&#' . $code_point . ';';
					$blanks[] = $this->convert_int_to_utf8($code_point);
				}
				else
				{
					$blanks[] = chr($code_point);
				}
			}
		}

		if ($blanks)
		{
			$text = str_replace($blanks, '**', $text);
		}


		// $bad_characters: All ASCII characters below ASCII 32 (except 9, 10 and 13 (tab, newline and carrige return)).
		$bad_characters = array_diff(range(chr(0), chr(31)), array(chr(9), chr(10), chr(13)));
		$text = str_replace($bad_characters, "", $text);

        return $text;
	}

 	function feltr_words($text)
	{
		global $PowerBB;
       // feltr words2
         $text = str_replace('&lt;','<',$text);
         $text = str_replace('&quot;','"',$text);
         $text = str_replace('&gt;','>',$text);
         $text = str_replace("&amp;#39;","'",$text);
		 $text = stripslashes($text);
         $text = str_replace('{39}',"'",$text);
         $text = str_ireplace('xss',"**",$text);
         $text = str_ireplace('document',"**",$text);
         $text = str_ireplace('cookie',"**",$text);
         $text = str_ireplace('alert',"**",$text);
         $text = str_ireplace('location',"**",$text);
         $text = str_ireplace('equiv',"**",$text);
         $text = str_ireplace('script',"**",$text);
         $text = str_ireplace('equiv',"**",$text);
         $text = str_ireplace('refresh',"**",$text);
         $text = str_ireplace('meta',"**",$text);
         $text = str_ireplace('base',"**",$text);
         $text = str_ireplace('iframe',"**",$text);
        $censorwords = preg_split('#[ \r\n\t]+#', $PowerBB->_CONF['info_row']['censorwords'], -1, PREG_SPLIT_NO_EMPTY);
        $text = str_ireplace($censorwords,'**', $text);

         $blankasciistrip ="160 173 u8205 u8204 u8237 u8238";

		if ($blanks === null AND trim($blankasciistrip) != '')
		{
			$blanks = array();

			$charset_unicode = (strtolower($PowerBB->_CONF['info_row']['charset']) == 'utf-8');

			$raw_blanks = preg_split('#\s+#', $blankasciistrip, -1, PREG_SPLIT_NO_EMPTY);
			foreach ($raw_blanks AS $code_point)
			{
				if ($code_point[0] == 'u')
				{
					// this is a unicode character to remove
					$code_point = intval(substr($code_point, 1));
					$force_unicode = true;
				}
				else
				{
					$code_point = intval($code_point);
					$force_unicode = false;
				}

				if ($code_point > 255 OR $force_unicode OR $charset_unicode)
				{
					// outside ASCII range or forced Unicode, so the chr function wouldn't work anyway
					$blanks[] = '&#' . $code_point . ';';
					$blanks[] = $this->convert_int_to_utf8($code_point);
				}
				else
				{
					$blanks[] = chr($code_point);
				}
			}
		}

		if ($blanks)
		{
			$text = str_replace($blanks, '**', $text);
		}


		// $bad_characters: All ASCII characters below ASCII 32 (except 9, 10 and 13 (tab, newline and carrige return)).
		$bad_characters = array_diff(range(chr(0), chr(31)), array(chr(9), chr(10), chr(13)));
		$text = str_replace($bad_characters, "", $text);

        return $text;
	}

 	function replace_smiles(&$text)
	{
		global $PowerBB;

		$smiles = $PowerBB->icon->GetCachedSmiles();

		foreach ($smiles as $smile)
		{
			$PowerBB->functions->CleanVariable($smile,'html');

			$text = str_replace($smile['smile_short'],'<img src="' . $smile['smile_path'] . '" border="0" alt="' . $smile['smile_short'] . '" />',$text);
		}
	}


 	function replace_smiles_print(&$text)
	{
		global $PowerBB;

		$smiles = $PowerBB->icon->GetCachedSmiles();

		foreach ($smiles as $smile)
		{
            $Adress = $PowerBB->functions->GetForumAdress();
			$text = str_replace($smile['smile_short'],'<img src="' . $Adress.$smile['smile_path'] . '" border="0" />',$text);
		}
	}


	function replace_wordwrap(&$text)
	{
		global $PowerBB;
       $wordwrap = $PowerBB->_CONF['info_row']['wordwrap'];
	   $text = @wordwrap($text, $wordwrap, "\n", true);

	}


 	function _wordwrap($text,$lg_max)
	{
		global $PowerBB;
       $num =$lg_max;
       $start ='0';
       $text = preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'. $start .'}'.'((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'. $num .'}).*#s','$1', $text);
       return $text;
	}

       function PowerCode_Tag_Url($link, $message)
        {
        	global $PowerBB;
          $Guest_message = ($PowerBB->_CONF['info_row']['guest_message_for_haid_links']);
          $register_link = ('index.php?page=register&index=1');

                if (trim($message) == '')
                {
                        return '';
                }

                $message = str_replace('\\"', '"', $message);
                $link = str_replace(array('"', "'"), array('&quot;', '&#39;'), $link);

				if ($PowerBB->_CONF['info_row']['haid_links_for_guest'] == 0)
				{
				 return "<a href=\"$link\" target=\"_blank\">$message</a>";
				}
				else
				{

	                 if ($PowerBB->_CONF['member_permission'])
					 {
						return "<a href=\"$link\" target=\"_blank\">$message</a>";
					 }
	                if (!$PowerBB->_CONF['member_permission'])
					{
					return "<a href=\"$register_link\" target=\"_blank\">$Guest_message</a>";
	                }
				}
        }

	function strip_smiles(&$text)
	{
   		global $PowerBB;

		$smiles = $PowerBB->icon->GetCachedSmiles();

		foreach ($smiles as $smile)
		{
			$PowerBB->functions->CleanVariable($smile,'html');

			$text = str_replace('<img src="' . $smile['smile_path'] . '" border="0" alt="' . $smile['smile_short'] . '" />',$smile['smile_short'],$text);
		}
    }

 // Resize Image proportionally and return the resized image url
    function resize_image($img)
    {
        global $PowerBB;
        $img = trim($img);
        $img = str_replace("&amp;quot;", "", $img);
		$img = str_replace("alt=", '', $img);
		$img = str_replace("border=0", '', $img);
        if ($PowerBB->_CONF['info_row']['resize_imagesAllow'] == 1)
        {
		return '<img src="'.$img.'" border="0" alt="" onload="ResizeIt(this)"/>';
        }
	    else
	    {
        return '<img border="0" alt="" src="'.$img.'" />';
		}
     }

	/*-------------------------------------------------------------------------*/
	// Content search hightlight
	/*-------------------------------------------------------------------------*/

	/**
	* Replaces text with highlighted blocks
	*
	* @param	string	Incoming Content
	* @param	string	HL attribute
	* @return	string	Formatted text
	*/

	function content_search_highlight( $text, $highlight )
	{
        global $PowerBB;

		//-----------------------------------------
		// INIT
		//-----------------------------------------

		$highlight  = urldecode( $highlight );
		$loosematch = strstr( $highlight, '*' ) ? 1 : 0;
		$keywords   = str_replace( '*', '', str_replace( "+", " ", str_replace( "++", "+", str_replace( '-', '', trim($highlight) ) ) ) );
		$word_array = array();
		$endmatch   = "(.)?";
		$beginmatch = "(.)?";

		//-----------------------------------------
		// Go!
		//-----------------------------------------

		if ( $keywords )
		{
			if ( preg_match("/,(and|or),/i", $keywords) )
			{
				while ( preg_match("/,(and|or),/i", $keywords, $match) )
				{
					$word_array = explode( ",".$match[1].",", $keywords );
					$keywords   = str_replace( $match[0], '' ,$keywords );
				}
			}
			else if ( strstr( $keywords, ' ' ) )
			{
				$word_array = explode( ' ', str_replace( '  ', ' ', $keywords ) );
			}
			else
			{
				$word_array[] = $keywords;
			}

			if ( ! $loosematch )
			{
				$beginmatch = "(^|\s|\>|;)";
				$endmatch   = "(\s|,|\.|!|<br|&|$)";
			}

			if ( is_array($word_array) )
			{
				foreach ( $word_array as $keywords )
				{
					preg_match_all( "/{$beginmatch}(".preg_quote($keywords, '/')."){$endmatch}/is", $text, $matches );

					for ( $i = 0; $i < count($matches[0]); $i++ )
					{
						$text = str_replace( $matches[0][$i], $matches[1][$i]."[color=#ff0000]".$matches[2][$i]."[/color]".$matches[3][$i], $text );
					}
				}
			}
		}

		return $text;
	}

	// HTML conversion common to both bbcode and text result
	function html_common($string)
	{
        global $PowerBB;

		// First extract just the body of the message
		if (stristr($string, "<body"))
		{
      if (preg_match('#<body.*?>(.*)</body>#is', $string, $matches))
      {
        $string = $matches[1];
      }
      elseif (preg_match('#<body.*?>(.*)#is', $string, $matches))
      {
        $string = $matches[1];
      }
		}

		// Convert all HTML tags to lower case
		$string = preg_replace('#(</?)(\w+)([^>]*>)#e','"$1".strtolower("$2")."$3"',$string);

		//
		// Save the pre-formatted text
		//
		preg_match_all('#<pre(| .*?)>(.*?)</pre>#s', $string, $matches);
		$preformated_strings = $matches[2];
		$cp = count($preformated_strings);

		for ($i = 0; $i < $cp; $i++)
		{
			$string = preg_replace('#<pre(| .*?)>(.*?)</pre>#s', "***pre_string***$i", $string, 1);
		}

		//
		// Replace formatting elements
		//
		$string = str_replace('&amp;quot;', '"', $string);

		// Replace all CR LF with a single space
		$string = str_replace("\r\n", ' ', $string);
		// Then replace CR or LF alone with a single space
		$string = str_replace("\r", ' ', $string);
		$string = str_replace("\n", ' ', $string);
		// Replace line break with a CR LF
		$string = str_replace('<br>', "\r\n", $string);
		$string = str_replace('<br />', "\r\n", $string);
		// The end of a division should trigger a line break
//		$string = str_replace('</div>', "\r\n", $string);
		// replace spaces
		$string = str_replace('&nbsp;', ' ', $string);
		// replace multiple spaces
		$string = preg_replace('/ {2,}/', ' ', $string);
		// Outlook sometimes puts extra stuff with the paragraph marker, so match
		// <p> and <p otherjunk>
		//$string = preg_replace('#<p(| .*?)>#', "\r\n", $string);
		// Restore the preformatted text
		//
		for ($i = 0; $i < $cp; $i++)
		{
			$string = str_replace("***pre_string***$i", '<pre>' . $preformated_strings[$i] . '</pre>', $string);
		}
		return $string;
	}

	// Converts an HTML email into bbcode
	// This function is loosely based on cbparser.php by corz.org
	function html2bb($string)
	{
        global $PowerBB;

		// Do common conversion stuff
		$string = $this->html_common($string);
		// Do simple string replacements

//@emovip 22/Oct/2010 2:56 hey b creative man

//<font color="#ff4040"><font size="6"><font face="Impact">gggggggggg</font></font></font>
//[color=#ff4040][size=6][font=Impact]gggggggggg[/font][/size][/color]

	  $string = preg_replace('#<font color="(.*?)">(.*?)</font>#i', " $2 ", $string);
	  $string = preg_replace('#<font size="(.*?)">(.*?)</font>#i', " $2 ", $string);
	  $string = preg_replace('#<font face="(.*?)">(.*?)</font>#i', " $2 ", $string);
	  $string = preg_replace('#<p align="(.*?)">(.*?)</p>#i', "[$1] $2 [/$1]", $string);
	  $string = preg_replace('#<div align="(.*?)">(.*?)</div>#i', "[$1] $2 [/$1]", $string);


		$string = str_replace('</b>',  '[/b]',    $string);
		$string = str_replace('</i>',  '[/i]',    $string);
		$string = str_replace('</u>',  '[/u]',    $string);
		$string = str_replace('</ul>', '[/list]', $string);
		$string = str_replace('</ol>', '[/list]', $string);
		$string = str_replace('</em>', '[/i]',    $string);
		$string = str_replace('</strong>', '[/b]', $string);
		$string = str_replace('</blockquote>', '[/quote]', $string);
		$string = str_replace('</pre>', '[/quote]', $string);

		// Do simple reg expr replacements
		$string = preg_replace('#<b(| .*?)>#',      '[b]',      $string);
		$string = preg_replace('#<i(| .*?)>#',      '[i]',      $string);
		$string = preg_replace('#<u(| .*?)>#',      '[u]',      $string);
		$string = preg_replace('#<ul(| .*?)>#',     '[list]',   $string);
		$string = preg_replace('#<ol(| .*?)>#',     '[list=1]', $string);
		$string = preg_replace('#<li(| .*?)>#',     '[*]',      $string);
		$string = preg_replace('#<em(| .*?)>#',     '[i]',      $string);
		$string = preg_replace('#<strong(| .*?)>#', '[b]',      $string);
		$string = preg_replace('#<blockquote(| .*?)>#', '[quote]',  $string);
		$string = preg_replace('#<pre(| .*?)>#', '[quote]',  $string);

		// replace multiple instances of [b] or [i] with single tags
		$string = preg_replace('#(\[b\])+#',      '[b]',      $string);
		$string = preg_replace('#(\[i\])+#',      '[i]',      $string);
		$string = preg_replace('#(\[/b\])+#',     '[/b]',      $string);
		$string = preg_replace('#(\[/i\])+#',     '[/i]',      $string);

		// fix for thunderbird which chops up quotes into little chunks for some reason. Remove if necessary!
		$string = preg_replace('#\[\/quote\]\s*?\[quote\]#', '',  $string);

		// Replace email address
		$string = preg_replace('#<a .*?href=.*?"mailto:(.*?)".*?>(.*?)</a>#i', "$2 ([email]$1[/email])", $string);

		// Replace links
		$string = preg_replace('#<a .*href=.*"(.*)".*>(.*)</a>#iUe', "'[url'. (trim('$1') ? '='.trim('$1') : '') .']'.trim('$2').'[/url]'", $string);

		// Remove any image tags whose source starts with 'cid:' - this is an inline attachment, and will be added to the post as a normal attachment.
		$string = preg_replace('#<img[^>]+src="cid:[^>]+>#i', '', $string);

		// Replace image references
		$string = preg_replace('#<img .*src="(.*)".*>#iUe', "'[img]'.trim('$1').'[/img]'", $string);

		// Remove all remaining HTML tags
		$string = preg_replace('#<(/?\w+|!--)[^>]*>#', '', $string);

		// Convert HTML entities
		$string = html_entity_decode($string);

		// Convert quotes
		if (get_magic_quotes_gpc()) {
			return stripslashes($string);
		} else {
			return ($string);
		}
	}

	function convert_int_to_utf8($intval)
	{
		$intval = intval($intval);
		switch ($intval)
		{
			// 1 byte, 7 bits
			case 0:
				return chr(0);
			case ($intval & 0x7F):
				return chr($intval);

			// 2 bytes, 11 bits
			case ($intval & 0x7FF):
				return chr(0xC0 | (($intval >> 6) & 0x1F)) .
					chr(0x80 | ($intval & 0x3F));

			// 3 bytes, 16 bits
			case ($intval & 0xFFFF):
				return chr(0xE0 | (($intval >> 12) & 0x0F)) .
					chr(0x80 | (($intval >> 6) & 0x3F)) .
					chr (0x80 | ($intval & 0x3F));

			// 4 bytes, 21 bits
			case ($intval & 0x1FFFFF):
				return chr(0xF0 | ($intval >> 18)) .
					chr(0x80 | (($intval >> 12) & 0x3F)) .
					chr(0x80 | (($intval >> 6) & 0x3F)) .
					chr(0x80 | ($intval & 0x3F));
		}
	}

   //end_function

 }

?>
