';
const FIRST_AFTER = '';
/** Heading classes that are always skipped. */
const SKIP_CLASSES = array( 'no-toc', 'aritoc-skip', 'ez-toc-exclude-headings', 'lwptoc-skip', 'simpletoc-hidden' );
/**
* Parse HTML.
*
* @param string $html Rendered content.
* @param array $opts {
* @type int[] $levels Heading levels to list.
* @type string $exclude Text patterns, one per line or separated by |. * is a wildcard.
* @type string $exclude_classes Extra classes that skip a heading.
* @type string $anchor_format readable, ascii or numbered.
* @type string $anchor_prefix Optional prefix for generated anchors.
* @type bool $heading_links Add a "link to this section" anchor inside each heading.
* @type bool $mark_first Put markers around the first listed heading (used for positioning).
* @type int $page Page number for paginated posts.
* }
* @return array { content: string, items: array }
*/
public static function parse( $html, array $opts = array() ) {
$html = (string) $html;
$opts = wp_parse_args(
$opts,
array(
'levels' => array( 2, 3, 4 ),
'exclude' => '',
'exclude_classes' => '',
'anchor_format' => 'readable',
'anchor_prefix' => '',
'heading_links' => false,
'mark_first' => false,
'page' => 1,
'report' => false,
)
);
$levels = array_map( 'intval', (array) $opts['levels'] );
$patterns = self::exclude_patterns( $opts['exclude'] );
$skip = array_merge( self::SKIP_CLASSES, preg_split( '/\s+/', trim( (string) $opts['exclude_classes'] ), -1, PREG_SPLIT_NO_EMPTY ) );
$items = array();
$report = array();
if ( false === stripos( $html, ' $html,
'items' => array(),
'report' => array(),
);
}
// Keep code, scripts and similar blocks out of reach.
$vault = array();
$work = preg_replace_callback(
'#<(script|style|textarea|template|noscript|pre|form)\b[^>]*>.*?\1\s*>#is',
function ( $m ) use ( &$vault ) {
$key = '';
$vault[ $key ] = $m[0];
return $key;
},
$html
);
if ( null === $work ) {
$work = $html;
$vault = array();
}
// Every id already on the page, so a generated one never collides.
/**
* Ids themes commonly use outside the content (comments, skip links).
* A generated anchor never takes one of these.
*
* @param string[] $reserved Ids.
*/
$reserved = (array) apply_filters( 'aritoc_reserved_ids', array( 'comments', 'respond', 'content', 'main', 'primary', 'secondary', 'page', 'masthead', 'colophon', 'site-navigation', 'wp--skip-link--target' ) );
$used = array_fill_keys( array_map( 'strval', $reserved ), 1 );
if ( preg_match_all( '/\sid\s*=\s*(["\'])(.*?)\1/is', $html, $found ) ) {
foreach ( $found[2] as $existing ) {
$used[ $existing ] = 1;
}
}
$state = array(
'count' => 0,
'first' => true,
);
$result = preg_replace_callback(
'/"\']|"[^"]*"|\'[^\']*\')*)?)>(.*?)<\/h\1\s*>/is',
function ( $m ) use ( &$items, &$used, &$state, &$report, $levels, $patterns, $skip, $opts ) {
$level = (int) $m[1];
$attrs = $m[2];
$inner = $m[3];
$label = self::attr( $attrs, 'data-aritoc-label' );
$text = '' !== $label ? self::clean_text( $label ) : self::clean_text( $inner );
// Report mode (settings screen checks) records why each heading is left out.
$skipped = self::why_skipped( $level, $attrs, $text, $levels, $skip, $patterns );
if ( null !== $skipped ) {
if ( $opts['report'] ) {
$report[] = array(
'level' => $level,
'text' => $text,
'id' => self::attr( $attrs, 'id' ),
'status' => $skipped[0],
'detail' => $skipped[1],
);
}
return $m[0];
}
++$state['count'];
$id = self::attr( $attrs, 'id' );
if ( '' === $id ) {
$attrs = (string) preg_replace( '/\sid\s*=\s*(?:""|\'\')/i', '', $attrs );
$id = self::unique_id( self::make_id( $text, $state['count'], $opts ), $used );
$attrs .= ' id="' . esc_attr( $id ) . '"';
}
/**
* Filter one listed heading.
*
* @param array $item { level, id, text, page }.
*/
$items[] = apply_filters(
'aritoc_heading',
array(
'level' => $level,
'id' => $id,
'text' => $text,
'page' => (int) $opts['page'],
)
);
if ( ! empty( $opts['heading_links'] ) ) {
$inner .= sprintf(
'#',
esc_attr( rawurlencode( $id ) ),
esc_attr__( 'Copy a link to this section', 'aritoc' ),
esc_attr__( 'Link copied', 'aritoc' )
);
}
if ( $opts['report'] ) {
$report[] = array(
'level' => $level,
'text' => $text,
'id' => $id,
'status' => 'listed',
'detail' => '',
);
}
$out = '' . $inner . '';
if ( $state['first'] && ! empty( $opts['mark_first'] ) ) {
$out = AriTOC_Parser::FIRST_BEFORE . $out . AriTOC_Parser::FIRST_AFTER;
}
$state['first'] = false;
return $out;
},
$work
);
if ( null === $result ) {
return array(
'content' => $html,
'items' => array(),
'report' => array(),
);
}
if ( $vault ) {
$result = strtr( $result, $vault );
}
return array(
'content' => $result,
'items' => $items,
'report' => $report,
);
}
/**
* Remove the positioning markers.
*
* @param string $html HTML.
* @return string
*/
public static function strip_markers( $html ) {
return str_replace( array( self::FIRST_BEFORE, self::FIRST_AFTER ), '', $html );
}
/**
* Value of one attribute in an attribute string, decoded.
*
* @param string $attrs Attribute string.
* @param string $name Attribute name.
* @return string
*/
private static function attr( $attrs, $name ) {
if ( '' === $attrs ) {
return '';
}
if ( preg_match( '/\s' . preg_quote( $name, '/' ) . '\s*=\s*(?:"([^"]*)"|\'([^\']*)\'|([^\s"\'>]+))/i', $attrs, $m ) ) {
$value = isset( $m[3] ) ? $m[3] : ( isset( $m[2] ) && '' !== $m[2] ? $m[2] : $m[1] );
return trim( html_entity_decode( $value, ENT_QUOTES | ENT_HTML5, 'UTF-8' ) );
}
return '';
}
/**
* Why a heading is left out of the table.
*
* @param int $level Heading level.
* @param string $attrs Heading attributes.
* @param string $text Heading text.
* @param int[] $levels Selected levels.
* @param string[] $skip Skip classes.
* @param string[] $patterns Skip patterns.
* @return array|null [ reason, detail ], or null when the heading is listed.
*/
private static function why_skipped( $level, $attrs, $text, array $levels, array $skip, array $patterns ) {
if ( ! in_array( $level, $levels, true ) ) {
return array( 'level', '' );
}
$class = self::skip_class( $attrs, $skip );
if ( '' !== $class ) {
return array( 'class', $class );
}
if ( preg_match( '/\sdata-aritoc-skip\b/i', $attrs ) ) {
return array( 'class', 'data-aritoc-skip' );
}
if ( '' === $text ) {
return array( 'empty', '' );
}
$pattern = self::matched_pattern( $text, $patterns );
return '' !== $pattern ? array( 'text', $pattern ) : null;
}
/**
* The first skip class a heading carries.
*
* @param string $attrs Heading attributes.
* @param string[] $skip Skip classes.
* @return string Empty when none.
*/
private static function skip_class( $attrs, array $skip ) {
$class = self::attr( $attrs, 'class' );
if ( '' === $class ) {
return '';
}
$classes = preg_split( '/\s+/', strtolower( $class ), -1, PREG_SPLIT_NO_EMPTY );
$found = array_values( array_intersect( $classes, array_map( 'strtolower', $skip ) ) );
return $found ? (string) $found[0] : '';
}
/**
* Plain text from heading HTML.
*
* @param string $html Inner HTML.
* @return string
*/
public static function clean_text( $html ) {
$html = preg_replace( '#<(script|style)\b[^>]*>.*?\1>#is', '', (string) $html );
$text = html_entity_decode( wp_strip_all_tags( (string) $html ), ENT_QUOTES | ENT_HTML5, 'UTF-8' );
$flat = preg_replace( '/[\s\x{00A0}]+/u', ' ', $text );
return trim( null === $flat ? $text : $flat );
}
/**
* Anchor for a heading, before making it unique.
*
* @param string $text Heading text.
* @param int $index Position of the heading in the list (1 based).
* @param array $opts Parser options.
* @return string
*/
private static function make_id( $text, $index, array $opts ) {
$prefix = (string) $opts['anchor_prefix'];
if ( 'numbered' === $opts['anchor_format'] ) {
$id = ( '' !== $prefix ? $prefix : 'section' ) . '-' . (int) $index;
} else {
$id = self::slugify( $text, 'ascii' === $opts['anchor_format'] );
if ( '' === $id ) {
$id = 'section-' . (int) $index;
}
if ( '' !== $prefix ) {
$id = $prefix . '-' . $id;
}
}
/**
* Filter a generated anchor before it is made unique.
*
* @param string $id Anchor.
* @param string $text Heading text.
* @param array $opts Parser options.
*/
return (string) apply_filters( 'aritoc_anchor', $id, $text, $opts );
}
/**
* URL friendly anchor from heading text.
*
* @param string $text Heading text.
* @param bool $ascii Keep only a-z and 0-9.
* @return string Empty when nothing usable is left.
*/
public static function slugify( $text, $ascii = false ) {
$slug = remove_accents( (string) $text );
$slug = function_exists( 'mb_strtolower' ) ? mb_strtolower( $slug, 'UTF-8' ) : strtolower( $slug );
$slug = str_replace( array( '&', '@' ), array( ' and ', ' at ' ), $slug );
if ( $ascii ) {
$slug = preg_replace( '/[^a-z0-9]+/', '-', $slug );
} else {
// Letters, combining marks (needed for Bengali, Hindi and similar scripts) and numbers.
$slug = preg_replace( '/[^\p{L}\p{M}\p{N}]+/u', '-', $slug );
}
$slug = trim( (string) $slug, '-' );
if ( function_exists( 'mb_substr' ) ) {
$slug = trim( mb_substr( $slug, 0, 70, 'UTF-8' ), '-' );
} else {
$slug = trim( substr( $slug, 0, 70 ), '-' );
}
return $slug;
}
private static function unique_id( $slug, array &$used ) {
$id = $slug;
$n = 2;
while ( isset( $used[ $id ] ) ) {
$id = $slug . '-' . $n;
++$n;
}
$used[ $id ] = 1;
return $id;
}
/**
* Exclude patterns from lines or | separated text.
*
* A pattern without * must match the whole heading (any case).
* Use * for "anything", for example: Related* or *FAQ*
*
* @param string $raw Raw patterns.
* @return string[] Regular expressions, keyed by the pattern as typed.
*/
public static function exclude_patterns( $raw ) {
$out = array();
foreach ( preg_split( '/[\r\n|]+/u', (string) $raw ) as $line ) {
$line = trim( $line );
if ( '' === $line ) {
continue;
}
$out[ ' ' . $line ] = '/^' . str_replace( '\*', '.*', preg_quote( $line, '/' ) ) . '$/iu';
}
return $out;
}
/**
* The skip pattern (as typed) that matches a heading.
*
* @param string $text Heading text.
* @param string[] $patterns From exclude_patterns().
* @return string Empty when none matches.
*/
public static function matched_pattern( $text, array $patterns ) {
foreach ( $patterns as $typed => $pattern ) {
if ( preg_match( $pattern, $text ) ) {
return ltrim( (string) $typed, ' ' );
}
}
return '';
}
}