Remove silly 'm' prefix from StubObject/DeprecatedGlobal members
[mediawiki.git] / includes / HtmlFormatter.php
blobb2209c358ed3636f68817015f2b2c907f1bf61e2
1 <?php
2 /**
3 * Performs transformations of HTML by wrapping around libxml2 and working
4 * around its countless bugs.
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.
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.
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
21 * @file
23 class HtmlFormatter {
24 /**
25 * @var DOMDocument
27 private $doc;
29 private $html;
30 private $itemsToRemove = array();
31 private $elementsToFlatten = array();
32 protected $removeMedia = false;
34 /**
35 * Constructor
37 * @param string $html Text to process
39 public function __construct( $html ) {
40 $this->html = $html;
43 /**
44 * Turns a chunk of HTML into a proper document
45 * @param string $html
46 * @return string
48 public static function wrapHTML( $html ) {
49 return '<!doctype html><html><head></head><body>' . $html . '</body></html>';
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
57 protected function onHtmlReady( $html ) {
58 return $html;
61 /**
62 * @return DOMDocument DOM to manipulate
64 public function getDoc() {
65 if ( !$this->doc ) {
66 $html = mb_convert_encoding( $this->html, 'HTML-ENTITIES', 'UTF-8' );
68 // Workaround for bug that caused spaces before references
69 // to disappear during processing:
70 // https://bugzilla.wikimedia.org/show_bug.cgi?id=53086
72 // Please replace with a better fix if one can be found.
73 $html = str_replace( ' <', '&#32;<', $html );
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';
84 return $this->doc;
87 /**
88 * Sets whether images/videos/sounds should be removed from output
89 * @param bool $flag
91 public function setRemoveMedia( $flag = true ) {
92 $this->removeMedia = $flag;
95 /**
96 * Adds one or more selector of content to remove. A subset of CSS selector
97 * syntax is supported:
99 * <tag>
100 * <tag>.class
101 * .<class>
102 * #<id>
104 * @param array|string $selectors Selector(s) of stuff to remove
106 public function remove( $selectors ) {
107 $this->itemsToRemove = array_merge( $this->itemsToRemove, (array)$selectors );
111 * Adds one or more element name to the list to flatten (remove tag, but not its content)
112 * Can accept undelimited regexes
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.
117 * @param array|string $elements Name(s) of tag(s) to flatten
119 public function flatten( $elements ) {
120 $this->elementsToFlatten = array_merge( $this->elementsToFlatten, (array)$elements );
124 * Instructs the formatter to flatten all tags
126 public function flattenAllTags() {
127 $this->flatten( '[?!]?[a-z0-9]+' );
131 * Removes content we've chosen to remove. The text of the removed elements can be
132 * extracted with the getText method.
133 * @return array of removed DOMElements
135 public function filterContent() {
136 wfProfileIn( __METHOD__ );
137 $removals = $this->parseItemsToRemove();
139 // Bail out early if nothing to do
140 if ( array_reduce( $removals,
141 function( $carry, $item ) {
142 return $carry && !$item;
144 true
145 ) ) {
146 wfProfileOut( __METHOD__ );
147 return array();
150 $doc = $this->getDoc();
152 // Remove tags
154 // You can't remove DOMNodes from a DOMNodeList as you're iterating
155 // over them in a foreach loop. It will seemingly leave the internal
156 // iterator on the foreach out of wack and results will be quite
157 // strange. Though, making a queue of items to remove seems to work.
158 $domElemsToRemove = array();
159 foreach ( $removals['TAG'] as $tagToRemove ) {
160 $tagToRemoveNodes = $doc->getElementsByTagName( $tagToRemove );
161 foreach ( $tagToRemoveNodes as $tagToRemoveNode ) {
162 if ( $tagToRemoveNode ) {
163 $domElemsToRemove[] = $tagToRemoveNode;
167 $removed = $this->removeElements( $domElemsToRemove );
169 // Elements with named IDs
170 $domElemsToRemove = array();
171 foreach ( $removals['ID'] as $itemToRemove ) {
172 $itemToRemoveNode = $doc->getElementById( $itemToRemove );
173 if ( $itemToRemoveNode ) {
174 $domElemsToRemove[] = $itemToRemoveNode;
177 $removed = array_merge( $removed, $this->removeElements( $domElemsToRemove ) );
179 // CSS Classes
180 $domElemsToRemove = array();
181 $xpath = new DOMXpath( $doc );
182 foreach ( $removals['CLASS'] as $classToRemove ) {
183 $elements = $xpath->query( '//*[contains(@class, "' . $classToRemove . '")]' );
185 /** @var $element DOMElement */
186 foreach ( $elements as $element ) {
187 $classes = $element->getAttribute( 'class' );
188 if ( preg_match( "/\b$classToRemove\b/", $classes ) && $element->parentNode ) {
189 $domElemsToRemove[] = $element;
193 $removed = array_merge( $removed, $this->removeElements( $domElemsToRemove ) );
195 // Tags with CSS Classes
196 foreach ( $removals['TAG_CLASS'] as $classToRemove ) {
197 $parts = explode( '.', $classToRemove );
199 $elements = $xpath->query(
200 '//' . $parts[0] . '[@class="' . $parts[1] . '"]'
202 $removed = array_merge( $removed, $this->removeElements( $elements ) );
205 wfProfileOut( __METHOD__ );
206 return $removed;
210 * Removes a list of elelments from DOMDocument
211 * @param array|DOMNodeList $elements
212 * @return array of removed elements
214 private function removeElements( $elements ) {
215 $list = $elements;
216 if ( $elements instanceof DOMNodeList ) {
217 $list = array();
218 foreach ( $elements as $element ) {
219 $list[] = $element;
222 /** @var $element DOMElement */
223 foreach ( $list as $element ) {
224 if ( $element->parentNode ) {
225 $element->parentNode->removeChild( $element );
228 return $list;
232 * libxml in its usual pointlessness converts many chars to entities - this function
233 * perfoms a reverse conversion
234 * @param string $html
235 * @return string
237 private function fixLibXML( $html ) {
238 wfProfileIn( __METHOD__ );
239 static $replacements;
240 if ( ! $replacements ) {
241 // We don't include rules like '&#34;' => '&amp;quot;' because entities had already been
242 // normalized by libxml. Using this function with input not sanitized by libxml is UNSAFE!
243 $replacements = new ReplacementArray( array(
244 '&quot;' => '&amp;quot;',
245 '&amp;' => '&amp;amp;',
246 '&lt;' => '&amp;lt;',
247 '&gt;' => '&amp;gt;',
248 ) );
250 $html = $replacements->replace( $html );
251 $html = mb_convert_encoding( $html, 'UTF-8', 'HTML-ENTITIES' );
252 wfProfileOut( __METHOD__ );
253 return $html;
257 * Performs final transformations and returns resulting HTML. Note that if you want to call this
258 * both without an element and with an element you should call it without an element first. If you
259 * specify the $element in the method it'll change the underlying dom and you won't be able to get
260 * it back.
262 * @param DOMElement|string|null $element ID of element to get HTML from or
263 * false to get it from the whole tree
264 * @return string Processed HTML
266 public function getText( $element = null ) {
267 wfProfileIn( __METHOD__ );
269 if ( $this->doc ) {
270 wfProfileIn( __METHOD__ . '-dom' );
271 if ( $element !== null && !( $element instanceof DOMElement ) ) {
272 $element = $this->doc->getElementById( $element );
274 if ( $element ) {
275 $body = $this->doc->getElementsByTagName( 'body' )->item( 0 );
276 $nodesArray = array();
277 foreach ( $body->childNodes as $node ) {
278 $nodesArray[] = $node;
280 foreach ( $nodesArray as $nodeArray ) {
281 $body->removeChild( $nodeArray );
283 $body->appendChild( $element );
285 $html = $this->doc->saveHTML();
286 wfProfileOut( __METHOD__ . '-dom' );
288 wfProfileIn( __METHOD__ . '-fixes' );
289 $html = $this->fixLibXml( $html );
290 if ( wfIsWindows() ) {
291 // Cleanup for CRLF misprocessing of unknown origin on Windows.
293 // If this error continues in the future, please track it down in the
294 // XML code paths if possible and fix there.
295 $html = str_replace( '&#13;', '', $html );
297 wfProfileOut( __METHOD__ . '-fixes' );
298 } else {
299 $html = $this->html;
301 // Remove stuff added by wrapHTML()
302 $html = preg_replace( '/<!--.*?-->|^.*?<body>|<\/body>.*$/s', '', $html );
303 $html = $this->onHtmlReady( $html );
305 wfProfileIn( __METHOD__ . '-flatten' );
306 if ( $this->elementsToFlatten ) {
307 $elements = implode( '|', $this->elementsToFlatten );
308 $html = preg_replace( "#</?($elements)\\b[^>]*>#is", '', $html );
310 wfProfileOut( __METHOD__ . '-flatten' );
312 wfProfileOut( __METHOD__ );
313 return $html;
317 * @param string $selector CSS selector to parse
318 * @param string $type
319 * @param string $rawName
320 * @return bool Whether the selector was successfully recognised
322 protected function parseSelector( $selector, &$type, &$rawName ) {
323 if ( strpos( $selector, '.' ) === 0 ) {
324 $type = 'CLASS';
325 $rawName = substr( $selector, 1 );
326 } elseif ( strpos( $selector, '#' ) === 0 ) {
327 $type = 'ID';
328 $rawName = substr( $selector, 1 );
329 } elseif ( strpos( $selector, '.' ) !== 0 && strpos( $selector, '.' ) !== false ) {
330 $type = 'TAG_CLASS';
331 $rawName = $selector;
332 } elseif ( strpos( $selector, '[' ) === false && strpos( $selector, ']' ) === false ) {
333 $type = 'TAG';
334 $rawName = $selector;
335 } else {
336 throw new MWException( __METHOD__ . "(): unrecognized selector '$selector'" );
339 return true;
343 * Transforms CSS selectors into an internal representation suitable for processing
344 * @return array
346 protected function parseItemsToRemove() {
347 wfProfileIn( __METHOD__ );
348 $removals = array(
349 'ID' => array(),
350 'TAG' => array(),
351 'CLASS' => array(),
352 'TAG_CLASS' => array(),
355 foreach ( $this->itemsToRemove as $itemToRemove ) {
356 $type = '';
357 $rawName = '';
358 if ( $this->parseSelector( $itemToRemove, $type, $rawName ) ) {
359 $removals[$type][] = $rawName;
363 if ( $this->removeMedia ) {
364 $removals['TAG'][] = 'img';
365 $removals['TAG'][] = 'audio';
366 $removals['TAG'][] = 'video';
369 wfProfileOut( __METHOD__ );
370 return $removals;