base = $base_url ? $base_url : home_url( '/' );
$doc = new DOMDocument();
$prev = libxml_use_internal_errors( true );
$ok = $doc->loadHTML(
'
' . $html . '
',
LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_PARSEHUGE
);
libxml_clear_errors();
libxml_use_internal_errors( $prev );
if ( ! $ok ) {
return self::fallback( $html );
}
$root = $doc->getElementById( 'aeoora-md-root' );
if ( ! $root ) {
return self::fallback( $html );
}
$md = $self->children( $root, array( 'pre' => false ) );
return self::tidy( $md );
}
/**
* Regex fallback when DOM is not available.
*
* @param string $html HTML.
* @return string
*/
private static function fallback( $html ) {
$html = preg_replace( '~<(script|style|noscript|svg|form)[^>]*>.*?\1>~is', '', $html );
for ( $i = 6; $i >= 1; $i-- ) {
$html = preg_replace( '~]*>(.*?)~is', "\n\n" . str_repeat( '#', $i ) . ' $1' . "\n\n", $html );
}
$html = preg_replace( '~]*>~i', "\n- ", $html );
$html = preg_replace( '~<(p|div|br|tr|ul|ol|table)[^>]*>~i', "\n", $html );
$html = preg_replace( '~]*href=["\']([^"\']+)["\'][^>]*>(.*?)~is', '[$2]($1)', $html );
$text = wp_strip_all_tags( $html );
$text = html_entity_decode( $text, ENT_QUOTES | ENT_HTML5, 'UTF-8' );
return self::tidy( $text );
}
/**
* Final whitespace cleanup.
*
* @param string $md Markdown.
* @return string
*/
private static function tidy( $md ) {
$md = str_replace( array( "\r\n", "\r", "\xC2\xA0" ), array( "\n", "\n", ' ' ), $md );
$md = preg_replace( "/[ \t]+\n/", "\n", $md );
$md = preg_replace( "/\n{3,}/", "\n\n", $md );
return trim( (string) $md ) . "\n";
}
/**
* Convert all children of a node.
*
* @param DOMNode $node Node.
* @param array $ctx Context.
* @return string
*/
private function children( DOMNode $node, array $ctx ) {
$out = '';
foreach ( $node->childNodes as $child ) {
$out .= $this->node( $child, $ctx );
}
return $out;
}
/**
* Convert one node.
*
* @param DOMNode $node Node.
* @param array $ctx Context.
* @return string
*/
private function node( DOMNode $node, array $ctx ) {
if ( XML_TEXT_NODE === $node->nodeType || XML_CDATA_SECTION_NODE === $node->nodeType ) {
if ( ! empty( $ctx['pre'] ) ) {
return $node->nodeValue;
}
$text = preg_replace( '/[ \t\r\n\f]+/', ' ', $node->nodeValue );
return (string) $text;
}
if ( XML_ELEMENT_NODE !== $node->nodeType ) {
return '';
}
/** @var DOMElement $node */
$tag = strtolower( $node->nodeName );
if ( in_array( $tag, self::$skip, true ) || $this->is_hidden( $node ) ) {
return '';
}
switch ( $tag ) {
case 'h1':
case 'h2':
case 'h3':
case 'h4':
case 'h5':
case 'h6':
$text = $this->inline( $node, $ctx );
return '' === $text ? '' : "\n\n" . str_repeat( '#', (int) substr( $tag, 1 ) ) . ' ' . $text . "\n\n";
case 'p':
$text = trim( $this->children( $node, $ctx ) );
return '' === $text ? '' : "\n\n" . $text . "\n\n";
case 'br':
return " \n";
case 'hr':
return "\n\n---\n\n";
case 'strong':
case 'b':
return $this->wrap( $this->children( $node, $ctx ), '**' );
case 'em':
case 'i':
case 'cite':
return $this->wrap( $this->children( $node, $ctx ), '*' );
case 'del':
case 's':
case 'strike':
return $this->wrap( $this->children( $node, $ctx ), '~~' );
case 'mark':
case 'u':
case 'ins':
case 'small':
case 'sup':
case 'sub':
case 'abbr':
case 'span':
case 'label':
case 'time':
case 'font':
return $this->children( $node, $ctx );
case 'q':
return '"' . trim( $this->children( $node, $ctx ) ) . '"';
case 'code':
case 'kbd':
case 'samp':
if ( ! empty( $ctx['pre'] ) ) {
return $node->textContent;
}
$code = trim( $node->textContent );
if ( '' === $code ) {
return '';
}
$fence = false !== strpos( $code, '`' ) ? '``' : '`';
return $fence . $code . $fence;
case 'pre':
return $this->pre( $node );
case 'a':
return $this->link( $node, $ctx );
case 'img':
return $this->image( $node );
case 'picture':
foreach ( $node->getElementsByTagName( 'img' ) as $img ) {
return $this->image( $img );
}
return '';
case 'ul':
case 'ol':
return $this->listing( $node, $ctx );
case 'li':
// Stray outside a list.
return "\n- " . trim( $this->children( $node, $ctx ) ) . "\n";
case 'blockquote':
$inner = trim( self::tidy( $this->children( $node, $ctx ) ) );
if ( '' === $inner ) {
return '';
}
$lines = explode( "\n", $inner );
return "\n\n" . implode( "\n", array_map( static function ( $l ) {
return '' === $l ? '>' : '> ' . $l;
}, $lines ) ) . "\n\n";
case 'table':
return $this->table( $node, $ctx );
case 'figcaption':
$text = trim( $this->inline( $node, $ctx ) );
return '' === $text ? '' : "\n\n*" . $text . "*\n\n";
case 'dl':
return "\n\n" . $this->children( $node, $ctx ) . "\n\n";
case 'dt':
return "\n- **" . trim( $this->inline( $node, $ctx ) ) . '**';
case 'dd':
return ': ' . trim( $this->inline( $node, $ctx ) ) . "\n";
case 'details':
return "\n\n" . $this->children( $node, $ctx ) . "\n\n";
case 'summary':
$text = trim( $this->inline( $node, $ctx ) );
return '' === $text ? '' : "\n\n**" . $text . "**\n\n";
case 'iframe':
$src = $this->url( $node->getAttribute( 'src' ) ? $node->getAttribute( 'src' ) : $node->getAttribute( 'data-src' ) );
if ( $src && preg_match( '~(youtube\.com|youtu\.be|vimeo\.com|loom\.com|spotify\.com|soundcloud\.com)~i', $src ) ) {
$title = trim( $node->getAttribute( 'title' ) );
return "\n\n[" . ( $title ? $title : __( 'Embedded media', 'aeoora' ) ) . '](' . $src . ")\n\n";
}
return '';
case 'video':
case 'audio':
$src = $node->getAttribute( 'src' );
if ( ! $src ) {
foreach ( $node->getElementsByTagName( 'source' ) as $source ) {
$src = $source->getAttribute( 'src' );
break;
}
}
$src = $this->url( $src );
return $src ? "\n\n[" . ( 'video' === $tag ? __( 'Video', 'aeoora' ) : __( 'Audio', 'aeoora' ) ) . '](' . $src . ")\n\n" : '';
default:
if ( in_array( $tag, self::$blocks, true ) ) {
$inner = $this->children( $node, $ctx );
return '' === trim( $inner ) ? '' : "\n\n" . $inner . "\n\n";
}
return $this->children( $node, $ctx );
}
}
/**
* Is the element hidden from readers?
*
* @param DOMElement $node Node.
* @return bool
*/
private function is_hidden( DOMElement $node ) {
if ( $node->hasAttribute( 'hidden' ) || 'true' === $node->getAttribute( 'aria-hidden' ) ) {
return true;
}
$style = strtolower( $node->getAttribute( 'style' ) );
if ( $style && preg_match( '/display\s*:\s*none|visibility\s*:\s*hidden/', $style ) ) {
return true;
}
$class = ' ' . strtolower( $node->getAttribute( 'class' ) ) . ' ';
foreach ( array( ' screen-reader-text ', ' sr-only ', ' visually-hidden ', ' sharedaddy ', ' jp-relatedposts ', ' addtoany_share_save_container ', ' a2a_kit ', ' yarpp-related ', ' crp_related ', ' related-posts ', ' social-share ', ' share-buttons ', ' adsbygoogle ', ' heateor_sss_sharing_container ', ' wp-block-jetpack-sharing-buttons ', ' aeoora-no-md ', ' aeoora-tldr-box ' ) as $hide ) {
if ( false !== strpos( $class, $hide ) ) {
return true;
}
}
return false;
}
/**
* Inline text of a node, newlines collapsed.
*
* @param DOMNode $node Node.
* @param array $ctx Context.
* @return string
*/
private function inline( DOMNode $node, array $ctx ) {
$text = $this->children( $node, $ctx );
$text = preg_replace( '/\s*\n+\s*/', ' ', $text );
return trim( preg_replace( '/ {2,}/', ' ', (string) $text ) );
}
/**
* Wrap text in emphasis markers, keeping surrounding whitespace outside.
*
* @param string $text Text.
* @param string $marker Marker.
* @return string
*/
private function wrap( $text, $marker ) {
if ( '' === trim( $text ) ) {
return $text;
}
preg_match( '/^(\s*)(.*?)(\s*)$/s', $text, $m );
$inner = preg_replace( '/\s*\n+\s*/', ' ', $m[2] );
return $m[1] . $marker . $inner . $marker . $m[3];
}
/**
* Resolve a URL against the base.
*
* @param string $url URL.
* @return string
*/
private function url( $url ) {
$url = trim( (string) $url );
if ( '' === $url || 0 === strpos( $url, 'data:' ) || 0 === stripos( $url, 'javascript:' ) ) {
return '';
}
if ( preg_match( '~^(https?:|mailto:|tel:)~i', $url ) ) {
return $url;
}
if ( 0 === strpos( $url, '//' ) ) {
return ( is_ssl() ? 'https:' : 'http:' ) . $url;
}
if ( 0 === strpos( $url, '#' ) ) {
return $url;
}
if ( 0 === strpos( $url, '/' ) ) {
$parts = wp_parse_url( $this->base );
$host = ( isset( $parts['scheme'] ) ? $parts['scheme'] : 'https' ) . '://' . ( isset( $parts['host'] ) ? $parts['host'] : '' ) . ( isset( $parts['port'] ) ? ':' . $parts['port'] : '' );
return $host . $url;
}
return trailingslashit( preg_replace( '~[^/]*$~', '', $this->base ) ) . $url;
}
/**
* Link.
*
* @param DOMElement $node Node.
* @param array $ctx Context.
* @return string
*/
private function link( DOMElement $node, array $ctx ) {
$text = $this->inline( $node, $ctx );
$href = $node->getAttribute( 'href' );
if ( '' === $text ) {
return '';
}
if ( '' === $href || 0 === strpos( $href, '#' ) || 0 === stripos( $href, 'javascript:' ) ) {
return $text;
}
$url = $this->url( $href );
if ( '' === $url ) {
return $text;
}
$title = trim( $node->getAttribute( 'title' ) );
$url = str_replace( array( ' ', ')' ), array( '%20', '%29' ), $url );
return '[' . str_replace( array( '[', ']' ), array( '\[', '\]' ), $text ) . '](' . $url . ( $title && $title !== $text ? ' "' . str_replace( '"', '\'', $title ) . '"' : '' ) . ')';
}
/**
* Image (handles common lazy-load attributes).
*
* @param DOMElement $node Node.
* @return string
*/
private function image( DOMElement $node ) {
$src = '';
foreach ( array( 'data-src', 'data-lazy-src', 'data-original', 'data-lazy', 'src' ) as $attr ) {
$candidate = $node->getAttribute( $attr );
if ( $candidate && 0 !== strpos( $candidate, 'data:' ) ) {
$src = $candidate;
break;
}
}
if ( ! $src ) {
$srcset = $node->getAttribute( 'data-srcset' ) ? $node->getAttribute( 'data-srcset' ) : $node->getAttribute( 'srcset' );
if ( $srcset ) {
$first = trim( explode( ',', $srcset )[0] );
$src = trim( explode( ' ', $first )[0] );
}
}
$src = $this->url( $src );
if ( '' === $src ) {
return '';
}
$w = (int) $node->getAttribute( 'width' );
$h = (int) $node->getAttribute( 'height' );
if ( ( $w && $w < 3 ) || ( $h && $h < 3 ) ) {
return ''; // Tracking pixel.
}
$alt = trim( preg_replace( '/\s+/', ' ', $node->getAttribute( 'alt' ) ) );
return '![' . str_replace( array( '[', ']' ), '', $alt ) . '](' . str_replace( array( ' ', ')' ), array( '%20', '%29' ), $src ) . ')';
}
/**
* Preformatted code block.
*
* @param DOMElement $node Node.
* @return string
*/
private function pre( DOMElement $node ) {
$lang = '';
$class = $node->getAttribute( 'class' );
foreach ( $node->getElementsByTagName( 'code' ) as $code ) {
$class .= ' ' . $code->getAttribute( 'class' );
break;
}
if ( preg_match( '/(?:language|lang)-([a-z0-9_+-]+)/i', $class, $m ) ) {
$lang = strtolower( $m[1] );
}
$code = rtrim( $node->textContent );
if ( '' === trim( $code ) ) {
return '';
}
$fence = false !== strpos( $code, '```' ) ? '~~~~' : '```';
return "\n\n" . $fence . $lang . "\n" . $code . "\n" . $fence . "\n\n";
}
/**
* Ordered / unordered list (nested).
*
* @param DOMElement $node Node.
* @param array $ctx Context.
* @return string
*/
private function listing( DOMElement $node, array $ctx ) {
$ordered = 'ol' === strtolower( $node->nodeName );
$i = $node->hasAttribute( 'start' ) ? (int) $node->getAttribute( 'start' ) : 1;
$items = array();
foreach ( $node->childNodes as $child ) {
if ( XML_ELEMENT_NODE !== $child->nodeType || 'li' !== strtolower( $child->nodeName ) ) {
continue;
}
$marker = $ordered ? $i . '. ' : '- ';
$content = trim( self::tidy( $this->children( $child, $ctx ) ) );
if ( '' === $content ) {
continue;
}
// Tight list: single newlines between paragraphs inside an item.
$content = preg_replace( "/\n{2,}(?!\s*(?:[-*] |\d+\. ))/", "\n", $content );
$pad = str_repeat( ' ', strlen( $marker ) );
$lines = explode( "\n", $content );
$first = array_shift( $lines );
$body = $marker . $first;
foreach ( $lines as $line ) {
$body .= "\n" . ( '' === $line ? '' : $pad . $line );
}
$items[] = $body;
$i++;
}
if ( ! $items ) {
return '';
}
return "\n\n" . implode( "\n", $items ) . "\n\n";
}
/**
* Table as GFM.
*
* @param DOMElement $node Node.
* @param array $ctx Context.
* @return string
*/
private function table( DOMElement $node, array $ctx ) {
$rows = array();
$has_th = false;
$caption = '';
foreach ( $node->getElementsByTagName( 'caption' ) as $cap ) {
$caption = trim( $this->inline( $cap, $ctx ) );
break;
}
foreach ( $node->getElementsByTagName( 'tr' ) as $tr ) {
$cells = array();
foreach ( $tr->childNodes as $cell ) {
if ( XML_ELEMENT_NODE !== $cell->nodeType ) {
continue;
}
$name = strtolower( $cell->nodeName );
if ( 'td' !== $name && 'th' !== $name ) {
continue;
}
if ( 'th' === $name && ! $rows ) {
$has_th = true;
}
$text = $this->inline( $cell, $ctx );
$cells[] = str_replace( '|', '\|', $text );
$span = (int) $cell->getAttribute( 'colspan' );
for ( $s = 1; $s < $span; $s++ ) {
$cells[] = '';
}
}
if ( $cells ) {
$rows[] = $cells;
}
}
if ( ! $rows ) {
return '';
}
$cols = max( array_map( 'count', $rows ) );
foreach ( $rows as &$r ) {
$r = array_pad( $r, $cols, '' );
}
unset( $r );
if ( ! $has_th ) {
// GFM needs a header row; use the first row.
$has_th = true;
}
$out = array();
$out[] = '| ' . implode( ' | ', $rows[0] ) . ' |';
$out[] = '|' . str_repeat( ' --- |', $cols );
foreach ( array_slice( $rows, 1 ) as $r ) {
$out[] = '| ' . implode( ' | ', $r ) . ' |';
}
return "\n\n" . ( $caption ? '**' . $caption . "**\n\n" : '' ) . implode( "\n", $out ) . "\n\n";
}
}