Blame Identity/Webenv/App/phpBB/3.0.4/includes/message_parser.php

f2e824
f2e824
/**
f2e824
*
f2e824
* @package phpBB3
f2e824
* @version $Id: message_parser.php 9034 2008-10-24 00:49:30Z toonarmy $
f2e824
* @copyright (c) 2005 phpBB Group
f2e824
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
f2e824
*
f2e824
*/
f2e824
f2e824
/**
f2e824
* @ignore
f2e824
*/
f2e824
if (!defined('IN_PHPBB'))
f2e824
{
f2e824
	exit;
f2e824
}
f2e824
f2e824
if (!class_exists('bbcode'))
f2e824
{
f2e824
	include($phpbb_root_path . 'includes/bbcode.' . $phpEx);
f2e824
}
f2e824
f2e824
/**
f2e824
* BBCODE FIRSTPASS
f2e824
* BBCODE first pass class (functions for parsing messages for db storage)
f2e824
* @package phpBB3
f2e824
*/
f2e824
class bbcode_firstpass extends bbcode
f2e824
{
f2e824
	var $message = '';
f2e824
	var $warn_msg = array();
f2e824
	var $parsed_items = array();
f2e824
f2e824
	/**
f2e824
	* Parse BBCode
f2e824
	*/
f2e824
	function parse_bbcode()
f2e824
	{
f2e824
		if (!$this->bbcodes)
f2e824
		{
f2e824
			$this->bbcode_init();
f2e824
		}
f2e824
f2e824
		global $user;
f2e824
f2e824
		$this->bbcode_bitfield = '';
f2e824
		$bitfield = new bitfield();
f2e824
f2e824
		foreach ($this->bbcodes as $bbcode_name => $bbcode_data)
f2e824
		{
f2e824
			if (isset($bbcode_data['disabled']) && $bbcode_data['disabled'])
f2e824
			{
f2e824
				foreach ($bbcode_data['regexp'] as $regexp => $replacement)
f2e824
				{
f2e824
					if (preg_match($regexp, $this->message))
f2e824
					{
f2e824
						$this->warn_msg[] = sprintf($user->lang['UNAUTHORISED_BBCODE'] , '[' . $bbcode_name . ']');
f2e824
						continue;
f2e824
					}
f2e824
				}
f2e824
			}
f2e824
			else
f2e824
			{
f2e824
				foreach ($bbcode_data['regexp'] as $regexp => $replacement)
f2e824
				{
f2e824
					// The pattern gets compiled and cached by the PCRE extension,
f2e824
					// it should not demand recompilation
f2e824
					if (preg_match($regexp, $this->message))
f2e824
					{
f2e824
						$this->message = preg_replace($regexp, $replacement, $this->message);
f2e824
						$bitfield->set($bbcode_data['bbcode_id']);
f2e824
					}
f2e824
				}
f2e824
			}
f2e824
		}
f2e824
f2e824
		$this->bbcode_bitfield = $bitfield->get_base64();
f2e824
	}
f2e824
f2e824
	/**
f2e824
	* Prepare some bbcodes for better parsing
f2e824
	*/
f2e824
	function prepare_bbcodes()
f2e824
	{
f2e824
		// Ok, seems like users instead want the no-parsing of urls, smilies, etc. after and before and within quote tags being tagged as "not a bug".
f2e824
		// Fine by me ;) Will ease our live... but do not come back and cry at us, we won't hear you.
f2e824
f2e824
		/* Add newline at the end and in front of each quote block to prevent parsing errors (urls, smilies, etc.)
f2e824
		if (strpos($this->message, '[quote') !== false && strpos($this->message, '[/quote]') !== false)
f2e824
		{
f2e824
			$this->message = str_replace("\r\n", "\n", $this->message);
f2e824
f2e824
			// We strip newlines and spaces after and before quotes in quotes (trimming) and then add exactly one newline
f2e824
			$this->message = preg_replace('#\[quote(=".*?")?\]\s*(.*?)\s*\[/quote\]#siu', '[quote\1]' . "\n" . '\2' ."\n[/quote]", $this->message);
f2e824
		}
f2e824
		*/
f2e824
f2e824
		// Add other checks which needs to be placed before actually parsing anything (be it bbcodes, smilies, urls...)
f2e824
	}
f2e824
f2e824
	/**
f2e824
	* Init bbcode data for later parsing
f2e824
	*/
f2e824
	function bbcode_init()
f2e824
	{
f2e824
		static $rowset;
f2e824
f2e824
		// This array holds all bbcode data. BBCodes will be processed in this
f2e824
		// order, so it is important to keep [code] in first position and
f2e824
		// [quote] in second position.
f2e824
		$this->bbcodes = array(
f2e824
			'code'			=> array('bbcode_id' => 8,	'regexp' => array('#\[code(?:=([a-z]+))?\](.+\[/code\])#ise' => "\$this->bbcode_code('\$1', '\$2')")),
f2e824
			'quote'			=> array('bbcode_id' => 0,	'regexp' => array('#\[quote(?:="(.*?)")?\](.+)\[/quote\]#ise' => "\$this->bbcode_quote('\$0')")),
f2e824
			'attachment'	=> array('bbcode_id' => 12,	'regexp' => array('#\[attachment=([0-9]+)\](.*?)\[/attachment\]#ise' => "\$this->bbcode_attachment('\$1', '\$2')")),
f2e824
			'b'				=> array('bbcode_id' => 1,	'regexp' => array('#\[b\](.*?)\[/b\]#ise' => "\$this->bbcode_strong('\$1')")),
f2e824
			'i'				=> array('bbcode_id' => 2,	'regexp' => array('#\[i\](.*?)\[/i\]#ise' => "\$this->bbcode_italic('\$1')")),
f2e824
			'url'			=> array('bbcode_id' => 3,	'regexp' => array('#\[url(=(.*))?\](.*)\[/url\]#iUe' => "\$this->validate_url('\$2', '\$3')")),
f2e824
			'img'			=> array('bbcode_id' => 4,	'regexp' => array('#\[img\](.*)\[/img\]#iUe' => "\$this->bbcode_img('\$1')")),
f2e824
			'size'			=> array('bbcode_id' => 5,	'regexp' => array('#\[size=([\-\+]?\d+)\](.*?)\[/size\]#ise' => "\$this->bbcode_size('\$1', '\$2')")),
f2e824
			'color'			=> array('bbcode_id' => 6,	'regexp' => array('!\[color=(#[0-9a-f]{6}|[a-z\-]+)\](.*?)\[/color\]!ise' => "\$this->bbcode_color('\$1', '\$2')")),
f2e824
			'u'				=> array('bbcode_id' => 7,	'regexp' => array('#\[u\](.*?)\[/u\]#ise' => "\$this->bbcode_underline('\$1')")),
f2e824
			'list'			=> array('bbcode_id' => 9,	'regexp' => array('#\[list(?:=(?:[a-z0-9]|disc|circle|square))?].*\[/list]#ise' => "\$this->bbcode_parse_list('\$0')")),
f2e824
			'email'			=> array('bbcode_id' => 10,	'regexp' => array('#\[email=?(.*?)?\](.*?)\[/email\]#ise' => "\$this->validate_email('\$1', '\$2')")),
f2e824
			'flash'			=> array('bbcode_id' => 11,	'regexp' => array('#\[flash=([0-9]+),([0-9]+)\](.*?)\[/flash\]#ie' => "\$this->bbcode_flash('\$1', '\$2', '\$3')"))
f2e824
		);
f2e824
f2e824
		// Zero the parsed items array
f2e824
		$this->parsed_items = array();
f2e824
f2e824
		foreach ($this->bbcodes as $tag => $bbcode_data)
f2e824
		{
f2e824
			$this->parsed_items[$tag] = 0;
f2e824
		}
f2e824
f2e824
		if (!is_array($rowset))
f2e824
		{
f2e824
			global $db;
f2e824
			$rowset = array();
f2e824
f2e824
			$sql = 'SELECT *
f2e824
				FROM ' . BBCODES_TABLE;
f2e824
			$result = $db->sql_query($sql);
f2e824
f2e824
			while ($row = $db->sql_fetchrow($result))
f2e824
			{
f2e824
				$rowset[] = $row;
f2e824
			}
f2e824
			$db->sql_freeresult($result);
f2e824
		}
f2e824
f2e824
		foreach ($rowset as $row)
f2e824
		{
f2e824
			$this->bbcodes[$row['bbcode_tag']] = array(
f2e824
				'bbcode_id'	=> (int) $row['bbcode_id'],
f2e824
				'regexp'	=> array($row['first_pass_match'] => str_replace('$uid', $this->bbcode_uid, $row['first_pass_replace']))
f2e824
			);
f2e824
		}
f2e824
	}
f2e824
f2e824
	/**
f2e824
	* Making some pre-checks for bbcodes as well as increasing the number of parsed items
f2e824
	*/
f2e824
	function check_bbcode($bbcode, &$in)
f2e824
	{
f2e824
		// when using the /e modifier, preg_replace slashes double-quotes but does not
f2e824
		// seem to slash anything else
f2e824
		$in = str_replace("\r\n", "\n", str_replace('\"', '"', $in));
f2e824
f2e824
		// Trimming here to make sure no empty bbcodes are parsed accidently
f2e824
		if (trim($in) == '')
f2e824
		{
f2e824
			return false;
f2e824
		}
f2e824
f2e824
		$this->parsed_items[$bbcode]++;
f2e824
f2e824
		return true;
f2e824
	}
f2e824
f2e824
	/**
f2e824
	* Transform some characters in valid bbcodes
f2e824
	*/
f2e824
	function bbcode_specialchars($text)
f2e824
	{
f2e824
		$str_from = array('<', '>', '[', ']', '.', ':');
f2e824
		$str_to = array('<', '>', '[', ']', '.', ':');
f2e824
f2e824
		return str_replace($str_from, $str_to, $text);
f2e824
	}
f2e824
f2e824
	/**
f2e824
	* Parse size tag
f2e824
	*/
f2e824
	function bbcode_size($stx, $in)
f2e824
	{
f2e824
		global $user, $config;
f2e824
f2e824
		if (!$this->check_bbcode('size', $in))
f2e824
		{
f2e824
			return $in;
f2e824
		}
f2e824
f2e824
		if ($config['max_' . $this->mode . '_font_size'] && $config['max_' . $this->mode . '_font_size'] < $stx)
f2e824
		{
f2e824
			$this->warn_msg[] = sprintf($user->lang['MAX_FONT_SIZE_EXCEEDED'], $config['max_' . $this->mode . '_font_size']);
f2e824
f2e824
			return '[size=' . $stx . ']' . $in . '[/size]';
f2e824
		}
f2e824
f2e824
		// Do not allow size=0
f2e824
		if ($stx <= 0)
f2e824
		{
f2e824
			return '[size=' . $stx . ']' . $in . '[/size]';
f2e824
		}
f2e824
f2e824
		return '[size=' . $stx . ':' . $this->bbcode_uid . ']' . $in . '[/size:' . $this->bbcode_uid . ']';
f2e824
	}
f2e824
f2e824
	/**
f2e824
	* Parse color tag
f2e824
	*/
f2e824
	function bbcode_color($stx, $in)
f2e824
	{
f2e824
		if (!$this->check_bbcode('color', $in))
f2e824
		{
f2e824
			return $in;
f2e824
		}
f2e824
f2e824
		return '[color=' . $stx . ':' . $this->bbcode_uid . ']' . $in . '[/color:' . $this->bbcode_uid . ']';
f2e824
	}
f2e824
f2e824
	/**
f2e824
	* Parse u tag
f2e824
	*/
f2e824
	function bbcode_underline($in)
f2e824
	{
f2e824
		if (!$this->check_bbcode('u', $in))
f2e824
		{
f2e824
			return $in;
f2e824
		}
f2e824
f2e824
		return '[u:' . $this->bbcode_uid . ']' . $in . '[/u:' . $this->bbcode_uid . ']';
f2e824
	}
f2e824
f2e824
	/**
f2e824
	* Parse b tag
f2e824
	*/
f2e824
	function bbcode_strong($in)
f2e824
	{
f2e824
		if (!$this->check_bbcode('b', $in))
f2e824
		{
f2e824
			return $in;
f2e824
		}
f2e824
f2e824
		return '[b:' . $this->bbcode_uid . ']' . $in . '[/b:' . $this->bbcode_uid . ']';
f2e824
	}
f2e824
f2e824
	/**
f2e824
	* Parse i tag
f2e824
	*/
f2e824
	function bbcode_italic($in)
f2e824
	{
f2e824
		if (!$this->check_bbcode('i', $in))
f2e824
		{
f2e824
			return $in;
f2e824
		}
f2e824
f2e824
		return '[i:' . $this->bbcode_uid . ']' . $in . '[/i:' . $this->bbcode_uid . ']';
f2e824
	}
f2e824
f2e824
	/**
f2e824
	* Parse img tag
f2e824
	*/
f2e824
	function bbcode_img($in)
f2e824
	{
f2e824
		global $user, $config;
f2e824
f2e824
		if (!$this->check_bbcode('img', $in))
f2e824
		{
f2e824
			return $in;
f2e824
		}
f2e824
f2e824
		$in = trim($in);
f2e824
		$error = false;
f2e824
f2e824
		$in = str_replace(' ', '%20', $in);
f2e824
f2e824
		// Checking urls
f2e824
		if (!preg_match('#^' . get_preg_expression('url') . '$#i', $in) && !preg_match('#^' . get_preg_expression('www_url') . '$#i', $in))
f2e824
		{
f2e824
			return '[img]' . $in . '[/img]';
f2e824
		}
f2e824
f2e824
		// Try to cope with a common user error... not specifying a protocol but only a subdomain
f2e824
		if (!preg_match('#^[a-z0-9]+://#i', $in))
f2e824
		{
f2e824
			$in = 'http://' . $in;
f2e824
		}
f2e824
f2e824
		if ($config['max_' . $this->mode . '_img_height'] || $config['max_' . $this->mode . '_img_width'])
f2e824
		{
f2e824
			$stats = @getimagesize($in);
f2e824
f2e824
			if ($stats === false)
f2e824
			{
f2e824
				$error = true;
f2e824
				$this->warn_msg[] = $user->lang['UNABLE_GET_IMAGE_SIZE'];
f2e824
			}
f2e824
			else
f2e824
			{
f2e824
				if ($config['max_' . $this->mode . '_img_height'] && $config['max_' . $this->mode . '_img_height'] < $stats[1])
f2e824
				{
f2e824
					$error = true;
f2e824
					$this->warn_msg[] = sprintf($user->lang['MAX_IMG_HEIGHT_EXCEEDED'], $config['max_' . $this->mode . '_img_height']);
f2e824
				}
f2e824
f2e824
				if ($config['max_' . $this->mode . '_img_width'] && $config['max_' . $this->mode . '_img_width'] < $stats[0])
f2e824
				{
f2e824
					$error = true;
f2e824
					$this->warn_msg[] = sprintf($user->lang['MAX_IMG_WIDTH_EXCEEDED'], $config['max_' . $this->mode . '_img_width']);
f2e824
				}
f2e824
			}
f2e824
		}
f2e824
f2e824
		if ($error || $this->path_in_domain($in))
f2e824
		{
f2e824
			return '[img]' . $in . '[/img]';
f2e824
		}
f2e824
f2e824
		return '[img:' . $this->bbcode_uid . ']' . $this->bbcode_specialchars($in) . '[/img:' . $this->bbcode_uid . ']';
f2e824
	}
f2e824
f2e824
	/**
f2e824
	* Parse flash tag
f2e824
	*/
f2e824
	function bbcode_flash($width, $height, $in)
f2e824
	{
f2e824
		global $user, $config;
f2e824
f2e824
		if (!$this->check_bbcode('flash', $in))
f2e824
		{
f2e824
			return $in;
f2e824
		}
f2e824
f2e824
		$in = trim($in);
f2e824
		$error = false;
f2e824
f2e824
		// Do not allow 0-sizes generally being entered
f2e824
		if ($width <= 0 || $height <= 0)
f2e824
		{
f2e824
			return '[flash=' . $width . ',' . $height . ']' . $in . '[/flash]';
f2e824
		}
f2e824
f2e824
		// Apply the same size checks on flash files as on images
f2e824
		if ($config['max_' . $this->mode . '_img_height'] || $config['max_' . $this->mode . '_img_width'])
f2e824
		{
f2e824
			if ($config['max_' . $this->mode . '_img_height'] && $config['max_' . $this->mode . '_img_height'] < $height)
f2e824
			{
f2e824
				$error = true;
f2e824
				$this->warn_msg[] = sprintf($user->lang['MAX_FLASH_HEIGHT_EXCEEDED'], $config['max_' . $this->mode . '_img_height']);
f2e824
			}
f2e824
f2e824
			if ($config['max_' . $this->mode . '_img_width'] && $config['max_' . $this->mode . '_img_width'] < $width)
f2e824
			{
f2e824
				$error = true;
f2e824
				$this->warn_msg[] = sprintf($user->lang['MAX_FLASH_WIDTH_EXCEEDED'], $config['max_' . $this->mode . '_img_width']);
f2e824
			}
f2e824
		}
f2e824
f2e824
		if ($error || $this->path_in_domain($in))
f2e824
		{
f2e824
			return '[flash=' . $width . ',' . $height . ']' . $in . '[/flash]';
f2e824
		}
f2e824
f2e824
		return '[flash=' . $width . ',' . $height . ':' . $this->bbcode_uid . ']' . $this->bbcode_specialchars($in) . '[/flash:' . $this->bbcode_uid . ']';
f2e824
	}
f2e824
f2e824
	/**
f2e824
	* Parse inline attachments [ia]
f2e824
	*/
f2e824
	function bbcode_attachment($stx, $in)
f2e824
	{
f2e824
		if (!$this->check_bbcode('attachment', $in))
f2e824
		{
f2e824
			return $in;
f2e824
		}
f2e824
f2e824
		return '[attachment=' . $stx . ':' . $this->bbcode_uid . ']' . trim($in) . '[/attachment:' . $this->bbcode_uid . ']';
f2e824
	}
f2e824
f2e824
	/**
f2e824
	* Parse code text from code tag
f2e824
	* @access private
f2e824
	*/
f2e824
	function bbcode_parse_code($stx, &$code)
f2e824
	{
f2e824
		switch (strtolower($stx))
f2e824
		{
f2e824
			case 'php':
f2e824
f2e824
				$remove_tags = false;
f2e824
f2e824
				$str_from = array('<', '>', '[', ']', '.', ':', ':');
f2e824
				$str_to = array('<', '>', '[', ']', '.', ':', ':');
f2e824
				$code = str_replace($str_from, $str_to, $code);
f2e824
f2e824
				if (!preg_match('/\<\?.*?\?\>/is', $code))
f2e824
				{
f2e824
					$remove_tags = true;
f2e824
					$code = "";
f2e824
				}
f2e824
f2e824
				$conf = array('highlight.bg', 'highlight.comment', 'highlight.default', 'highlight.html', 'highlight.keyword', 'highlight.string');
f2e824
				foreach ($conf as $ini_var)
f2e824
				{
f2e824
					@ini_set($ini_var, str_replace('highlight.', 'syntax', $ini_var));
f2e824
				}
f2e824
f2e824
				// Because highlight_string is specialcharing the text (but we already did this before), we have to reverse this in order to get correct results
f2e824
				$code = htmlspecialchars_decode($code);
f2e824
				$code = highlight_string($code, true);
f2e824
f2e824
				$str_from = array('', '', '','[', ']', '.', ':');
f2e824
				$str_to = array('', '', '', '[', ']', '.', ':');
f2e824
f2e824
				if ($remove_tags)
f2e824
				{
f2e824
					$str_from[] = '<?php ';
f2e824
					$str_to[] = '';
f2e824
					$str_from[] = '<?php ';
f2e824
					$str_to[] = '';
f2e824
				}
f2e824
f2e824
				$code = str_replace($str_from, $str_to, $code);
f2e824
				$code = preg_replace('#^()\n?(.*?)\n?()$#is', '$1$2$3', $code);
f2e824
f2e824
				if ($remove_tags)
f2e824
				{
f2e824
					$code = preg_replace('#()?\?>()#', '$1 $2', $code);
f2e824
				}
f2e824
f2e824
				$code = preg_replace('#^(.*)#s', '$2', $code);
f2e824
				$code = preg_replace('#(?:\s++| )*+$#u', '', $code);
f2e824
f2e824
				// remove newline at the end
f2e824
				if (!empty($code) && substr($code, -1) == "\n")
f2e824
				{
f2e824
					$code = substr($code, 0, -1);
f2e824
				}
f2e824
f2e824
				return "[code=$stx:" . $this->bbcode_uid . ']' . $code . '[/code:' . $this->bbcode_uid . ']';
f2e824
			break;
f2e824
f2e824
			default:
f2e824
				return '[code:' . $this->bbcode_uid . ']' . $this->bbcode_specialchars($code) . '[/code:' . $this->bbcode_uid . ']';
f2e824
			break;
f2e824
		}
f2e824
	}
f2e824
f2e824
	/**
f2e824
	* Parse code tag
f2e824
	* Expects the argument to start right after the opening [code] tag and to end with [/code]
f2e824
	*/
f2e824
	function bbcode_code($stx, $in)
f2e824
	{
f2e824
		if (!$this->check_bbcode('code', $in))
f2e824
		{
f2e824
			return $in;
f2e824
		}
f2e824
f2e824
		// We remove the hardcoded elements from the code block here because it is not used in code blocks
f2e824
		// Having it here saves us one preg_replace per message containing [code] blocks
f2e824
		// Additionally, magic url parsing should go after parsing bbcodes, but for safety those are stripped out too...
f2e824
		$htm_match = get_preg_expression('bbcode_htm');
f2e824
		unset($htm_match[4], $htm_match[5]);
f2e824
		$htm_replace = array('\1', '\1', '\2', '\1');
f2e824
f2e824
		$out = $code_block = '';
f2e824
		$open = 1;
f2e824
f2e824
		while ($in)
f2e824
		{
f2e824
			// Determine position and tag length of next code block
f2e824
			preg_match('#(.*?)(\[code(?:=([a-z]+))?\])(.+)#is', $in, $buffer);
f2e824
			$pos = (isset($buffer[1])) ? strlen($buffer[1]) : false;
f2e824
			$tag_length = (isset($buffer[2])) ? strlen($buffer[2]) : false;
f2e824
f2e824
			// Determine position of ending code tag
f2e824
			$pos2 = stripos($in, '[/code]');
f2e824
f2e824
			// Which is the next block, ending code or code block
f2e824
			if ($pos !== false && $pos < $pos2)
f2e824
			{
f2e824
				// Open new block
f2e824
				if (!$open)
f2e824
				{
f2e824
					$out .= substr($in, 0, $pos);
f2e824
					$in = substr($in, $pos);
f2e824
					$stx = (isset($buffer[3])) ? $buffer[3] : '';
f2e824
					$code_block = '';
f2e824
				}
f2e824
				else
f2e824
				{
f2e824
					// Already opened block, just append to the current block
f2e824
					$code_block .= substr($in, 0, $pos) . ((isset($buffer[2])) ? $buffer[2] : '');
f2e824
					$in = substr($in, $pos);
f2e824
				}
f2e824
f2e824
				$in = substr($in, $tag_length);
f2e824
				$open++;
f2e824
			}
f2e824
			else
f2e824
			{
f2e824
				// Close the block
f2e824
				if ($open == 1)
f2e824
				{
f2e824
					$code_block .= substr($in, 0, $pos2);
f2e824
					$code_block = preg_replace($htm_match, $htm_replace, $code_block);
f2e824
f2e824
					// Parse this code block
f2e824
					$out .= $this->bbcode_parse_code($stx, $code_block);
f2e824
					$code_block = '';
f2e824
					$open--;
f2e824
				}
f2e824
				else if ($open)
f2e824
				{
f2e824
					// Close one open tag... add to the current code block
f2e824
					$code_block .= substr($in, 0, $pos2 + 7);
f2e824
					$open--;
f2e824
				}
f2e824
				else
f2e824
				{
f2e824
					// end code without opening code... will be always outside code block
f2e824
					$out .= substr($in, 0, $pos2 + 7);
f2e824
				}
f2e824
f2e824
				$in = substr($in, $pos2 + 7);
f2e824
			}
f2e824
		}
f2e824
f2e824
		// if now $code_block has contents we need to parse the remaining code while removing the last closing tag to match up.
f2e824
		if ($code_block)
f2e824
		{
f2e824
			$code_block = substr($code_block, 0, -7);
f2e824
			$code_block = preg_replace($htm_match, $htm_replace, $code_block);
f2e824
f2e824
			$out .= $this->bbcode_parse_code($stx, $code_block);
f2e824
		}
f2e824
f2e824
		return $out;
f2e824
	}
f2e824
f2e824
	/**
f2e824
	* Parse list bbcode
f2e824
	* Expects the argument to start with a tag
f2e824
	*/
f2e824
	function bbcode_parse_list($in)
f2e824
	{
f2e824
		if (!$this->check_bbcode('list', $in))
f2e824
		{
f2e824
			return $in;
f2e824
		}
f2e824
f2e824
		// $tok holds characters to stop at. Since the string starts with a '[' we'll get everything up to the first ']' which should be the opening [list] tag
f2e824
		$tok = ']';
f2e824
		$out = '[';
f2e824
f2e824
		// First character is [
f2e824
		$in = substr($in, 1);
f2e824
		$list_end_tags = $item_end_tags = array();
f2e824
f2e824
		do
f2e824
		{
f2e824
			$pos = strlen($in);
f2e824
f2e824
			for ($i = 0, $tok_len = strlen($tok); $i < $tok_len; ++$i)
f2e824
			{
f2e824
				$tmp_pos = strpos($in, $tok[$i]);
f2e824
f2e824
				if ($tmp_pos !== false && $tmp_pos < $pos)
f2e824
				{
f2e824
					$pos = $tmp_pos;
f2e824
				}
f2e824
			}
f2e824
f2e824
			$buffer = substr($in, 0, $pos);
f2e824
			$tok = $in[$pos];
f2e824
f2e824
			$in = substr($in, $pos + 1);
f2e824
f2e824
			if ($tok == ']')
f2e824
			{
f2e824
				// if $tok is ']' the buffer holds a tag
f2e824
				if (strtolower($buffer) == '/list' && sizeof($list_end_tags))
f2e824
				{
f2e824
					// valid [/list] tag, check nesting so that we don't hit false positives
f2e824
					if (sizeof($item_end_tags) && sizeof($item_end_tags) >= sizeof($list_end_tags))
f2e824
					{
f2e824
						// current li tag has not been closed
f2e824
						$out = preg_replace('/\n?\[$/', '[', $out) . array_pop($item_end_tags) . '][';
f2e824
					}
f2e824
f2e824
					$out .= array_pop($list_end_tags) . ']';
f2e824
					$tok = '[';
f2e824
				}
f2e824
				else if (preg_match('#^list(=[0-9a-z]+)?$#i', $buffer, $m))
f2e824
				{
f2e824
					// sub-list, add a closing tag
f2e824
					if (empty($m[1]) || preg_match('/^=(?:disc|square|circle)$/i', $m[1]))
f2e824
					{
f2e824
						array_push($list_end_tags, '/list:u:' . $this->bbcode_uid);
f2e824
					}
f2e824
					else
f2e824
					{
f2e824
						array_push($list_end_tags, '/list:o:' . $this->bbcode_uid);
f2e824
					}
f2e824
					$out .= 'list' . substr($buffer, 4) . ':' . $this->bbcode_uid . ']';
f2e824
					$tok = '[';
f2e824
				}
f2e824
				else
f2e824
				{
f2e824
					if (($buffer == '*' || substr($buffer, -2) == '[*') && sizeof($list_end_tags))
f2e824
					{
f2e824
						// the buffer holds a bullet tag and we have a [list] tag open
f2e824
						if (sizeof($item_end_tags) >= sizeof($list_end_tags))
f2e824
						{
f2e824
							if (substr($buffer, -2) == '[*')
f2e824
							{
f2e824
								$out .= substr($buffer, 0, -2) . '[';
f2e824
							}
f2e824
							// current li tag has not been closed
f2e824
							if (preg_match('/\n\[$/', $out, $m))
f2e824
							{
f2e824
								$out = preg_replace('/\n\[$/', '[', $out);
f2e824
								$buffer = array_pop($item_end_tags) . "]\n[*:" . $this->bbcode_uid;
f2e824
							}
f2e824
							else
f2e824
							{
f2e824
								$buffer = array_pop($item_end_tags) . '][*:' . $this->bbcode_uid;
f2e824
							}
f2e824
						}
f2e824
						else
f2e824
						{
f2e824
							$buffer = '*:' . $this->bbcode_uid;
f2e824
						}
f2e824
f2e824
						$item_end_tags[] = '/*:m:' . $this->bbcode_uid;
f2e824
					}
f2e824
					else if ($buffer == '/*')
f2e824
					{
f2e824
						array_pop($item_end_tags);
f2e824
						$buffer = '/*:' . $this->bbcode_uid;
f2e824
					}
f2e824
f2e824
					$out .= $buffer . $tok;
f2e824
					$tok = '[]';
f2e824
				}
f2e824
			}
f2e824
			else
f2e824
			{
f2e824
				// Not within a tag, just add buffer to the return string
f2e824
				$out .= $buffer . $tok;
f2e824
				$tok = ($tok == '[') ? ']' : '[]';
f2e824
			}
f2e824
		}
f2e824
		while ($in);
f2e824
f2e824
		// do we have some tags open? close them now
f2e824
		if (sizeof($item_end_tags))
f2e824
		{
f2e824
			$out .= '[' . implode('][', $item_end_tags) . ']';
f2e824
		}
f2e824
		if (sizeof($list_end_tags))
f2e824
		{
f2e824
			$out .= '[' . implode('][', $list_end_tags) . ']';
f2e824
		}
f2e824
f2e824
		return $out;
f2e824
	}
f2e824
f2e824
	/**
f2e824
	* Parse quote bbcode
f2e824
	* Expects the argument to start with a tag
f2e824
	*/
f2e824
	function bbcode_quote($in)
f2e824
	{
f2e824
		global $config, $user;
f2e824
f2e824
		/**
f2e824
		* If you change this code, make sure the cases described within the following reports are still working:
f2e824
		* #3572 - [quote="[test]test"]test [ test[/quote] - (correct: parsed)
f2e824
		* #14667 - [quote]test[/quote] test ] and [ test [quote]test[/quote] (correct: parsed)
f2e824
		* #14770 - [quote="["]test[/quote] (correct: parsed)
f2e824
		* [quote="[i]test[/i]"]test[/quote] (correct: parsed)
f2e824
		* [quote="[quote]test[/quote]"]test[/quote] (correct: parsed - Username displayed as [quote]test[/quote])
f2e824
		* #20735 - [quote]test[/[/b]quote] test [/quote][/quote] test - (correct: quoted: "test[/[/b]quote] test" / non-quoted: "[/quote] test" - also failed if layout distorted)
f2e824
		*/
f2e824
f2e824
		$in = str_replace("\r\n", "\n", str_replace('\"', '"', trim($in)));
f2e824
f2e824
		if (!$in)
f2e824
		{
f2e824
			return '';
f2e824
		}
f2e824
f2e824
		// To let the parser not catch tokens within quote_username quotes we encode them before we start this...
f2e824
		$in = preg_replace('#quote="(.*?)"\]#ie', "'quote="' . str_replace(array('[', ']'), array('[', ']'), '\$1') . '"]'", $in);
f2e824
f2e824
		$tok = ']';
f2e824
		$out = '[';
f2e824
f2e824
		$in = substr($in, 1);
f2e824
		$close_tags = $error_ary = array();
f2e824
		$buffer = '';
f2e824
f2e824
		do
f2e824
		{
f2e824
			$pos = strlen($in);
f2e824
			for ($i = 0, $tok_len = strlen($tok); $i < $tok_len; ++$i)
f2e824
			{
f2e824
				$tmp_pos = strpos($in, $tok[$i]);
f2e824
				if ($tmp_pos !== false && $tmp_pos < $pos)
f2e824
				{
f2e824
					$pos = $tmp_pos;
f2e824
				}
f2e824
			}
f2e824
f2e824
			$buffer .= substr($in, 0, $pos);
f2e824
			$tok = $in[$pos];
f2e824
			$in = substr($in, $pos + 1);
f2e824
f2e824
			if ($tok == ']')
f2e824
			{
f2e824
				if (strtolower($buffer) == '/quote' && sizeof($close_tags) && substr($out, -1, 1) == '[')
f2e824
				{
f2e824
					// we have found a closing tag
f2e824
					$out .= array_pop($close_tags) . ']';
f2e824
					$tok = '[';
f2e824
					$buffer = '';
f2e824
f2e824
					/* Add space at the end of the closing tag if not happened before to allow following urls/smilies to be parsed correctly
f2e824
					* Do not try to think for the user. :/ Do not parse urls/smilies if there is no space - is the same as with other bbcodes too.
f2e824
					* Also, we won't have any spaces within $in anyway, only adding up spaces -> #10982
f2e824
					if (!$in || $in[0] !== ' ')
f2e824
					{
f2e824
						$out .= ' ';
f2e824
					}*/
f2e824
				}
f2e824
				else if (preg_match('#^quote(?:="(.*?)")?$#is', $buffer, $m) && substr($out, -1, 1) == '[')
f2e824
				{
f2e824
					$this->parsed_items['quote']++;
f2e824
f2e824
					// the buffer holds a valid opening tag
f2e824
					if ($config['max_quote_depth'] && sizeof($close_tags) >= $config['max_quote_depth'])
f2e824
					{
f2e824
						// there are too many nested quotes
f2e824
						$error_ary['quote_depth'] = sprintf($user->lang['QUOTE_DEPTH_EXCEEDED'], $config['max_quote_depth']);
f2e824
f2e824
						$out .= $buffer . $tok;
f2e824
						$tok = '[]';
f2e824
						$buffer = '';
f2e824
f2e824
						continue;
f2e824
					}
f2e824
f2e824
					array_push($close_tags, '/quote:' . $this->bbcode_uid);
f2e824
f2e824
					if (isset($m[1]) && $m[1])
f2e824
					{
f2e824
						$username = str_replace(array('[', ']'), array('[', ']'), $m[1]);
f2e824
						$username = preg_replace('#\[(?!b|i|u|color|url|email|/b|/i|/u|/color|/url|/email)#iU', '[$1', $username);
f2e824
f2e824
						$end_tags = array();
f2e824
						$error = false;
f2e824
f2e824
						preg_match_all('#\[((?:/)?(?:[a-z]+))#i', $username, $tags);
f2e824
						foreach ($tags[1] as $tag)
f2e824
						{
f2e824
							if ($tag[0] != '/')
f2e824
							{
f2e824
								$end_tags[] = '/' . $tag;
f2e824
							}
f2e824
							else
f2e824
							{
f2e824
								$end_tag = array_pop($end_tags);
f2e824
								$error = ($end_tag != $tag) ? true : false;
f2e824
							}
f2e824
						}
f2e824
f2e824
						if ($error)
f2e824
						{
f2e824
							$username = $m[1];
f2e824
						}
f2e824
f2e824
						$out .= 'quote="' . $username . '":' . $this->bbcode_uid . ']';
f2e824
					}
f2e824
					else
f2e824
					{
f2e824
						$out .= 'quote:' . $this->bbcode_uid . ']';
f2e824
					}
f2e824
f2e824
					$tok = '[';
f2e824
					$buffer = '';
f2e824
				}
f2e824
				else if (preg_match('#^quote="(.*?)#is', $buffer, $m))
f2e824
				{
f2e824
					// the buffer holds an invalid opening tag
f2e824
					$buffer .= ']';
f2e824
				}
f2e824
				else
f2e824
				{
f2e824
					$out .= $buffer . $tok;
f2e824
					$tok = '[]';
f2e824
					$buffer = '';
f2e824
				}
f2e824
			}
f2e824
			else
f2e824
			{
f2e824
/**
f2e824
*				Old quote code working fine, but having errors listed in bug #3572
f2e824
*
f2e824
*				$out .= $buffer . $tok;
f2e824
*				$tok = ($tok == '[') ? ']' : '[]';
f2e824
*				$buffer = '';
f2e824
*/
f2e824
f2e824
				$out .= $buffer . $tok;
f2e824
f2e824
				if ($tok == '[')
f2e824
				{
f2e824
					// Search the text for the next tok... if an ending quote comes first, then change tok to []
f2e824
					$pos1 = stripos($in, '[/quote');
f2e824
					// If the token ] comes first, we change it to ]
f2e824
					$pos2 = strpos($in, ']');
f2e824
					// If the token [ comes first, we change it to [
f2e824
					$pos3 = strpos($in, '[');
f2e824
f2e824
					if ($pos1 !== false && ($pos2 === false || $pos1 < $pos2) && ($pos3 === false || $pos1 < $pos3))
f2e824
					{
f2e824
						$tok = '[]';
f2e824
					}
f2e824
					else if ($pos3 !== false && ($pos2 === false || $pos3 < $pos2))
f2e824
					{
f2e824
						$tok = '[';
f2e824
					}
f2e824
					else
f2e824
					{
f2e824
						$tok = ']';
f2e824
					}
f2e824
				}
f2e824
				else
f2e824
				{
f2e824
					$tok = '[]';
f2e824
				}
f2e824
				$buffer = '';
f2e824
			}
f2e824
		}
f2e824
		while ($in);
f2e824
f2e824
		if (sizeof($close_tags))
f2e824
		{
f2e824
			$out .= '[' . implode('][', $close_tags) . ']';
f2e824
		}
f2e824
f2e824
		foreach ($error_ary as $error_msg)
f2e824
		{
f2e824
			$this->warn_msg[] = $error_msg;
f2e824
		}
f2e824
f2e824
		return $out;
f2e824
	}
f2e824
f2e824
	/**
f2e824
	* Validate email
f2e824
	*/
f2e824
	function validate_email($var1, $var2)
f2e824
	{
f2e824
		$var1 = str_replace("\r\n", "\n", str_replace('\"', '"', trim($var1)));
f2e824
		$var2 = str_replace("\r\n", "\n", str_replace('\"', '"', trim($var2)));
f2e824
f2e824
		$txt = $var2;
f2e824
		$email = ($var1) ? $var1 : $var2;
f2e824
f2e824
		$validated = true;
f2e824
f2e824
		if (!preg_match('/^' . get_preg_expression('email') . '$/i', $email))
f2e824
		{
f2e824
			$validated = false;
f2e824
		}
f2e824
f2e824
		if (!$validated)
f2e824
		{
f2e824
			return '[email' . (($var1) ? "=$var1" : '') . ']' . $var2 . '[/email]';
f2e824
		}
f2e824
f2e824
		$this->parsed_items['email']++;
f2e824
f2e824
		if ($var1)
f2e824
		{
f2e824
			$retval = '[email=' . $this->bbcode_specialchars($email) . ':' . $this->bbcode_uid . ']' . $txt . '[/email:' . $this->bbcode_uid . ']';
f2e824
		}
f2e824
		else
f2e824
		{
f2e824
			$retval = '[email:' . $this->bbcode_uid . ']' . $this->bbcode_specialchars($email) . '[/email:' . $this->bbcode_uid . ']';
f2e824
		}
f2e824
f2e824
		return $retval;
f2e824
	}
f2e824
f2e824
	/**
f2e824
	* Validate url
f2e824
	*
f2e824
	* @param string $var1 optional url parameter for url bbcode: [url(=$var1)]$var2[/url]
f2e824
	* @param string $var2 url bbcode content: [url(=$var1)]$var2[/url]
f2e824
	*/
f2e824
	function validate_url($var1, $var2)
f2e824
	{
f2e824
		global $config;
f2e824
f2e824
		$var1 = str_replace("\r\n", "\n", str_replace('\"', '"', trim($var1)));
f2e824
		$var2 = str_replace("\r\n", "\n", str_replace('\"', '"', trim($var2)));
f2e824
f2e824
		$url = ($var1) ? $var1 : $var2;
f2e824
f2e824
		if ($var1 && !$var2)
f2e824
		{
f2e824
			$var2 = $var1;
f2e824
		}
f2e824
f2e824
		if (!$url)
f2e824
		{
f2e824
			return '[url' . (($var1) ? '=' . $var1 : '') . ']' . $var2 . '[/url]';
f2e824
		}
f2e824
f2e824
		$valid = false;
f2e824
f2e824
		$url = str_replace(' ', '%20', $url);
f2e824
f2e824
		// Checking urls
f2e824
		if (preg_match('#^' . get_preg_expression('url') . '$#i', $url) ||
f2e824
			preg_match('#^' . get_preg_expression('www_url') . '$#i', $url) ||
f2e824
			preg_match('#^' . preg_quote(generate_board_url(), '#') . get_preg_expression('relative_url') . '$#i', $url))
f2e824
		{
f2e824
			$valid = true;
f2e824
		}
f2e824
f2e824
		if ($valid)
f2e824
		{
f2e824
			$this->parsed_items['url']++;
f2e824
f2e824
			// if there is no scheme, then add http schema
f2e824
			if (!preg_match('#^[a-z][a-z\d+\-.]*:/{2}#i', $url))
f2e824
			{
f2e824
				$url = 'http://' . $url;
f2e824
			}
f2e824
f2e824
			// Is this a link to somewhere inside this board? If so then remove the session id from the url
f2e824
			if (strpos($url, generate_board_url()) !== false && strpos($url, 'sid=') !== false)
f2e824
			{
f2e824
				$url = preg_replace('/(&|\?)sid=[0-9a-f]{32}&/', '\1', $url);
f2e824
				$url = preg_replace('/(&|\?)sid=[0-9a-f]{32}$/', '', $url);
f2e824
				$url = append_sid($url);
f2e824
			}
f2e824
f2e824
			return ($var1) ? '[url=' . $this->bbcode_specialchars($url) . ':' . $this->bbcode_uid . ']' . $var2 . '[/url:' . $this->bbcode_uid . ']' : '[url:' . $this->bbcode_uid . ']' . $this->bbcode_specialchars($url) . '[/url:' . $this->bbcode_uid . ']';
f2e824
		}
f2e824
f2e824
		return '[url' . (($var1) ? '=' . $var1 : '') . ']' . $var2 . '[/url]';
f2e824
	}
f2e824
f2e824
	/**
f2e824
	* Check if url is pointing to this domain/script_path/php-file
f2e824
	*
f2e824
	* @param string $url the url to check
f2e824
	* @return true if the url is pointing to this domain/script_path/php-file, false if not
f2e824
	*
f2e824
	* @access private
f2e824
	*/
f2e824
	function path_in_domain($url)
f2e824
	{
f2e824
		global $config, $phpEx, $user;
f2e824
f2e824
		if ($config['force_server_vars'])
f2e824
		{
f2e824
			$check_path = $config['script_path'];
f2e824
		}
f2e824
		else
f2e824
		{
f2e824
			$check_path = ($user->page['root_script_path'] != '/') ? substr($user->page['root_script_path'], 0, -1) : '/';
f2e824
		}
f2e824
f2e824
		// Is the user trying to link to a php file in this domain and script path?
f2e824
		if (strpos($url, ".{$phpEx}") !== false && strpos($url, $check_path) !== false)
f2e824
		{
f2e824
			$server_name = $user->host;
f2e824
f2e824
			// Forcing server vars is the only way to specify/override the protocol
f2e824
			if ($config['force_server_vars'] || !$server_name)
f2e824
			{
f2e824
				$server_name = $config['server_name'];
f2e824
			}
f2e824
f2e824
			// Check again in correct order...
f2e824
			$pos_ext = strpos($url, ".{$phpEx}");
f2e824
			$pos_path = strpos($url, $check_path);
f2e824
			$pos_domain = strpos($url, $server_name);
f2e824
f2e824
			if ($pos_domain !== false && $pos_path >= $pos_domain && $pos_ext >= $pos_path)
f2e824
			{
f2e824
				// Ok, actually we allow linking to some files (this may be able to be extended in some way later...)
f2e824
				if (strpos($url, '/' . $check_path . '/download/file.' . $phpEx) !== 0)
f2e824
				{
f2e824
					return false;
f2e824
				}
f2e824
f2e824
				return true;
f2e824
			}
f2e824
		}
f2e824
f2e824
		return false;
f2e824
	}
f2e824
}
f2e824
f2e824
/**
f2e824
* Main message parser for posting, pm, etc. takes raw message
f2e824
* and parses it for attachments, bbcode and smilies
f2e824
* @package phpBB3
f2e824
*/
f2e824
class parse_message extends bbcode_firstpass
f2e824
{
f2e824
	var $attachment_data = array();
f2e824
	var $filename_data = array();
f2e824
f2e824
	// Helps ironing out user error
f2e824
	var $message_status = '';
f2e824
f2e824
	var $allow_img_bbcode = true;
f2e824
	var $allow_flash_bbcode = true;
f2e824
	var $allow_quote_bbcode = true;
f2e824
	var $allow_url_bbcode = true;
f2e824
f2e824
	var $mode;
f2e824
f2e824
	/**
f2e824
	* Init - give message here or manually
f2e824
	*/
f2e824
	function parse_message($message = '')
f2e824
	{
f2e824
		// Init BBCode UID
f2e824
		$this->bbcode_uid = substr(base_convert(unique_id(), 16, 36), 0, BBCODE_UID_LEN);
f2e824
f2e824
		if ($message)
f2e824
		{
f2e824
			$this->message = $message;
f2e824
		}
f2e824
	}
f2e824
f2e824
	/**
f2e824
	* Parse Message
f2e824
	*/
f2e824
	function parse($allow_bbcode, $allow_magic_url, $allow_smilies, $allow_img_bbcode = true, $allow_flash_bbcode = true, $allow_quote_bbcode = true, $allow_url_bbcode = true, $update_this_message = true, $mode = 'post')
f2e824
	{
f2e824
		global $config, $db, $user;
f2e824
f2e824
		$mode = ($mode != 'post') ? 'sig' : 'post';
f2e824
f2e824
		$this->mode = $mode;
f2e824
f2e824
		$this->allow_img_bbcode = $allow_img_bbcode;
f2e824
		$this->allow_flash_bbcode = $allow_flash_bbcode;
f2e824
		$this->allow_quote_bbcode = $allow_quote_bbcode;
f2e824
		$this->allow_url_bbcode = $allow_url_bbcode;
f2e824
f2e824
		// If false, then $this->message won't be altered, the text will be returned instead.
f2e824
		if (!$update_this_message)
f2e824
		{
f2e824
			$tmp_message = $this->message;
f2e824
			$return_message = &$this->message;
f2e824
		}
f2e824
f2e824
		if ($this->message_status == 'display')
f2e824
		{
f2e824
			$this->decode_message();
f2e824
		}
f2e824
f2e824
		// Do some general 'cleanup' first before processing message,
f2e824
		// e.g. remove excessive newlines(?), smilies(?)
f2e824
		$match = array('#(script|about|applet|activex|chrome):#i');
f2e824
		$replace = array("\\1:");
f2e824
		$this->message = preg_replace($match, $replace, trim($this->message));
f2e824
f2e824
		// Message length check. 0 disables this check completely.
f2e824
		if ($config['max_' . $mode . '_chars'] > 0)
f2e824
		{
f2e824
			$msg_len = ($mode == 'post') ? utf8_strlen($this->message) : utf8_strlen(preg_replace('#\[\/?[a-z\*\+\-]+(=[\S]+)?\]#ius', ' ', $this->message));
f2e824
f2e824
			if ((!$msg_len && $mode !== 'sig') || $config['max_' . $mode . '_chars'] && $msg_len > $config['max_' . $mode . '_chars'])
f2e824
			{
f2e824
				$this->warn_msg[] = (!$msg_len) ? $user->lang['TOO_FEW_CHARS'] : sprintf($user->lang['TOO_MANY_CHARS_' . strtoupper($mode)], $msg_len, $config['max_' . $mode . '_chars']);
f2e824
				return (!$update_this_message) ? $return_message : $this->warn_msg;
f2e824
			}
f2e824
		}
f2e824
f2e824
		// Check for "empty" message
f2e824
		if ($mode !== 'sig' && utf8_clean_string($this->message) === '')
f2e824
		{
f2e824
			$this->warn_msg[] = $user->lang['TOO_FEW_CHARS'];
f2e824
			return (!$update_this_message) ? $return_message : $this->warn_msg;
f2e824
		}
f2e824
f2e824
		// Prepare BBcode (just prepares some tags for better parsing)
f2e824
		if ($allow_bbcode && strpos($this->message, '[') !== false)
f2e824
		{
f2e824
			$this->bbcode_init();
f2e824
			$disallow = array('img', 'flash', 'quote', 'url');
f2e824
			foreach ($disallow as $bool)
f2e824
			{
f2e824
				if (!${'allow_' . $bool . '_bbcode'})
f2e824
				{
f2e824
					$this->bbcodes[$bool]['disabled'] = true;
f2e824
				}
f2e824
			}
f2e824
f2e824
			$this->prepare_bbcodes();
f2e824
		}
f2e824
f2e824
		// Parse smilies
f2e824
		if ($allow_smilies)
f2e824
		{
f2e824
			$this->smilies($config['max_' . $mode . '_smilies']);
f2e824
		}
f2e824
f2e824
		$num_urls = 0;
f2e824
f2e824
		// Parse BBCode
f2e824
		if ($allow_bbcode && strpos($this->message, '[') !== false)
f2e824
		{
f2e824
			$this->parse_bbcode();
f2e824
			$num_urls += $this->parsed_items['url'];
f2e824
		}
f2e824
f2e824
		// Parse URL's
f2e824
		if ($allow_magic_url)
f2e824
		{
f2e824
			$this->magic_url(generate_board_url());
f2e824
f2e824
			if ($config['max_' . $mode . '_urls'])
f2e824
			{
f2e824
				$num_urls += preg_match_all('#\
f2e824
			}
f2e824
		}
f2e824
f2e824
		// Check number of links
f2e824
		if ($config['max_' . $mode . '_urls'] && $num_urls > $config['max_' . $mode . '_urls'])
f2e824
		{
f2e824
			$this->warn_msg[] = sprintf($user->lang['TOO_MANY_URLS'], $config['max_' . $mode . '_urls']);
f2e824
			return (!$update_this_message) ? $return_message : $this->warn_msg;
f2e824
		}
f2e824
f2e824
		if (!$update_this_message)
f2e824
		{
f2e824
			unset($this->message);
f2e824
			$this->message = $tmp_message;
f2e824
			return $return_message;
f2e824
		}
f2e824
f2e824
		$this->message_status = 'parsed';
f2e824
		return false;
f2e824
	}
f2e824
f2e824
	/**
f2e824
	* Formatting text for display
f2e824
	*/
f2e824
	function format_display($allow_bbcode, $allow_magic_url, $allow_smilies, $update_this_message = true)
f2e824
	{
f2e824
		// If false, then the parsed message get returned but internal message not processed.
f2e824
		if (!$update_this_message)
f2e824
		{
f2e824
			$tmp_message = $this->message;
f2e824
			$return_message = &$this->message;
f2e824
		}
f2e824
f2e824
		if ($this->message_status == 'plain')
f2e824
		{
f2e824
			// Force updating message - of course.
f2e824
			$this->parse($allow_bbcode, $allow_magic_url, $allow_smilies, $this->allow_img_bbcode, $this->allow_flash_bbcode, $this->allow_quote_bbcode, $this->allow_url_bbcode, true);
f2e824
		}
f2e824
f2e824
		// Replace naughty words such as farty pants
f2e824
		$this->message = censor_text($this->message);
f2e824
f2e824
		// Parse BBcode
f2e824
		if ($allow_bbcode)
f2e824
		{
f2e824
			$this->bbcode_cache_init();
f2e824
f2e824
			// We are giving those parameters to be able to use the bbcode class on its own
f2e824
			$this->bbcode_second_pass($this->message, $this->bbcode_uid);
f2e824
		}
f2e824
f2e824
		$this->message = bbcode_nl2br($this->message);
f2e824
		$this->message = smiley_text($this->message, !$allow_smilies);
f2e824
f2e824
		if (!$update_this_message)
f2e824
		{
f2e824
			unset($this->message);
f2e824
			$this->message = $tmp_message;
f2e824
			return $return_message;
f2e824
		}
f2e824
f2e824
		$this->message_status = 'display';
f2e824
		return false;
f2e824
	}
f2e824
f2e824
	/**
f2e824
	* Decode message to be placed back into form box
f2e824
	*/
f2e824
	function decode_message($custom_bbcode_uid = '', $update_this_message = true)
f2e824
	{
f2e824
		// If false, then the parsed message get returned but internal message not processed.
f2e824
		if (!$update_this_message)
f2e824
		{
f2e824
			$tmp_message = $this->message;
f2e824
			$return_message = &$this->message;
f2e824
		}
f2e824
f2e824
		($custom_bbcode_uid) ? decode_message($this->message, $custom_bbcode_uid) : decode_message($this->message, $this->bbcode_uid);
f2e824
f2e824
		if (!$update_this_message)
f2e824
		{
f2e824
			unset($this->message);
f2e824
			$this->message = $tmp_message;
f2e824
			return $return_message;
f2e824
		}
f2e824
f2e824
		$this->message_status = 'plain';
f2e824
		return false;
f2e824
	}
f2e824
f2e824
	/**
f2e824
	* Replace magic urls of form http://xxx.xxx., www.xxx. and xxx@xxx.xxx.
f2e824
	* Cuts down displayed size of link if over 50 chars, turns absolute links
f2e824
	* into relative versions when the server/script path matches the link
f2e824
	*/
f2e824
	function magic_url($server_url)
f2e824
	{
f2e824
		// We use the global make_clickable function
f2e824
		$this->message = make_clickable($this->message, $server_url);
f2e824
	}
f2e824
f2e824
	/**
f2e824
	* Parse Smilies
f2e824
	*/
f2e824
	function smilies($max_smilies = 0)
f2e824
	{
f2e824
		global $db, $user;
f2e824
		static $match;
f2e824
		static $replace;
f2e824
f2e824
		// See if the static arrays have already been filled on an earlier invocation
f2e824
		if (!is_array($match))
f2e824
		{
f2e824
			$match = $replace = array();
f2e824
f2e824
			// NOTE: obtain_* function? chaching the table contents?
f2e824
f2e824
			// For now setting the ttl to 10 minutes
f2e824
			switch ($db->sql_layer)
f2e824
			{
f2e824
				case 'mssql':
f2e824
				case 'mssql_odbc':
f2e824
					$sql = 'SELECT *
f2e824
						FROM ' . SMILIES_TABLE . '
f2e824
						ORDER BY LEN(code) DESC';
f2e824
				break;
f2e824
f2e824
				case 'firebird':
f2e824
					$sql = 'SELECT *
f2e824
						FROM ' . SMILIES_TABLE . '
f2e824
						ORDER BY CHAR_LENGTH(code) DESC';
f2e824
				break;
f2e824
f2e824
				// LENGTH supported by MySQL, IBM DB2, Oracle and Access for sure...
f2e824
				default:
f2e824
					$sql = 'SELECT *
f2e824
						FROM ' . SMILIES_TABLE . '
f2e824
						ORDER BY LENGTH(code) DESC';
f2e824
				break;
f2e824
			}
f2e824
			$result = $db->sql_query($sql, 600);
f2e824
f2e824
			while ($row = $db->sql_fetchrow($result))
f2e824
			{
f2e824
				if (empty($row['code']))
f2e824
				{
f2e824
					continue;
f2e824
				}
f2e824
f2e824
				// (assertion)
f2e824
				$match[] = '(?<=^|[\n .])' . preg_quote($row['code'], '#') . '(?![^<>]*>)';
f2e824
				$replace[] = '' . $row['code'] . '';
f2e824
			}
f2e824
			$db->sql_freeresult($result);
f2e824
		}
f2e824
f2e824
		if (sizeof($match))
f2e824
		{
f2e824
			if ($max_smilies)
f2e824
			{
f2e824
				$num_matches = preg_match_all('#' . implode('|', $match) . '#', $this->message, $matches);
f2e824
				unset($matches);
f2e824
f2e824
				if ($num_matches !== false && $num_matches > $max_smilies)
f2e824
				{
f2e824
					$this->warn_msg[] = sprintf($user->lang['TOO_MANY_SMILIES'], $max_smilies);
f2e824
					return;
f2e824
				}
f2e824
			}
f2e824
f2e824
			// Make sure the delimiter # is added in front and at the end of every element within $match
f2e824
			$this->message = trim(preg_replace(explode(chr(0), '#' . implode('#' . chr(0) . '#', $match) . '#'), $replace, $this->message));
f2e824
		}
f2e824
	}
f2e824
f2e824
	/**
f2e824
	* Parse Attachments
f2e824
	*/
f2e824
	function parse_attachments($form_name, $mode, $forum_id, $submit, $preview, $refresh, $is_message = false)
f2e824
	{
f2e824
		global $config, $auth, $user, $phpbb_root_path, $phpEx, $db;
f2e824
f2e824
		$error = array();
f2e824
f2e824
		$num_attachments = sizeof($this->attachment_data);
f2e824
		$this->filename_data['filecomment'] = utf8_normalize_nfc(request_var('filecomment', '', true));
f2e824
		$upload_file = (isset($_FILES[$form_name]) && $_FILES[$form_name]['name'] != 'none' && trim($_FILES[$form_name]['name'])) ? true : false;
f2e824
f2e824
		$add_file		= (isset($_POST['add_file'])) ? true : false;
f2e824
		$delete_file	= (isset($_POST['delete_file'])) ? true : false;
f2e824
f2e824
		// First of all adjust comments if changed
f2e824
		$actual_comment_list = utf8_normalize_nfc(request_var('comment_list', array(''), true));
f2e824
f2e824
		foreach ($actual_comment_list as $comment_key => $comment)
f2e824
		{
f2e824
			if (!isset($this->attachment_data[$comment_key]))
f2e824
			{
f2e824
				continue;
f2e824
			}
f2e824
f2e824
			if ($this->attachment_data[$comment_key]['attach_comment'] != $actual_comment_list[$comment_key])
f2e824
			{
f2e824
				$this->attachment_data[$comment_key]['attach_comment'] = $actual_comment_list[$comment_key];
f2e824
			}
f2e824
		}
f2e824
f2e824
		$cfg = array();
f2e824
		$cfg['max_attachments'] = ($is_message) ? $config['max_attachments_pm'] : $config['max_attachments'];
f2e824
		$forum_id = ($is_message) ? 0 : $forum_id;
f2e824
f2e824
		if ($submit && in_array($mode, array('post', 'reply', 'quote', 'edit')) && $upload_file)
f2e824
		{
f2e824
			if ($num_attachments < $cfg['max_attachments'] || $auth->acl_get('a_') || $auth->acl_get('m_', $forum_id))
f2e824
			{
f2e824
				$filedata = upload_attachment($form_name, $forum_id, false, '', $is_message);
f2e824
				$error = $filedata['error'];
f2e824
f2e824
				if ($filedata['post_attach'] && !sizeof($error))
f2e824
				{
f2e824
					$sql_ary = array(
f2e824
						'physical_filename'	=> $filedata['physical_filename'],
f2e824
						'attach_comment'	=> $this->filename_data['filecomment'],
f2e824
						'real_filename'		=> $filedata['real_filename'],
f2e824
						'extension'			=> $filedata['extension'],
f2e824
						'mimetype'			=> $filedata['mimetype'],
f2e824
						'filesize'			=> $filedata['filesize'],
f2e824
						'filetime'			=> $filedata['filetime'],
f2e824
						'thumbnail'			=> $filedata['thumbnail'],
f2e824
						'is_orphan'			=> 1,
f2e824
						'in_message'		=> ($is_message) ? 1 : 0,
f2e824
						'poster_id'			=> $user->data['user_id'],
f2e824
					);
f2e824
f2e824
					$db->sql_query('INSERT INTO ' . ATTACHMENTS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary));
f2e824
f2e824
					$new_entry = array(
f2e824
						'attach_id'		=> $db->sql_nextid(),
f2e824
						'is_orphan'		=> 1,
f2e824
						'real_filename'	=> $filedata['real_filename'],
f2e824
						'attach_comment'=> $this->filename_data['filecomment'],
f2e824
					);
f2e824
f2e824
					$this->attachment_data = array_merge(array(0 => $new_entry), $this->attachment_data);
f2e824
					$this->message = preg_replace('#\[attachment=([0-9]+)\](.*?)\[\/attachment\]#e', "'[attachment='.(\\1 + 1).']\\2[/attachment]'", $this->message);
f2e824
f2e824
					$this->filename_data['filecomment'] = '';
f2e824
f2e824
					// This Variable is set to false here, because Attachments are entered into the
f2e824
					// Database in two modes, one if the id_list is 0 and the second one if post_attach is true
f2e824
					// Since post_attach is automatically switched to true if an Attachment got added to the filesystem,
f2e824
					// but we are assigning an id of 0 here, we have to reset the post_attach variable to false.
f2e824
					//
f2e824
					// This is very relevant, because it could happen that the post got not submitted, but we do not
f2e824
					// know this circumstance here. We could be at the posting page or we could be redirected to the entered
f2e824
					// post. :)
f2e824
					$filedata['post_attach'] = false;
f2e824
				}
f2e824
			}
f2e824
			else
f2e824
			{
f2e824
				$error[] = sprintf($user->lang['TOO_MANY_ATTACHMENTS'], $cfg['max_attachments']);
f2e824
			}
f2e824
		}
f2e824
f2e824
		if ($preview || $refresh || sizeof($error))
f2e824
		{
f2e824
			// Perform actions on temporary attachments
f2e824
			if ($delete_file)
f2e824
			{
f2e824
				include_once($phpbb_root_path . 'includes/functions_admin.' . $phpEx);
f2e824
f2e824
				$index = array_keys(request_var('delete_file', array(0 => 0)));
f2e824
				$index = (!empty($index)) ? $index[0] : false;
f2e824
f2e824
				if ($index !== false && !empty($this->attachment_data[$index]))
f2e824
				{
f2e824
					// delete selected attachment
f2e824
					if ($this->attachment_data[$index]['is_orphan'])
f2e824
					{
f2e824
						$sql = 'SELECT attach_id, physical_filename, thumbnail
f2e824
							FROM ' . ATTACHMENTS_TABLE . '
f2e824
							WHERE attach_id = ' . (int) $this->attachment_data[$index]['attach_id'] . '
f2e824
								AND is_orphan = 1
f2e824
								AND poster_id = ' . $user->data['user_id'];
f2e824
						$result = $db->sql_query($sql);
f2e824
						$row = $db->sql_fetchrow($result);
f2e824
						$db->sql_freeresult($result);
f2e824
f2e824
						if ($row)
f2e824
						{
f2e824
							phpbb_unlink($row['physical_filename'], 'file');
f2e824
f2e824
							if ($row['thumbnail'])
f2e824
							{
f2e824
								phpbb_unlink($row['physical_filename'], 'thumbnail');
f2e824
							}
f2e824
f2e824
							$db->sql_query('DELETE FROM ' . ATTACHMENTS_TABLE . ' WHERE attach_id = ' . (int) $this->attachment_data[$index]['attach_id']);
f2e824
						}
f2e824
					}
f2e824
					else
f2e824
					{
f2e824
						delete_attachments('attach', array(intval($this->attachment_data[$index]['attach_id'])));
f2e824
					}
f2e824
f2e824
					unset($this->attachment_data[$index]);
f2e824
					$this->message = preg_replace('#\[attachment=([0-9]+)\](.*?)\[\/attachment\]#e', "(\\1 == \$index) ? '' : ((\\1 > \$index) ? '[attachment=' . (\\1 - 1) . ']\\2[/attachment]' : '\\0')", $this->message);
f2e824
f2e824
					// Reindex Array
f2e824
					$this->attachment_data = array_values($this->attachment_data);
f2e824
				}
f2e824
			}
f2e824
			else if (($add_file || $preview) && $upload_file)
f2e824
			{
f2e824
				if ($num_attachments < $cfg['max_attachments'] || $auth->acl_gets('m_', 'a_', $forum_id))
f2e824
				{
f2e824
					$filedata = upload_attachment($form_name, $forum_id, false, '', $is_message);
f2e824
					$error = array_merge($error, $filedata['error']);
f2e824
f2e824
					if (!sizeof($error))
f2e824
					{
f2e824
						$sql_ary = array(
f2e824
							'physical_filename'	=> $filedata['physical_filename'],
f2e824
							'attach_comment'	=> $this->filename_data['filecomment'],
f2e824
							'real_filename'		=> $filedata['real_filename'],
f2e824
							'extension'			=> $filedata['extension'],
f2e824
							'mimetype'			=> $filedata['mimetype'],
f2e824
							'filesize'			=> $filedata['filesize'],
f2e824
							'filetime'			=> $filedata['filetime'],
f2e824
							'thumbnail'			=> $filedata['thumbnail'],
f2e824
							'is_orphan'			=> 1,
f2e824
							'in_message'		=> ($is_message) ? 1 : 0,
f2e824
							'poster_id'			=> $user->data['user_id'],
f2e824
						);
f2e824
f2e824
						$db->sql_query('INSERT INTO ' . ATTACHMENTS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary));
f2e824
f2e824
						$new_entry = array(
f2e824
							'attach_id'		=> $db->sql_nextid(),
f2e824
							'is_orphan'		=> 1,
f2e824
							'real_filename'	=> $filedata['real_filename'],
f2e824
							'attach_comment'=> $this->filename_data['filecomment'],
f2e824
						);
f2e824
f2e824
						$this->attachment_data = array_merge(array(0 => $new_entry), $this->attachment_data);
f2e824
						$this->message = preg_replace('#\[attachment=([0-9]+)\](.*?)\[\/attachment\]#e', "'[attachment='.(\\1 + 1).']\\2[/attachment]'", $this->message);
f2e824
						$this->filename_data['filecomment'] = '';
f2e824
					}
f2e824
				}
f2e824
				else
f2e824
				{
f2e824
					$error[] = sprintf($user->lang['TOO_MANY_ATTACHMENTS'], $cfg['max_attachments']);
f2e824
				}
f2e824
			}
f2e824
		}
f2e824
f2e824
		foreach ($error as $error_msg)
f2e824
		{
f2e824
			$this->warn_msg[] = $error_msg;
f2e824
		}
f2e824
	}
f2e824
f2e824
	/**
f2e824
	* Get Attachment Data
f2e824
	*/
f2e824
	function get_submitted_attachment_data($check_user_id = false)
f2e824
	{
f2e824
		global $user, $db, $phpbb_root_path, $phpEx, $config;
f2e824
f2e824
		$this->filename_data['filecomment'] = utf8_normalize_nfc(request_var('filecomment', '', true));
f2e824
		$attachment_data = (isset($_POST['attachment_data'])) ? $_POST['attachment_data'] : array();
f2e824
		$this->attachment_data = array();
f2e824
f2e824
		$check_user_id = ($check_user_id === false) ? $user->data['user_id'] : $check_user_id;
f2e824
f2e824
		if (!sizeof($attachment_data))
f2e824
		{
f2e824
			return;
f2e824
		}
f2e824
f2e824
		$not_orphan = $orphan = array();
f2e824
f2e824
		foreach ($attachment_data as $pos => $var_ary)
f2e824
		{
f2e824
			if ($var_ary['is_orphan'])
f2e824
			{
f2e824
				$orphan[(int) $var_ary['attach_id']] = $pos;
f2e824
			}
f2e824
			else
f2e824
			{
f2e824
				$not_orphan[(int) $var_ary['attach_id']] = $pos;
f2e824
			}
f2e824
		}
f2e824
f2e824
		// Regenerate already posted attachments
f2e824
		if (sizeof($not_orphan))
f2e824
		{
f2e824
			// Get the attachment data, based on the poster id...
f2e824
			$sql = 'SELECT attach_id, is_orphan, real_filename, attach_comment
f2e824
				FROM ' . ATTACHMENTS_TABLE . '
f2e824
				WHERE ' . $db->sql_in_set('attach_id', array_keys($not_orphan)) . '
f2e824
					AND poster_id = ' . $check_user_id;
f2e824
			$result = $db->sql_query($sql);
f2e824
f2e824
			while ($row = $db->sql_fetchrow($result))
f2e824
			{
f2e824
				$pos = $not_orphan[$row['attach_id']];
f2e824
				$this->attachment_data[$pos] = $row;
f2e824
				set_var($this->attachment_data[$pos]['attach_comment'], $_POST['attachment_data'][$pos]['attach_comment'], 'string', true);
f2e824
f2e824
				unset($not_orphan[$row['attach_id']]);
f2e824
			}
f2e824
			$db->sql_freeresult($result);
f2e824
		}
f2e824
f2e824
		if (sizeof($not_orphan))
f2e824
		{
f2e824
			trigger_error('NO_ACCESS_ATTACHMENT', E_USER_ERROR);
f2e824
		}
f2e824
f2e824
		// Regenerate newly uploaded attachments
f2e824
		if (sizeof($orphan))
f2e824
		{
f2e824
			$sql = 'SELECT attach_id, is_orphan, real_filename, attach_comment
f2e824
				FROM ' . ATTACHMENTS_TABLE . '
f2e824
				WHERE ' . $db->sql_in_set('attach_id', array_keys($orphan)) . '
f2e824
					AND poster_id = ' . $user->data['user_id'] . '
f2e824
					AND is_orphan = 1';
f2e824
			$result = $db->sql_query($sql);
f2e824
f2e824
			while ($row = $db->sql_fetchrow($result))
f2e824
			{
f2e824
				$pos = $orphan[$row['attach_id']];
f2e824
				$this->attachment_data[$pos] = $row;
f2e824
				set_var($this->attachment_data[$pos]['attach_comment'], $_POST['attachment_data'][$pos]['attach_comment'], 'string', true);
f2e824
f2e824
				unset($orphan[$row['attach_id']]);
f2e824
			}
f2e824
			$db->sql_freeresult($result);
f2e824
		}
f2e824
f2e824
		if (sizeof($orphan))
f2e824
		{
f2e824
			trigger_error('NO_ACCESS_ATTACHMENT', E_USER_ERROR);
f2e824
		}
f2e824
f2e824
		ksort($this->attachment_data);
f2e824
	}
f2e824
f2e824
	/**
f2e824
	* Parse Poll
f2e824
	*/
f2e824
	function parse_poll(&$poll)
f2e824
	{
f2e824
		global $auth, $user, $config;
f2e824
f2e824
		$poll_max_options = $poll['poll_max_options'];
f2e824
f2e824
		// Parse Poll Option text ;)
f2e824
		$tmp_message = $this->message;
f2e824
		$this->message = $poll['poll_option_text'];
f2e824
		$bbcode_bitfield = $this->bbcode_bitfield;
f2e824
f2e824
		$poll['poll_option_text'] = $this->parse($poll['enable_bbcode'], ($config['allow_post_links']) ? $poll['enable_urls'] : false, $poll['enable_smilies'], $poll['img_status'], false, false, $config['allow_post_links'], false);
f2e824
f2e824
		$bbcode_bitfield = base64_encode(base64_decode($bbcode_bitfield) | base64_decode($this->bbcode_bitfield));
f2e824
		$this->message = $tmp_message;
f2e824
f2e824
		// Parse Poll Title
f2e824
		$tmp_message = $this->message;
f2e824
		$this->message = $poll['poll_title'];
f2e824
		$this->bbcode_bitfield = $bbcode_bitfield;
f2e824
f2e824
		$poll['poll_options'] = explode("\n", trim($poll['poll_option_text']));
f2e824
		$poll['poll_options_size'] = sizeof($poll['poll_options']);
f2e824
f2e824
		if (!$poll['poll_title'] && $poll['poll_options_size'])
f2e824
		{
f2e824
			$this->warn_msg[] = $user->lang['NO_POLL_TITLE'];
f2e824
		}
f2e824
		else
f2e824
		{
f2e824
			if (utf8_strlen(preg_replace('#\[\/?[a-z\*\+\-]+(=[\S]+)?\]#ius', ' ', $this->message)) > 100)
f2e824
			{
f2e824
				$this->warn_msg[] = $user->lang['POLL_TITLE_TOO_LONG'];
f2e824
			}
f2e824
			$poll['poll_title'] = $this->parse($poll['enable_bbcode'], ($config['allow_post_links']) ? $poll['enable_urls'] : false, $poll['enable_smilies'], $poll['img_status'], false, false, $config['allow_post_links'], false);
f2e824
			if (strlen($poll['poll_title']) > 255)
f2e824
			{
f2e824
				$this->warn_msg[] = $user->lang['POLL_TITLE_COMP_TOO_LONG'];
f2e824
			}
f2e824
		}
f2e824
f2e824
		$this->bbcode_bitfield = base64_encode(base64_decode($bbcode_bitfield) | base64_decode($this->bbcode_bitfield));
f2e824
		$this->message = $tmp_message;
f2e824
		unset($tmp_message);
f2e824
f2e824
		if (sizeof($poll['poll_options']) == 1)
f2e824
		{
f2e824
			$this->warn_msg[] = $user->lang['TOO_FEW_POLL_OPTIONS'];
f2e824
		}
f2e824
		else if ($poll['poll_options_size'] > (int) $config['max_poll_options'])
f2e824
		{
f2e824
			$this->warn_msg[] = $user->lang['TOO_MANY_POLL_OPTIONS'];
f2e824
		}
f2e824
		else if ($poll_max_options > $poll['poll_options_size'])
f2e824
		{
f2e824
			$this->warn_msg[] = $user->lang['TOO_MANY_USER_OPTIONS'];
f2e824
		}
f2e824
f2e824
		$poll['poll_max_options'] = ($poll['poll_max_options'] < 1) ? 1 : (($poll['poll_max_options'] > $config['max_poll_options']) ? $config['max_poll_options'] : $poll['poll_max_options']);
f2e824
	}
f2e824
}
f2e824
f2e824
?>