Last active
November 17, 2015 13:02
-
-
Save mattheu/e7907a433510c0c3b1c9 to your computer and use it in GitHub Desktop.
Dom Kses
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
trait Dom_Kses { | |
/** | |
* wp_kses, but using DOMDocument. | |
* | |
* Clean HTML to allowed_html. | |
* Also restrict attributes by those in whitelist. | |
* | |
* @param \DOMNode $node Dom node | |
* @param array $allowed_html kses allowed html. | |
* | |
* @return void. | |
*/ | |
function dom_kses( \DOMNode $node, array $allowed_html ) { | |
$this->dom_kses_children( $node, $allowed_html ); | |
// If not allowed, remove node. | |
if ( | |
! ( '#text' === $node->nodeName ) | |
&& ! ( array_key_exists( $node->nodeName, $allowed_html ) ) | |
) { | |
$fragment = $node->ownerDocument->createDocumentFragment(); | |
while ( $node->childNodes->length > 0 ) { | |
$fragment->appendChild( $node->childNodes->item(0) ); | |
} | |
$node->parentNode->replaceChild( $fragment, $node ); | |
} elseif ( $node->hasAttributes() ) { | |
$this->dom_kses_node_attr( $node, $allowed_html[ $node->nodeName ] ); | |
} | |
} | |
/** | |
* Call dom_kses recursively on childNodes. | |
* | |
* Useful for cleaning inner html. | |
* | |
* @param \DOMNode $node Dom node | |
* @param array $allowed_html kses allowed html. | |
* | |
* @return void. | |
*/ | |
function dom_kses_children( \DOMNode $node, array $allowed_html ) { | |
if ( $node->hasChildNodes() ) { | |
foreach ( range( $node->childNodes->length - 1, 0 ) as $i ) { | |
$this->dom_kses( $node->childNodes->item( $i ), $allowed_html ); | |
} | |
} | |
} | |
/** | |
* Filter attributes by whitelist | |
* | |
* @param \DOMNode $node | |
* @param array $allowed_attributes | |
* @return [type] [description] | |
*/ | |
function dom_kses_node_attr( \DOMNode $node, array $allowed_attr ) { | |
if ( $node->hasAttributes() ) { | |
foreach ( $node->attributes as $attr ) { | |
if ( ! ( isset( $allowed_attr[ $attr->nodeName ] ) && $allowed_attr[ $attr->nodeName ] ) ) { | |
$node->removeAttribute( $attr->nodeName ); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment