Completed
Push — development ( 8981a4...d3a488 )
by Stephen
18s
created

PreparseCode::instance()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 0
dl 0
loc 9
ccs 6
cts 6
cp 1
crap 2
rs 9.6666
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * This class contains those functions pertaining to preparsing BBC data
5
 *
6
 * @name      ElkArte Forum
7
 * @copyright ElkArte Forum contributors
8
 * @license   BSD http://opensource.org/licenses/BSD-3-Clause
9
 *
10
 * This file contains code covered by:
11
 * copyright:    2011 Simple Machines (http://www.simplemachines.org)
12
 * license:    BSD, See included LICENSE.TXT for terms and conditions.
13
 *
14
 * @version 1.1 Release Candidate 1
15
 *
16
 */
17
18
namespace BBC;
19
20
/**
21
 * Class PreparseCode
22
 *
23
 * @package BBC
24
 */
25
class PreparseCode
26
{
27
	/** The regular expression non breaking space */
28
	const NBS = '\x{A0}';
29
	/** @var string the message to preparse */
30
	public $message = '';
31
	/** @var bool if this is just a preview */
32
	protected $previewing = false;
33
	/** @var array the code blocks that we want to protect */
34
	public $code_blocks = array();
35
	/** @var PreparseCode */
36
	public static $instance;
37
38
	/**
39
	 * PreparseCode constructor.
40
	 */
41 2
	public function __construct()
42
	{
43 2
	}
44
45
	/**
46
	 * Takes a message and parses it, returning the prepared message as a reference
47
	 * for use by parse_bbc.
48
	 *
49
	 * What it does:
50
	 *   - Cleans up links (javascript, etc.)
51
	 *   - Fixes improperly constructed lists [lists]
52
	 *   - Repairs improperly constructed tables, row, headers, etc
53
	 *   - Protects code sections
54
	 *   - Checks for proper quote open / closing
55
	 *   - Processes /me tag
56
	 *   - Converts color tags to ones parse_bbc will understand
57
	 *   - Removes empty tags outside of code blocks
58
	 *   - Won't convert \n's and a few other things if previewing is true.
59
	 *
60
	 * @param string $message
61
	 * @param boolean $previewing
62
	 */
63 3
	public function preparsecode(&$message, $previewing = false)
64
	{
65
		// Load passed values to the class
66 3
		$this->message = $message;
67 3
		$this->previewing = $previewing;
68
69
		// This line makes all languages *theoretically* work even with the wrong charset ;).
70 3
		$this->message = preg_replace('~&amp;#(\d{4,5}|[2-9]\d{2,4}|1[2-9]\d);~', '&#$1;', $this->message);
71
72
		// Clean up after nobbc ;).
73 3
		$this->message = preg_replace_callback('~\[nobbc\](.+?)\[/nobbc\]~i', array($this, '_preparsecode_nobbc_callback'), $this->message);
74
75
		// Remove \r's... they're evil!
76 3
		$this->message = strtr($this->message, array("\r" => ''));
77
78
		// You won't believe this - but too many periods upsets apache it seems!
79 3
		$this->message = preg_replace('~\.{100,}~', '...', $this->message);
80
81
		// Remove Trailing Quotes
82 3
		$this->_trimTrailingQuotes();
83
84
		// Validate code blocks are properly closed.
85 3
		$this->_validateCodeBlocks();
86
87
		// Protect CODE blocks from further processing
88 3
		$this->_tokenizeCodeBlocks();
89
90
		//  Now that we've fixed all the code tags, let's fix the img and url tags...
91 3
		$this->_fixTags();
92
93
		// Replace /me.+?\n with [me=name]dsf[/me]\n.
94 3
		$this->_itsAllAbout();
95
96
		// Make sure list and table tags are lowercase.
97 3
		$this->message = preg_replace_callback('~\[([/]?)(list|li|table|tr|td|th)((\s[^\]]+)*)\]~i', array($this, '_preparsecode_lowertags_callback'), $this->message);
98
99
		// Don't leave any lists that were never opened or closed
100 3
		$this->_validateLists();
101
102
		// Attempt to repair common BBC input mistakes
103 3
		$this->_fixMistakes();
104
105
		// Remove empty bbc tags
106 3
		$this->message = preg_replace('~\[[bisu]\]\s*\[/[bisu]\]~', '', $this->message);
107 3
		$this->message = preg_replace('~\[quote\]\s*\[/quote\]~', '', $this->message);
108
109
		// Fix color tags of many forms so they parse properly
110 3
		$this->message = preg_replace('~\[color=(?:#[\da-fA-F]{3}|#[\da-fA-F]{6}|[A-Za-z]{1,20}|rgb\(\d{1,3}, ?\d{1,3}, ?\d{1,3}\))\]\s*\[/color\]~', '', $this->message);
111
112
		// Font tags with multiple fonts (copy&paste in the WYSIWYG by some browsers).
113 3
		$this->message = preg_replace_callback('~\[font=([^\]]*)\](.*?(?:\[/font\]))~s', array($this, '_preparsecode_font_callback'), $this->message);
114
115
		// Put it back together!
116 3
		$this->_restoreCodeBlocks();
117
118
		// Allow integration to do further processing
119 3
		call_integration_hook('integrate_preparse_code', array(&$this->message, 0, $previewing));
120
121
		// Safe Spacing
122 3
		if (!$previewing)
123 3
		{
124 3
			$this->message = strtr($this->message, array('  ' => '&nbsp; ', "\n" => '<br />', "\xC2\xA0" => '&nbsp;'));
125 3
		}
126
		else
127
		{
128
			$this->message = strtr($this->message, array('  ' => '&nbsp; ', "\xC2\xA0" => '&nbsp;'));
129
		}
130
131
		// Now we're going to do full scale table checking...
132 3
		$this->_preparseTable();
133
134
		// Quickly clean up things that will slow our parser (which are common in posted code.)
135 3
		$message = strtr($this->message, array('[]' => '&#91;]', '[&#039;' => '&#91;&#039;'));
136 3
	}
137
138
	/**
139
	 * Trim dangling quotes
140
	 */
141 3
	private function _trimTrailingQuotes()
142
	{
143
		// Trim off trailing quotes - these often happen by accident.
144 3 View Code Duplication
		while (substr($this->message, -7) === '[quote]')
145
		{
146
			$this->message = trim(substr($this->message, 0, -7));
147
		}
148
149
		// Trim off leading ones as well
150 3 View Code Duplication
		while (substr($this->message, 0, 8) === '[/quote]')
151
		{
152
			$this->message = trim(substr($this->message, 8));
153
		}
154 3
	}
155
156
	/**
157
	 * Find all code blocks, work out whether we'd be parsing them,
158
	 * then ensure they are all closed.
159
	 */
160 3
	private function _validateCodeBlocks()
161
	{
162 3
		$in_tag = false;
163 3
		$had_tag = false;
164 3
		$code_open = false;
165
166 3
		if (preg_match_all('~(\[(/)*code(?:=[^\]]+)?\])~is', $this->message, $matches))
167 3
		{
168 2
			foreach ($matches[0] as $index => $dummy)
169
			{
170
				// Closing?
171 2
				if (!empty($matches[2][$index]))
172 2
				{
173
					// If it's closing and we're not in a tag we need to open it...
174 2
					if (!$in_tag)
175 2
					{
176
						$code_open = true;
177
					}
178
179
					// Either way we ain't in one any more.
180 2
					$in_tag = false;
181 2
				}
182
				// Opening tag...
183
				else
184
				{
185 2
					$had_tag = true;
186
187
					// If we're in a tag don't do nought!
188 2
					if (!$in_tag)
189 2
					{
190 2
						$in_tag = true;
191 2
					}
192
				}
193 2
			}
194 2
		}
195
196
		// If we have an open code tag, close it.
197
		if ($in_tag)
198 3
		{
199 2
			$this->message .= '[/code]';
200 2
		}
201
202
		// Open any ones that need to be open, only if we've never had a tag.
203 3
		if ($code_open && !$had_tag)
204 3
		{
205
			$this->message = '[code]' . $this->message;
206
		}
207 3
	}
208
209
	/**
210
	 * Protects code blocks from preparse by replacing them with %%token%% values
211
	 */
212 3
	private function _tokenizeCodeBlocks()
213
	{
214
		// Split up the message on the code start/end tags/
215 3
		$parts = preg_split('~(\[/code\]|\[code(?:=[^\]]+)?\])~i', $this->message, -1, PREG_SPLIT_DELIM_CAPTURE);
216
217
		// Token generator
218 3
		$tokenizer = new \Token_Hash();
219
220
		// Separate all code blocks
221 3
		for ($i = 0, $n = count($parts); $i < $n; $i++)
222
		{
223
			// It goes 0 = outside, 1 = begin tag, 2 = inside, 3 = close tag, repeat.
224 3
			if ($i % 4 === 0 && isset($parts[$i + 3]))
225 3
			{
226
				// Create a unique key to put in place of the code block
227 2
				$key = $tokenizer->generate_hash(8);
228
229
				// Save what is there [code]stuff[/code]
230 2
				$this->code_blocks['%%' . $key . '%%'] = $parts[$i + 1] . $parts[$i + 2] . $parts[$i + 3];
231
232
				// Replace the code block with %%$key%% so its protected from further preparsecode processing
233 2
				$parts[$i + 1] = '%%';
234 2
				$parts[$i + 2] = $key;
235 2
				$parts[$i + 3] = '%%';
236 2
			}
237 3
		}
238
239
		// The message with code blocks as %%tokens%%
240 3
		$this->message = implode('', $parts);
241 3
	}
242
243
	/**
244
	 * Fix any URLs posted - ie. remove 'javascript:'.
245
	 *
246
	 * - Fix the img and url tags...
247
	 * - Fixes links in message and returns nothing.
248
	 */
249 3
	private function _fixTags()
250
	{
251 3
		global $modSettings;
252
253
		// WARNING: Editing the below can cause large security holes in your forum.
254
		// Edit only if you are sure you know what you are doing.
255
256
		$fixArray = array(
257
			// [img]http://...[/img] or [img width=1]http://...[/img]
258
			array(
259 3
				'tag' => 'img',
260 3
				'protocols' => array('http', 'https'),
261 3
				'embeddedUrl' => false,
262 3
				'hasEqualSign' => false,
263 3
				'hasExtra' => true,
264 3
			),
265
			// [url]http://...[/url]
266
			array(
267 3
				'tag' => 'url',
268 3
				'protocols' => array('http', 'https'),
269 3
				'embeddedUrl' => true,
270 3
				'hasEqualSign' => false,
271 3
			),
272
			// [url=http://...]name[/url]
273
			array(
274 3
				'tag' => 'url',
275 3
				'protocols' => array('http', 'https'),
276 3
				'embeddedUrl' => true,
277 3
				'hasEqualSign' => true,
278 3
			),
279
			// [iurl]http://...[/iurl]
280
			array(
281 3
				'tag' => 'iurl',
282 3
				'protocols' => array('http', 'https'),
283 3
				'embeddedUrl' => true,
284 3
				'hasEqualSign' => false,
285 3
			),
286
			// [iurl=http://...]name[/iurl]
287
			array(
288 3
				'tag' => 'iurl',
289 3
				'protocols' => array('http', 'https'),
290 3
				'embeddedUrl' => true,
291 3
				'hasEqualSign' => true,
292 3
			),
293 3
		);
294
295
		// Integration may want to add to this array
296 3
		call_integration_hook('integrate_fixtags', array(&$fixArray, &$this->message));
297
298
		// Fix each type of tag.
299 3
		foreach ($fixArray as $param)
300
		{
301 3
			$this->_fixTag($param['tag'], $param['protocols'], $param['embeddedUrl'], $param['hasEqualSign'], !empty($param['hasExtra']));
302 3
		}
303
304
		// Now fix possible security problems with images loading links automatically...
305 3
		$this->message = preg_replace_callback('~(\[img.*?\])(.+?)\[/img\]~is', array($this, '_fixTags_img_callback'), $this->message);
306
307
		// Limit the size of images posted?
308 3
		if (!empty($modSettings['max_image_width']) || !empty($modSettings['max_image_height']))
309 3
		{
310
			$this->resizeBBCImages();
311
		}
312 3
	}
313
314
	/**
315
	 * Fix a specific class of tag - ie. url with =.
316
	 *
317
	 * - Used by fixTags, fixes a specific tag's links.
318
	 *
319
	 * @param string   $myTag - the tag
320
	 * @param string[] $protocols - http, https or ftp
321
	 * @param bool     $embeddedUrl = false - whether it *can* be set to something
322
	 * @param bool     $hasEqualSign = false, whether it *is* set to something
323
	 * @param bool     $hasExtra = false - whether it can have extra cruft after the begin tag.
324
	 */
325 3
	private function _fixTag($myTag, $protocols, $embeddedUrl = false, $hasEqualSign = false, $hasExtra = false)
326
	{
327 3
		global $boardurl, $scripturl;
328
329 3
		$replaces = array();
330
331
		// Ensure it has a domain name, use the site name if needed
332 3
		if (preg_match('~^([^:]+://[^/]+)~', $boardurl, $match) != 0)
333 3
		{
334 3
			$domain_url = $match[1];
335 3
		}
336
		else
337
		{
338
			$domain_url = $boardurl . '/';
339
		}
340
341
		if ($hasEqualSign)
342 3
		{
343 3
			preg_match_all('~\[(' . $myTag . ')=([^\]]*?)\](?:(.+?)\[/(' . $myTag . ')\])?~is', $this->message, $matches);
344 3
		}
345
		else
346
		{
347 3
			preg_match_all('~\[(' . $myTag . ($hasExtra ? '(?:[^\]]*?)' : '') . ')\](.+?)\[/(' . $myTag . ')\]~is', $this->message, $matches);
348
		}
349
350 3
		foreach ($matches[0] as $k => $dummy)
351
		{
352
			// Remove all leading and trailing whitespace.
353 1
			$replace = trim($matches[2][$k]);
354 1
			$this_tag = $matches[1][$k];
355 1
			$this_close = $hasEqualSign ? (empty($matches[4][$k]) ? '' : $matches[4][$k]) : $matches[3][$k];
356
357 1
			$found = false;
358 1
			foreach ($protocols as $protocol)
359
			{
360 1
				$found = strncasecmp($replace, $protocol . '://', strlen($protocol) + 3) === 0;
361
				if ($found)
362 1
				{
363 1
					break;
364
				}
365 1
			}
366
367
			// Http url checking?
368 1
			if (!$found && $protocols[0] === 'http')
369 1
			{
370 1
				if (substr($replace, 0, 1) === '/' && substr($replace, 0, 2) !== '//')
371 1
				{
372
					$replace = $domain_url . $replace;
373
				}
374 1
				elseif (substr($replace, 0, 1) === '?')
375
				{
376
					$replace = $scripturl . $replace;
377
				}
378 1
				elseif (substr($replace, 0, 1) === '#' && $embeddedUrl)
379
				{
380
					$replace = '#' . preg_replace('~[^A-Za-z0-9_\-#]~', '', substr($replace, 1));
381
					$this_tag = 'iurl';
382
					$this_close = 'iurl';
383
				}
384 1
				elseif (substr($replace, 0, 2) === '//')
385
				{
386 1
					$replace = $protocols[0] . ':' . $replace;
387 1
				}
388
				else
389
				{
390 1
					$replace = $protocols[0] . '://' . $replace;
391
				}
392 1
			}
393
			// FTP URL Checking
394 1
			elseif (!$found && $protocols[0] === 'ftp')
395
			{
396
				$replace = $protocols[0] . '://' . preg_replace('~^(?!ftps?)[^:]+://~', '', $replace);
397
			}
398 1
			elseif (!$found)
399
			{
400
				$replace = $protocols[0] . '://' . $replace;
401
			}
402
403
			// Build a replacement array that is considered safe and proper
404 1
			if ($hasEqualSign && $embeddedUrl)
405 1
			{
406 1
				$replaces[$matches[0][$k]] = '[' . $this_tag . '=' . $replace . ']' . (empty($matches[4][$k]) ? '' : $matches[3][$k] . '[/' . $this_close . ']');
407 1
			}
408 1
			elseif ($hasEqualSign)
409
			{
410
				$replaces['[' . $matches[1][$k] . '=' . $matches[2][$k] . ']'] = '[' . $this_tag . '=' . $replace . ']';
411
			}
412 1
			elseif ($embeddedUrl)
413
			{
414 1
				$replaces['[' . $matches[1][$k] . ']' . $matches[2][$k] . '[/' . $matches[3][$k] . ']'] = '[' . $this_tag . '=' . $replace . ']' . $matches[2][$k] . '[/' . $this_close . ']';
415 1
			}
416
			else
417
			{
418
				$replaces['[' . $matches[1][$k] . ']' . $matches[2][$k] . '[/' . $matches[3][$k] . ']'] = '[' . $this_tag . ']' . $replace . '[/' . $this_close . ']';
419
			}
420 3
		}
421
422 3
		foreach ($replaces as $k => $v)
423
		{
424 1
			if ($k == $v)
425 1
			{
426 1
				unset($replaces[$k]);
427 1
			}
428 3
		}
429
430
		// Update as needed
431 3
		if (!empty($replaces))
432 3
		{
433 1
			$this->message = strtr($this->message, $replaces);
434 1
		}
435 3
	}
436
437
	/**
438
	 * Updates BBC img tags in a message so that the width / height respect the forum settings.
439
	 *
440
	 * - Will add the width/height attrib if needed, or update existing ones if they break the rules
441
	 */
442
	public function resizeBBCImages()
443
	{
444
		global $modSettings;
445
446
		// We'll need this for image processing
447
		require_once(SUBSDIR . '/Attachments.subs.php');
448
449
		// Find all the img tags - with or without width and height.
450
		preg_match_all('~\[img(\s+width=\d+)?(\s+height=\d+)?(\s+width=\d+)?\](.+?)\[/img\]~is', $this->message, $matches, PREG_PATTERN_ORDER);
451
452
		$replaces = array();
453
		foreach ($matches[0] as $match => $dummy)
454
		{
455
			// If the width was after the height, handle it.
456
			$matches[1][$match] = !empty($matches[3][$match]) ? $matches[3][$match] : $matches[1][$match];
457
458
			// Now figure out if they had a desired height or width...
459
			$desired_width = !empty($matches[1][$match]) ? (int) substr(trim($matches[1][$match]), 6) : 0;
460
			$desired_height = !empty($matches[2][$match]) ? (int) substr(trim($matches[2][$match]), 7) : 0;
461
462
			// One was omitted, or both.  We'll have to find its real size...
463
			if (empty($desired_width) || empty($desired_height))
464
			{
465
				list ($width, $height) = url_image_size(un_htmlspecialchars($matches[4][$match]));
466
467
				// They don't have any desired width or height!
468
				if (empty($desired_width) && empty($desired_height))
469
				{
470
					$desired_width = $width;
471
					$desired_height = $height;
472
				}
473
				// Scale it to the width...
474
				elseif (empty($desired_width) && !empty($height))
475
				{
476
					$desired_width = (int) (($desired_height * $width) / $height);
477
				}
478
				// Scale if to the height.
479
				elseif (!empty($width))
480
				{
481
					$desired_height = (int) (($desired_width * $height) / $width);
482
				}
483
			}
484
485
			// If the width and height are fine, just continue along...
486
			if ($desired_width <= $modSettings['max_image_width'] && $desired_height <= $modSettings['max_image_height'])
487
			{
488
				continue;
489
			}
490
491
			// Too bad, it's too wide.  Make it as wide as the maximum.
492 View Code Duplication
			if ($desired_width > $modSettings['max_image_width'] && !empty($modSettings['max_image_width']))
493
			{
494
				$desired_height = (int) (($modSettings['max_image_width'] * $desired_height) / $desired_width);
495
				$desired_width = $modSettings['max_image_width'];
496
			}
497
498
			// Now check the height, as well.  Might have to scale twice, even...
499 View Code Duplication
			if ($desired_height > $modSettings['max_image_height'] && !empty($modSettings['max_image_height']))
500
			{
501
				$desired_width = (int) (($modSettings['max_image_height'] * $desired_width) / $desired_height);
502
				$desired_height = $modSettings['max_image_height'];
503
			}
504
505
			$replaces[$matches[0][$match]] = '[img' . (!empty($desired_width) ? ' width=' . $desired_width : '') . (!empty($desired_height) ? ' height=' . $desired_height : '') . ']' . $matches[4][$match] . '[/img]';
506
		}
507
508
		// If any img tags were actually changed...
509
		if (!empty($replaces))
510
		{
511
			$this->message = strtr($this->message, $replaces);
512
		}
513
	}
514
515
	/**
516
	 * Replace /me with the users name, including inside footnotes
517
	 */
518 3
	private function _itsAllAbout()
519
	{
520 3
		global $user_info;
521
522 3
		$me_regex = '~(\A|\n)/me(?: |&nbsp;)([^\n]*)(?:\z)?~i';
523 3
		$footnote_regex = '~(\[footnote\])/me(?: |&nbsp;)([^\n]*?)(\[\/footnote\])~i';
524
525 3
		if (preg_match('~[\[\]\\"]~', $user_info['name']) !== false)
526 3
		{
527 3
			$this->message = preg_replace($me_regex, '$1[me=&quot;' . $user_info['name'] . '&quot;]$2[/me]', $this->message);
528 3
			$this->message = preg_replace($footnote_regex, '$1[me=&quot;' . $user_info['name'] . '&quot;]$2[/me]$3', $this->message);
529 3
		}
530
		else
531
		{
532
			$this->message = preg_replace($me_regex, '$1[me=' . $user_info['name'] . ']$2[/me]', $this->message);
533
			$this->message = preg_replace($footnote_regex, '$1[me=' . $user_info['name'] . ']$2[/me]$3', $this->message);
534
		}
535 3
	}
536
537
	/**
538
	 * Make sure lists have open and close tags
539
	 */
540 3
	private function _validateLists()
541
	{
542 3
		$list_open = substr_count($this->message, '[list]') + substr_count($this->message, '[list ');
543 3
		$list_close = substr_count($this->message, '[/list]');
544
545 3 View Code Duplication
		if ($list_close - $list_open > 0)
546 3
		{
547
			$this->message = str_repeat('[list]', $list_close - $list_open) . $this->message;
548
		}
549
550 3 View Code Duplication
		if ($list_open - $list_close > 0)
551 3
		{
552
			$this->message = $this->message . str_repeat('[/list]', $list_open - $list_close);
553
		}
554 3
	}
555
556
	/**
557
	 * Repair a few *cough* common mistakes from user input and from wizzy cut/paste
558
	 */
559 3
	private function _fixMistakes()
560
	{
561
		$mistake_fixes = array(
562
			// Find [table]s not followed by [tr].
563 3
			'~\[table\](?![\s' . self::NBS . ']*\[tr\])~su' => '[table][tr]',
564
			// Find [tr]s not followed by [td] or [th]
565 3
			'~\[tr\](?![\s' . self::NBS . ']*\[t[dh]\])~su' => '[tr][td]',
566
			// Find [/td] and [/th]s not followed by something valid.
567 3
			'~\[/t([dh])\](?![\s' . self::NBS . ']*(?:\[t[dh]\]|\[/tr\]|\[/table\]))~su' => '[/t$1][/tr]',
568
			// Find [/tr]s not followed by something valid.
569 3
			'~\[/tr\](?![\s' . self::NBS . ']*(?:\[tr\]|\[/table\]))~su' => '[/tr][/table]',
570
			// Find [/td] [/th]s incorrectly followed by [/table].
571 3
			'~\[/t([dh])\][\s' . self::NBS . ']*\[/table\]~su' => '[/t$1][/tr][/table]',
572
			// Find [table]s, [tr]s, and [/td]s (possibly correctly) followed by [td].
573 3
			'~\[(table|tr|/td)\]([\s' . self::NBS . ']*)\[td\]~su' => '[$1]$2[_td_]',
574
			// Now, any [td]s left should have a [tr] before them.
575 3
			'~\[td\]~s' => '[tr][td]',
576
			// Look for [tr]s which are correctly placed.
577 3
			'~\[(table|/tr)\]([\s' . self::NBS . ']*)\[tr\]~su' => '[$1]$2[_tr_]',
578
			// Any remaining [tr]s should have a [table] before them.
579 3
			'~\[tr\]~s' => '[table][tr]',
580
			// Look for [/td]s or [/th]s followed by [/tr].
581 3
			'~\[/t([dh])\]([\s' . self::NBS . ']*)\[/tr\]~su' => '[/t$1]$2[_/tr_]',
582
			// Any remaining [/tr]s should have a [/td].
583 3
			'~\[/tr\]~s' => '[/td][/tr]',
584
			// Look for properly opened [li]s which aren't closed.
585 3
			'~\[li\]([^\[\]]+?)\[li\]~s' => '[li]$1[_/li_][_li_]',
586 3
			'~\[li\]([^\[\]]+?)\[/list\]~s' => '[_li_]$1[_/li_][/list]',
587 3
			'~\[li\]([^\[\]]+?)$~s' => '[li]$1[/li]',
588
			// Lists - find correctly closed items/lists.
589 3
			'~\[/li\]([\s' . self::NBS . ']*)\[/list\]~su' => '[_/li_]$1[/list]',
590
			// Find list items closed and then opened.
591 3
			'~\[/li\]([\s' . self::NBS . ']*)\[li\]~su' => '[_/li_]$1[_li_]',
592
			// Now, find any [list]s or [/li]s followed by [li].
593 3
			'~\[(list(?: [^\]]*?)?|/li)\]([\s' . self::NBS . ']*)\[li\]~su' => '[$1]$2[_li_]',
594
			// Allow for sub lists.
595 3
			'~\[/li\]([\s' . self::NBS . ']*)\[list\]~u' => '[_/li_]$1[list]',
596 3
			'~\[/list\]([\s' . self::NBS . ']*)\[li\]~u' => '[/list]$1[_li_]',
597
			// Any remaining [li]s weren't inside a [list].
598 3
			'~\[li\]~' => '[list][li]',
599
			// Any remaining [/li]s weren't before a [/list].
600 3
			'~\[/li\]~' => '[/li][/list]',
601
			// Put the correct ones back how we found them.
602 3
			'~\[_(li|/li|td|tr|/tr)_\]~' => '[$1]',
603
			// Images with no real url.
604 3
			'~\[img\]https?://.{0,7}\[/img\]~' => '',
605 3
		);
606
607
		// Fix up some use of tables without [tr]s, etc. (it has to be done more than once to catch it all.)
608 3
		for ($j = 0; $j < 3; $j++)
609
		{
610 3
			$this->message = preg_replace(array_keys($mistake_fixes), $mistake_fixes, $this->message);
611 3
		}
612 3
	}
613
614
	/**
615
	 * Replace our token-ized message with the saved code blocks
616
	 */
617 3
	private function _restoreCodeBlocks()
618
	{
619 3
		if (!empty($this->code_blocks))
620 3
		{
621 2
			$this->message = str_replace(array_keys($this->code_blocks), array_values($this->code_blocks), $this->message);
622 2
		}
623 3
	}
624
625
	/**
626
	 * Validates and corrects table structure
627
	 *
628
	 * What it does
629
	 *   - Checks tables for correct tag order / nesting
630
	 *   - Adds in missing closing tags, removes excess closing tags
631
	 *   - Although it prevents markup error, it can mess-up the intended (abiet wrong) layout
632
	 * driving the post author in to a furious rage
633
	 *
634
	 */
635 3
	private function _preparseTable()
636
	{
637 3
		$table_check = $this->message;
638 3
		$table_offset = 0;
639 3
		$table_array = array();
640
641
		// Define the allowable tags after a give tag
642
		$table_order = array(
643 3
			'table' => array('tr'),
644 3
			'tr' => array('td', 'th'),
645 3
			'td' => array('table'),
646 3
			'th' => array(''),
647 3
		);
648
649
		// Find all closing tags (/table /tr /td etc)
650 3
		while (preg_match('~\[(/)*(table|tr|td|th)\]~', $table_check, $matches) === 1)
651
		{
652
			// Keep track of where this is.
653 1
			$offset = strpos($table_check, $matches[0]);
654 1
			$remove_tag = false;
655
656
			// Is it opening?
657 1
			if ($matches[1] != '/')
658 1
			{
659
				// If the previous table tag isn't correct simply remove it.
660 1
				if ((!empty($table_array) && !in_array($matches[2], $table_order[$table_array[0]])) || (empty($table_array) && $matches[2] !== 'table'))
661 1
				{
662
					$remove_tag = true;
663
				}
664
				// Record this was the last tag.
665
				else
666
				{
667 1
					array_unshift($table_array, $matches[2]);
668
				}
669 1
			}
670
			// Otherwise is closed!
671
			else
672
			{
673
				// Only keep the tag if it's closing the right thing.
674 1
				if (empty($table_array) || ($table_array[0] != $matches[2]))
675 1
				{
676
					$remove_tag = true;
677
				}
678
				else
679
				{
680 1
					array_shift($table_array);
681
				}
682
			}
683
684
			// Removing?
685
			if ($remove_tag)
686 1
			{
687
				$this->message = substr($this->message, 0, $table_offset + $offset) . substr($this->message, $table_offset + strlen($matches[0]) + $offset);
688
689
				// We've lost some data.
690
				$table_offset -= strlen($matches[0]);
691
			}
692
693
			// Remove everything up to here.
694 1
			$table_offset += $offset + strlen($matches[0]);
695 1
			$table_check = substr($table_check, $offset + strlen($matches[0]));
696 1
		}
697
698
		// Close any remaining table tags.
699 3
		foreach ($table_array as $tag)
700
		{
701
			$this->message .= '[/' . $tag . ']';
702 3
		}
703 3
	}
704
705
	/**
706
	 * This is very simple, and just removes things done by preparsecode.
707
	 *
708
	 * @param string $message
709
	 */
710
	public function un_preparsecode($message)
711
	{
712
		// Protect CODE blocks from further processing
713
		$this->message = $message;
714
		$this->_tokenizeCodeBlocks();
715
716
		// Pass integration the tokenized message and array
717
		call_integration_hook('integrate_unpreparse_code', array(&$this->message, &$this->code_blocks, 0));
718
719
		// Restore the code blocks
720
		$this->_restoreCodeBlocks();
721
722
		// Change breaks back to \n's and &nsbp; back to spaces.
723
		return preg_replace('~<br( /)?' . '>~', "\n", str_replace('&nbsp;', ' ', $this->message));
724
	}
725
726
	/**
727
	 * Ensure tags inside of nobbc do not get parsed by converting the markers to html entities
728
	 *
729
	 * @param string[] $matches
730
	 */
731
	private function _preparsecode_nobbc_callback($matches)
732
	{
733
		return '[nobbc]' . strtr($matches[1], array('[' => '&#91;', ']' => '&#93;', ':' => '&#58;', '@' => '&#64;')) . '[/nobbc]';
734
	}
735
736
	/**
737
	 * Use only the primary (first) font face when multiple are supplied
738
	 *
739
	 * @param string[] $matches
740
	 */
741 2
	private function _preparsecode_font_callback($matches)
742
	{
743 2
		$fonts = explode(',', $matches[1]);
744 2
		$font = trim(un_htmlspecialchars($fonts[0]), ' "\'');
745
746 2
		return '[font=' . $font . ']' . $matches[2];
747
	}
748
749
	/**
750
	 * Takes a tag and changes it to lowercase
751
	 *
752
	 * @param string[] $matches
753
	 */
754 2
	private function _preparsecode_lowertags_callback($matches)
755
	{
756 2
		return '[' . $matches[1] . strtolower($matches[2]) . $matches[3] . ']';
757
	}
758
759
	/**
760
	 * Ensure image tags do not load anything by themselves (security)
761
	 *
762
	 * @param string[] $matches
763
	 */
764
	private function _fixTags_img_callback($matches)
765
	{
766
		return $matches[1] . preg_replace('~action(=|%3d)(?!dlattach)~i', 'action-', $matches[2]) . '[/img]';
767
	}
768
769
	/**
770
	 * Find and return PreparseCode instance if it exists,
771
	 * or create a new instance
772
	 *
773
	 * @return PreparseCode
774
	 */
775 2
	public static function instance()
776
	{
777 2
		if (self::$instance === null)
778 2
		{
779 1
			self::$instance = new PreparseCode;
780 1
		}
781
782 2
		return self::$instance;
783
	}
784
}
785