Standardise wording of verbs relating to revision deletion
[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 $loader = libxml_disable_entity_loader();
77 $this->doc = new DOMDocument();
78 $this->doc->strictErrorChecking = false;
79 $this->doc->loadHTML( $html );
80 libxml_disable_entity_loader( $loader );
81 libxml_use_internal_errors( false );
82 $this->doc->encoding = 'UTF-8';
83 }
84 return $this->doc;
85 }
86
87 /**
88 * Sets whether images/videos/sounds should be removed from output
89 * @param bool $flag
90 */
91 public function setRemoveMedia( $flag = true ) {
92 $this->removeMedia = $flag;
93 }
94
95 /**
96 * Adds one or more selector of content to remove. A subset of CSS selector
97 * syntax is supported:
98 *
99 * <tag>
100 * <tag>.class
101 * .<class>
102 * #<id>
103 *
104 * @param Array|string $selectors: Selector(s) of stuff to remove
105 */
106 public function remove( $selectors ) {
107 $this->itemsToRemove = array_merge( $this->itemsToRemove, (array)$selectors );
108 }
109
110 /**
111 * Adds one or more element name to the list to flatten (remove tag, but not its content)
112 * Can accept undelimited regexes
113 *
114 * Note this interface may fail in surprising unexpected ways due to usage of regexes,
115 * so should not be relied on for HTML markup security measures.
116 *
117 * @param Array|string $elements: Name(s) of tag(s) to flatten
118 */
119 public function flatten( $elements ) {
120 $this->elementsToFlatten = array_merge( $this->elementsToFlatten, (array)$elements );
121 }
122
123 /**
124 * Instructs the formatter to flatten all tags
125 */
126 public function flattenAllTags() {
127 $this->flatten( '[?!]?[a-z0-9]+' );
128 }
129
130 /**
131 * Removes content we've chosen to remove
132 */
133 public function filterContent() {
134 wfProfileIn( __METHOD__ );
135 $removals = $this->parseItemsToRemove();
136
137 if ( !$removals ) {
138 wfProfileOut( __METHOD__ );
139 return;
140 }
141
142 $doc = $this->getDoc();
143
144 // Remove tags
145
146 // You can't remove DOMNodes from a DOMNodeList as you're iterating
147 // over them in a foreach loop. It will seemingly leave the internal
148 // iterator on the foreach out of wack and results will be quite
149 // strange. Though, making a queue of items to remove seems to work.
150 $domElemsToRemove = array();
151 foreach ( $removals['TAG'] as $tagToRemove ) {
152 $tagToRemoveNodes = $doc->getElementsByTagName( $tagToRemove );
153 foreach ( $tagToRemoveNodes as $tagToRemoveNode ) {
154 if ( $tagToRemoveNode ) {
155 $domElemsToRemove[] = $tagToRemoveNode;
156 }
157 }
158 }
159
160 $this->removeElements( $domElemsToRemove );
161
162 // Elements with named IDs
163 $domElemsToRemove = array();
164 foreach ( $removals['ID'] as $itemToRemove ) {
165 $itemToRemoveNode = $doc->getElementById( $itemToRemove );
166 if ( $itemToRemoveNode ) {
167 $domElemsToRemove[] = $itemToRemoveNode;
168 }
169 }
170 $this->removeElements( $domElemsToRemove );
171
172 // CSS Classes
173 $domElemsToRemove = array();
174 $xpath = new DOMXpath( $doc );
175 foreach ( $removals['CLASS'] as $classToRemove ) {
176 $elements = $xpath->query( '//*[contains(@class, "' . $classToRemove . '")]' );
177
178 /** @var $element DOMElement */
179 foreach ( $elements as $element ) {
180 $classes = $element->getAttribute( 'class' );
181 if ( preg_match( "/\b$classToRemove\b/", $classes ) && $element->parentNode ) {
182 $domElemsToRemove[] = $element;
183 }
184 }
185 }
186 $this->removeElements( $domElemsToRemove );
187
188 // Tags with CSS Classes
189 foreach ( $removals['TAG_CLASS'] as $classToRemove ) {
190 $parts = explode( '.', $classToRemove );
191
192 $elements = $xpath->query(
193 '//' . $parts[0] . '[@class="' . $parts[1] . '"]'
194 );
195
196 $this->removeElements( $elements );
197 }
198
199 wfProfileOut( __METHOD__ );
200 }
201
202 /**
203 * Removes a list of elelments from DOMDocument
204 * @param array|DOMNodeList $elements
205 */
206 private function removeElements( $elements ) {
207 $list = $elements;
208 if ( $elements instanceof DOMNodeList ) {
209 $list = array();
210 foreach ( $elements as $element ) {
211 $list[] = $element;
212 }
213 }
214 /** @var $element DOMElement */
215 foreach ( $list as $element ) {
216 if ( $element->parentNode ) {
217 $element->parentNode->removeChild( $element );
218 }
219 }
220 }
221
222 /**
223 * libxml in its usual pointlessness converts many chars to entities - this function
224 * perfoms a reverse conversion
225 * @param string $html
226 * @return string
227 */
228 private function fixLibXML( $html ) {
229 wfProfileIn( __METHOD__ );
230 static $replacements;
231 if ( ! $replacements ) {
232 // We don't include rules like '&#34;' => '&amp;quot;' because entities had already been
233 // normalized by libxml. Using this function with input not sanitized by libxml is UNSAFE!
234 $replacements = new ReplacementArray( array(
235 '&quot;' => '&amp;quot;',
236 '&amp;' => '&amp;amp;',
237 '&lt;' => '&amp;lt;',
238 '&gt;' => '&amp;gt;',
239 ) );
240 }
241 $html = $replacements->replace( $html );
242 $html = mb_convert_encoding( $html, 'UTF-8', 'HTML-ENTITIES' );
243 wfProfileOut( __METHOD__ );
244 return $html;
245 }
246
247 /**
248 * Performs final transformations and returns resulting HTML
249 *
250 * @param DOMElement|string|null $element: ID of element to get HTML from or false to get it from the whole tree
251 * @return string: Processed HTML
252 */
253 public function getText( $element = null ) {
254 wfProfileIn( __METHOD__ );
255
256 if ( $this->doc ) {
257 if ( $element !== null && !( $element instanceof DOMElement ) ) {
258 $element = $this->doc->getElementById( $element );
259 }
260 if ( $element ) {
261 $body = $this->doc->getElementsByTagName( 'body' )->item( 0 );
262 $nodesArray = array();
263 foreach ( $body->childNodes as $node ) {
264 $nodesArray[] = $node;
265 }
266 foreach ( $nodesArray as $nodeArray ) {
267 $body->removeChild( $nodeArray );
268 }
269 $body->appendChild( $element );
270 }
271 $html = $this->doc->saveHTML();
272 $html = $this->fixLibXml( $html );
273 } else {
274 $html = $this->html;
275 }
276 if ( wfIsWindows() ) {
277 // Appears to be cleanup for CRLF misprocessing of unknown origin
278 // when running server on Windows platform.
279 //
280 // If this error continues in the future, please track it down in the
281 // XML code paths if possible and fix there.
282 $html = str_replace( '&#13;', '', $html );
283 }
284 $html = preg_replace( '/<!--.*?-->|^.*?<body>|<\/body>.*$/s', '', $html );
285 $html = $this->onHtmlReady( $html );
286
287 if ( $this->elementsToFlatten ) {
288 $elements = implode( '|', $this->elementsToFlatten );
289 $html = preg_replace( "#</?($elements)\\b[^>]*>#is", '', $html );
290 }
291
292 wfProfileOut( __METHOD__ );
293 return $html;
294 }
295
296 /**
297 * @param $selector: CSS selector to parse
298 * @param $type
299 * @param $rawName
300 * @return bool: Whether the selector was successfully recognised
301 */
302 protected function parseSelector( $selector, &$type, &$rawName ) {
303 if ( strpos( $selector, '.' ) === 0 ) {
304 $type = 'CLASS';
305 $rawName = substr( $selector, 1 );
306 } elseif ( strpos( $selector, '#' ) === 0 ) {
307 $type = 'ID';
308 $rawName = substr( $selector, 1 );
309 } elseif ( strpos( $selector, '.' ) !== 0 &&
310 strpos( $selector, '.' ) !== false )
311 {
312 $type = 'TAG_CLASS';
313 $rawName = $selector;
314 } elseif ( strpos( $selector, '[' ) === false
315 && strpos( $selector, ']' ) === false )
316 {
317 $type = 'TAG';
318 $rawName = $selector;
319 } else {
320 throw new MWException( __METHOD__ . "(): unrecognized selector '$selector'" );
321 }
322
323 return true;
324 }
325
326 /**
327 * Transforms CSS selectors into an internal representation suitable for processing
328 * @return array
329 */
330 protected function parseItemsToRemove() {
331 wfProfileIn( __METHOD__ );
332 $removals = array(
333 'ID' => array(),
334 'TAG' => array(),
335 'CLASS' => array(),
336 'TAG_CLASS' => array(),
337 );
338
339 foreach ( $this->itemsToRemove as $itemToRemove ) {
340 $type = '';
341 $rawName = '';
342 if ( $this->parseSelector( $itemToRemove, $type, $rawName ) ) {
343 $removals[$type][] = $rawName;
344 }
345 }
346
347 if ( $this->removeMedia ) {
348 $removals['TAG'][] = 'img';
349 $removals['TAG'][] = 'audio';
350 $removals['TAG'][] = 'video';
351 }
352
353 wfProfileOut( __METHOD__ );
354 return $removals;
355 }
356 }