aboutsummaryrefslogtreecommitdiff
path: root/engine/classes/ElggAutoP.php
blob: 40600aa1339e21ddf0ea4d00c041d1cf94d9770d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
<?php

/**
 * Create wrapper P and BR elements in HTML depending on newlines. Useful when
 * users use newlines to signal line and paragraph breaks. In all cases output
 * should be well-formed markup.
 *
 * In DIV elements, Ps are only added when there would be at
 * least two of them.
 */
class ElggAutoP {

	public $encoding = 'UTF-8';

	/**
	 * @var DOMDocument
	 */
	protected $_doc = null;

	/**
	 * @var DOMXPath
	 */
	protected $_xpath = null;

	protected $_blocks = 'address article area aside blockquote caption col colgroup dd 
		details div dl dt fieldset figure figcaption footer form h1 h2 h3 h4 h5 h6 header 
		hr hgroup legend map math menu nav noscript p pre section select style summary
		table tbody td tfoot th thead tr ul ol option li';

	/**
	 * @var array
	 */
	protected $_inlines = 'a abbr audio b button canvas caption cite code command datalist
		del dfn em embed i iframe img input ins kbd keygen label map mark meter object
		output progress q rp rt ruby s samp script select small source span strong style
		sub sup textarea time var video wbr';

	/**
	 * Descend into these elements to add Ps
	 *
	 * @var array
	 */
	protected $_descendList = 'article aside blockquote body details div footer form
		header section';

	/**
	 * Add Ps inside these elements
	 *
	 * @var array
	 */
	protected $_alterList = 'article aside blockquote body details div footer header
		section';

	protected $_unique = '';

	public function __construct() {
		$this->_blocks = preg_split('@\\s+@', $this->_blocks);
		$this->_descendList = preg_split('@\\s+@', $this->_descendList);
		$this->_alterList = preg_split('@\\s+@', $this->_alterList);
		$this->_inlines = preg_split('@\\s+@', $this->_inlines);
		$this->_unique = md5(__FILE__);
	}

	/**
	 * Intance of class for singleton pattern.
	 * @var ElggAutoP
	 */
	private static $instance;
	
	/**
	 * Singleton pattern.
	 * @return ElggAutoP
	 */
	public static function getInstance() {
		$className = __CLASS__;
		if (!(self::$instance instanceof $className)) {
			self::$instance = new $className();
		}
		return self::$instance;
	}
	
	/**
	 * Create wrapper P and BR elements in HTML depending on newlines. Useful when
	 * users use newlines to signal line and paragraph breaks. In all cases output
	 * should be well-formed markup.
	 *
	 * In DIV, LI, TD, and TH elements, Ps are only added when their would be at
	 * least two of them.
	 *
	 * @param string $html snippet
	 * @return string|false output or false if parse error occurred
	 */
	public function process($html) {
		// normalize whitespace
		$html = str_replace(array("\r\n", "\r"), "\n", $html);

		// allows preserving entities untouched
		$html = str_replace('&', $this->_unique . 'AMP', $html);

		$this->_doc = new DOMDocument();
	   
		// parse to DOM, suppressing loadHTML warnings
		// http://www.php.net/manual/en/domdocument.loadhtml.php#95463
		libxml_use_internal_errors(true);

		if (!$this->_doc->loadHTML("<html><meta http-equiv='content-type' " 
				. "content='text/html; charset={$this->encoding}'><body>{$html}</body>"
				. "</html>")) {
			return false;
		}

		$this->_xpath = new DOMXPath($this->_doc);
		// start processing recursively at the BODY element
		$nodeList = $this->_xpath->query('//body[1]');
		$this->_addParagraphs($nodeList->item(0));

		// serialize back to HTML
		$html = $this->_doc->saveHTML();

		// Note: we create <autop> elements, which will later be converted to paragraphs

		// split AUTOPs into multiples at /\n\n+/
		$html = preg_replace('/(' . $this->_unique . 'NL){2,}/', '</autop><autop>', $html);
		$html = str_replace(array($this->_unique . 'BR', $this->_unique . 'NL', '<br>'), 
				'<br />',
				$html);
		$html = str_replace('<br /></autop>', '</autop>', $html);

		// re-parse so we can handle new AUTOP elements

		if (!$this->_doc->loadHTML($html)) {
			return false;
		}
		// must re-create XPath object after DOM load
		$this->_xpath = new DOMXPath($this->_doc);

		// strip AUTOPs that only have comments/whitespace
		foreach ($this->_xpath->query('//autop') as $autop) {
			/* @var DOMElement $autop */
			$hasContent = false;
			if (trim($autop->textContent) !== '') {
				$hasContent = true;
			} else {
				foreach ($autop->childNodes as $node) {
					if ($node->nodeType === XML_ELEMENT_NODE) {
						$hasContent = true;
						break;
					}
				}
			}
			if (!$hasContent) {
				// mark to be later replaced w/ preg_replace (faster than moving nodes out)
				$autop->setAttribute("r", "1");
			}
		}

		// If a DIV contains a single AUTOP, remove it
		foreach ($this->_xpath->query('//div') as $el) {
			/* @var DOMElement $el */
			$autops = $this->_xpath->query('./autop', $el);
			if ($autops->length === 1) {
				// strip w/ preg_replace later (faster than moving nodes out)
				$autops->item(0)->setAttribute("r", "1");
			}
		}

		$html = $this->_doc->saveHTML();

		// trim to the contents of BODY
		$bodyStart = strpos($html, '<body>');
		$bodyEnd = strpos($html, '</body>', $bodyStart + 6);
		$html = substr($html, $bodyStart + 6, $bodyEnd - $bodyStart - 6);
		
		// strip AUTOPs that should be removed
		$html = preg_replace('@<autop r="1">(.*?)</autop>@', '\\1', $html);

		// commit to converting AUTOPs to Ps
		$html = str_replace('<autop>', "\n<p>", $html);
		$html = str_replace('</autop>', "</p>\n", $html);
		
		$html = str_replace('<br>', '<br />', $html);
		$html = str_replace($this->_unique . 'AMP', '&', $html);
		return $html;
	}

	/**
	 * Add P and BR elements as necessary
	 *
	 * @param DOMElement $el
	 */
	protected function _addParagraphs(DOMElement $el) {
		// no need to call recursively, just queue up
		$elsToProcess = array($el);
		$inlinesToProcess = array();
		while ($el = array_shift($elsToProcess)) {
			// if true, we can alter all child nodes, if not, we'll just call
			// _addParagraphs on each element in the descendInto list
			$alterInline = in_array($el->nodeName, $this->_alterList);

			// inside affected elements, we want to trim leading whitespace from
			// the first text node
			$ltrimFirstTextNode = true;

			// should we open a new AUTOP element to move inline elements into?
			$openP = true;
			$autop = null;

			// after BR, ignore a newline
			$isFollowingBr = false;

			$node = $el->firstChild;
			while (null !== $node) {
				if ($alterInline) {
					if ($openP) {
						$openP = false;
						// create a P to move inline content into (this may be removed later)
						$autop = $el->insertBefore($this->_doc->createElement('autop'), $node);
					}
				}

				$isElement = ($node->nodeType === XML_ELEMENT_NODE);
				if ($isElement) {
					$elName = $node->nodeName;
				}
				$isBlock = ($isElement && in_array($elName, $this->_blocks));

				if ($alterInline) {
					$isInline = $isElement && ! $isBlock;
					$isText = ($node->nodeType === XML_TEXT_NODE);
					$isLastInline = (! $node->nextSibling
								   || ($node->nextSibling->nodeType === XML_ELEMENT_NODE
									   && in_array($node->nextSibling->nodeName, $this->_blocks)));
					if ($isElement) {
						$isFollowingBr = ($node->nodeName === 'br');
					}

					if ($isText) {
						$nodeText = $node->nodeValue;
						if ($ltrimFirstTextNode) {
							$nodeText = ltrim($nodeText);
							$ltrimFirstTextNode = false;
						}
						if ($isFollowingBr && preg_match('@^[ \\t]*\\n[ \\t]*@', $nodeText, $m)) {
							// if a user ends a line with <br>, don't add a second BR
							$nodeText = substr($nodeText, strlen($m[0]));
						}
						if ($isLastInline) {
							$nodeText = rtrim($nodeText);
						}
						$nodeText = str_replace("\n", $this->_unique . 'NL', $nodeText);
						$tmpNode = $node;
						$node = $node->nextSibling; // move loop to next node

						// alter node in place, then move into AUTOP
						$tmpNode->nodeValue = $nodeText;
						$autop->appendChild($tmpNode);

						continue;
					}
				}
				if ($isBlock || ! $node->nextSibling) {
					if ($isBlock) {
						if (in_array($node->nodeName, $this->_descendList)) {
							$elsToProcess[] = $node;
							//$this->_addParagraphs($node);
						}
					}
					$openP = true;
					$ltrimFirstTextNode = true;
				}
				if ($alterInline) {
					if (! $isBlock) {
						$tmpNode = $node;
						if ($isElement && false !== strpos($tmpNode->textContent, "\n")) {
							$inlinesToProcess[] = $tmpNode;
						}
						$node = $node->nextSibling;
						$autop->appendChild($tmpNode);
						continue;
					}
				}

				$node = $node->nextSibling;
			}
		}

		// handle inline nodes
		// no need to recurse, just queue up
		while ($el = array_shift($inlinesToProcess)) {
			$ignoreLeadingNewline = false;
			foreach ($el->childNodes as $node) {
				if ($node->nodeType === XML_ELEMENT_NODE) {
					if ($node->nodeValue === 'BR') {
						$ignoreLeadingNewline = true;
					} else {
						$ignoreLeadingNewline = false;
						if (false !== strpos($node->textContent, "\n")) {
							$inlinesToProcess[] = $node;
						}
					}
					continue;
				} elseif ($node->nodeType === XML_TEXT_NODE) {
					$text = $node->nodeValue;
					if ($text[0] === "\n" && $ignoreLeadingNewline) {
						$text = substr($text, 1);
						$ignoreLeadingNewline = false;
					}
					$node->nodeValue = str_replace("\n", $this->_unique . 'BR', $text);
				}
			}
		}
	}
}