Fix doc for HtmlFormatter
[lhc/web/wiklou.git] / includes / HtmlFormatter.php
1 <?php
2 /**
3 * Performs transformations of HTML by wrapping around libxml2 and working
4 * around its countless bugs.
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19 * http://www.gnu.org/copyleft/gpl.html
20 *
21 * @file
22 */
23 class HtmlFormatter {
24 /**
25 * @var DOMDocument
26 */
27 private $doc;
28
29 private $html;
30 private $itemsToRemove = array();
31 private $elementsToFlatten = array();
32 protected $removeMedia = false;
33
34 /**
35 * Constructor
36 *
37 * @param string $html: Text to process
38 */
39 public function __construct( $html ) {
40 $this->html = $html;
41 }
42
43 /**
44 * Turns a chunk of HTML into a proper document
45 * @param string $html
46 * @return string
47 */
48 public static function wrapHTML( $html ) {
49 return '<!doctype html><html><head></head><body>' . $html . '</body></html>';
50 }
51
52 /**
53 * Override this in descendant class to modify HTML after it has been converted from DOM tree
54 * @param string $html: HTML to process
55 * @return string: Processed HTML
56 */
57 protected function onHtmlReady( $html ) {
58 return $html;
59 }
60
61 /**
62 * @return DOMDocument: DOM to manipulate
63 */
64 public function getDoc() {
65 if ( !$this->doc ) {
66 $html = mb_convert_encoding( $this->html, 'HTML-ENTITIES', 'UTF-8' );
67
68 // Workaround for bug that caused spaces before references
69 // to disappear during processing:
70 // https://bugzilla.wikimedia.org/show_bug.cgi?id=53086
71 //
72 // Please replace with a better fix if one can be found.
73 $html = str_replace( ' <', '&#32;<', $html );
74
75 libxml_use_internal_errors( true );
76 $this->doc = new DOMDocument();
77 $this->doc->strictErrorChecking = false;
78 $this->doc->loadHTML( $html );
79 libxml_use_internal_errors( false );
80 $this->doc->encoding = 'UTF-8';
81 }
82 return $this->doc;
83 }
84
85 /**
86 * Sets whether images/videos/sounds should be removed from output
87 * @param bool $flag
88 */
89 public function setRemoveMedia( $flag = true ) {
90 $this->removeMedia = $flag;
91 }
92
93 /**
94 * Adds one or more selector of content to remove. A subset of CSS selector
95 * syntax is supported:
96 *
97 * <tag>
98 * <tag>.class
99 * .<class>
100 * #<id>
101 *
102 * @param Array|string $selectors: Selector(s) of stuff to remove
103 */
104 public function remove( $selectors ) {
105 $this->itemsToRemove = array_merge( $this->itemsToRemove, (array)$selectors );
106 }
107
108 /**
109 * Adds one or more element name to the list to flatten (remove tag, but not its content)
110 * Can accept undelimited regexes
111 *
112 * Note this interface may fail in surprising unexpected ways due to usage of regexes,
113 * so should not be relied on for HTML markup security measures.
114 *
115 * @param Array|string $elements: Name(s) of tag(s) to flatten
116 */
117 public function flatten( $elements ) {
118 $this->elementsToFlatten = array_merge( $this->elementsToFlatten, (array)$elements );
119 }
120
121 /**
122 * Instructs the formatter to flatten all tags
123 */
124 public function flattenAllTags() {
125 $this->flatten( '[?!]?[a-z0-9]+' );
126 }
127
128 /**
129 * Removes content we've chosen to remove
130 */
131 public function filterContent() {
132 wfProfileIn( __METHOD__ );
133 $removals = $this->parseItemsToRemove();
134
135 if ( !$removals ) {
136 return;
137 }
138
139 $doc = $this->getDoc();
140
141 // Remove tags
142
143 // You can't remove DOMNodes from a DOMNodeList as you're iterating
144 // over them in a foreach loop. It will seemingly leave the internal
145 // iterator on the foreach out of wack and results will be quite
146 // strange. Though, making a queue of items to remove seems to work.
147 $domElemsToRemove = array();
148 foreach ( $removals['TAG'] as $tagToRemove ) {
149 $tagToRemoveNodes = $doc->getElementsByTagName( $tagToRemove );
150 foreach ( $tagToRemoveNodes as $tagToRemoveNode ) {
151 if ( $tagToRemoveNode ) {
152 $domElemsToRemove[] = $tagToRemoveNode;
153 }
154 }
155 }
156
157 $this->removeElements( $domElemsToRemove );
158
159 // Elements with named IDs
160 $domElemsToRemove = array();
161 foreach ( $removals['ID'] as $itemToRemove ) {
162 $itemToRemoveNode = $doc->getElementById( $itemToRemove );
163 if ( $itemToRemoveNode ) {
164 $domElemsToRemove[] = $itemToRemoveNode;
165 }
166 }
167 $this->removeElements( $domElemsToRemove );
168
169 // CSS Classes
170 $domElemsToRemove = array();
171 $xpath = new DOMXpath( $doc );
172 foreach ( $removals['CLASS'] as $classToRemove ) {
173 $elements = $xpath->query( '//*[contains(@class, "' . $classToRemove . '")]' );
174
175 /** @var $element DOMElement */
176 foreach ( $elements as $element ) {
177 $classes = $element->getAttribute( 'class' );
178 if ( preg_match( "/\b$classToRemove\b/", $classes ) && $element->parentNode ) {
179 $domElemsToRemove[] = $element;
180 }
181 }
182 }
183 $this->removeElements( $domElemsToRemove );
184
185 // Tags with CSS Classes
186 foreach ( $removals['TAG_CLASS'] as $classToRemove ) {
187 $parts = explode( '.', $classToRemove );
188
189 $elements = $xpath->query(
190 '//' . $parts[0] . '[@class="' . $parts[1] . '"]'
191 );
192
193 $this->removeElements( $elements );
194 }
195
196 wfProfileOut( __METHOD__ );
197 }
198
199 /**
200 * Removes a list of elelments from DOMDocument
201 * @param array|DOMNodeList $elements
202 */
203 private function removeElements( $elements ) {
204 $list = $elements;
205 if ( $elements instanceof DOMNodeList ) {
206 $list = array();
207 foreach ( $elements as $element ) {
208 $list[] = $element;
209 }
210 }
211 /** @var $element DOMElement */
212 foreach ( $list as $element ) {
213 if ( $element->parentNode ) {
214 $element->parentNode->removeChild( $element );
215 }
216 }
217 }
218
219 /**
220 * libxml in its usual pointlessness converts many chars to entities - this function
221 * perfoms a reverse conversion
222 * @param string $html
223 * @return string
224 */
225 private function fixLibXML( $html ) {
226 wfProfileIn( __METHOD__ );
227 static $replacements;
228 if ( ! $replacements ) {
229 // We don't include rules like '&#34;' => '&amp;quot;' because entities had already been
230 // normalized by libxml. Using this function with input not sanitized by libxml is UNSAFE!
231 $replacements = new ReplacementArray( array(
232 '&quot;' => '&amp;quot;',
233 '&amp;' => '&amp;amp;',
234 '&lt;' => '&amp;lt;',
235 '&gt;' => '&amp;gt;',
236 ) );
237 }
238 $html = $replacements->replace( $html );
239 $html = mb_convert_encoding( $html, 'UTF-8', 'HTML-ENTITIES' );
240 wfProfileOut( __METHOD__ );
241 return $html;
242 }
243
244 /**
245 * Performs final transformations and returns resulting HTML
246 *
247 * @param DOMElement|string|null $element: ID of element to get HTML from or false to get it from the whole tree
248 * @return string: Processed HTML
249 */
250 public function getText( $element = null ) {
251 wfProfileIn( __METHOD__ );
252
253 if ( $this->doc ) {
254 if ( $element !== null && !( $element instanceof DOMElement ) ) {
255 $element = $this->doc->getElementById( $element );
256 }
257 if ( $element ) {
258 $body = $this->doc->getElementsByTagName( 'body' )->item( 0 );
259 $nodesArray = array();
260 foreach ( $body->childNodes as $node ) {
261 $nodesArray[] = $node;
262 }
263 foreach ( $nodesArray as $nodeArray ) {
264 $body->removeChild( $nodeArray );
265 }
266 $body->appendChild( $element );
267 }
268 $html = $this->doc->saveHTML();
269 $html = $this->fixLibXml( $html );
270 } else {
271 $html = $this->html;
272 }
273 if ( wfIsWindows() ) {
274 // Appears to be cleanup for CRLF misprocessing of unknown origin
275 // when running server on Windows platform.
276 //
277 // If this error continues in the future, please track it down in the
278 // XML code paths if possible and fix there.
279 $html = str_replace( '&#13;', '', $html );
280 }
281 $html = preg_replace( '/<!--.*?-->|^.*?<body>|<\/body>.*$/s', '', $html );
282 $html = $this->onHtmlReady( $html );
283
284 if ( $this->elementsToFlatten ) {
285 $elements = implode( '|', $this->elementsToFlatten );
286 $html = preg_replace( "#</?($elements)\\b[^>]*>#is", '', $html );
287 }
288
289 wfProfileOut( __METHOD__ );
290 return $html;
291 }
292
293 /**
294 * @param $selector: CSS selector to parse
295 * @param $type
296 * @param $rawName
297 * @return bool: Whether the selector was successfully recognised
298 */
299 protected function parseSelector( $selector, &$type, &$rawName ) {
300 if ( strpos( $selector, '.' ) === 0 ) {
301 $type = 'CLASS';
302 $rawName = substr( $selector, 1 );
303 } elseif ( strpos( $selector, '#' ) === 0 ) {
304 $type = 'ID';
305 $rawName = substr( $selector, 1 );
306 } elseif ( strpos( $selector, '.' ) !== 0 &&
307 strpos( $selector, '.' ) !== false )
308 {
309 $type = 'TAG_CLASS';
310 $rawName = $selector;
311 } elseif ( strpos( $selector, '[' ) === false
312 && strpos( $selector, ']' ) === false )
313 {
314 $type = 'TAG';
315 $rawName = $selector;
316 } else {
317 throw new MWException( __METHOD__ . "(): unrecognized selector '$selector'" );
318 }
319
320 return true;
321 }
322
323 /**
324 * Transforms CSS selectors into an internal representation suitable for processing
325 * @return array
326 */
327 protected function parseItemsToRemove() {
328 wfProfileIn( __METHOD__ );
329 $removals = array(
330 'ID' => array(),
331 'TAG' => array(),
332 'CLASS' => array(),
333 'TAG_CLASS' => array(),
334 );
335
336 foreach ( $this->itemsToRemove as $itemToRemove ) {
337 $type = '';
338 $rawName = '';
339 if ( $this->parseSelector( $itemToRemove, $type, $rawName ) ) {
340 $removals[$type][] = $rawName;
341 }
342 }
343
344 if ( $this->removeMedia ) {
345 $removals['TAG'][] = 'img';
346 $removals['TAG'][] = 'audio';
347 $removals['TAG'][] = 'video';
348 }
349
350 wfProfileOut( __METHOD__ );
351 return $removals;
352 }
353 }