includes/message_parser.php
changeset 0 ceef6d64c21d
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/includes/message_parser.php	Wed Mar 07 16:41:10 2012 +0400
     1.3 @@ -0,0 +1,1702 @@
     1.4 +<?php
     1.5 +/**
     1.6 +*
     1.7 +* @package phpBB3
     1.8 +* @version $Id$
     1.9 +* @copyright (c) 2005 phpBB Group
    1.10 +* @license http://opensource.org/licenses/gpl-license.php GNU Public License
    1.11 +*
    1.12 +*/
    1.13 +
    1.14 +/**
    1.15 +* @ignore
    1.16 +*/
    1.17 +if (!defined('IN_PHPBB'))
    1.18 +{
    1.19 +	exit;
    1.20 +}
    1.21 +
    1.22 +if (!class_exists('bbcode'))
    1.23 +{
    1.24 +	include($phpbb_root_path . 'includes/bbcode.' . $phpEx);
    1.25 +}
    1.26 +
    1.27 +/**
    1.28 +* BBCODE FIRSTPASS
    1.29 +* BBCODE first pass class (functions for parsing messages for db storage)
    1.30 +* @package phpBB3
    1.31 +*/
    1.32 +class bbcode_firstpass extends bbcode
    1.33 +{
    1.34 +	var $message = '';
    1.35 +	var $warn_msg = array();
    1.36 +	var $parsed_items = array();
    1.37 +
    1.38 +	/**
    1.39 +	* Parse BBCode
    1.40 +	*/
    1.41 +	function parse_bbcode()
    1.42 +	{
    1.43 +		if (!$this->bbcodes)
    1.44 +		{
    1.45 +			$this->bbcode_init();
    1.46 +		}
    1.47 +
    1.48 +		global $user;
    1.49 +
    1.50 +		$this->bbcode_bitfield = '';
    1.51 +		$bitfield = new bitfield();
    1.52 +
    1.53 +		foreach ($this->bbcodes as $bbcode_name => $bbcode_data)
    1.54 +		{
    1.55 +			if (isset($bbcode_data['disabled']) && $bbcode_data['disabled'])
    1.56 +			{
    1.57 +				foreach ($bbcode_data['regexp'] as $regexp => $replacement)
    1.58 +				{
    1.59 +					if (preg_match($regexp, $this->message))
    1.60 +					{
    1.61 +						$this->warn_msg[] = sprintf($user->lang['UNAUTHORISED_BBCODE'] , '[' . $bbcode_name . ']');
    1.62 +						continue;
    1.63 +					}
    1.64 +				}
    1.65 +			}
    1.66 +			else
    1.67 +			{
    1.68 +				foreach ($bbcode_data['regexp'] as $regexp => $replacement)
    1.69 +				{
    1.70 +					// The pattern gets compiled and cached by the PCRE extension,
    1.71 +					// it should not demand recompilation
    1.72 +					if (preg_match($regexp, $this->message))
    1.73 +					{
    1.74 +						$this->message = preg_replace($regexp, $replacement, $this->message);
    1.75 +						$bitfield->set($bbcode_data['bbcode_id']);
    1.76 +					}
    1.77 +				}
    1.78 +			}
    1.79 +		}
    1.80 +
    1.81 +		$this->bbcode_bitfield = $bitfield->get_base64();
    1.82 +	}
    1.83 +
    1.84 +	/**
    1.85 +	* Prepare some bbcodes for better parsing
    1.86 +	*/
    1.87 +	function prepare_bbcodes()
    1.88 +	{
    1.89 +		// 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".
    1.90 +		// Fine by me ;) Will ease our live... but do not come back and cry at us, we won't hear you.
    1.91 +
    1.92 +		/* Add newline at the end and in front of each quote block to prevent parsing errors (urls, smilies, etc.)
    1.93 +		if (strpos($this->message, '[quote') !== false && strpos($this->message, '[/quote]') !== false)
    1.94 +		{
    1.95 +			$this->message = str_replace("\r\n", "\n", $this->message);
    1.96 +
    1.97 +			// We strip newlines and spaces after and before quotes in quotes (trimming) and then add exactly one newline
    1.98 +			$this->message = preg_replace('#\[quote(=&quot;.*?&quot;)?\]\s*(.*?)\s*\[/quote\]#siu', '[quote\1]' . "\n" . '\2' ."\n[/quote]", $this->message);
    1.99 +		}
   1.100 +		*/
   1.101 +
   1.102 +		// Add other checks which needs to be placed before actually parsing anything (be it bbcodes, smilies, urls...)
   1.103 +	}
   1.104 +
   1.105 +	/**
   1.106 +	* Init bbcode data for later parsing
   1.107 +	*/
   1.108 +	function bbcode_init($allow_custom_bbcode = true)
   1.109 +	{
   1.110 +		static $rowset;
   1.111 +
   1.112 +		// This array holds all bbcode data. BBCodes will be processed in this
   1.113 +		// order, so it is important to keep [code] in first position and
   1.114 +		// [quote] in second position.
   1.115 +		// To parse multiline URL we enable dotall option setting only for URL text
   1.116 +		// but not for link itself, thus [url][/url] is not affected.
   1.117 +		$this->bbcodes = array(
   1.118 +			'code'			=> array('bbcode_id' => 8,	'regexp' => array('#\[code(?:=([a-z]+))?\](.+\[/code\])#uise' => "\$this->bbcode_code('\$1', '\$2')")),
   1.119 +			'quote'			=> array('bbcode_id' => 0,	'regexp' => array('#\[quote(?:=&quot;(.*?)&quot;)?\](.+)\[/quote\]#uise' => "\$this->bbcode_quote('\$0')")),
   1.120 +			'attachment'	=> array('bbcode_id' => 12,	'regexp' => array('#\[attachment=([0-9]+)\](.*?)\[/attachment\]#uise' => "\$this->bbcode_attachment('\$1', '\$2')")),
   1.121 +			'b'				=> array('bbcode_id' => 1,	'regexp' => array('#\[b\](.*?)\[/b\]#uise' => "\$this->bbcode_strong('\$1')")),
   1.122 +			'i'				=> array('bbcode_id' => 2,	'regexp' => array('#\[i\](.*?)\[/i\]#uise' => "\$this->bbcode_italic('\$1')")),
   1.123 +			'url'			=> array('bbcode_id' => 3,	'regexp' => array('#\[url(=(.*))?\](?(1)((?s).*(?-s))|(.*))\[/url\]#uiUe' => "\$this->validate_url('\$2', ('\$3') ? '\$3' : '\$4')")),
   1.124 +			'img'			=> array('bbcode_id' => 4,	'regexp' => array('#\[img\](.*)\[/img\]#uiUe' => "\$this->bbcode_img('\$1')")),
   1.125 +			'size'			=> array('bbcode_id' => 5,	'regexp' => array('#\[size=([\-\+]?\d+)\](.*?)\[/size\]#uise' => "\$this->bbcode_size('\$1', '\$2')")),
   1.126 +			'color'			=> array('bbcode_id' => 6,	'regexp' => array('!\[color=(#[0-9a-f]{3}|#[0-9a-f]{6}|[a-z\-]+)\](.*?)\[/color\]!uise' => "\$this->bbcode_color('\$1', '\$2')")),
   1.127 +			'u'				=> array('bbcode_id' => 7,	'regexp' => array('#\[u\](.*?)\[/u\]#uise' => "\$this->bbcode_underline('\$1')")),
   1.128 +			'list'			=> array('bbcode_id' => 9,	'regexp' => array('#\[list(?:=(?:[a-z0-9]|disc|circle|square))?].*\[/list]#uise' => "\$this->bbcode_parse_list('\$0')")),
   1.129 +			'email'			=> array('bbcode_id' => 10,	'regexp' => array('#\[email=?(.*?)?\](.*?)\[/email\]#uise' => "\$this->validate_email('\$1', '\$2')")),
   1.130 +			'flash'			=> array('bbcode_id' => 11,	'regexp' => array('#\[flash=([0-9]+),([0-9]+)\](.*?)\[/flash\]#uie' => "\$this->bbcode_flash('\$1', '\$2', '\$3')"))
   1.131 +		);
   1.132 +
   1.133 +		// Zero the parsed items array
   1.134 +		$this->parsed_items = array();
   1.135 +
   1.136 +		foreach ($this->bbcodes as $tag => $bbcode_data)
   1.137 +		{
   1.138 +			$this->parsed_items[$tag] = 0;
   1.139 +		}
   1.140 +
   1.141 +		if (!$allow_custom_bbcode)
   1.142 +		{
   1.143 +			return;
   1.144 +		}
   1.145 +
   1.146 +		if (!is_array($rowset))
   1.147 +		{
   1.148 +			global $db;
   1.149 +			$rowset = array();
   1.150 +
   1.151 +			$sql = 'SELECT *
   1.152 +				FROM ' . BBCODES_TABLE;
   1.153 +			$result = $db->sql_query($sql);
   1.154 +
   1.155 +			while ($row = $db->sql_fetchrow($result))
   1.156 +			{
   1.157 +				$rowset[] = $row;
   1.158 +			}
   1.159 +			$db->sql_freeresult($result);
   1.160 +		}
   1.161 +
   1.162 +		foreach ($rowset as $row)
   1.163 +		{
   1.164 +			$this->bbcodes[$row['bbcode_tag']] = array(
   1.165 +				'bbcode_id'	=> (int) $row['bbcode_id'],
   1.166 +				'regexp'	=> array($row['first_pass_match'] => str_replace('$uid', $this->bbcode_uid, $row['first_pass_replace']))
   1.167 +			);
   1.168 +		}
   1.169 +	}
   1.170 +
   1.171 +	/**
   1.172 +	* Making some pre-checks for bbcodes as well as increasing the number of parsed items
   1.173 +	*/
   1.174 +	function check_bbcode($bbcode, &$in)
   1.175 +	{
   1.176 +		// when using the /e modifier, preg_replace slashes double-quotes but does not
   1.177 +		// seem to slash anything else
   1.178 +		$in = str_replace("\r\n", "\n", str_replace('\"', '"', $in));
   1.179 +
   1.180 +		// Trimming here to make sure no empty bbcodes are parsed accidently
   1.181 +		if (trim($in) == '')
   1.182 +		{
   1.183 +			return false;
   1.184 +		}
   1.185 +
   1.186 +		$this->parsed_items[$bbcode]++;
   1.187 +
   1.188 +		return true;
   1.189 +	}
   1.190 +
   1.191 +	/**
   1.192 +	* Transform some characters in valid bbcodes
   1.193 +	*/
   1.194 +	function bbcode_specialchars($text)
   1.195 +	{
   1.196 +		$str_from = array('<', '>', '[', ']', '.', ':');
   1.197 +		$str_to = array('&lt;', '&gt;', '&#91;', '&#93;', '&#46;', '&#58;');
   1.198 +
   1.199 +		return str_replace($str_from, $str_to, $text);
   1.200 +	}
   1.201 +
   1.202 +	/**
   1.203 +	* Parse size tag
   1.204 +	*/
   1.205 +	function bbcode_size($stx, $in)
   1.206 +	{
   1.207 +		global $user, $config;
   1.208 +
   1.209 +		if (!$this->check_bbcode('size', $in))
   1.210 +		{
   1.211 +			return $in;
   1.212 +		}
   1.213 +
   1.214 +		if ($config['max_' . $this->mode . '_font_size'] && $config['max_' . $this->mode . '_font_size'] < $stx)
   1.215 +		{
   1.216 +			$this->warn_msg[] = sprintf($user->lang['MAX_FONT_SIZE_EXCEEDED'], $config['max_' . $this->mode . '_font_size']);
   1.217 +
   1.218 +			return '[size=' . $stx . ']' . $in . '[/size]';
   1.219 +		}
   1.220 +
   1.221 +		// Do not allow size=0
   1.222 +		if ($stx <= 0)
   1.223 +		{
   1.224 +			return '[size=' . $stx . ']' . $in . '[/size]';
   1.225 +		}
   1.226 +
   1.227 +		return '[size=' . $stx . ':' . $this->bbcode_uid . ']' . $in . '[/size:' . $this->bbcode_uid . ']';
   1.228 +	}
   1.229 +
   1.230 +	/**
   1.231 +	* Parse color tag
   1.232 +	*/
   1.233 +	function bbcode_color($stx, $in)
   1.234 +	{
   1.235 +		if (!$this->check_bbcode('color', $in))
   1.236 +		{
   1.237 +			return $in;
   1.238 +		}
   1.239 +
   1.240 +		return '[color=' . $stx . ':' . $this->bbcode_uid . ']' . $in . '[/color:' . $this->bbcode_uid . ']';
   1.241 +	}
   1.242 +
   1.243 +	/**
   1.244 +	* Parse u tag
   1.245 +	*/
   1.246 +	function bbcode_underline($in)
   1.247 +	{
   1.248 +		if (!$this->check_bbcode('u', $in))
   1.249 +		{
   1.250 +			return $in;
   1.251 +		}
   1.252 +
   1.253 +		return '[u:' . $this->bbcode_uid . ']' . $in . '[/u:' . $this->bbcode_uid . ']';
   1.254 +	}
   1.255 +
   1.256 +	/**
   1.257 +	* Parse b tag
   1.258 +	*/
   1.259 +	function bbcode_strong($in)
   1.260 +	{
   1.261 +		if (!$this->check_bbcode('b', $in))
   1.262 +		{
   1.263 +			return $in;
   1.264 +		}
   1.265 +
   1.266 +		return '[b:' . $this->bbcode_uid . ']' . $in . '[/b:' . $this->bbcode_uid . ']';
   1.267 +	}
   1.268 +
   1.269 +	/**
   1.270 +	* Parse i tag
   1.271 +	*/
   1.272 +	function bbcode_italic($in)
   1.273 +	{
   1.274 +		if (!$this->check_bbcode('i', $in))
   1.275 +		{
   1.276 +			return $in;
   1.277 +		}
   1.278 +
   1.279 +		return '[i:' . $this->bbcode_uid . ']' . $in . '[/i:' . $this->bbcode_uid . ']';
   1.280 +	}
   1.281 +
   1.282 +	/**
   1.283 +	* Parse img tag
   1.284 +	*/
   1.285 +	function bbcode_img($in)
   1.286 +	{
   1.287 +		global $user, $config;
   1.288 +
   1.289 +		if (!$this->check_bbcode('img', $in))
   1.290 +		{
   1.291 +			return $in;
   1.292 +		}
   1.293 +
   1.294 +		$in = trim($in);
   1.295 +		$error = false;
   1.296 +
   1.297 +		$in = str_replace(' ', '%20', $in);
   1.298 +
   1.299 +		// Checking urls
   1.300 +		if (!preg_match('#^' . get_preg_expression('url') . '$#i', $in) && !preg_match('#^' . get_preg_expression('www_url') . '$#i', $in))
   1.301 +		{
   1.302 +			return '[img]' . $in . '[/img]';
   1.303 +		}
   1.304 +
   1.305 +		// Try to cope with a common user error... not specifying a protocol but only a subdomain
   1.306 +		if (!preg_match('#^[a-z0-9]+://#i', $in))
   1.307 +		{
   1.308 +			$in = 'http://' . $in;
   1.309 +		}
   1.310 +
   1.311 +		if ($config['max_' . $this->mode . '_img_height'] || $config['max_' . $this->mode . '_img_width'])
   1.312 +		{
   1.313 +			$stats = @getimagesize(htmlspecialchars_decode($in));
   1.314 +
   1.315 +			if ($stats === false)
   1.316 +			{
   1.317 +				$error = true;
   1.318 +				$this->warn_msg[] = $user->lang['UNABLE_GET_IMAGE_SIZE'];
   1.319 +			}
   1.320 +			else
   1.321 +			{
   1.322 +				if ($config['max_' . $this->mode . '_img_height'] && $config['max_' . $this->mode . '_img_height'] < $stats[1])
   1.323 +				{
   1.324 +					$error = true;
   1.325 +					$this->warn_msg[] = sprintf($user->lang['MAX_IMG_HEIGHT_EXCEEDED'], $config['max_' . $this->mode . '_img_height']);
   1.326 +				}
   1.327 +
   1.328 +				if ($config['max_' . $this->mode . '_img_width'] && $config['max_' . $this->mode . '_img_width'] < $stats[0])
   1.329 +				{
   1.330 +					$error = true;
   1.331 +					$this->warn_msg[] = sprintf($user->lang['MAX_IMG_WIDTH_EXCEEDED'], $config['max_' . $this->mode . '_img_width']);
   1.332 +				}
   1.333 +			}
   1.334 +		}
   1.335 +
   1.336 +		if ($error || $this->path_in_domain($in))
   1.337 +		{
   1.338 +			return '[img]' . $in . '[/img]';
   1.339 +		}
   1.340 +
   1.341 +		return '[img:' . $this->bbcode_uid . ']' . $this->bbcode_specialchars($in) . '[/img:' . $this->bbcode_uid . ']';
   1.342 +	}
   1.343 +
   1.344 +	/**
   1.345 +	* Parse flash tag
   1.346 +	*/
   1.347 +	function bbcode_flash($width, $height, $in)
   1.348 +	{
   1.349 +		global $user, $config;
   1.350 +
   1.351 +		if (!$this->check_bbcode('flash', $in))
   1.352 +		{
   1.353 +			return $in;
   1.354 +		}
   1.355 +
   1.356 +		$in = trim($in);
   1.357 +		$error = false;
   1.358 +
   1.359 +		// Do not allow 0-sizes generally being entered
   1.360 +		if ($width <= 0 || $height <= 0)
   1.361 +		{
   1.362 +			return '[flash=' . $width . ',' . $height . ']' . $in . '[/flash]';
   1.363 +		}
   1.364 +
   1.365 +		$in = str_replace(' ', '%20', $in);
   1.366 +
   1.367 +		// Make sure $in is a URL.
   1.368 +		if (!preg_match('#^' . get_preg_expression('url') . '$#i', $in) &&
   1.369 +			!preg_match('#^' . get_preg_expression('www_url') . '$#i', $in))
   1.370 +		{
   1.371 +			return '[flash=' . $width . ',' . $height . ']' . $in . '[/flash]';
   1.372 +		}
   1.373 +
   1.374 +		// Apply the same size checks on flash files as on images
   1.375 +		if ($config['max_' . $this->mode . '_img_height'] || $config['max_' . $this->mode . '_img_width'])
   1.376 +		{
   1.377 +			if ($config['max_' . $this->mode . '_img_height'] && $config['max_' . $this->mode . '_img_height'] < $height)
   1.378 +			{
   1.379 +				$error = true;
   1.380 +				$this->warn_msg[] = sprintf($user->lang['MAX_FLASH_HEIGHT_EXCEEDED'], $config['max_' . $this->mode . '_img_height']);
   1.381 +			}
   1.382 +
   1.383 +			if ($config['max_' . $this->mode . '_img_width'] && $config['max_' . $this->mode . '_img_width'] < $width)
   1.384 +			{
   1.385 +				$error = true;
   1.386 +				$this->warn_msg[] = sprintf($user->lang['MAX_FLASH_WIDTH_EXCEEDED'], $config['max_' . $this->mode . '_img_width']);
   1.387 +			}
   1.388 +		}
   1.389 +
   1.390 +		if ($error || $this->path_in_domain($in))
   1.391 +		{
   1.392 +			return '[flash=' . $width . ',' . $height . ']' . $in . '[/flash]';
   1.393 +		}
   1.394 +
   1.395 +		return '[flash=' . $width . ',' . $height . ':' . $this->bbcode_uid . ']' . $this->bbcode_specialchars($in) . '[/flash:' . $this->bbcode_uid . ']';
   1.396 +	}
   1.397 +
   1.398 +	/**
   1.399 +	* Parse inline attachments [ia]
   1.400 +	*/
   1.401 +	function bbcode_attachment($stx, $in)
   1.402 +	{
   1.403 +		if (!$this->check_bbcode('attachment', $in))
   1.404 +		{
   1.405 +			return $in;
   1.406 +		}
   1.407 +
   1.408 +		return '[attachment=' . $stx . ':' . $this->bbcode_uid . ']<!-- ia' . $stx . ' -->' . trim($in) . '<!-- ia' . $stx . ' -->[/attachment:' . $this->bbcode_uid . ']';
   1.409 +	}
   1.410 +
   1.411 +	/**
   1.412 +	* Parse code text from code tag
   1.413 +	* @access private
   1.414 +	*/
   1.415 +	function bbcode_parse_code($stx, &$code)
   1.416 +	{
   1.417 +		switch (strtolower($stx))
   1.418 +		{
   1.419 +			case 'php':
   1.420 +
   1.421 +				$remove_tags = false;
   1.422 +
   1.423 +				$str_from = array('&lt;', '&gt;', '&#91;', '&#93;', '&#46;', '&#58;', '&#058;');
   1.424 +				$str_to = array('<', '>', '[', ']', '.', ':', ':');
   1.425 +				$code = str_replace($str_from, $str_to, $code);
   1.426 +
   1.427 +				if (!preg_match('/\<\?.*?\?\>/is', $code))
   1.428 +				{
   1.429 +					$remove_tags = true;
   1.430 +					$code = "<?php $code ?>";
   1.431 +				}
   1.432 +
   1.433 +				$conf = array('highlight.bg', 'highlight.comment', 'highlight.default', 'highlight.html', 'highlight.keyword', 'highlight.string');
   1.434 +				foreach ($conf as $ini_var)
   1.435 +				{
   1.436 +					@ini_set($ini_var, str_replace('highlight.', 'syntax', $ini_var));
   1.437 +				}
   1.438 +
   1.439 +				// Because highlight_string is specialcharing the text (but we already did this before), we have to reverse this in order to get correct results
   1.440 +				$code = htmlspecialchars_decode($code);
   1.441 +				$code = highlight_string($code, true);
   1.442 +
   1.443 +				$str_from = array('<span style="color: ', '<font color="syntax', '</font>', '<code>', '</code>','[', ']', '.', ':');
   1.444 +				$str_to = array('<span class="', '<span class="syntax', '</span>', '', '', '&#91;', '&#93;', '&#46;', '&#58;');
   1.445 +
   1.446 +				if ($remove_tags)
   1.447 +				{
   1.448 +					$str_from[] = '<span class="syntaxdefault">&lt;?php </span>';
   1.449 +					$str_to[] = '';
   1.450 +					$str_from[] = '<span class="syntaxdefault">&lt;?php&nbsp;';
   1.451 +					$str_to[] = '<span class="syntaxdefault">';
   1.452 +				}
   1.453 +
   1.454 +				$code = str_replace($str_from, $str_to, $code);
   1.455 +				$code = preg_replace('#^(<span class="[a-z_]+">)\n?(.*?)\n?(</span>)$#is', '$1$2$3', $code);
   1.456 +
   1.457 +				if ($remove_tags)
   1.458 +				{
   1.459 +					$code = preg_replace('#(<span class="[a-z]+">)?\?&gt;(</span>)#', '$1&nbsp;$2', $code);
   1.460 +				}
   1.461 +
   1.462 +				$code = preg_replace('#^<span class="[a-z]+"><span class="([a-z]+)">(.*)</span></span>#s', '<span class="$1">$2</span>', $code);
   1.463 +				$code = preg_replace('#(?:\s++|&nbsp;)*+</span>$#u', '</span>', $code);
   1.464 +
   1.465 +				// remove newline at the end
   1.466 +				if (!empty($code) && substr($code, -1) == "\n")
   1.467 +				{
   1.468 +					$code = substr($code, 0, -1);
   1.469 +				}
   1.470 +
   1.471 +				return "[code=$stx:" . $this->bbcode_uid . ']' . $code . '[/code:' . $this->bbcode_uid . ']';
   1.472 +			break;
   1.473 +
   1.474 +			default:
   1.475 +				return '[code:' . $this->bbcode_uid . ']' . $this->bbcode_specialchars($code) . '[/code:' . $this->bbcode_uid . ']';
   1.476 +			break;
   1.477 +		}
   1.478 +	}
   1.479 +
   1.480 +	/**
   1.481 +	* Parse code tag
   1.482 +	* Expects the argument to start right after the opening [code] tag and to end with [/code]
   1.483 +	*/
   1.484 +	function bbcode_code($stx, $in)
   1.485 +	{
   1.486 +		if (!$this->check_bbcode('code', $in))
   1.487 +		{
   1.488 +			return $in;
   1.489 +		}
   1.490 +
   1.491 +		// We remove the hardcoded elements from the code block here because it is not used in code blocks
   1.492 +		// Having it here saves us one preg_replace per message containing [code] blocks
   1.493 +		// Additionally, magic url parsing should go after parsing bbcodes, but for safety those are stripped out too...
   1.494 +		$htm_match = get_preg_expression('bbcode_htm');
   1.495 +		unset($htm_match[4], $htm_match[5]);
   1.496 +		$htm_replace = array('\1', '\1', '\2', '\1');
   1.497 +
   1.498 +		$out = $code_block = '';
   1.499 +		$open = 1;
   1.500 +
   1.501 +		while ($in)
   1.502 +		{
   1.503 +			// Determine position and tag length of next code block
   1.504 +			preg_match('#(.*?)(\[code(?:=([a-z]+))?\])(.+)#is', $in, $buffer);
   1.505 +			$pos = (isset($buffer[1])) ? strlen($buffer[1]) : false;
   1.506 +			$tag_length = (isset($buffer[2])) ? strlen($buffer[2]) : false;
   1.507 +
   1.508 +			// Determine position of ending code tag
   1.509 +			$pos2 = stripos($in, '[/code]');
   1.510 +
   1.511 +			// Which is the next block, ending code or code block
   1.512 +			if ($pos !== false && $pos < $pos2)
   1.513 +			{
   1.514 +				// Open new block
   1.515 +				if (!$open)
   1.516 +				{
   1.517 +					$out .= substr($in, 0, $pos);
   1.518 +					$in = substr($in, $pos);
   1.519 +					$stx = (isset($buffer[3])) ? $buffer[3] : '';
   1.520 +					$code_block = '';
   1.521 +				}
   1.522 +				else
   1.523 +				{
   1.524 +					// Already opened block, just append to the current block
   1.525 +					$code_block .= substr($in, 0, $pos) . ((isset($buffer[2])) ? $buffer[2] : '');
   1.526 +					$in = substr($in, $pos);
   1.527 +				}
   1.528 +
   1.529 +				$in = substr($in, $tag_length);
   1.530 +				$open++;
   1.531 +			}
   1.532 +			else
   1.533 +			{
   1.534 +				// Close the block
   1.535 +				if ($open == 1)
   1.536 +				{
   1.537 +					$code_block .= substr($in, 0, $pos2);
   1.538 +					$code_block = preg_replace($htm_match, $htm_replace, $code_block);
   1.539 +
   1.540 +					// Parse this code block
   1.541 +					$out .= $this->bbcode_parse_code($stx, $code_block);
   1.542 +					$code_block = '';
   1.543 +					$open--;
   1.544 +				}
   1.545 +				else if ($open)
   1.546 +				{
   1.547 +					// Close one open tag... add to the current code block
   1.548 +					$code_block .= substr($in, 0, $pos2 + 7);
   1.549 +					$open--;
   1.550 +				}
   1.551 +				else
   1.552 +				{
   1.553 +					// end code without opening code... will be always outside code block
   1.554 +					$out .= substr($in, 0, $pos2 + 7);
   1.555 +				}
   1.556 +
   1.557 +				$in = substr($in, $pos2 + 7);
   1.558 +			}
   1.559 +		}
   1.560 +
   1.561 +		// if now $code_block has contents we need to parse the remaining code while removing the last closing tag to match up.
   1.562 +		if ($code_block)
   1.563 +		{
   1.564 +			$code_block = substr($code_block, 0, -7);
   1.565 +			$code_block = preg_replace($htm_match, $htm_replace, $code_block);
   1.566 +
   1.567 +			$out .= $this->bbcode_parse_code($stx, $code_block);
   1.568 +		}
   1.569 +
   1.570 +		return $out;
   1.571 +	}
   1.572 +
   1.573 +	/**
   1.574 +	* Parse list bbcode
   1.575 +	* Expects the argument to start with a tag
   1.576 +	*/
   1.577 +	function bbcode_parse_list($in)
   1.578 +	{
   1.579 +		if (!$this->check_bbcode('list', $in))
   1.580 +		{
   1.581 +			return $in;
   1.582 +		}
   1.583 +
   1.584 +		// $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
   1.585 +		$tok = ']';
   1.586 +		$out = '[';
   1.587 +
   1.588 +		// First character is [
   1.589 +		$in = substr($in, 1);
   1.590 +		$list_end_tags = $item_end_tags = array();
   1.591 +
   1.592 +		do
   1.593 +		{
   1.594 +			$pos = strlen($in);
   1.595 +
   1.596 +			for ($i = 0, $tok_len = strlen($tok); $i < $tok_len; ++$i)
   1.597 +			{
   1.598 +				$tmp_pos = strpos($in, $tok[$i]);
   1.599 +
   1.600 +				if ($tmp_pos !== false && $tmp_pos < $pos)
   1.601 +				{
   1.602 +					$pos = $tmp_pos;
   1.603 +				}
   1.604 +			}
   1.605 +
   1.606 +			$buffer = substr($in, 0, $pos);
   1.607 +			$tok = $in[$pos];
   1.608 +
   1.609 +			$in = substr($in, $pos + 1);
   1.610 +
   1.611 +			if ($tok == ']')
   1.612 +			{
   1.613 +				// if $tok is ']' the buffer holds a tag
   1.614 +				if (strtolower($buffer) == '/list' && sizeof($list_end_tags))
   1.615 +				{
   1.616 +					// valid [/list] tag, check nesting so that we don't hit false positives
   1.617 +					if (sizeof($item_end_tags) && sizeof($item_end_tags) >= sizeof($list_end_tags))
   1.618 +					{
   1.619 +						// current li tag has not been closed
   1.620 +						$out = preg_replace('/\n?\[$/', '[', $out) . array_pop($item_end_tags) . '][';
   1.621 +					}
   1.622 +
   1.623 +					$out .= array_pop($list_end_tags) . ']';
   1.624 +					$tok = '[';
   1.625 +				}
   1.626 +				else if (preg_match('#^list(=[0-9a-z]+)?$#i', $buffer, $m))
   1.627 +				{
   1.628 +					// sub-list, add a closing tag
   1.629 +					if (empty($m[1]) || preg_match('/^=(?:disc|square|circle)$/i', $m[1]))
   1.630 +					{
   1.631 +						array_push($list_end_tags, '/list:u:' . $this->bbcode_uid);
   1.632 +					}
   1.633 +					else
   1.634 +					{
   1.635 +						array_push($list_end_tags, '/list:o:' . $this->bbcode_uid);
   1.636 +					}
   1.637 +					$out .= 'list' . substr($buffer, 4) . ':' . $this->bbcode_uid . ']';
   1.638 +					$tok = '[';
   1.639 +				}
   1.640 +				else
   1.641 +				{
   1.642 +					if (($buffer == '*' || substr($buffer, -2) == '[*') && sizeof($list_end_tags))
   1.643 +					{
   1.644 +						// the buffer holds a bullet tag and we have a [list] tag open
   1.645 +						if (sizeof($item_end_tags) >= sizeof($list_end_tags))
   1.646 +						{
   1.647 +							if (substr($buffer, -2) == '[*')
   1.648 +							{
   1.649 +								$out .= substr($buffer, 0, -2) . '[';
   1.650 +							}
   1.651 +							// current li tag has not been closed
   1.652 +							if (preg_match('/\n\[$/', $out, $m))
   1.653 +							{
   1.654 +								$out = preg_replace('/\n\[$/', '[', $out);
   1.655 +								$buffer = array_pop($item_end_tags) . "]\n[*:" . $this->bbcode_uid;
   1.656 +							}
   1.657 +							else
   1.658 +							{
   1.659 +								$buffer = array_pop($item_end_tags) . '][*:' . $this->bbcode_uid;
   1.660 +							}
   1.661 +						}
   1.662 +						else
   1.663 +						{
   1.664 +							$buffer = '*:' . $this->bbcode_uid;
   1.665 +						}
   1.666 +
   1.667 +						$item_end_tags[] = '/*:m:' . $this->bbcode_uid;
   1.668 +					}
   1.669 +					else if ($buffer == '/*')
   1.670 +					{
   1.671 +						array_pop($item_end_tags);
   1.672 +						$buffer = '/*:' . $this->bbcode_uid;
   1.673 +					}
   1.674 +
   1.675 +					$out .= $buffer . $tok;
   1.676 +					$tok = '[]';
   1.677 +				}
   1.678 +			}
   1.679 +			else
   1.680 +			{
   1.681 +				// Not within a tag, just add buffer to the return string
   1.682 +				$out .= $buffer . $tok;
   1.683 +				$tok = ($tok == '[') ? ']' : '[]';
   1.684 +			}
   1.685 +		}
   1.686 +		while ($in);
   1.687 +
   1.688 +		// do we have some tags open? close them now
   1.689 +		if (sizeof($item_end_tags))
   1.690 +		{
   1.691 +			$out .= '[' . implode('][', $item_end_tags) . ']';
   1.692 +		}
   1.693 +		if (sizeof($list_end_tags))
   1.694 +		{
   1.695 +			$out .= '[' . implode('][', $list_end_tags) . ']';
   1.696 +		}
   1.697 +
   1.698 +		return $out;
   1.699 +	}
   1.700 +
   1.701 +	/**
   1.702 +	* Parse quote bbcode
   1.703 +	* Expects the argument to start with a tag
   1.704 +	*/
   1.705 +	function bbcode_quote($in)
   1.706 +	{
   1.707 +		global $config, $user;
   1.708 +
   1.709 +		/**
   1.710 +		* If you change this code, make sure the cases described within the following reports are still working:
   1.711 +		* #3572 - [quote="[test]test"]test [ test[/quote] - (correct: parsed)
   1.712 +		* #14667 - [quote]test[/quote] test ] and [ test [quote]test[/quote] (correct: parsed)
   1.713 +		* #14770 - [quote="["]test[/quote] (correct: parsed)
   1.714 +		* [quote="[i]test[/i]"]test[/quote] (correct: parsed)
   1.715 +		* [quote="[quote]test[/quote]"]test[/quote] (correct: parsed - Username displayed as [quote]test[/quote])
   1.716 +		* #20735 - [quote]test[/[/b]quote] test [/quote][/quote] test - (correct: quoted: "test[/[/b]quote] test" / non-quoted: "[/quote] test" - also failed if layout distorted)
   1.717 +		* #40565 - [quote="a"]a[/quote][quote="a]a[/quote] (correct: first quote tag parsed, second quote tag unparsed)
   1.718 +		*/
   1.719 +
   1.720 +		$in = str_replace("\r\n", "\n", str_replace('\"', '"', trim($in)));
   1.721 +
   1.722 +		if (!$in)
   1.723 +		{
   1.724 +			return '';
   1.725 +		}
   1.726 +
   1.727 +		// To let the parser not catch tokens within quote_username quotes we encode them before we start this...
   1.728 +		$in = preg_replace('#quote=&quot;(.*?)&quot;\]#ie', "'quote=&quot;' . str_replace(array('[', ']', '\\\"'), array('&#91;', '&#93;', '\"'), '\$1') . '&quot;]'", $in);
   1.729 +
   1.730 +		$tok = ']';
   1.731 +		$out = '[';
   1.732 +
   1.733 +		$in = substr($in, 1);
   1.734 +		$close_tags = $error_ary = array();
   1.735 +		$buffer = '';
   1.736 +
   1.737 +		do
   1.738 +		{
   1.739 +			$pos = strlen($in);
   1.740 +			for ($i = 0, $tok_len = strlen($tok); $i < $tok_len; ++$i)
   1.741 +			{
   1.742 +				$tmp_pos = strpos($in, $tok[$i]);
   1.743 +				if ($tmp_pos !== false && $tmp_pos < $pos)
   1.744 +				{
   1.745 +					$pos = $tmp_pos;
   1.746 +				}
   1.747 +			}
   1.748 +
   1.749 +			$buffer .= substr($in, 0, $pos);
   1.750 +			$tok = $in[$pos];
   1.751 +			$in = substr($in, $pos + 1);
   1.752 +
   1.753 +			if ($tok == ']')
   1.754 +			{
   1.755 +				if (strtolower($buffer) == '/quote' && sizeof($close_tags) && substr($out, -1, 1) == '[')
   1.756 +				{
   1.757 +					// we have found a closing tag
   1.758 +					$out .= array_pop($close_tags) . ']';
   1.759 +					$tok = '[';
   1.760 +					$buffer = '';
   1.761 +
   1.762 +					/* Add space at the end of the closing tag if not happened before to allow following urls/smilies to be parsed correctly
   1.763 +					* 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.
   1.764 +					* Also, we won't have any spaces within $in anyway, only adding up spaces -> #10982
   1.765 +					if (!$in || $in[0] !== ' ')
   1.766 +					{
   1.767 +						$out .= ' ';
   1.768 +					}*/
   1.769 +				}
   1.770 +				else if (preg_match('#^quote(?:=&quot;(.*?)&quot;)?$#is', $buffer, $m) && substr($out, -1, 1) == '[')
   1.771 +				{
   1.772 +					$this->parsed_items['quote']++;
   1.773 +
   1.774 +					// the buffer holds a valid opening tag
   1.775 +					if ($config['max_quote_depth'] && sizeof($close_tags) >= $config['max_quote_depth'])
   1.776 +					{
   1.777 +						// there are too many nested quotes
   1.778 +						$error_ary['quote_depth'] = sprintf($user->lang['QUOTE_DEPTH_EXCEEDED'], $config['max_quote_depth']);
   1.779 +
   1.780 +						$out .= $buffer . $tok;
   1.781 +						$tok = '[]';
   1.782 +						$buffer = '';
   1.783 +
   1.784 +						continue;
   1.785 +					}
   1.786 +
   1.787 +					array_push($close_tags, '/quote:' . $this->bbcode_uid);
   1.788 +
   1.789 +					if (isset($m[1]) && $m[1])
   1.790 +					{
   1.791 +						$username = str_replace(array('&#91;', '&#93;'), array('[', ']'), $m[1]);
   1.792 +						$username = preg_replace('#\[(?!b|i|u|color|url|email|/b|/i|/u|/color|/url|/email)#iU', '&#91;$1', $username);
   1.793 +
   1.794 +						$end_tags = array();
   1.795 +						$error = false;
   1.796 +
   1.797 +						preg_match_all('#\[((?:/)?(?:[a-z]+))#i', $username, $tags);
   1.798 +						foreach ($tags[1] as $tag)
   1.799 +						{
   1.800 +							if ($tag[0] != '/')
   1.801 +							{
   1.802 +								$end_tags[] = '/' . $tag;
   1.803 +							}
   1.804 +							else
   1.805 +							{
   1.806 +								$end_tag = array_pop($end_tags);
   1.807 +								$error = ($end_tag != $tag) ? true : false;
   1.808 +							}
   1.809 +						}
   1.810 +
   1.811 +						if ($error)
   1.812 +						{
   1.813 +							$username = $m[1];
   1.814 +						}
   1.815 +
   1.816 +						$out .= 'quote=&quot;' . $username . '&quot;:' . $this->bbcode_uid . ']';
   1.817 +					}
   1.818 +					else
   1.819 +					{
   1.820 +						$out .= 'quote:' . $this->bbcode_uid . ']';
   1.821 +					}
   1.822 +
   1.823 +					$tok = '[';
   1.824 +					$buffer = '';
   1.825 +				}
   1.826 +				else if (preg_match('#^quote=&quot;(.*?)#is', $buffer, $m))
   1.827 +				{
   1.828 +					// the buffer holds an invalid opening tag
   1.829 +					$buffer .= ']';
   1.830 +				}
   1.831 +				else
   1.832 +				{
   1.833 +					$out .= $buffer . $tok;
   1.834 +					$tok = '[]';
   1.835 +					$buffer = '';
   1.836 +				}
   1.837 +			}
   1.838 +			else
   1.839 +			{
   1.840 +/**
   1.841 +*				Old quote code working fine, but having errors listed in bug #3572
   1.842 +*
   1.843 +*				$out .= $buffer . $tok;
   1.844 +*				$tok = ($tok == '[') ? ']' : '[]';
   1.845 +*				$buffer = '';
   1.846 +*/
   1.847 +
   1.848 +				$out .= $buffer . $tok;
   1.849 +
   1.850 +				if ($tok == '[')
   1.851 +				{
   1.852 +					// Search the text for the next tok... if an ending quote comes first, then change tok to []
   1.853 +					$pos1 = stripos($in, '[/quote');
   1.854 +					// If the token ] comes first, we change it to ]
   1.855 +					$pos2 = strpos($in, ']');
   1.856 +					// If the token [ comes first, we change it to [
   1.857 +					$pos3 = strpos($in, '[');
   1.858 +
   1.859 +					if ($pos1 !== false && ($pos2 === false || $pos1 < $pos2) && ($pos3 === false || $pos1 < $pos3))
   1.860 +					{
   1.861 +						$tok = '[]';
   1.862 +					}
   1.863 +					else if ($pos3 !== false && ($pos2 === false || $pos3 < $pos2))
   1.864 +					{
   1.865 +						$tok = '[';
   1.866 +					}
   1.867 +					else
   1.868 +					{
   1.869 +						$tok = ']';
   1.870 +					}
   1.871 +				}
   1.872 +				else
   1.873 +				{
   1.874 +					$tok = '[]';
   1.875 +				}
   1.876 +				$buffer = '';
   1.877 +			}
   1.878 +		}
   1.879 +		while ($in);
   1.880 +
   1.881 +		$out .= $buffer;
   1.882 +
   1.883 +		if (sizeof($close_tags))
   1.884 +		{
   1.885 +			$out .= '[' . implode('][', $close_tags) . ']';
   1.886 +		}
   1.887 +
   1.888 +		foreach ($error_ary as $error_msg)
   1.889 +		{
   1.890 +			$this->warn_msg[] = $error_msg;
   1.891 +		}
   1.892 +
   1.893 +		return $out;
   1.894 +	}
   1.895 +
   1.896 +	/**
   1.897 +	* Validate email
   1.898 +	*/
   1.899 +	function validate_email($var1, $var2)
   1.900 +	{
   1.901 +		$var1 = str_replace("\r\n", "\n", str_replace('\"', '"', trim($var1)));
   1.902 +		$var2 = str_replace("\r\n", "\n", str_replace('\"', '"', trim($var2)));
   1.903 +
   1.904 +		$txt = $var2;
   1.905 +		$email = ($var1) ? $var1 : $var2;
   1.906 +
   1.907 +		$validated = true;
   1.908 +
   1.909 +		if (!preg_match('/^' . get_preg_expression('email') . '$/i', $email))
   1.910 +		{
   1.911 +			$validated = false;
   1.912 +		}
   1.913 +
   1.914 +		if (!$validated)
   1.915 +		{
   1.916 +			return '[email' . (($var1) ? "=$var1" : '') . ']' . $var2 . '[/email]';
   1.917 +		}
   1.918 +
   1.919 +		$this->parsed_items['email']++;
   1.920 +
   1.921 +		if ($var1)
   1.922 +		{
   1.923 +			$retval = '[email=' . $this->bbcode_specialchars($email) . ':' . $this->bbcode_uid . ']' . $txt . '[/email:' . $this->bbcode_uid . ']';
   1.924 +		}
   1.925 +		else
   1.926 +		{
   1.927 +			$retval = '[email:' . $this->bbcode_uid . ']' . $this->bbcode_specialchars($email) . '[/email:' . $this->bbcode_uid . ']';
   1.928 +		}
   1.929 +
   1.930 +		return $retval;
   1.931 +	}
   1.932 +
   1.933 +	/**
   1.934 +	* Validate url
   1.935 +	*
   1.936 +	* @param string $var1 optional url parameter for url bbcode: [url(=$var1)]$var2[/url]
   1.937 +	* @param string $var2 url bbcode content: [url(=$var1)]$var2[/url]
   1.938 +	*/
   1.939 +	function validate_url($var1, $var2)
   1.940 +	{
   1.941 +		global $config;
   1.942 +
   1.943 +		$var1 = str_replace("\r\n", "\n", str_replace('\"', '"', trim($var1)));
   1.944 +		$var2 = str_replace("\r\n", "\n", str_replace('\"', '"', trim($var2)));
   1.945 +
   1.946 +		$url = ($var1) ? $var1 : $var2;
   1.947 +
   1.948 +		if ($var1 && !$var2)
   1.949 +		{
   1.950 +			$var2 = $var1;
   1.951 +		}
   1.952 +
   1.953 +		if (!$url)
   1.954 +		{
   1.955 +			return '[url' . (($var1) ? '=' . $var1 : '') . ']' . $var2 . '[/url]';
   1.956 +		}
   1.957 +
   1.958 +		$valid = false;
   1.959 +
   1.960 +		$url = str_replace(' ', '%20', $url);
   1.961 +
   1.962 +		// Checking urls
   1.963 +		if (preg_match('#^' . get_preg_expression('url') . '$#i', $url) ||
   1.964 +			preg_match('#^' . get_preg_expression('www_url') . '$#i', $url) ||
   1.965 +			preg_match('#^' . preg_quote(generate_board_url(), '#') . get_preg_expression('relative_url') . '$#i', $url))
   1.966 +		{
   1.967 +			$valid = true;
   1.968 +		}
   1.969 +
   1.970 +		if ($valid)
   1.971 +		{
   1.972 +			$this->parsed_items['url']++;
   1.973 +
   1.974 +			// if there is no scheme, then add http schema
   1.975 +			if (!preg_match('#^[a-z][a-z\d+\-.]*:/{2}#i', $url))
   1.976 +			{
   1.977 +				$url = 'http://' . $url;
   1.978 +			}
   1.979 +
   1.980 +			// Is this a link to somewhere inside this board? If so then remove the session id from the url
   1.981 +			if (strpos($url, generate_board_url()) !== false && strpos($url, 'sid=') !== false)
   1.982 +			{
   1.983 +				$url = preg_replace('/(&amp;|\?)sid=[0-9a-f]{32}&amp;/', '\1', $url);
   1.984 +				$url = preg_replace('/(&amp;|\?)sid=[0-9a-f]{32}$/', '', $url);
   1.985 +				$url = append_sid($url);
   1.986 +			}
   1.987 +
   1.988 +			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 . ']';
   1.989 +		}
   1.990 +
   1.991 +		return '[url' . (($var1) ? '=' . $var1 : '') . ']' . $var2 . '[/url]';
   1.992 +	}
   1.993 +
   1.994 +	/**
   1.995 +	* Check if url is pointing to this domain/script_path/php-file
   1.996 +	*
   1.997 +	* @param string $url the url to check
   1.998 +	* @return true if the url is pointing to this domain/script_path/php-file, false if not
   1.999 +	*
  1.1000 +	* @access private
  1.1001 +	*/
  1.1002 +	function path_in_domain($url)
  1.1003 +	{
  1.1004 +		global $config, $phpEx, $user;
  1.1005 +
  1.1006 +		if ($config['force_server_vars'])
  1.1007 +		{
  1.1008 +			$check_path = $config['script_path'];
  1.1009 +		}
  1.1010 +		else
  1.1011 +		{
  1.1012 +			$check_path = ($user->page['root_script_path'] != '/') ? substr($user->page['root_script_path'], 0, -1) : '/';
  1.1013 +		}
  1.1014 +
  1.1015 +		// Is the user trying to link to a php file in this domain and script path?
  1.1016 +		if (strpos($url, ".{$phpEx}") !== false && strpos($url, $check_path) !== false)
  1.1017 +		{
  1.1018 +			$server_name = $user->host;
  1.1019 +
  1.1020 +			// Forcing server vars is the only way to specify/override the protocol
  1.1021 +			if ($config['force_server_vars'] || !$server_name)
  1.1022 +			{
  1.1023 +				$server_name = $config['server_name'];
  1.1024 +			}
  1.1025 +
  1.1026 +			// Check again in correct order...
  1.1027 +			$pos_ext = strpos($url, ".{$phpEx}");
  1.1028 +			$pos_path = strpos($url, $check_path);
  1.1029 +			$pos_domain = strpos($url, $server_name);
  1.1030 +
  1.1031 +			if ($pos_domain !== false && $pos_path >= $pos_domain && $pos_ext >= $pos_path)
  1.1032 +			{
  1.1033 +				// Ok, actually we allow linking to some files (this may be able to be extended in some way later...)
  1.1034 +				if (strpos($url, '/' . $check_path . '/download/file.' . $phpEx) !== 0)
  1.1035 +				{
  1.1036 +					return false;
  1.1037 +				}
  1.1038 +
  1.1039 +				return true;
  1.1040 +			}
  1.1041 +		}
  1.1042 +
  1.1043 +		return false;
  1.1044 +	}
  1.1045 +}
  1.1046 +
  1.1047 +/**
  1.1048 +* Main message parser for posting, pm, etc. takes raw message
  1.1049 +* and parses it for attachments, bbcode and smilies
  1.1050 +* @package phpBB3
  1.1051 +*/
  1.1052 +class parse_message extends bbcode_firstpass
  1.1053 +{
  1.1054 +	var $attachment_data = array();
  1.1055 +	var $filename_data = array();
  1.1056 +
  1.1057 +	// Helps ironing out user error
  1.1058 +	var $message_status = '';
  1.1059 +
  1.1060 +	var $allow_img_bbcode = true;
  1.1061 +	var $allow_flash_bbcode = true;
  1.1062 +	var $allow_quote_bbcode = true;
  1.1063 +	var $allow_url_bbcode = true;
  1.1064 +
  1.1065 +	var $mode;
  1.1066 +
  1.1067 +	/**
  1.1068 +	* Init - give message here or manually
  1.1069 +	*/
  1.1070 +	function parse_message($message = '')
  1.1071 +	{
  1.1072 +		// Init BBCode UID
  1.1073 +		$this->bbcode_uid = substr(base_convert(unique_id(), 16, 36), 0, BBCODE_UID_LEN);
  1.1074 +		$this->message = $message;
  1.1075 +	}
  1.1076 +
  1.1077 +	/**
  1.1078 +	* Parse Message
  1.1079 +	*/
  1.1080 +	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')
  1.1081 +	{
  1.1082 +		global $config, $db, $user;
  1.1083 +
  1.1084 +		$this->mode = $mode;
  1.1085 +
  1.1086 +		foreach (array('chars', 'smilies', 'urls', 'font_size', 'img_height', 'img_width') as $key)
  1.1087 +		{
  1.1088 +			if (!isset($config['max_' . $mode . '_' . $key]))
  1.1089 +			{
  1.1090 +				$config['max_' . $mode . '_' . $key] = 0;
  1.1091 +			}
  1.1092 +		}
  1.1093 +
  1.1094 +		$this->allow_img_bbcode = $allow_img_bbcode;
  1.1095 +		$this->allow_flash_bbcode = $allow_flash_bbcode;
  1.1096 +		$this->allow_quote_bbcode = $allow_quote_bbcode;
  1.1097 +		$this->allow_url_bbcode = $allow_url_bbcode;
  1.1098 +
  1.1099 +		// If false, then $this->message won't be altered, the text will be returned instead.
  1.1100 +		if (!$update_this_message)
  1.1101 +		{
  1.1102 +			$tmp_message = $this->message;
  1.1103 +			$return_message = &$this->message;
  1.1104 +		}
  1.1105 +
  1.1106 +		if ($this->message_status == 'display')
  1.1107 +		{
  1.1108 +			$this->decode_message();
  1.1109 +		}
  1.1110 +
  1.1111 +		// Do some general 'cleanup' first before processing message,
  1.1112 +		// e.g. remove excessive newlines(?), smilies(?)
  1.1113 +		$match = array('#(script|about|applet|activex|chrome):#i');
  1.1114 +		$replace = array("\\1&#058;");
  1.1115 +		$this->message = preg_replace($match, $replace, trim($this->message));
  1.1116 +
  1.1117 +		// Store message length...
  1.1118 +		$message_length = ($mode == 'post') ? utf8_strlen($this->message) : utf8_strlen(preg_replace('#\[\/?[a-z\*\+\-]+(=[\S]+)?\]#ius', ' ', $this->message));
  1.1119 +
  1.1120 +		// Maximum message length check. 0 disables this check completely.
  1.1121 +		if ((int) $config['max_' . $mode . '_chars'] > 0 && $message_length > (int) $config['max_' . $mode . '_chars'])
  1.1122 +		{
  1.1123 +			$this->warn_msg[] = sprintf($user->lang['TOO_MANY_CHARS_' . strtoupper($mode)], $message_length, (int) $config['max_' . $mode . '_chars']);
  1.1124 +			return (!$update_this_message) ? $return_message : $this->warn_msg;
  1.1125 +		}
  1.1126 +
  1.1127 +		// Minimum message length check for post only
  1.1128 +		if ($mode === 'post')
  1.1129 +		{
  1.1130 +			if (!$message_length || $message_length < (int) $config['min_post_chars'])
  1.1131 +			{
  1.1132 +				$this->warn_msg[] = (!$message_length) ? $user->lang['TOO_FEW_CHARS'] : sprintf($user->lang['TOO_FEW_CHARS_LIMIT'], $message_length, (int) $config['min_post_chars']);
  1.1133 +				return (!$update_this_message) ? $return_message : $this->warn_msg;
  1.1134 +			}
  1.1135 +		}
  1.1136 +
  1.1137 +		// Prepare BBcode (just prepares some tags for better parsing)
  1.1138 +		if ($allow_bbcode && strpos($this->message, '[') !== false)
  1.1139 +		{
  1.1140 +			$this->bbcode_init();
  1.1141 +			$disallow = array('img', 'flash', 'quote', 'url');
  1.1142 +			foreach ($disallow as $bool)
  1.1143 +			{
  1.1144 +				if (!${'allow_' . $bool . '_bbcode'})
  1.1145 +				{
  1.1146 +					$this->bbcodes[$bool]['disabled'] = true;
  1.1147 +				}
  1.1148 +			}
  1.1149 +
  1.1150 +			$this->prepare_bbcodes();
  1.1151 +		}
  1.1152 +
  1.1153 +		// Parse smilies
  1.1154 +		if ($allow_smilies)
  1.1155 +		{
  1.1156 +			$this->smilies($config['max_' . $mode . '_smilies']);
  1.1157 +		}
  1.1158 +
  1.1159 +		$num_urls = 0;
  1.1160 +
  1.1161 +		// Parse BBCode
  1.1162 +		if ($allow_bbcode && strpos($this->message, '[') !== false)
  1.1163 +		{
  1.1164 +			$this->parse_bbcode();
  1.1165 +			$num_urls += $this->parsed_items['url'];
  1.1166 +		}
  1.1167 +
  1.1168 +		// Parse URL's
  1.1169 +		if ($allow_magic_url)
  1.1170 +		{
  1.1171 +			$this->magic_url(generate_board_url());
  1.1172 +
  1.1173 +			if ($config['max_' . $mode . '_urls'])
  1.1174 +			{
  1.1175 +				$num_urls += preg_match_all('#\<!-- ([lmwe]) --\>.*?\<!-- \1 --\>#', $this->message, $matches);
  1.1176 +			}
  1.1177 +		}
  1.1178 +
  1.1179 +		// Check for "empty" message. We do not check here for maximum length, because bbcode, smilies, etc. can add to the length.
  1.1180 +		// The maximum length check happened before any parsings.
  1.1181 +		if ($mode === 'post' && utf8_clean_string($this->message) === '')
  1.1182 +		{
  1.1183 +			$this->warn_msg[] = $user->lang['TOO_FEW_CHARS'];
  1.1184 +			return (!$update_this_message) ? $return_message : $this->warn_msg;
  1.1185 +		}
  1.1186 +
  1.1187 +		// Check number of links
  1.1188 +		if ($config['max_' . $mode . '_urls'] && $num_urls > $config['max_' . $mode . '_urls'])
  1.1189 +		{
  1.1190 +			$this->warn_msg[] = sprintf($user->lang['TOO_MANY_URLS'], $config['max_' . $mode . '_urls']);
  1.1191 +			return (!$update_this_message) ? $return_message : $this->warn_msg;
  1.1192 +		}
  1.1193 +
  1.1194 +		if (!$update_this_message)
  1.1195 +		{
  1.1196 +			unset($this->message);
  1.1197 +			$this->message = $tmp_message;
  1.1198 +			return $return_message;
  1.1199 +		}
  1.1200 +
  1.1201 +		$this->message_status = 'parsed';
  1.1202 +		return false;
  1.1203 +	}
  1.1204 +
  1.1205 +	/**
  1.1206 +	* Formatting text for display
  1.1207 +	*/
  1.1208 +	function format_display($allow_bbcode, $allow_magic_url, $allow_smilies, $update_this_message = true)
  1.1209 +	{
  1.1210 +		// If false, then the parsed message get returned but internal message not processed.
  1.1211 +		if (!$update_this_message)
  1.1212 +		{
  1.1213 +			$tmp_message = $this->message;
  1.1214 +			$return_message = &$this->message;
  1.1215 +		}
  1.1216 +
  1.1217 +		if ($this->message_status == 'plain')
  1.1218 +		{
  1.1219 +			// Force updating message - of course.
  1.1220 +			$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);
  1.1221 +		}
  1.1222 +
  1.1223 +		// Replace naughty words such as farty pants
  1.1224 +		$this->message = censor_text($this->message);
  1.1225 +
  1.1226 +		// Parse BBcode
  1.1227 +		if ($allow_bbcode)
  1.1228 +		{
  1.1229 +			$this->bbcode_cache_init();
  1.1230 +
  1.1231 +			// We are giving those parameters to be able to use the bbcode class on its own
  1.1232 +			$this->bbcode_second_pass($this->message, $this->bbcode_uid);
  1.1233 +		}
  1.1234 +
  1.1235 +		$this->message = bbcode_nl2br($this->message);
  1.1236 +		$this->message = smiley_text($this->message, !$allow_smilies);
  1.1237 +
  1.1238 +		if (!$update_this_message)
  1.1239 +		{
  1.1240 +			unset($this->message);
  1.1241 +			$this->message = $tmp_message;
  1.1242 +			return $return_message;
  1.1243 +		}
  1.1244 +
  1.1245 +		$this->message_status = 'display';
  1.1246 +		return false;
  1.1247 +	}
  1.1248 +
  1.1249 +	/**
  1.1250 +	* Decode message to be placed back into form box
  1.1251 +	*/
  1.1252 +	function decode_message($custom_bbcode_uid = '', $update_this_message = true)
  1.1253 +	{
  1.1254 +		// If false, then the parsed message get returned but internal message not processed.
  1.1255 +		if (!$update_this_message)
  1.1256 +		{
  1.1257 +			$tmp_message = $this->message;
  1.1258 +			$return_message = &$this->message;
  1.1259 +		}
  1.1260 +
  1.1261 +		($custom_bbcode_uid) ? decode_message($this->message, $custom_bbcode_uid) : decode_message($this->message, $this->bbcode_uid);
  1.1262 +
  1.1263 +		if (!$update_this_message)
  1.1264 +		{
  1.1265 +			unset($this->message);
  1.1266 +			$this->message = $tmp_message;
  1.1267 +			return $return_message;
  1.1268 +		}
  1.1269 +
  1.1270 +		$this->message_status = 'plain';
  1.1271 +		return false;
  1.1272 +	}
  1.1273 +
  1.1274 +	/**
  1.1275 +	* Replace magic urls of form http://xxx.xxx., www.xxx. and xxx@xxx.xxx.
  1.1276 +	* Cuts down displayed size of link if over 50 chars, turns absolute links
  1.1277 +	* into relative versions when the server/script path matches the link
  1.1278 +	*/
  1.1279 +	function magic_url($server_url)
  1.1280 +	{
  1.1281 +		// We use the global make_clickable function
  1.1282 +		$this->message = make_clickable($this->message, $server_url);
  1.1283 +	}
  1.1284 +
  1.1285 +	/**
  1.1286 +	* Parse Smilies
  1.1287 +	*/
  1.1288 +	function smilies($max_smilies = 0)
  1.1289 +	{
  1.1290 +		global $db, $user;
  1.1291 +		static $match;
  1.1292 +		static $replace;
  1.1293 +
  1.1294 +		// See if the static arrays have already been filled on an earlier invocation
  1.1295 +		if (!is_array($match))
  1.1296 +		{
  1.1297 +			$match = $replace = array();
  1.1298 +
  1.1299 +			// NOTE: obtain_* function? chaching the table contents?
  1.1300 +
  1.1301 +			// For now setting the ttl to 10 minutes
  1.1302 +			switch ($db->sql_layer)
  1.1303 +			{
  1.1304 +				case 'mssql':
  1.1305 +				case 'mssql_odbc':
  1.1306 +				case 'mssqlnative':
  1.1307 +					$sql = 'SELECT *
  1.1308 +						FROM ' . SMILIES_TABLE . '
  1.1309 +						ORDER BY LEN(code) DESC';
  1.1310 +				break;
  1.1311 +
  1.1312 +				case 'firebird':
  1.1313 +					$sql = 'SELECT *
  1.1314 +						FROM ' . SMILIES_TABLE . '
  1.1315 +						ORDER BY CHAR_LENGTH(code) DESC';
  1.1316 +				break;
  1.1317 +
  1.1318 +				// LENGTH supported by MySQL, IBM DB2, Oracle and Access for sure...
  1.1319 +				default:
  1.1320 +					$sql = 'SELECT *
  1.1321 +						FROM ' . SMILIES_TABLE . '
  1.1322 +						ORDER BY LENGTH(code) DESC';
  1.1323 +				break;
  1.1324 +			}
  1.1325 +			$result = $db->sql_query($sql, 600);
  1.1326 +
  1.1327 +			while ($row = $db->sql_fetchrow($result))
  1.1328 +			{
  1.1329 +				if (empty($row['code']))
  1.1330 +				{
  1.1331 +					continue;
  1.1332 +				}
  1.1333 +
  1.1334 +				// (assertion)
  1.1335 +				$match[] = preg_quote($row['code'], '#');
  1.1336 +				$replace[] = '<!-- s' . $row['code'] . ' --><img src="{SMILIES_PATH}/' . $row['smiley_url'] . '" alt="' . $row['code'] . '" title="' . $row['emotion'] . '" /><!-- s' . $row['code'] . ' -->';
  1.1337 +			}
  1.1338 +			$db->sql_freeresult($result);
  1.1339 +		}
  1.1340 +
  1.1341 +		if (sizeof($match))
  1.1342 +		{
  1.1343 +			if ($max_smilies)
  1.1344 +			{
  1.1345 +				// 'u' modifier has been added to correctly parse smilies within unicode strings
  1.1346 +				// For details: http://tracker.phpbb.com/browse/PHPBB3-10117
  1.1347 +				$num_matches = preg_match_all('#(?<=^|[\n .])(?:' . implode('|', $match) . ')(?![^<>]*>)#u', $this->message, $matches);
  1.1348 +				unset($matches);
  1.1349 +
  1.1350 +				if ($num_matches !== false && $num_matches > $max_smilies)
  1.1351 +				{
  1.1352 +					$this->warn_msg[] = sprintf($user->lang['TOO_MANY_SMILIES'], $max_smilies);
  1.1353 +					return;
  1.1354 +				}
  1.1355 +			}
  1.1356 +
  1.1357 +			// Make sure the delimiter # is added in front and at the end of every element within $match
  1.1358 +			// 'u' modifier has been added to correctly parse smilies within unicode strings
  1.1359 +			// For details: http://tracker.phpbb.com/browse/PHPBB3-10117
  1.1360 +
  1.1361 +			$this->message = trim(preg_replace(explode(chr(0), '#(?<=^|[\n .])' . implode('(?![^<>]*>)#u' . chr(0) . '#(?<=^|[\n .])', $match) . '(?![^<>]*>)#u'), $replace, $this->message));
  1.1362 +		}
  1.1363 +	}
  1.1364 +
  1.1365 +	/**
  1.1366 +	* Parse Attachments
  1.1367 +	*/
  1.1368 +	function parse_attachments($form_name, $mode, $forum_id, $submit, $preview, $refresh, $is_message = false)
  1.1369 +	{
  1.1370 +		global $config, $auth, $user, $phpbb_root_path, $phpEx, $db;
  1.1371 +
  1.1372 +		$error = array();
  1.1373 +
  1.1374 +		$num_attachments = sizeof($this->attachment_data);
  1.1375 +		$this->filename_data['filecomment'] = utf8_normalize_nfc(request_var('filecomment', '', true));
  1.1376 +		$upload_file = (isset($_FILES[$form_name]) && $_FILES[$form_name]['name'] != 'none' && trim($_FILES[$form_name]['name'])) ? true : false;
  1.1377 +
  1.1378 +		$add_file		= (isset($_POST['add_file'])) ? true : false;
  1.1379 +		$delete_file	= (isset($_POST['delete_file'])) ? true : false;
  1.1380 +
  1.1381 +		// First of all adjust comments if changed
  1.1382 +		$actual_comment_list = utf8_normalize_nfc(request_var('comment_list', array(''), true));
  1.1383 +
  1.1384 +		foreach ($actual_comment_list as $comment_key => $comment)
  1.1385 +		{
  1.1386 +			if (!isset($this->attachment_data[$comment_key]))
  1.1387 +			{
  1.1388 +				continue;
  1.1389 +			}
  1.1390 +
  1.1391 +			if ($this->attachment_data[$comment_key]['attach_comment'] != $actual_comment_list[$comment_key])
  1.1392 +			{
  1.1393 +				$this->attachment_data[$comment_key]['attach_comment'] = $actual_comment_list[$comment_key];
  1.1394 +			}
  1.1395 +		}
  1.1396 +
  1.1397 +		$cfg = array();
  1.1398 +		$cfg['max_attachments'] = ($is_message) ? $config['max_attachments_pm'] : $config['max_attachments'];
  1.1399 +		$forum_id = ($is_message) ? 0 : $forum_id;
  1.1400 +
  1.1401 +		if ($submit && in_array($mode, array('post', 'reply', 'quote', 'edit')) && $upload_file)
  1.1402 +		{
  1.1403 +			if ($num_attachments < $cfg['max_attachments'] || $auth->acl_get('a_') || $auth->acl_get('m_', $forum_id))
  1.1404 +			{
  1.1405 +				$filedata = upload_attachment($form_name, $forum_id, false, '', $is_message);
  1.1406 +				$error = $filedata['error'];
  1.1407 +
  1.1408 +				if ($filedata['post_attach'] && !sizeof($error))
  1.1409 +				{
  1.1410 +					$sql_ary = array(
  1.1411 +						'physical_filename'	=> $filedata['physical_filename'],
  1.1412 +						'attach_comment'	=> $this->filename_data['filecomment'],
  1.1413 +						'real_filename'		=> $filedata['real_filename'],
  1.1414 +						'extension'			=> $filedata['extension'],
  1.1415 +						'mimetype'			=> $filedata['mimetype'],
  1.1416 +						'filesize'			=> $filedata['filesize'],
  1.1417 +						'filetime'			=> $filedata['filetime'],
  1.1418 +						'thumbnail'			=> $filedata['thumbnail'],
  1.1419 +						'is_orphan'			=> 1,
  1.1420 +						'in_message'		=> ($is_message) ? 1 : 0,
  1.1421 +						'poster_id'			=> $user->data['user_id'],
  1.1422 +					);
  1.1423 +
  1.1424 +					$db->sql_query('INSERT INTO ' . ATTACHMENTS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary));
  1.1425 +
  1.1426 +					$new_entry = array(
  1.1427 +						'attach_id'		=> $db->sql_nextid(),
  1.1428 +						'is_orphan'		=> 1,
  1.1429 +						'real_filename'	=> $filedata['real_filename'],
  1.1430 +						'attach_comment'=> $this->filename_data['filecomment'],
  1.1431 +					);
  1.1432 +
  1.1433 +					$this->attachment_data = array_merge(array(0 => $new_entry), $this->attachment_data);
  1.1434 +					$this->message = preg_replace('#\[attachment=([0-9]+)\](.*?)\[\/attachment\]#e', "'[attachment='.(\\1 + 1).']\\2[/attachment]'", $this->message);
  1.1435 +
  1.1436 +					$this->filename_data['filecomment'] = '';
  1.1437 +
  1.1438 +					// This Variable is set to false here, because Attachments are entered into the
  1.1439 +					// Database in two modes, one if the id_list is 0 and the second one if post_attach is true
  1.1440 +					// Since post_attach is automatically switched to true if an Attachment got added to the filesystem,
  1.1441 +					// but we are assigning an id of 0 here, we have to reset the post_attach variable to false.
  1.1442 +					//
  1.1443 +					// This is very relevant, because it could happen that the post got not submitted, but we do not
  1.1444 +					// know this circumstance here. We could be at the posting page or we could be redirected to the entered
  1.1445 +					// post. :)
  1.1446 +					$filedata['post_attach'] = false;
  1.1447 +				}
  1.1448 +			}
  1.1449 +			else
  1.1450 +			{
  1.1451 +				$error[] = sprintf($user->lang['TOO_MANY_ATTACHMENTS'], $cfg['max_attachments']);
  1.1452 +			}
  1.1453 +		}
  1.1454 +
  1.1455 +		if ($preview || $refresh || sizeof($error))
  1.1456 +		{
  1.1457 +			// Perform actions on temporary attachments
  1.1458 +			if ($delete_file)
  1.1459 +			{
  1.1460 +				include_once($phpbb_root_path . 'includes/functions_admin.' . $phpEx);
  1.1461 +
  1.1462 +				$index = array_keys(request_var('delete_file', array(0 => 0)));
  1.1463 +				$index = (!empty($index)) ? $index[0] : false;
  1.1464 +
  1.1465 +				if ($index !== false && !empty($this->attachment_data[$index]))
  1.1466 +				{
  1.1467 +					// delete selected attachment
  1.1468 +					if ($this->attachment_data[$index]['is_orphan'])
  1.1469 +					{
  1.1470 +						$sql = 'SELECT attach_id, physical_filename, thumbnail
  1.1471 +							FROM ' . ATTACHMENTS_TABLE . '
  1.1472 +							WHERE attach_id = ' . (int) $this->attachment_data[$index]['attach_id'] . '
  1.1473 +								AND is_orphan = 1
  1.1474 +								AND poster_id = ' . $user->data['user_id'];
  1.1475 +						$result = $db->sql_query($sql);
  1.1476 +						$row = $db->sql_fetchrow($result);
  1.1477 +						$db->sql_freeresult($result);
  1.1478 +
  1.1479 +						if ($row)
  1.1480 +						{
  1.1481 +							phpbb_unlink($row['physical_filename'], 'file');
  1.1482 +
  1.1483 +							if ($row['thumbnail'])
  1.1484 +							{
  1.1485 +								phpbb_unlink($row['physical_filename'], 'thumbnail');
  1.1486 +							}
  1.1487 +
  1.1488 +							$db->sql_query('DELETE FROM ' . ATTACHMENTS_TABLE . ' WHERE attach_id = ' . (int) $this->attachment_data[$index]['attach_id']);
  1.1489 +						}
  1.1490 +					}
  1.1491 +					else
  1.1492 +					{
  1.1493 +						delete_attachments('attach', array(intval($this->attachment_data[$index]['attach_id'])));
  1.1494 +					}
  1.1495 +
  1.1496 +					unset($this->attachment_data[$index]);
  1.1497 +					$this->message = preg_replace('#\[attachment=([0-9]+)\](.*?)\[\/attachment\]#e', "(\\1 == \$index) ? '' : ((\\1 > \$index) ? '[attachment=' . (\\1 - 1) . ']\\2[/attachment]' : '\\0')", $this->message);
  1.1498 +
  1.1499 +					// Reindex Array
  1.1500 +					$this->attachment_data = array_values($this->attachment_data);
  1.1501 +				}
  1.1502 +			}
  1.1503 +			else if (($add_file || $preview) && $upload_file)
  1.1504 +			{
  1.1505 +				if ($num_attachments < $cfg['max_attachments'] || $auth->acl_gets('m_', 'a_', $forum_id))
  1.1506 +				{
  1.1507 +					$filedata = upload_attachment($form_name, $forum_id, false, '', $is_message);
  1.1508 +					$error = array_merge($error, $filedata['error']);
  1.1509 +
  1.1510 +					if (!sizeof($error))
  1.1511 +					{
  1.1512 +						$sql_ary = array(
  1.1513 +							'physical_filename'	=> $filedata['physical_filename'],
  1.1514 +							'attach_comment'	=> $this->filename_data['filecomment'],
  1.1515 +							'real_filename'		=> $filedata['real_filename'],
  1.1516 +							'extension'			=> $filedata['extension'],
  1.1517 +							'mimetype'			=> $filedata['mimetype'],
  1.1518 +							'filesize'			=> $filedata['filesize'],
  1.1519 +							'filetime'			=> $filedata['filetime'],
  1.1520 +							'thumbnail'			=> $filedata['thumbnail'],
  1.1521 +							'is_orphan'			=> 1,
  1.1522 +							'in_message'		=> ($is_message) ? 1 : 0,
  1.1523 +							'poster_id'			=> $user->data['user_id'],
  1.1524 +						);
  1.1525 +
  1.1526 +						$db->sql_query('INSERT INTO ' . ATTACHMENTS_TABLE . ' ' . $db->sql_build_array('INSERT', $sql_ary));
  1.1527 +
  1.1528 +						$new_entry = array(
  1.1529 +							'attach_id'		=> $db->sql_nextid(),
  1.1530 +							'is_orphan'		=> 1,
  1.1531 +							'real_filename'	=> $filedata['real_filename'],
  1.1532 +							'attach_comment'=> $this->filename_data['filecomment'],
  1.1533 +						);
  1.1534 +
  1.1535 +						$this->attachment_data = array_merge(array(0 => $new_entry), $this->attachment_data);
  1.1536 +						$this->message = preg_replace('#\[attachment=([0-9]+)\](.*?)\[\/attachment\]#e', "'[attachment='.(\\1 + 1).']\\2[/attachment]'", $this->message);
  1.1537 +						$this->filename_data['filecomment'] = '';
  1.1538 +					}
  1.1539 +				}
  1.1540 +				else
  1.1541 +				{
  1.1542 +					$error[] = sprintf($user->lang['TOO_MANY_ATTACHMENTS'], $cfg['max_attachments']);
  1.1543 +				}
  1.1544 +			}
  1.1545 +		}
  1.1546 +
  1.1547 +		foreach ($error as $error_msg)
  1.1548 +		{
  1.1549 +			$this->warn_msg[] = $error_msg;
  1.1550 +		}
  1.1551 +	}
  1.1552 +
  1.1553 +	/**
  1.1554 +	* Get Attachment Data
  1.1555 +	*/
  1.1556 +	function get_submitted_attachment_data($check_user_id = false)
  1.1557 +	{
  1.1558 +		global $user, $db, $phpbb_root_path, $phpEx, $config;
  1.1559 +
  1.1560 +		$this->filename_data['filecomment'] = utf8_normalize_nfc(request_var('filecomment', '', true));
  1.1561 +		$attachment_data = (isset($_POST['attachment_data'])) ? $_POST['attachment_data'] : array();
  1.1562 +		$this->attachment_data = array();
  1.1563 +
  1.1564 +		$check_user_id = ($check_user_id === false) ? $user->data['user_id'] : $check_user_id;
  1.1565 +
  1.1566 +		if (!sizeof($attachment_data))
  1.1567 +		{
  1.1568 +			return;
  1.1569 +		}
  1.1570 +
  1.1571 +		$not_orphan = $orphan = array();
  1.1572 +
  1.1573 +		foreach ($attachment_data as $pos => $var_ary)
  1.1574 +		{
  1.1575 +			if ($var_ary['is_orphan'])
  1.1576 +			{
  1.1577 +				$orphan[(int) $var_ary['attach_id']] = $pos;
  1.1578 +			}
  1.1579 +			else
  1.1580 +			{
  1.1581 +				$not_orphan[(int) $var_ary['attach_id']] = $pos;
  1.1582 +			}
  1.1583 +		}
  1.1584 +
  1.1585 +		// Regenerate already posted attachments
  1.1586 +		if (sizeof($not_orphan))
  1.1587 +		{
  1.1588 +			// Get the attachment data, based on the poster id...
  1.1589 +			$sql = 'SELECT attach_id, is_orphan, real_filename, attach_comment
  1.1590 +				FROM ' . ATTACHMENTS_TABLE . '
  1.1591 +				WHERE ' . $db->sql_in_set('attach_id', array_keys($not_orphan)) . '
  1.1592 +					AND poster_id = ' . $check_user_id;
  1.1593 +			$result = $db->sql_query($sql);
  1.1594 +
  1.1595 +			while ($row = $db->sql_fetchrow($result))
  1.1596 +			{
  1.1597 +				$pos = $not_orphan[$row['attach_id']];
  1.1598 +				$this->attachment_data[$pos] = $row;
  1.1599 +				set_var($this->attachment_data[$pos]['attach_comment'], $_POST['attachment_data'][$pos]['attach_comment'], 'string', true);
  1.1600 +
  1.1601 +				unset($not_orphan[$row['attach_id']]);
  1.1602 +			}
  1.1603 +			$db->sql_freeresult($result);
  1.1604 +		}
  1.1605 +
  1.1606 +		if (sizeof($not_orphan))
  1.1607 +		{
  1.1608 +			trigger_error('NO_ACCESS_ATTACHMENT', E_USER_ERROR);
  1.1609 +		}
  1.1610 +
  1.1611 +		// Regenerate newly uploaded attachments
  1.1612 +		if (sizeof($orphan))
  1.1613 +		{
  1.1614 +			$sql = 'SELECT attach_id, is_orphan, real_filename, attach_comment
  1.1615 +				FROM ' . ATTACHMENTS_TABLE . '
  1.1616 +				WHERE ' . $db->sql_in_set('attach_id', array_keys($orphan)) . '
  1.1617 +					AND poster_id = ' . $user->data['user_id'] . '
  1.1618 +					AND is_orphan = 1';
  1.1619 +			$result = $db->sql_query($sql);
  1.1620 +
  1.1621 +			while ($row = $db->sql_fetchrow($result))
  1.1622 +			{
  1.1623 +				$pos = $orphan[$row['attach_id']];
  1.1624 +				$this->attachment_data[$pos] = $row;
  1.1625 +				set_var($this->attachment_data[$pos]['attach_comment'], $_POST['attachment_data'][$pos]['attach_comment'], 'string', true);
  1.1626 +
  1.1627 +				unset($orphan[$row['attach_id']]);
  1.1628 +			}
  1.1629 +			$db->sql_freeresult($result);
  1.1630 +		}
  1.1631 +
  1.1632 +		if (sizeof($orphan))
  1.1633 +		{
  1.1634 +			trigger_error('NO_ACCESS_ATTACHMENT', E_USER_ERROR);
  1.1635 +		}
  1.1636 +
  1.1637 +		ksort($this->attachment_data);
  1.1638 +	}
  1.1639 +
  1.1640 +	/**
  1.1641 +	* Parse Poll
  1.1642 +	*/
  1.1643 +	function parse_poll(&$poll)
  1.1644 +	{
  1.1645 +		global $auth, $user, $config;
  1.1646 +
  1.1647 +		$poll_max_options = $poll['poll_max_options'];
  1.1648 +
  1.1649 +		// Parse Poll Option text ;)
  1.1650 +		$tmp_message = $this->message;
  1.1651 +		$this->message = $poll['poll_option_text'];
  1.1652 +		$bbcode_bitfield = $this->bbcode_bitfield;
  1.1653 +
  1.1654 +		$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, 'poll');
  1.1655 +
  1.1656 +		$bbcode_bitfield = base64_encode(base64_decode($bbcode_bitfield) | base64_decode($this->bbcode_bitfield));
  1.1657 +		$this->message = $tmp_message;
  1.1658 +
  1.1659 +		// Parse Poll Title
  1.1660 +		$tmp_message = $this->message;
  1.1661 +		$this->message = $poll['poll_title'];
  1.1662 +		$this->bbcode_bitfield = $bbcode_bitfield;
  1.1663 +
  1.1664 +		$poll['poll_options'] = explode("\n", trim($poll['poll_option_text']));
  1.1665 +		$poll['poll_options_size'] = sizeof($poll['poll_options']);
  1.1666 +
  1.1667 +		if (!$poll['poll_title'] && $poll['poll_options_size'])
  1.1668 +		{
  1.1669 +			$this->warn_msg[] = $user->lang['NO_POLL_TITLE'];
  1.1670 +		}
  1.1671 +		else
  1.1672 +		{
  1.1673 +			if (utf8_strlen(preg_replace('#\[\/?[a-z\*\+\-]+(=[\S]+)?\]#ius', ' ', $this->message)) > 100)
  1.1674 +			{
  1.1675 +				$this->warn_msg[] = $user->lang['POLL_TITLE_TOO_LONG'];
  1.1676 +			}
  1.1677 +			$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, 'poll');
  1.1678 +			if (strlen($poll['poll_title']) > 255)
  1.1679 +			{
  1.1680 +				$this->warn_msg[] = $user->lang['POLL_TITLE_COMP_TOO_LONG'];
  1.1681 +			}
  1.1682 +		}
  1.1683 +
  1.1684 +		$this->bbcode_bitfield = base64_encode(base64_decode($bbcode_bitfield) | base64_decode($this->bbcode_bitfield));
  1.1685 +		$this->message = $tmp_message;
  1.1686 +		unset($tmp_message);
  1.1687 +
  1.1688 +		if (sizeof($poll['poll_options']) == 1)
  1.1689 +		{
  1.1690 +			$this->warn_msg[] = $user->lang['TOO_FEW_POLL_OPTIONS'];
  1.1691 +		}
  1.1692 +		else if ($poll['poll_options_size'] > (int) $config['max_poll_options'])
  1.1693 +		{
  1.1694 +			$this->warn_msg[] = $user->lang['TOO_MANY_POLL_OPTIONS'];
  1.1695 +		}
  1.1696 +		else if ($poll_max_options > $poll['poll_options_size'])
  1.1697 +		{
  1.1698 +			$this->warn_msg[] = $user->lang['TOO_MANY_USER_OPTIONS'];
  1.1699 +		}
  1.1700 +
  1.1701 +		$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']);
  1.1702 +	}
  1.1703 +}
  1.1704 +
  1.1705 +?>
  1.1706 \ No newline at end of file