wrapper (added by wpautop) is only dropped when it wraps the marker alone.
const MARKER_RE = '#
\s*\s*
|#';
/** Left by [no_toc]: turns the table off for this post. */
const OFF_MARKER = '';
/** @var AriTOC_Plugin|null */
private static $instance = null;
/** @var array Items per post id, shared with the widget and the block. */
private static $items = array();
/** @var bool Guards against running inside ourselves. */
private static $running = false;
/** @var bool */
private static $assets_done = false;
public static function instance() {
if ( null === self::$instance ) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct() {
add_action( 'init', array( $this, 'init' ) );
add_action( 'widgets_init', array( $this, 'register_widget' ) );
add_action( 'wp_enqueue_scripts', array( $this, 'maybe_enqueue' ) );
add_filter( 'the_content', array( $this, 'filter_content' ), 20 );
AriTOC_Post::init();
AriTOC_Block::init();
AriTOC_Migrate::init();
AriTOC_Compat::init();
if ( is_admin() ) {
AriTOC_Admin::init();
}
}
public function init() {
wp_register_style( 'aritoc', ARITOC_URL . 'assets/css/aritoc.css', array(), ARITOC_VERSION );
wp_register_script(
'aritoc',
ARITOC_URL . 'assets/js/aritoc.js',
array(),
ARITOC_VERSION,
array(
'in_footer' => true,
'strategy' => 'defer',
)
);
add_shortcode( 'aritoc', array( $this, 'shortcode' ) );
}
public function register_widget() {
register_widget( 'AriTOC_Widget' );
}
/* ------------------------------------------------------------------ *
* Assets
* ------------------------------------------------------------------ */
/**
* Load the stylesheet and script once. Safe to call while rendering:
* WordPress prints late styles and scripts in the footer.
*/
public static function enqueue_assets() {
if ( ! wp_style_is( 'aritoc', 'registered' ) ) {
return;
}
wp_enqueue_style( 'aritoc' );
wp_enqueue_script( 'aritoc' );
if ( self::$assets_done ) {
return;
}
self::$assets_done = true;
$s = AriTOC_Settings::all();
$css = ':root{--aritoc-offset:' . (int) $s['scroll_offset'] . 'px}';
if ( ! empty( $s['smooth_scroll'] ) ) {
$css .= '@media (prefers-reduced-motion:no-preference){html{scroll-behavior:smooth}}';
}
wp_add_inline_style( 'aritoc', $css );
/**
* Fires once when AriTOC loads its front-end assets on a page (add-ons load theirs here).
*/
do_action( 'aritoc_assets' );
}
/**
* Load assets in the head when we already know the page needs them.
*/
public function maybe_enqueue() {
if ( ! is_singular() ) {
return;
}
$post = get_queried_object();
if ( ! $post instanceof WP_Post ) {
return;
}
$content = (string) $post->post_content;
// Cheap guess: enough headings in the raw content to show a table.
// When the guess is wrong, rendering still loads the assets late.
$enough = preg_match_all( '/]/i', $content ) >= max( 1, (int) AriTOC_Settings::get( 'min_headings' ) );
$placed = has_shortcode( $content, 'aritoc' )
|| has_block( 'aritoc/toc', $post )
|| is_active_widget( false, false, 'aritoc_widget', true )
|| ( AriTOC_Migrate::takeover_active() && AriTOC_Migrate::has_foreign_shortcode( $content ) );
$wanted = $enough && ( $placed || $this->auto_enabled( $post ) );
/**
* Filter whether to load AriTOC assets in the head on this page.
*
* @param bool $wanted Whether assets are wanted.
* @param WP_Post $post Current post.
*/
if ( apply_filters( 'aritoc_enqueue', $wanted, $post ) ) {
self::enqueue_assets();
}
}
/* ------------------------------------------------------------------ *
* Shortcode and markers
* ------------------------------------------------------------------ */
/**
* [aritoc title="In this article" levels="2,3" exclude="FAQ|Related*" numbering="roman"
* theme="dark" collapsible="yes" collapsed="no" hierarchical="yes" class="my-class"]
*
* @param array|string $atts Attributes.
* @return string
*/
public function shortcode( $atts ) {
return self::placeholder( is_array( $atts ) ? $atts : array(), 'shortcode' );
}
/**
* Inside the post content, leave a marker that the content filter swaps
* for the table (the headings are only known then). Anywhere else, render
* the table of the current post straight away.
*
* @param array $args Overrides.
* @param string $context shortcode or block.
* @return string
*/
public static function placeholder( array $args, $context ) {
$args = array_filter(
$args,
function ( $v ) {
return null !== $v && '' !== $v && array() !== $v;
}
);
if ( self::$running || doing_filter( 'the_content' ) ) {
return $args ? '' : '';
}
$post = is_singular() ? get_queried_object() : get_post();
if ( ! $post instanceof WP_Post ) {
return '';
}
return self::render_for_post( $post, $args, $context );
}
private static function decode_marker( $data ) {
if ( '' === (string) $data ) {
return array();
}
$json = json_decode( rawurldecode( (string) $data ), true );
return is_array( $json ) ? $json : array();
}
public static function strip_all_markers( $content ) {
$content = preg_replace( self::MARKER_RE, '', (string) $content );
return AriTOC_Parser::strip_markers( str_replace( self::OFF_MARKER, '', (string) $content ) );
}
/* ------------------------------------------------------------------ *
* Decisions
* ------------------------------------------------------------------ */
/**
* Settings for one post: global settings with the post's own overrides.
*
* @param WP_Post $post Post.
* @return array
*/
public static function settings_for( WP_Post $post ) {
$settings = AriTOC_Settings::merge( AriTOC_Settings::all(), AriTOC_Post::overrides( $post->ID ) );
$settings['post_id'] = (int) $post->ID;
return $settings;
}
/**
* Should the table be inserted automatically into this post?
*
* @param WP_Post $post Post.
* @return bool
*/
public function auto_enabled( WP_Post $post ) {
$mode = AriTOC_Post::mode( $post->ID );
if ( 'hide' === $mode ) {
$auto = false;
} elseif ( 'show' === $mode ) {
$auto = true;
} else {
$auto = in_array( $post->post_type, (array) AriTOC_Settings::get( 'post_types' ), true );
}
/**
* Filter whether the table is inserted automatically.
*
* @param bool $auto Insert automatically.
* @param WP_Post $post Post.
*/
return (bool) apply_filters( 'aritoc_auto_insert', $auto, $post );
}
/**
* Is this the_content call for the main post of a single view?
* Works on block themes too, where in_the_loop() is false.
*
* @return WP_Post|null
*/
private function main_post() {
if ( is_admin() || is_feed() || ! is_singular() ) {
return null;
}
if ( doing_filter( 'get_the_excerpt' ) || doing_action( 'wp_head' ) || doing_filter( 'wp_trim_excerpt' ) ) {
return null;
}
$post = get_post();
if ( ! $post instanceof WP_Post || (int) $post->ID !== (int) get_queried_object_id() ) {
return null;
}
if ( post_password_required( $post ) ) {
return null;
}
return $post;
}
/**
* Headings of the main post get anchors even without a table in the
* content, because a table elsewhere on the page may link to them.
*
* @param WP_Post $post Post.
* @return bool
*/
private function anchors_wanted( WP_Post $post ) {
// A table outside the content (widget, block in a widget area or
// template, template tag) may render after it, so always add them.
$wanted = true;
/**
* Filter whether headings of this post get anchors when no table is inserted.
*
* @param bool $wanted Add anchors.
* @param WP_Post $post Post.
*/
return (bool) apply_filters( 'aritoc_add_anchors', $wanted, $post );
}
/* ------------------------------------------------------------------ *
* Content filter
* ------------------------------------------------------------------ */
public function filter_content( $content ) {
if ( self::$running ) {
return $content;
}
$has_marker = false !== strpos( $content, ')
* ------------------------------------------------------------------ */
/**
* Split post content into pages the way WordPress does.
*
* @param WP_Post $post Post.
* @return string[]
*/
public static function pages_of( WP_Post $post ) {
$content = (string) $post->post_content;
if ( false === strpos( $content, '' ) ) {
return array( $content );
}
// Same steps as core's WP_Query::generate_postdata().
$content = str_replace( array( '', '' ), '', $content );
$content = str_replace( array( "\n\n", "\n", "\n" ), '', $content );
if ( 0 === strpos( $content, '' ) ) {
$content = substr( $content, 15 );
}
return explode( '', $content );
}
/**
* Add headings from the other pages of a paginated post, in order.
*
* @param WP_Post $post Post.
* @param array $settings Settings.
* @param int $current Current page.
* @param array $items Items of the current page.
* @return array
*/
private static function with_other_pages( WP_Post $post, array $settings, $current, array $items ) {
if ( empty( $settings['nextpage'] ) ) {
return $items;
}
$pages = self::pages_of( $post );
if ( count( $pages ) < 2 ) {
return $items;
}
$all = array();
foreach ( $pages as $index => $raw ) {
$num = $index + 1;
if ( $num === (int) $current ) {
$all = array_merge( $all, $items );
continue;
}
/**
* Filter the HTML of another page of a paginated post before its headings are read.
*
* @param string $html Page HTML (blocks rendered, shortcodes not run).
* @param WP_Post $post Post.
* @param int $num Page number.
*/
$html = (string) apply_filters( 'aritoc_page_html', self::like_the_content( do_blocks( $raw ) ), $post, $num );
$parsed = AriTOC_Parser::parse( $html, self::parser_opts( $settings, $num ) );
$url = self::page_url( $post, $num );
foreach ( $parsed['items'] as $item ) {
$item['url'] = $url . '#' . rawurlencode( $item['id'] );
$all[] = $item;
}
}
return $all;
}
/**
* Apply the text filters that run on the_content before AriTOC, so
* headings read outside the content filter get the same anchors.
*
* @param string $html HTML.
* @return string
*/
private static function like_the_content( $html ) {
return convert_smilies( wptexturize( (string) $html ) );
}
/**
* URL of one page of a paginated post (mirrors core's _wp_link_page()).
*
* @param WP_Post $post Post.
* @param int $num Page number.
* @return string
*/
public static function page_url( WP_Post $post, $num ) {
global $wp_rewrite;
$url = get_permalink( $post );
if ( 1 === (int) $num ) {
return $url;
}
if ( ! get_option( 'permalink_structure' ) || in_array( $post->post_status, array( 'draft', 'pending' ), true ) ) {
return add_query_arg( 'page', (int) $num, $url );
}
if ( 'page' === get_option( 'show_on_front' ) && (int) get_option( 'page_on_front' ) === (int) $post->ID ) {
return trailingslashit( $url ) . user_trailingslashit( $wp_rewrite->pagination_base . '/' . (int) $num, 'single_paged' );
}
return trailingslashit( $url ) . user_trailingslashit( (string) (int) $num, 'single_paged' );
}
/* ------------------------------------------------------------------ *
* Outside the content: widget, template block, template tag
* ------------------------------------------------------------------ */
/**
* Headings of a post. Uses what the content filter found when it already
* ran, otherwise reads the post once and keeps the result for the request.
*
* @param WP_Post $post Post.
* @return array
*/
public static function items_for( WP_Post $post ) {
if ( isset( self::$items[ $post->ID ] ) ) {
return self::$items[ $post->ID ];
}
if ( self::$running || post_password_required( $post ) ) {
return array();
}
$settings = self::settings_for( $post );
$pages = self::pages_of( $post );
$page = ( (int) $post->ID === (int) get_queried_object_id() ) ? max( 1, (int) get_query_var( 'page' ) ) : 1;
$page = min( $page, count( $pages ) );
self::$running = true;
$html = self::like_the_content( do_shortcode( do_blocks( $pages[ $page - 1 ] ) ) );
$parsed = AriTOC_Parser::parse( $html, self::parser_opts( $settings, $page ) );
$items = self::with_other_pages( $post, $settings, $page, $parsed['items'] );
self::$running = false;
self::$items[ $post->ID ] = $items;
return $items;
}
/**
* Render the table of a post with optional overrides.
*
* @param WP_Post $post Post.
* @param array $overrides Overrides.
* @param string $context widget, block, shortcode or template.
* @return string
*/
public static function render_for_post( WP_Post $post, array $overrides = array(), $context = 'template' ) {
if ( 'hide' === AriTOC_Post::mode( $post->ID ) || ( AriTOC_Migrate::takeover_active() && has_shortcode( (string) $post->post_content, 'no_toc' ) ) ) {
return '';
}
$args = AriTOC_Settings::merge( self::settings_for( $post ), $overrides );
$args['context'] = sanitize_key( $context );
return self::build_for( self::items_for( $post ), $args );
}
/* ------------------------------------------------------------------ *
* Diagnosis (settings screen: "Check a page")
* ------------------------------------------------------------------ */
/**
* Explain what AriTOC does on one post: whether a table shows, why, and
* what happens to every heading. Reads the saved post, not the live page,
* so content added by page builders outside post_content is not seen.
*
* @param WP_Post $post Post.
* @param array|null $settings Settings to test (unsaved screen values), or null for the saved ones.
* @return array {
* @type bool $shows Whether a table shows in or next to the content.
* @type string $verdict One sentence.
* @type array $checks Each: state (ok, no, info) and text.
* @type array $headings Each: level, text, id, page, status (listed, level, class, text, empty), detail.
* @type int $listed Headings that would be listed.
* @type int $min Minimum headings.
* }
*/
public static function diagnose( WP_Post $post, $settings = null ) {
$base = is_array( $settings ) ? $settings : AriTOC_Settings::all();
$settings = AriTOC_Settings::merge( $base, AriTOC_Post::overrides( $post->ID ) );
$content = (string) $post->post_content;
$checks = array();
$type = get_post_type_object( $post->post_type );
$type = $type ? $type->labels->name : $post->post_type;
// Pass 1: render every page as the front end would. While $running is
// set, the block and shortcodes leave markers carrying their options.
$rendered = array();
$previous = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
$buffers = ob_get_level();
$GLOBALS['post'] = $post; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- restored below; blocks read the current post.
setup_postdata( $post );
self::$running = true;
try {
foreach ( self::pages_of( $post ) as $raw ) {
ob_start(); // Some shortcodes echo instead of returning.
$rendered[] = self::like_the_content( do_shortcode( do_blocks( $raw ) ) );
ob_end_clean();
}
} finally {
while ( ob_get_level() > $buffers ) {
ob_end_clean();
}
self::$running = false;
$GLOBALS['post'] = $previous; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited -- restoring.
if ( $previous instanceof WP_Post ) {
setup_postdata( $previous );
} else {
wp_reset_postdata();
}
}
// A placed block or shortcode uses its own options; the first one decides.
$placed_args = null;
foreach ( $rendered as $html ) {
if ( preg_match( self::MARKER_RE, $html, $m ) ) {
$placed_args = AriTOC_Settings::merge( $settings, self::decode_marker( ! empty( $m[1] ) ? $m[1] : ( isset( $m[2] ) ? $m[2] : '' ) ) );
break;
}
}
$effective = $placed_args ? $placed_args : $settings;
// Pass 2: every heading and what happens to it.
$headings = array();
foreach ( $rendered as $index => $html ) {
$opts = self::parser_opts( $effective, $index + 1 );
$opts['report'] = true;
$parsed = AriTOC_Parser::parse( $html, $opts );
foreach ( $parsed['report'] as $row ) {
$row['page'] = $index + 1;
$headings[] = $row;
}
if ( empty( $effective['nextpage'] ) ) {
break; // Each page lists only its own headings then; the first page stands for the rest.
}
}
$listed = count(
array_filter(
$headings,
function ( $h ) {
return 'listed' === $h['status'];
}
)
);
$min = max( 1, (int) $effective['min_headings'] );
// Decided from the settings being tested, which may be unsaved.
$mode = AriTOC_Post::mode( $post->ID );
if ( 'hide' === $mode ) {
$auto = false;
} elseif ( 'show' === $mode ) {
$auto = true;
} else {
$auto = in_array( $post->post_type, (array) $settings['post_types'], true );
}
/** This filter is documented in includes/class-aritoc-plugin.php (auto_enabled). */
$auto = (bool) apply_filters( 'aritoc_auto_insert', $auto, $post );
$takeover = AriTOC_Migrate::takeover_active();
$block = has_block( 'aritoc/toc', $post );
$code = has_shortcode( $content, 'aritoc' ) || ( $takeover && AriTOC_Migrate::has_foreign_shortcode( $content ) );
$off = $takeover && has_shortcode( $content, 'no_toc' );
$widget = is_active_widget( false, false, 'aritoc_widget', true );
if ( 'publish' !== $post->post_status ) {
$checks[] = array( 'info', __( 'This page is not published, so visitors cannot see it yet.', 'aritoc' ) );
}
if ( 'hide' === $mode ) {
$checks[] = array( 'no', __( 'The page is set to “Hide on this page” in its Table of contents box.', 'aritoc' ) );
} elseif ( 'show' === $mode ) {
$checks[] = array( 'ok', __( 'The page is set to “Show on this page” in its Table of contents box.', 'aritoc' ) );
} elseif ( $auto ) {
/* translators: %s: post type name, such as Posts. */
$checks[] = array( 'ok', sprintf( __( 'Automatic insertion is on for %s.', 'aritoc' ), $type ) );
} else {
/* translators: %s: post type name, such as Posts. */
$checks[] = array( $block || $code ? 'info' : 'no', sprintf( __( 'Automatic insertion is off for %s.', 'aritoc' ), $type ) );
}
if ( $block ) {
$checks[] = array( 'ok', __( 'The page contains the AriTOC block.', 'aritoc' ) );
}
if ( $code ) {
$checks[] = array( 'ok', __( 'The page contains a table of contents shortcode.', 'aritoc' ) );
}
if ( $off ) {
$checks[] = array( 'no', __( 'The page contains [no_toc], which turns the table off.', 'aritoc' ) );
}
if ( '' !== $post->post_password ) {
$checks[] = array( 'info', __( 'The page is password protected: the table appears once the visitor enters the password.', 'aritoc' ) );
}
if ( 'builder' === get_post_meta( $post->ID, '_elementor_edit_mode', true ) ) {
$checks[] = array( 'info', __( 'The page is built with Elementor. Its headings are stored outside the post content, so add the [aritoc] shortcode with a Shortcode widget.', 'aritoc' ) );
}
$checks[] = array(
$listed >= $min ? 'ok' : 'no',
sprintf(
/* translators: 1: headings listed, 2: minimum headings. */
_n( '%1$d heading would be listed; the minimum is %2$d.', '%1$d headings would be listed; the minimum is %2$d.', $listed, 'aritoc' ),
$listed,
$min
),
);
if ( $widget ) {
$checks[] = array( 'info', __( 'An AriTOC widget is active, so a sidebar may show a table even when the content has none.', 'aritoc' ) );
}
// Markers also catch tables placed inside synced patterns or other blocks.
$placed = $block || $code || null !== $placed_args;
$shows = false;
if ( 'hide' === $mode || $off ) {
$verdict = __( 'No table: it is turned off for this page.', 'aritoc' );
} elseif ( ! $auto && ! $placed ) {
$verdict = __( 'No table in the content: automatic insertion does not apply here and the page has no AriTOC block or shortcode.', 'aritoc' );
} elseif ( $listed < $min ) {
$verdict = __( 'No table: the page has fewer headings than the minimum.', 'aritoc' );
} elseif ( $placed ) {
$shows = true;
$verdict = __( 'A table shows where the block or shortcode is placed.', 'aritoc' );
} else {
$shows = true;
$positions = AriTOC_Settings::positions();
$verdict = sprintf(
/* translators: %s: position, such as "Before the first heading". */
__( 'A table shows automatically: %s.', 'aritoc' ),
isset( $positions[ $settings['position'] ] ) ? $positions[ $settings['position'] ] : $settings['position']
);
}
return array(
'shows' => $shows,
'verdict' => $verdict,
'checks' => $checks,
'headings' => $headings,
'listed' => $listed,
'min' => $min,
);
}
}