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

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