key() ] = $s; } } return self::$sources = $out; } /** @return Source|null */ public static function source( $key ) { $all = self::sources(); return isset( $all[ $key ] ) ? $all[ $key ] : null; } /** For tests: forget the cached list. */ public static function reset() { self::$sources = null; } /* --------------------------------------------------------------------- * Mapping: source table => Nitida table * ------------------------------------------------------------------ */ /** @return array,takeover:int,time:int}> */ public static function state() { $s = get_option( self::OPTION, array() ); return is_array( $s ) ? $s : array(); } private static function save_state( array $s ) { update_option( self::OPTION, $s, true ); // Autoloaded: the takeover runs on every page with a shortcode. } /** @return array Source id => Nitida id, only for Nitida tables that still exist. */ public static function mapped( $key ) { $s = self::state(); $map = isset( $s[ $key ]['tables'] ) && is_array( $s[ $key ]['tables'] ) ? $s[ $key ]['tables'] : array(); $out = array(); foreach ( $map as $src => $tid ) { if ( Store::exists( (int) $tid ) ) { $out[ (string) $src ] = (int) $tid; } } return $out; } public static function nitida_id( $key, $src_id ) { $m = self::mapped( $key ); return isset( $m[ (string) $src_id ] ) ? $m[ (string) $src_id ] : 0; } public static function takeover_on( $key ) { if ( 'tablepress' === $key ) { return (bool) Settings::get( 'compat_shortcode' ); } $s = self::state(); return ! empty( $s[ $key ]['takeover'] ); } /** Turns showing the old shortcodes and blocks with Nitida Tables on or off. */ public static function set_takeover( $key, $on ) { if ( 'tablepress' === $key ) { Settings::update( array_merge( Settings::all(), array( 'compat_shortcode' => $on ? 1 : 0 ) ) ); } else { $s = self::state(); $s[ $key ]['takeover'] = $on ? 1 : 0; self::save_state( $s ); } self::flush(); /** * Fires after the takeover of a source's shortcodes changes (page caches may need clearing). * * @param string $key Source key. * @param bool $on New state. */ do_action( 'nitida_tables_migrate_takeover', $key, (bool) $on ); } /* --------------------------------------------------------------------- * Import * ------------------------------------------------------------------ */ /** * Copies tables of a source into Nitida Tables. * * @param string $key Source key. * @param string[]|null $ids Source ids, or null for every importable table. * @param bool $overwrite Replace the Nitida copy of tables imported before. * @return array{imported:array,skipped:array,errors:array,notes:array} */ public static function import( $key, $ids = null, $overwrite = false ) { $res = array( 'imported' => array(), 'skipped' => array(), 'errors' => array(), 'notes' => array() ); $src = self::source( $key ); if ( ! $src ) { $res['errors']['*'] = __( 'Unknown source.', 'nitida-tables' ); return $res; } if ( null === $ids ) { $ids = array(); foreach ( $src->tables() as $t ) { if ( ! empty( $t['importable'] ) ) { $ids[] = (string) $t['id']; } } } $state = self::state(); $map = isset( $state[ $key ]['tables'] ) && is_array( $state[ $key ]['tables'] ) ? $state[ $key ]['tables'] : array(); foreach ( $ids as $sid ) { $sid = (string) $sid; $existing = isset( $map[ $sid ] ) && Store::exists( (int) $map[ $sid ] ) ? (int) $map[ $sid ] : 0; if ( ! $existing && $src->keep_ids() && ctype_digit( $sid ) && Store::exists( (int) $sid ) ) { $existing = (int) $sid; } if ( $existing && ! $overwrite ) { $res['skipped'][ $sid ] = $existing; $map[ $sid ] = $existing; continue; } $t = $src->read( $sid ); if ( empty( $t['ok'] ) ) { $res['errors'][ $sid ] = isset( $t['error'] ) ? (string) $t['error'] : __( 'The table could not be read.', 'nitida-tables' ); continue; } $data = self::rectangle( isset( $t['data'] ) ? (array) $t['data'] : array() ); if ( ! $data ) { $res['errors'][ $sid ] = __( 'The table is empty.', 'nitida-tables' ); continue; } $name = isset( $t['name'] ) && '' !== trim( (string) $t['name'] ) ? (string) $t['name'] : sprintf( /* translators: 1: plugin name, 2: table id there */ __( '%1$s table %2$s', 'nitida-tables' ), $src->label(), $sid ); $desc = isset( $t['description'] ) ? (string) $t['description'] : ''; $opt = isset( $t['options'] ) && is_array( $t['options'] ) ? $t['options'] : array( 'table_head' => 1 ); $vis = isset( $t['visibility'] ) && is_array( $t['visibility'] ) ? $t['visibility'] : null; if ( $existing ) { $r = Store::save( $existing, array( 'name' => $name, 'description' => $desc, 'data' => $data, 'visibility' => $vis, 'options' => $opt ) ); if ( empty( $r['ok'] ) ) { $res['errors'][ $sid ] = isset( $r['error'] ) ? (string) $r['error'] : __( 'The table could not be saved.', 'nitida-tables' ); continue; } $new = $existing; } else { $want = ( $src->keep_ids() && ctype_digit( $sid ) ) ? (int) $sid : 0; $new = Store::create( $name, $data, $want, $desc, $vis, $opt ); if ( ! $new && $want ) { $new = Store::create( $name, $data, 0, $desc, $vis, $opt ); } if ( ! $new ) { $res['errors'][ $sid ] = __( 'The table could not be created.', 'nitida-tables' ); continue; } } $map[ $sid ] = (int) $new; $res['imported'][ $sid ] = (int) $new; if ( ! empty( $t['notes'] ) ) { $res['notes'][ $sid ] = array_values( array_map( 'strval', (array) $t['notes'] ) ); } } $state[ $key ]['tables'] = $map; $state[ $key ]['time'] = time(); if ( ! isset( $state[ $key ]['takeover'] ) ) { $state[ $key ]['takeover'] = 0; } self::save_state( $state ); if ( $src->keep_ids() ) { self::reserve_ids( array_keys( $map ) ); } self::flush(); /** * Fires after tables were copied from another plugin. * * @param string $key Source key. * @param array $res Result. */ do_action( 'nitida_tables_migrated', $key, $res ); return $res; } /** Pads rows to one length and caps the row count. */ public static function rectangle( array $rows ) { $rows = array_values( array_filter( $rows, 'is_array' ) ); if ( ! $rows ) { return array(); } $rows = array_slice( $rows, 0, self::MAX_ROWS + 1 ); $w = max( array_map( 'count', $rows ) ); if ( $w < 1 ) { return array(); } foreach ( $rows as &$r ) { $r = array_map( function ( $c ) { return is_scalar( $c ) || null === $c ? (string) $c : ''; }, array_values( $r ) ); $r = array_pad( $r, $w, '' ); } return $rows; } /** New Nitida tables must not take numbers kept from a source. */ private static function reserve_ids( array $ids ) { $max = 0; foreach ( $ids as $i ) { if ( ctype_digit( (string) $i ) ) { $max = max( $max, (int) $i ); } } $i = Store::index(); if ( $max > $i['last_id'] ) { $i['last_id'] = $max; Store::save_index( $i ); } } /* --------------------------------------------------------------------- * Where source tables are used * ------------------------------------------------------------------ */ /** * Source ids used in a piece of content, by shortcode or block. * * @return string[] */ public static function ids_in_content( Source $src, $content ) { $content = (string) $content; $ids = array(); $tags = $src->shortcodes(); if ( $tags ) { $re = '/\[(' . implode( '|', array_map( function ( $t ) { return preg_quote( $t, '/' ); }, $tags ) ) . ')(\s[^\]]*)?\]/'; if ( preg_match_all( $re, $content, $m, PREG_SET_ORDER ) ) { foreach ( $m as $sc ) { $atts = function_exists( 'shortcode_parse_atts' ) ? shortcode_parse_atts( isset( $sc[2] ) ? trim( $sc[2] ) : '' ) : array(); $id = $src->shortcode_id( is_array( $atts ) ? $atts : array() ); if ( '' !== $id ) { $ids[] = $id; } } } } foreach ( $src->blocks() as $name => $attr ) { if ( preg_match_all( '//s', $content, $m ) ) { foreach ( $m[1] as $json ) { $a = json_decode( $json, true ); if ( is_array( $a ) && isset( $a[ $attr ] ) && '' !== (string) $a[ $attr ] ) { $ids[] = (string) $a[ $attr ]; } } } } return array_values( array_unique( $ids ) ); } /** * Published content that shows tables of a source. * * @return array Source id => post ids. */ public static function usage( Source $src ) { global $wpdb; $likes = array(); foreach ( $src->shortcodes() as $t ) { $likes[] = '%' . $wpdb->esc_like( '[' . $t ) . '%'; } foreach ( array_keys( $src->blocks() ) as $b ) { $likes[] = '%' . $wpdb->esc_like( 'wp:' . $b ) . '%'; } if ( ! $likes ) { return array(); } $where = implode( ' OR ', array_fill( 0, count( $likes ), 'post_content LIKE %s' ) ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- $where is only '%s' placeholders; the scan result is cached. $rows = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_content FROM {$wpdb->posts} WHERE post_status IN ('publish','future','private') AND post_type NOT IN ('revision','attachment','nav_menu_item') AND ( {$where} ) LIMIT 5000", $likes ) ); $out = array(); foreach ( (array) $rows as $r ) { foreach ( self::ids_in_content( $src, $r->post_content ) as $id ) { $out[ $id ][] = (int) $r->ID; } } return $out; } /** * Everything the assistant screen needs, per present source. Cached for an hour. * * @return array */ public static function scan( $fresh = false ) { // Notes are translated: one cache per language, and a version number so flush() clears all of them. $key = self::SCAN . '_' . (int) get_option( self::SCAN . '_v', 0 ) . '_' . ( function_exists( 'determine_locale' ) ? determine_locale() : 'en_US' ); $c = $fresh ? false : get_transient( $key ); if ( is_array( $c ) ) { return $c; } $out = array(); foreach ( self::sources() as $key => $src ) { if ( ! $src->present() ) { continue; } $tables = $src->tables(); $mapped = self::mapped( $key ); if ( $src->keep_ids() ) { // Copies made before the assistant existed: same number and same name. foreach ( $tables as $t ) { $sid = (string) $t['id']; if ( isset( $mapped[ $sid ] ) || ! ctype_digit( $sid ) || ! Store::exists( (int) $sid ) ) { continue; } $copy = Store::get( (int) $sid ); if ( $copy && (string) $copy['name'] === (string) $t['name'] ) { $mapped[ $sid ] = (int) $sid; } } } $out[ $key ] = array( 'label' => $src->label(), 'active' => $src->is_active(), 'tables' => $tables, 'usage' => self::usage( $src ), 'mapped' => $mapped, 'takeover' => self::takeover_on( $key ), 'advice' => $src->advice(), ); } set_transient( $key, $out, HOUR_IN_SECONDS ); return $out; } public static function flush() { update_option( self::SCAN . '_v', (int) get_option( self::SCAN . '_v', 0 ) + 1, false ); } /** Totals for notices: tables still to move, across sources ('core' is counted apart). */ public static function pending() { $p = array( 'tables' => 0, 'sources' => array() ); foreach ( self::scan() as $key => $s ) { if ( 'core' === $key ) { continue; } $n = 0; foreach ( $s['tables'] as $t ) { $sid = (string) $t['id']; if ( empty( $t['importable'] ) || isset( $s['mapped'][ $sid ] ) ) { continue; } // Once old shortcodes show the copies, a leftover table no post uses needs no nudge. if ( $s['takeover'] && empty( $s['usage'][ $sid ] ) ) { continue; } $n++; } if ( $n ) { $p['tables'] += $n; $p['sources'][ $key ] = $n; } } return $p; } /* --------------------------------------------------------------------- * Takeover: old shortcodes and blocks show the Nitida copy * ------------------------------------------------------------------ */ public static function register_takeover() { global $shortcode_tags; foreach ( self::sources() as $key => $src ) { if ( 'tablepress' === $key || ! self::takeover_on( $key ) ) { continue; } // TablePress: Plugin::register_compat_shortcode(). if ( ! self::mapped( $key ) ) { continue; } foreach ( $src->shortcodes() as $tag ) { $prev = isset( $shortcode_tags[ $tag ] ) ? $shortcode_tags[ $tag ] : null; add_shortcode( $tag, function ( $atts, $content = '', $t = '' ) use ( $src, $key, $prev, $tag ) { $tid = self::nitida_id( $key, $src->shortcode_id( is_array( $atts ) ? $atts : array() ) ); if ( $tid ) { return Renderer::output( $tid, 'compat' ); } return ( $prev && is_callable( $prev ) ) ? call_user_func( $prev, $atts, $content, '' !== $t ? $t : $tag ) : ''; } ); } } } /** Blocks of a source with takeover on render the Nitida copy. */ public static function render_block( $html, $block ) { if ( empty( $block['blockName'] ) || is_admin() ) { return $html; } foreach ( self::sources() as $key => $src ) { $blocks = $src->blocks(); if ( ! isset( $blocks[ $block['blockName'] ] ) || ! self::takeover_on( $key ) ) { continue; } $attr = $blocks[ $block['blockName'] ]; $sid = isset( $block['attrs'][ $attr ] ) ? (string) $block['attrs'][ $attr ] : ''; $tid = '' !== $sid ? self::nitida_id( $key, $sid ) : 0; return $tid ? Renderer::output( $tid, 'compat' ) : $html; } return $html; } } add_action( 'init', array( Migrate::class, 'register_takeover' ), 1001 ); // After the source plugins register theirs. add_filter( 'render_block', array( Migrate::class, 'render_block' ), 10, 2 ); add_action( 'save_post', array( Migrate::class, 'flush' ) ); add_action( 'activated_plugin', array( Migrate::class, 'flush' ) ); add_action( 'deactivated_plugin', array( Migrate::class, 'flush' ) );