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
30 private $itemsToRemove = array();
31 private $elementsToFlatten = array();
32 protected $removeMedia = false;
37 * @param string $html: Text to process
39 public function __construct( $html ) {
44 * Turns a chunk of HTML into a proper document
48 public static function wrapHTML( $html ) {
49 return '<!doctype html><html><head></head><body>' . $html . '</body></html>';
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 ) {
62 * @return DOMDocument: DOM to manipulate
64 public function getDoc() {
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( ' <', ' <', $html );
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';
86 * Sets whether images/videos/sounds should be removed from output
89 public function setRemoveMedia( $flag = true ) {
90 $this->removeMedia
= $flag;
94 * Adds one or more selector of content to remove. A subset of CSS selector
95 * syntax is supported:
102 * @param Array|string $selectors: Selector(s) of stuff to remove
104 public function remove( $selectors ) {
105 $this->itemsToRemove
= array_merge( $this->itemsToRemove
, (array)$selectors );
109 * Adds one or more element name to the list to flatten (remove tag, but not its content)
110 * Can accept undelimited regexes
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.
115 * @param Array|string $elements: Name(s) of tag(s) to flatten
117 public function flatten( $elements ) {
118 $this->elementsToFlatten
= array_merge( $this->elementsToFlatten
, (array)$elements );
122 * Instructs the formatter to flatten all tags
124 public function flattenAllTags() {
125 $this->flatten( '[?!]?[a-z0-9]+' );
129 * Removes content we've chosen to remove
131 public function filterContent() {
132 wfProfileIn( __METHOD__
);
133 $removals = $this->parseItemsToRemove();
139 $doc = $this->getDoc();
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;
157 $this->removeElements( $domElemsToRemove );
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;
167 $this->removeElements( $domElemsToRemove );
170 $domElemsToRemove = array();
171 $xpath = new DOMXpath( $doc );
172 foreach ( $removals['CLASS'] as $classToRemove ) {
173 $elements = $xpath->query( '//*[contains(@class, "' . $classToRemove . '")]' );
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;
183 $this->removeElements( $domElemsToRemove );
185 // Tags with CSS Classes
186 foreach ( $removals['TAG_CLASS'] as $classToRemove ) {
187 $parts = explode( '.', $classToRemove );
189 $elements = $xpath->query(
190 '//' . $parts[0] . '[@class="' . $parts[1] . '"]'
193 $this->removeElements( $elements );
196 wfProfileOut( __METHOD__
);
200 * Removes a list of elelments from DOMDocument
201 * @param array|DOMNodeList $elements
203 private function removeElements( $elements ) {
205 if ( $elements instanceof DOMNodeList
) {
207 foreach ( $elements as $element ) {
211 /** @var $element DOMElement */
212 foreach ( $list as $element ) {
213 if ( $element->parentNode
) {
214 $element->parentNode
->removeChild( $element );
220 * libxml in its usual pointlessness converts many chars to entities - this function
221 * perfoms a reverse conversion
222 * @param string $html
225 private function fixLibXML( $html ) {
226 wfProfileIn( __METHOD__
);
227 static $replacements;
228 if ( ! $replacements ) {
229 // We don't include rules like '"' => '&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;',
233 '&' => '&amp;',
234 '<' => '&lt;',
235 '>' => '&gt;',
238 $html = $replacements->replace( $html );
239 $html = mb_convert_encoding( $html, 'UTF-8', 'HTML-ENTITIES' );
240 wfProfileOut( __METHOD__
);
245 * Performs final transformations and returns resulting HTML
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
250 public function getText( $element = null ) {
251 wfProfileIn( __METHOD__
);
254 if ( $element !== null && !( $element instanceof DOMElement
) ) {
255 $element = $this->doc
->getElementById( $element );
258 $body = $this->doc
->getElementsByTagName( 'body' )->item( 0 );
259 $nodesArray = array();
260 foreach ( $body->childNodes
as $node ) {
261 $nodesArray[] = $node;
263 foreach ( $nodesArray as $nodeArray ) {
264 $body->removeChild( $nodeArray );
266 $body->appendChild( $element );
268 $html = $this->doc
->saveHTML();
269 $html = $this->fixLibXml( $html );
273 if ( wfIsWindows() ) {
274 // Appears to be cleanup for CRLF misprocessing of unknown origin
275 // when running server on Windows platform.
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( ' ', '', $html );
281 $html = preg_replace( '/<!--.*?-->|^.*?<body>|<\/body>.*$/s', '', $html );
282 $html = $this->onHtmlReady( $html );
284 if ( $this->elementsToFlatten
) {
285 $elements = implode( '|', $this->elementsToFlatten
);
286 $html = preg_replace( "#</?($elements)\\b[^>]*>#is", '', $html );
289 wfProfileOut( __METHOD__
);
294 * @param $selector: CSS selector to parse
297 * @return bool: Whether the selector was successfully recognised
299 protected function parseSelector( $selector, &$type, &$rawName ) {
300 if ( strpos( $selector, '.' ) === 0 ) {
302 $rawName = substr( $selector, 1 );
303 } elseif ( strpos( $selector, '#' ) === 0 ) {
305 $rawName = substr( $selector, 1 );
306 } elseif ( strpos( $selector, '.' ) !== 0 &&
307 strpos( $selector, '.' ) !== false )
310 $rawName = $selector;
311 } elseif ( strpos( $selector, '[' ) === false
312 && strpos( $selector, ']' ) === false )
315 $rawName = $selector;
317 throw new MWException( __METHOD__
. "(): unrecognized selector '$selector'" );
324 * Transforms CSS selectors into an internal representation suitable for processing
327 protected function parseItemsToRemove() {
328 wfProfileIn( __METHOD__
);
333 'TAG_CLASS' => array(),
336 foreach ( $this->itemsToRemove
as $itemToRemove ) {
339 if ( $this->parseSelector( $itemToRemove, $type, $rawName ) ) {
340 $removals[$type][] = $rawName;
344 if ( $this->removeMedia
) {
345 $removals['TAG'][] = 'img';
346 $removals['TAG'][] = 'audio';
347 $removals['TAG'][] = 'video';
350 wfProfileOut( __METHOD__
);