_… (rows, sub-fields). */ const COMPOUND_TYPES = array( 'repeater', 'flexible_content', 'group', 'clone', 'gallery' ); public static function boot() { add_action( 'init', array( self::class, 'register_type' ) ); add_action( 'adibridge_register_tools', array( self::class, 'register_tools' ) ); add_action( 'before_delete_post', array( self::class, 'forget' ) ); } /** A post deleted for good takes its restore points (full copies of its content) with it. */ public static function forget( $post_id ) { if ( self::POST_TYPE === get_post_type( $post_id ) ) { return; } foreach ( self::ids_for( (int) $post_id ) as $id ) { wp_delete_post( $id, true ); } } public static function register_type() { register_post_type( self::POST_TYPE, array( 'label' => 'ADI restore points', 'public' => false, 'show_ui' => false, 'show_in_rest' => false, 'rewrite' => false, 'query_var' => false, 'supports' => array( 'title' ), // Nobody handles restore points through WordPress itself (XML-RPC, REST, admin): only // the bridge, which checks access against the content they belong to. 'capabilities' => array_fill_keys( array( 'edit_post', 'read_post', 'delete_post', 'edit_posts', 'edit_others_posts', 'delete_posts', 'delete_others_posts', 'publish_posts', 'read_private_posts', 'create_posts' ), 'do_not_allow' ), 'map_meta_cap' => false, ) ); } /** How many restore points to keep per target. */ public static function cap() { return max( 1, (int) apply_filters( 'adibridge_snapshot_cap', 20 ) ); } // ── Taking ────────────────────────────────────────────────────────────────────────── /** * Record $target's current state. $target: a post id, or "options:". $children: child post ids * recorded with it (null: those the adibridge_snapshot_children filter names for $path). * * @return int The snapshot id. */ public static function take( $target, $path, $before, $kind = 'before_update', $children = null ) { // Child posts the point also records (a variation, for a variation field's change: #22). $data = self::capture( $target, null === $children ? self::children_for( $target, $path ) : array_map( 'intval', (array) $children ) ); $user = wp_get_current_user(); $id = wp_insert_post( array( 'post_type' => self::POST_TYPE, 'post_status' => 'private', 'post_title' => wp_strip_all_tags( "$kind $path" ), 'post_parent' => is_int( $target ) ? $target : 0, 'post_author' => $user->ID, ), true ); if ( is_wp_error( $id ) ) { throw new Tool_Error( esc_html( 'Could not save a restore point, so nothing was changed: ' . $id->get_error_message() ) ); } $json = wp_json_encode( $data ); if ( false === $json ) { wp_delete_post( $id, true ); throw new Tool_Error( 'Could not save a restore point (the current content could not be recorded), so nothing was changed.' ); } update_post_meta( $id, self::DATA_META, wp_slash( $json ) ); update_post_meta( $id, '_adibridge_target', (string) $target ); update_post_meta( $id, '_adibridge_path', (string) $path ); update_post_meta( $id, '_adibridge_kind', $kind ); $preview = wp_json_encode( self::preview( $before ) ); update_post_meta( $id, '_adibridge_before', wp_slash( false === $preview ? 'null' : $preview ) ); $token = Auth::current_token_label(); if ( null !== $token ) { update_post_meta( $id, '_adibridge_token', $token ); } return $id; } /** * The write this restore point was taken for went through: drop the oldest points beyond the * cap. (Pruning only after success means refused attempts can't push real history out.) */ public static function kept( $target ) { self::prune( $target ); } /** * The write was refused. If the target is exactly as recorded (nothing was changed), the restore * point is noise: delete it. If anything differs — a put-back that didn't fully hold — keep it, * it is the way back. */ public static function discard_if_unchanged( $snapshot_id ) { $raw = get_post_meta( $snapshot_id, '_adibridge_target', true ); $target = ctype_digit( (string) $raw ) ? (int) $raw : $raw; $data = json_decode( (string) get_post_meta( $snapshot_id, self::DATA_META, true ), true ); try { $now = self::capture( $target, is_array( $data ) ? self::child_ids( $data ) : array() ); } catch ( Tool_Error $e ) { return; } if ( is_array( $data ) && self::same_state( $data, $now ) ) { wp_delete_post( $snapshot_id, true ); } } private static function same_state( array $a, array $b ) { if ( 'post' === $a['type'] ) { // Compared as JSON: $a came back through JSON, and loose == would equate "1" and "01". return wp_json_encode( array( $a['row'], $a['meta'], self::terms_of( $a ), self::children_of( $a ) ) ) === wp_json_encode( array( $b['row'], $b['meta'], self::terms_of( $b ), self::children_of( $b ) ) ); } $index = static function ( array $rows ) { $out = array(); foreach ( $rows as $o ) { $out[ $o['option_name'] ] = $o['option_value']; } ksort( $out ); return $out; }; return wp_json_encode( $index( $a['options'] ) ) === wp_json_encode( $index( $b['options'] ) ); } /** A short "before" for the history list: text cut to 300 characters, structures to 300 of JSON. */ private static function preview( $value ) { if ( is_string( $value ) ) { $text = wp_strip_all_tags( $value ); return mb_strlen( $text ) > 300 ? mb_substr( $text, 0, 300 ) . '…' : $text; } if ( is_array( $value ) ) { $json = wp_json_encode( $value ); if ( false === $json ) { return null; } return strlen( $json ) > 300 ? mb_substr( $json, 0, 300 ) . '…' : $value; } return $value; } /** * Stored bytes that aren't valid UTF-8 (legacy Latin-1 in serialized meta) can't go through * JSON unchanged: record those as base64 so a restore puts back exactly the same bytes. */ private static function enc( $value ) { return is_string( $value ) && 1 !== preg_match( '//u', $value ) ? array( 'b64' => base64_encode( $value ) ) : $value; // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode } private static function dec( $value ) { return is_array( $value ) && isset( $value['b64'] ) ? base64_decode( $value['b64'] ) : $value; // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode } /** * $wpdb->insert/update/replace refuse values that aren't valid in the column's charset (the * legacy bytes enc() preserved): write those rows with a prepared query that skips the check. */ private static function write_row( $verb, $table, array $data, array $where = array() ) { global $wpdb; $clean = true; foreach ( $data as $v ) { if ( is_string( $v ) && 1 !== preg_match( '//u', $v ) ) { $clean = false; } } if ( $clean ) { return 'update' === $verb ? $wpdb->update( $table, $data, $where ) : $wpdb->$verb( $table, $data ); } $cols = array_keys( $data ); if ( 'update' === $verb ) { $set = implode( ', ', array_map( static function ( $c ) { return "`$c` = %s"; }, $cols ) ); $cond = implode( ' AND ', array_map( static function ( $c ) { return "`$c` = %s"; }, array_keys( $where ) ) ); $sql = $wpdb->prepare( "UPDATE `$table` SET $set WHERE $cond", array_merge( array_values( $data ), array_values( $where ) ) ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- $table is a $wpdb table name and the columns are the keys of a row this class read itself; $set/$cond hold one %s per value } else { $keyword = 'replace' === $verb ? 'REPLACE' : 'INSERT'; $sql = $wpdb->prepare( "$keyword INTO `$table` (`" . implode( '`, `', $cols ) . '`) VALUES (' . implode( ', ', array_fill( 0, count( $cols ), '%s' ) ) . ')', array_values( $data ) ); // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.PreparedSQLPlaceholders.ReplacementsWrongNumber, WordPress.DB.PreparedSQLPlaceholders.UnfinishedPrepare -- $table is a $wpdb table name, the columns are the keys of a row this class read itself, and there is one %s per value } $wpdb->check_current_query = false; return $wpdb->query( $sql ); // phpcs:ignore WordPress.DB.PreparedSQL, PluginCheck.Security.DirectDB.UnescapedDBParameter -- $sql is the $wpdb->prepare() result above } /** Bookkeeping and SEO-plugin meta: not content this bridge records or restores. */ private static function skip_meta( $key, $target = null ) { if ( in_array( $key, self::SKIP_META, true ) ) { return true; } foreach ( self::SKIP_META_PREFIXES as $prefix ) { if ( 0 === strpos( $key, $prefix ) ) { return true; } } /** Lets other rules (the SEO rule, #11) keep more keys out of restore points. */ return (bool) apply_filters( 'adibridge_snapshot_skip_key', false, $key, 'meta', $target ); } /** Recorded meta rows as key => values (decoded, in order), bookkeeping keys left out. */ private static function meta_index( array $rows, $target ) { $out = array(); foreach ( $rows as $m ) { if ( ! self::skip_meta( $m['meta_key'], $target ) ) { $out[ $m['meta_key'] ][] = self::dec( $m['meta_value'] ); } } return $out; } /** $post_id's meta as stored now: key => values (in order), bookkeeping keys left out. */ private static function current_meta( $post_id ) { global $wpdb; return self::meta_index( $wpdb->get_results( $wpdb->prepare( "SELECT meta_key, meta_value FROM {$wpdb->postmeta} WHERE post_id = %d ORDER BY meta_id", $post_id ), ARRAY_A ), $post_id ); } /** * May a restore write (or remove) meta $key? Only meta the bridge itself writes: _elementor_data, * the featured image (_thumbnail_id), ACF value rows and their _ field-key references, and * the trash bookkeeping WordPress records when the bridge trashes a post, and on simple WooCommerce products the SKU * and (unless price writing is switched off) price meta WooCommerce's setters write for the woocommerce adapter * (Adapters\WooCommerce::META; never on variable/grouped parents, whose prices are synced from children) — plus its * stock meta only when $ctx['stock'] (a restore point taken for a stock change, or before a restore: orders move * stock between a point and its restore). Anything else — protected meta an administrator or * another plugin set (_price on a non-product, membership flags, _wp_page_template…) — is left as it is now. * * An ACF row is recognised by its reference (as Seo::acf_reference does): K is a value row when * _K holds a field key (ACF's own test: a string starting "field_", which allows the hyphens of * code-registered keys); _K is the reference itself. The reference as stored now decides; for a * key missing now, the one in the restore point. * * @param array $recorded key => values from the restore point. * @param array $now key => values as stored now. * @param array $ctx { product: the target is a simple WooCommerce product, stock: stock meta may go back, * prices: price meta may go back (the price switch), catalog: a simple or variable product * (its gallery may go back), taxonomies: whose recorded terms may go back } (context()). */ private static function restorable( $key, array $recorded, array $now, array $ctx = array() ) { $key = (string) $key; if ( Adapters\Elementor::META === $key || in_array( $key, self::TRASH_META, true ) || in_array( $key, self::BRIDGE_META, true ) ) { return true; } if ( ! empty( $ctx['product'] ) && Adapters\WooCommerce::restorable( $key, ! empty( $ctx['stock'] ), ! empty( $ctx['prices'] ) ) ) { return true; } if ( ! empty( $ctx['catalog'] ) && in_array( $key, Adapters\WooCommerce::CATALOG_META, true ) ) { return true; // the product gallery (#21) } if ( ! empty( $ctx['product'] ) && Adapters\WooCommerce::ATTRIBUTES_META === $key ) { return true; // merged: only local attribute values go back (wanted_meta(), Adapters\WooCommerce::restore_meta()) } $ref = '_' === substr( $key, 0, 1 ) ? $key : '_' . $key; $values = isset( $now[ $ref ] ) ? $now[ $ref ] : ( isset( $recorded[ $ref ] ) ? $recorded[ $ref ] : array() ); return 1 === count( $values ) && is_string( $values[0] ) && 0 === strpos( $values[0], 'field_' ); } /** * What restorable() needs to know about a post restore: is the target a WooCommerce product, and may * its stock meta go back ($stock: a roll-back of this request's own change, a point taken for a stock * change, or the point saved before a restore). */ private static function context( $target, $stock, $exact = false ) { $product = is_int( $target ) && Adapters\WooCommerce::restorable_product( $target ); $taxonomies = array(); foreach ( self::taxonomies_for( $target ) as $taxonomy ) { // As in wp-admin, terms go back only for a user who may assign them (a roll-back of this request's own change: always). $tax = get_taxonomy( $taxonomy ); if ( $exact || ( $tax && current_user_can( $tax->cap->assign_terms ) ) ) { $taxonomies[] = $taxonomy; } } return array( 'product' => $product, 'stock' => (bool) $stock, // The price switch (adibridge_woocommerce_prices_writable) holds for restores too; a roll-back // of this request's own refused change ($exact) puts everything back as it was. 'prices' => $product && ( $exact || Adapters\WooCommerce::prices_writable_for( $target ) ), 'catalog' => is_int( $target ) && Adapters\WooCommerce::catalog_product( $target ), // The price switch for the variations a point records (#22). 'child_prices' => is_int( $target ) && ( $exact || Adapters\WooCommerce::prices_writable_for( $target ) ), 'taxonomies' => $taxonomies, ); } /** The stored state of $target, exactly as in the database. */ private static function capture( $target, array $children = array() ) { global $wpdb; if ( is_int( $target ) ) { $row = $wpdb->get_row( $wpdb->prepare( 'SELECT ' . implode( ', ', self::COLUMNS ) . " FROM {$wpdb->posts} WHERE ID = %d", $target ), ARRAY_A ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- the column list is the class constant COLUMNS $meta = array(); foreach ( $wpdb->get_results( $wpdb->prepare( "SELECT meta_key, meta_value FROM {$wpdb->postmeta} WHERE post_id = %d ORDER BY meta_id", $target ), ARRAY_A ) as $m ) { if ( ! self::skip_meta( $m['meta_key'], $target ) ) { $meta[] = array( 'meta_key' => $m['meta_key'], 'meta_value' => self::enc( $m['meta_value'] ) ); } } $out = array( 'type' => 'post', 'row' => array_map( array( self::class, 'enc' ), (array) $row ), 'meta' => $meta ); $taxonomies = self::taxonomies_for( $target ); if ( $taxonomies ) { $out['terms'] = self::object_terms( $target, $taxonomies ); } if ( $children ) { $out['children'] = array(); foreach ( array_unique( $children ) as $child ) { $status = $wpdb->get_var( $wpdb->prepare( "SELECT post_status FROM {$wpdb->posts} WHERE ID = %d", $child ) ); if ( null === $status ) { continue; } $rows = array(); foreach ( $wpdb->get_results( $wpdb->prepare( "SELECT meta_key, meta_value FROM {$wpdb->postmeta} WHERE post_id = %d ORDER BY meta_id", $child ), ARRAY_A ) as $m ) { if ( ! self::skip_meta( $m['meta_key'], $child ) ) { $rows[] = array( 'meta_key' => $m['meta_key'], 'meta_value' => self::enc( $m['meta_value'] ) ); } } $out['children'][ (string) $child ] = array( 'status' => (string) $status, 'meta' => $rows ); } } return $out; } $scope = self::option_scope( substr( $target, strlen( 'options:' ) ) ); $out = array(); foreach ( self::option_rows( $scope ) as $o ) { $o['option_value'] = self::enc( $o['option_value'] ); $out[] = $o; } return array( 'type' => 'options', 'prefix' => $scope['prefix'], 'options' => $out ); } /** * Taxonomies whose term relationships a restore point of post $target records (WooCommerce products: * categories and tags, #21). Filter: adibridge_snapshot_taxonomies. */ private static function taxonomies_for( $target ) { if ( ! is_int( $target ) ) { return array(); } return array_values( array_unique( array_filter( (array) apply_filters( 'adibridge_snapshot_taxonomies', array(), $target ), 'taxonomy_exists' ) ) ); } /** $id's term ids per taxonomy, sorted, exactly as stored (no term cache). */ private static function object_terms( $id, array $taxonomies ) { global $wpdb; $out = array_fill_keys( $taxonomies, array() ); if ( ! $taxonomies ) { return $out; } $rows = $wpdb->get_results( $wpdb->prepare( "SELECT tt.taxonomy, tt.term_id FROM {$wpdb->term_relationships} tr INNER JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id WHERE tr.object_id = %d AND tt.taxonomy IN (" . implode( ', ', array_fill( 0, count( $taxonomies ), '%s' ) ) . ')', // phpcs:ignore WordPress.DB.PreparedSQLPlaceholders array_merge( array( $id ), $taxonomies ) ), ARRAY_A ); foreach ( $rows as $r ) { $out[ $r['taxonomy'] ][] = (int) $r['term_id']; } foreach ( $out as $taxonomy => $ids ) { sort( $ids ); $out[ $taxonomy ] = $ids; } ksort( $out ); return $out; } /** Child posts a restore point of $target records for a change at $path (filter adibridge_snapshot_children). */ private static function children_for( $target, $path ) { if ( ! is_int( $target ) ) { return array(); } return array_values( array_unique( array_filter( array_map( 'intval', (array) apply_filters( 'adibridge_snapshot_children', array(), $target, $path ) ) ) ) ); } /** The child post ids a captured state records. */ private static function child_ids( array $data ) { return isset( $data['children'] ) && is_array( $data['children'] ) ? array_map( 'intval', array_keys( $data['children'] ) ) : array(); } /** The recorded children of a captured state in a comparable form: id => { status, meta: key => values }. */ private static function children_of( array $data ) { if ( ! isset( $data['children'] ) || ! is_array( $data['children'] ) ) { return null; } $out = array(); foreach ( $data['children'] as $child => $rec ) { $meta = array(); foreach ( isset( $rec['meta'] ) ? (array) $rec['meta'] : array() as $m ) { $meta[ $m['meta_key'] ][] = (string) self::dec( $m['meta_value'] ); } ksort( $meta ); $out[ (int) $child ] = array( isset( $rec['status'] ) ? (string) $rec['status'] : '', $meta ); } ksort( $out ); return $out; } /** The recorded terms of a captured state (null: the point records none). */ private static function terms_of( array $data ) { return isset( $data['terms'] ) && is_array( $data['terms'] ) ? $data['terms'] : null; } /** * The meta a restore writes: the recorded values, adjusted by adapters for keys only partly theirs (a simple * product's attribute list: only local attribute values go back). Filter: adibridge_restore_meta. */ private static function wanted_meta( array $recorded, array $now, $id, array $ctx ) { $want = apply_filters( 'adibridge_restore_meta', $recorded, $now, $id, $ctx ); return is_array( $want ) ? $want : $recorded; } /** * Which option rows belong to an options page. ACF stores a page's fields as _ * (and the field-key reference __), sub-rows of repeaters/groups as * __…; several pages often share one prefix ("options"), and some prefixes collide * with core options (theme_mods_…, widget_…). So a row belongs to this page only if the longest * field name it can be stored under — across every options page with the same prefix — is one * of this page's fields. Nothing else is recorded, and a restore re-checks ownership before writing. * * @return array { prefix, own: name => compound, all: name => compound } */ private static function option_scope( $slug ) { $pages = Adapters\Acf::option_pages(); if ( ! isset( $pages[ $slug ] ) ) { throw new Tool_Error( esc_html( "There is no options page \"$slug\"." ) ); } $prefix = self::store_prefix( $pages[ $slug ]['post_id'] ); $own = self::top_fields( $slug ); $all = $own; $longer = array(); // other pages' stores that start with this one ("options_footer" vs "options"): store => fields foreach ( (array) acf_get_options_pages() as $other => $page ) { if ( $other === $slug ) { continue; } $theirs = self::store_prefix( isset( $page['post_id'] ) ? $page['post_id'] : 'options' ); if ( $theirs === $prefix ) { $all += self::top_fields( $other ); } elseif ( 0 === strpos( $theirs, $prefix . '_' ) ) { $longer[ $theirs ] = ( isset( $longer[ $theirs ] ) ? $longer[ $theirs ] : array() ) + self::top_fields( $other ); } } return array( 'slug' => $slug, 'prefix' => $prefix, 'own' => $own, 'all' => $all, 'longer' => $longer ); } /** The option-name prefix ACF really writes under (a language plugin may turn "options" into "options_fr"). */ private static function store_prefix( $post_id ) { $id = (string) $post_id; $id = 'option' === $id ? 'options' : $id; return function_exists( 'acf_get_valid_post_id' ) ? (string) acf_get_valid_post_id( $id ) : $id; } /** Top-level field names of an options page's field groups: name => stored as more rows. */ private static function top_fields( $slug ) { $out = array(); foreach ( acf_get_field_groups( array( 'options_page' => $slug ) ) as $group ) { foreach ( (array) acf_get_fields( $group ) as $field ) { if ( 'clone' === $field['type'] && empty( $field['prefix_name'] ) && ! empty( $field['sub_fields'] ) ) { // A seamless clone stores its fields under their own names. foreach ( $field['sub_fields'] as $sub ) { if ( ! empty( $sub['name'] ) ) { $out[ $sub['name'] ] = in_array( $sub['type'], self::COMPOUND_TYPES, true ); } } } elseif ( ! empty( $field['name'] ) ) { $out[ $field['name'] ] = in_array( $field['type'], self::COMPOUND_TYPES, true ); } } } return $out; } /** Does option $name belong to the page in $scope? */ private static function owns( array $scope, $name ) { $rest = ltrim( $name, '_' ) === $name ? $name : substr( $name, 1 ); if ( 0 !== strpos( $rest, $scope['prefix'] . '_' ) ) { return false; } foreach ( $scope['longer'] as $other => $fields ) { if ( 0 === strpos( $rest, $other . '_' ) && null !== self::owner_of( substr( $rest, strlen( $other ) + 1 ), $fields ) ) { return false; // a field of another page whose store starts like this one's } } $owner = self::owner_of( substr( $rest, strlen( $scope['prefix'] ) + 1 ), $scope['all'] ); if ( null === $owner || ! array_key_exists( $owner, $scope['own'] ) ) { return false; } return ! apply_filters( 'adibridge_snapshot_skip_key', false, $name, 'option', 'options:' . $scope['slug'] ); } /** The field (of name => compound) a stored name falls under: the longest that matches, or null. */ private static function owner_of( $rest, array $fields ) { $owner = null; foreach ( $fields as $field => $compound ) { $field = (string) $field; $hit = $rest === $field || ( $compound && 0 === strpos( $rest, $field . '_' ) ); if ( $hit && ( null === $owner || strlen( $field ) > strlen( $owner ) ) ) { $owner = $field; } } return $owner; } /** The option rows that belong to the page in $scope, as stored. */ private static function option_rows( array $scope ) { global $wpdb; $rows = $wpdb->get_results( $wpdb->prepare( "SELECT option_name, option_value, autoload FROM {$wpdb->options} WHERE option_name LIKE %s OR option_name LIKE %s ORDER BY option_id", $wpdb->esc_like( $scope['prefix'] . '_' ) . '%', $wpdb->esc_like( '_' . $scope['prefix'] . '_' ) . '%' ), ARRAY_A ); return array_values( array_filter( $rows, static function ( $o ) use ( $scope ) { return self::owns( $scope, $o['option_name'] ); } ) ); } private static function prune( $target ) { $ids = self::ids_for( $target ); foreach ( array_slice( $ids, self::cap() ) as $old ) { wp_delete_post( $old, true ); } } /** Snapshot ids for $target, newest first. */ private static function ids_for( $target ) { return array_map( 'intval', get_posts( array( 'post_type' => self::POST_TYPE, 'post_status' => 'private', 'meta_key' => '_adibridge_target', 'meta_value' => (string) $target, 'orderby' => 'ID', 'order' => 'DESC', 'posts_per_page' => -1, 'fields' => 'ids', ) ) ); } // ── Access ────────────────────────────────────────────────────────────────────────── /** Check the user may edit $target (and so see / restore its history). Returns the normalised target. */ public static function authorise( $target ) { if ( is_string( $target ) && 0 === strpos( $target, 'options:' ) ) { Content::option_fields( substr( $target, 8 ) ); // runs the options page's capability check return $target; } // A trashed post is no longer editable content, but its history is how ADI brings it back: // whoever may edit it may see and restore its restore points. $post = is_int( $target ) || ( is_string( $target ) && ctype_digit( $target ) ) ? get_post( (int) $target ) : null; if ( $post && 'trash' === $post->post_status && array_key_exists( $post->post_type, Content::post_types() ) ) { Auth::require_cap( 'edit_post', $post->ID ); return $post->ID; } return Content::post( $target )->ID; } /** * Undo a change that failed partway (a status change WordPress didn't make as asked, a * replacement over several fields refused at the third): put the target back to restore point * $id — the one the failed call took — and drop it, so history shows only real changes. Other * restore points are never touched. If the put-back doesn't hold, $id is kept: it is the way back. * * @return bool Whether the stored state now matches the restore point. */ public static function roll_back( $id ) { $raw = get_post_meta( $id, '_adibridge_target', true ); $target = ctype_digit( (string) $raw ) ? (int) $raw : (string) $raw; $data = json_decode( (string) get_post_meta( $id, self::DATA_META, true ), true ); if ( '' === $target || ! is_array( $data ) ) { return false; } $children = self::child_ids( $data ); do_action( 'adibridge_before_restore', $target, $children ); if ( 'post' === $data['type'] ) { if ( ! get_post( $target ) ) { return false; } self::restore_post( $target, $data, false, self::context( $target, true, true ) ); self::restore_children( $target, $data, self::context( $target, true, true ) ); do_action( 'adibridge_after_restore', $target, 'snapshot' ); } else { self::restore_option_target( $target, $data, self::units( $id ) ); do_action( 'adibridge_after_option_restore', self::option_key( $target ), 'snapshot' ); } $now = self::capture( $target, $children ); // Order-insensitive: restore_post re-inserts a changed key, which moves it to the end of meta_id order. if ( self::state( $now ) === self::state( $data ) ) { wp_delete_post( $id, true ); // exactly as recorded: nothing happened return true; } if ( 'post' === $data['type'] ) { // Only the row and the restorable meta are put back, so only they must match. $recorded = self::meta_index( $data['meta'], $target ); $current = self::meta_index( $now['meta'], $target ); $ctx = self::context( $target, true, true ); $keep = static function ( array $data ) use ( $recorded, $current, $ctx ) { $data['meta'] = array_values( array_filter( $data['meta'], static function ( $m ) use ( $recorded, $current, $ctx ) { // A product's _price is derived (re-synced after the put-back from the sale window): not compared. if ( ! empty( $ctx['product'] ) && '_price' === $m['meta_key'] ) { return false; } return self::restorable( $m['meta_key'], $recorded, $current, $ctx ); } ) ); return $data; }; // Children (variations): only what a restore writes on them, and their status. $keep_children = static function ( array $data ) use ( $ctx ) { if ( isset( $data['children'] ) && is_array( $data['children'] ) ) { foreach ( $data['children'] as $child => $rec ) { $data['children'][ $child ]['meta'] = array_values( array_filter( isset( $rec['meta'] ) ? (array) $rec['meta'] : array(), static function ( $m ) use ( $ctx ) { return Adapters\WooCommerce::restorable_child( $m['meta_key'], ! empty( $ctx['stock'] ), ! empty( $ctx['child_prices'] ) ); } ) ); } } return $data; }; $now = $keep_children( $keep( $now ) ); $data = $keep_children( $keep( $data ) ); } if ( self::state( $now ) !== self::state( $data ) ) { return false; } if ( 'post' !== $data['type'] ) { wp_delete_post( $id, true ); return true; } // What the bridge writes is back, but meta it doesn't write changed meanwhile (another plugin's // save hook, or someone else): keep the point, it is the record of the state before. Log::line( "roll-back of #$id to $target put back the content, but other meta changed meanwhile; restore point kept" ); return true; } /** A captured state in a comparable form: meta and options grouped by key, in key order. */ private static function state( array $data ) { if ( 'post' === $data['type'] ) { $meta = array(); foreach ( $data['meta'] as $m ) { $meta[ $m['meta_key'] ][] = (string) self::dec( $m['meta_value'] ); } ksort( $meta ); return array( array_map( 'strval', array_map( array( self::class, 'dec' ), (array) $data['row'] ) ), $meta, self::terms_of( $data ), self::children_of( $data ) ); } $options = array(); foreach ( $data['options'] as $o ) { $options[ $o['option_name'] ] = array( (string) $o['option_value'], (string) $o['autoload'] ); } ksort( $options ); return $options; } /** * Record what the target looks like right after the change this restore point was taken for * (#31). Restoring the point while the target still looks exactly like that is an exact undo of * the bridge's own change: see exact_undo(). */ public static function seal( $snapshot_id ) { $fingerprint = self::fingerprint_of( $snapshot_id ); if ( null !== $fingerprint ) { update_post_meta( $snapshot_id, '_adibridge_after', $fingerprint ); } } /** * Whether restoring $snapshot_id only reverses the change it was taken for: nothing has touched * the target since (its whole recorded state — row, every meta row, terms, children — is what * that change left). Such a restore may put back markup the bridge never adds (a pasted chat * app's tabindex wrappers), because it was on the page a moment before; scripts, embeds, forms, * event handlers and script links are still refused (Html::refuse_unsafe_additions). */ private static function exact_undo( $snapshot_id ) { $sealed = (string) get_post_meta( $snapshot_id, '_adibridge_after', true ); if ( '' === $sealed ) { return false; } $now = self::fingerprint_of( $snapshot_id ); return null !== $now && hash_equals( $sealed, $now ); } /** sha256 of the target's current state, captured the way restore point $snapshot_id records it. */ private static function fingerprint_of( $snapshot_id ) { $raw = get_post_meta( $snapshot_id, '_adibridge_target', true ); $data = json_decode( (string) get_post_meta( $snapshot_id, self::DATA_META, true ), true ); if ( '' === (string) $raw || ! is_array( $data ) ) { return null; } $target = ctype_digit( (string) $raw ) ? (int) $raw : (string) $raw; $json = wp_json_encode( self::state( self::capture( $target, 'post' === $data['type'] ? self::child_ids( $data ) : array() ) ) ); return false === $json ? null : hash( 'sha256', $json ); } /** Set while a restore runs that is an exact undo (exact_undo()). */ private static $exact = false; // ── Tools ─────────────────────────────────────────────────────────────────────────── public static function register_tools( Tools $tools ) { $tools->register( 'wp_list_snapshots', array( 'description' => 'The restore points of one page/post (or options page): one is saved automatically before every change ADI makes, newest first, with what was changed and its value before. Use wp_restore_snapshot to undo.' . Read_Tools::SITE_DATA, 'read_only' => true, 'input_schema' => array( 'type' => 'object', 'properties' => array( 'id' => array( 'type' => array( 'integer', 'string' ), 'description' => 'A content id or "options:".' ), ), 'required' => array( 'id' ), 'additionalProperties' => false, ), 'handler' => array( self::class, 'list_tool' ), ) ); $tools->register( 'wp_restore_snapshot', array( 'description' => 'Put a page/post (or options page) back exactly as it was at a restore point from wp_list_snapshots — all of its fields at once. The current state is saved as a new restore point first, so this can be undone too. Always confirm with the person before restoring.', 'input_schema' => array( 'type' => 'object', 'properties' => array( 'snapshot_id' => array( 'type' => 'integer', 'minimum' => 1 ), ), 'required' => array( 'snapshot_id' ), 'additionalProperties' => false, ), 'handler' => array( self::class, 'restore_tool' ), ) ); } public static function list_tool( array $args ) { $target = self::authorise( $args['id'] ); $out = array(); foreach ( self::ids_for( $target ) as $id ) { $snap = get_post( $id ); $user = get_userdata( (int) $snap->post_author ); $out[] = array( 'snapshot_id' => $id, 'taken' => mysql_to_rfc3339( $snap->post_date_gmt ), 'by' => $user ? $user->user_login : null, 'connection' => get_post_meta( $id, '_adibridge_token', true ) ?: null, 'kind' => get_post_meta( $id, '_adibridge_kind', true ), 'changed' => get_post_meta( $id, '_adibridge_path', true ), 'before' => json_decode( (string) get_post_meta( $id, '_adibridge_before', true ), true ), ); } return array( 'id' => $target, 'snapshots' => $out ); } public static function restore_tool( array $args ) { $raw = get_post_meta( (int) $args['snapshot_id'], '_adibridge_target', true ); if ( '' === (string) $raw ) { return self::restore_locked( $args ); // not a restore point: refused there with the usual message } return Lock::with( self::authorise( ctype_digit( (string) $raw ) ? (int) $raw : (string) $raw ), static function () use ( $args ) { return self::restore_locked( $args ); } ); } private static function restore_locked( array $args ) { $snap = get_post( (int) $args['snapshot_id'] ); if ( ! $snap || self::POST_TYPE !== $snap->post_type ) { throw new Tool_Error( esc_html( 'There is no restore point #' . (int) $args['snapshot_id'] . '. Call wp_list_snapshots to see them.' ) ); } $raw = get_post_meta( $snap->ID, '_adibridge_target', true ); $target = self::authorise( ctype_digit( (string) $raw ) ? (int) $raw : $raw ); $data = json_decode( (string) get_post_meta( $snap->ID, self::DATA_META, true ), true ); if ( ! is_array( $data ) ) { throw new Tool_Error( esc_html( "Restore point #{$snap->ID} can't be read." ) ); } // Stock meta goes back only from a point taken for a stock change, or from the point saved before a // restore that itself put stock back (_adibridge_stock): orders move stock between a point and its restore. $ctx = self::context( $target, '1' === (string) get_post_meta( $snap->ID, '_adibridge_stock', true ) || Adapters\WooCommerce::is_stock_path( (string) get_post_meta( $snap->ID, '_adibridge_path', true ) ) ); $children = 'post' === $data['type'] ? self::child_ids( $data ) : array(); self::$exact = self::exact_undo( $snap->ID ); try { return self::restore_checked( $snap, $target, $data, $ctx, $children ); } finally { self::$exact = false; } } private static function restore_checked( \WP_Post $snap, $target, array $data, array $ctx, array $children ) { if ( 'post' === $data['type'] ) { self::check_post_restore( get_post( $target ), array_map( array( self::class, 'dec' ), $data['row'] ), $data['meta'], $ctx, $data ); } elseif ( self::is_site_area( $target ) ) { } elseif ( self::option_scope( substr( $target, 8 ) )['prefix'] === $data['prefix'] ) { foreach ( $data['options'] as $o ) { if ( '_' !== substr( $o['option_name'], 0, 1 ) ) { Html::refuse_unsafe_additions( maybe_unserialize( self::dec( $o['option_value'] ) ), get_option( $o['option_name'], '' ), 'Restoring ' . $o['option_name'], self::$exact ); } } } else { // The page now stores its fields under another name (its post_id changed, or a language // plugin is active): none of the recorded rows are its rows any more. throw new Tool_Error( esc_html( "The \"" . substr( $target, 8 ) . '" options page stores its settings differently since this restore point was taken, so it can\'t be put back automatically. Nothing was changed.' ) ); } $saved = self::take( $target, 'wp_restore_snapshot #' . $snap->ID, null, 'before_restore', $children ); if ( self::is_site_area( $target ) ) { update_post_meta( $saved, '_adibridge_units', wp_slash( wp_json_encode( self::units( $snap->ID ) ) ) ); // undoing this restore puts back the same units } if ( ! empty( $ctx['stock'] ) ) { update_post_meta( $saved, '_adibridge_stock', '1' ); // undoing this restore may put stock back too } do_action( 'adibridge_before_restore', $target, $children ); // e.g. the cache purge (#10) notes the current public address $skipped = array(); $gone = array(); $no_assign = array(); $gone_kids = array(); $images = array(); if ( 'post' === $data['type'] ) { $done = self::restore_post( $target, $data, true, $ctx ); $kids = self::restore_children( $target, $data, $ctx ); $failed = $done['failed'] + $kids['failed']; $skipped = array_merge( $done['skipped'], $kids['skipped'] ); $gone = $done['gone']; $gone_kids = $kids['gone']; $images = $kids['images']; $no_assign = $done['no_assign']; } else { $failed = self::restore_option_target( $target, $data, self::units( $snap->ID ) ); } if ( 'post' === $data['type'] ) { do_action( 'adibridge_after_restore', $target, 'snapshot' ); } else { do_action( 'adibridge_after_option_restore', self::option_key( $target ), 'snapshot' ); } self::kept( $target ); if ( $failed ) { Log::line( "restore of #{$snap->ID} to $target: $failed database writes failed" ); throw new Tool_Error( esc_html( "Restoring went only part of the way ($failed database writes failed), so the page may be incomplete. Its state from just before the restore is saved: restore #$saved to put it back as it was, then check the page in wp-admin." ) ); } // Meta the bridge doesn't write, recorded with other values than now: left as it is. Its names // (protected keys other people set) only for users who may edit others' content. $type = 'post' === $data['type'] ? get_post_type_object( get_post_type( $target ) ) : null; $names = $skipped && $type && current_user_can( $type->cap->edit_others_posts ); $message = "Restored to the restore point of " . get_date_from_gmt( $snap->post_date_gmt, 'Y-m-d H:i' ) . ". To undo this, restore #$saved."; if ( $skipped ) { $message .= $names ? ' Left as they are now (not something ADI edits): ' . implode( ', ', $skipped ) . '.' : ' ' . count( $skipped ) . ' other setting(s) that ADI doesn\'t edit were left as they are now.'; } if ( $gone || $gone_kids ) { $message .= ' Not put back, deleted since: ' . implode( ', ', array_merge( $gone, $gone_kids ) ) . '.'; } if ( $no_assign ) { $labels = array_map( static function ( $taxonomy ) { $tax = get_taxonomy( $taxonomy ); return $tax ? strtolower( $tax->labels->name ) : $taxonomy; }, $no_assign ); $message .= ' Left as they are now, because the connected WordPress user may not assign them: ' . implode( ', ', $labels ) . '.'; } if ( 'post' === $data['type'] && null === self::terms_of( $data ) && self::taxonomies_for( $target ) ) { // Points recorded before term history (#21) hold no categories or tags. $message .= ' This restore point is older than category and tag history, so categories and tags were left as they are.'; } self::seal( $saved ); // undoing this restore right away is an exact undo too $result = array( 'restored' => $target, 'to' => mysql_to_rfc3339( $snap->post_date_gmt ), 'undo_snapshot_id' => $saved, 'skipped_meta_count' => count( $skipped ), 'message' => $message, ); if ( $names ) { $result['skipped_meta'] = $skipped; } if ( $gone ) { $result['deleted_terms'] = $gone; } if ( $no_assign ) { $result['terms_not_assignable'] = $no_assign; } if ( $gone_kids ) { $result['deleted_variations'] = $gone_kids; } if ( $images ) { $result['missing_images'] = $images; } return apply_filters( 'adibridge_write_result', $result, $target ); } /** * What a restore would do that the user couldn't do by hand: refuse before anything changes. * The row goes back directly (no wp_update_post), so WordPress's own checks don't run for it. */ private static function check_post_restore( \WP_Post $post, array $row, array $meta, array $ctx, array $data = array() ) { Content::refuse_if_locked( $post ); // The children (variations) the point records: id => { status, meta: key => values } for the rules below. $children = array(); foreach ( self::child_ids( $data ) as $child ) { if ( ! in_array( get_post_status( $child ), array( 'publish', 'private' ), true ) ) { continue; // skipped by restore_children(): nothing of it is written } $rec = $data['children'][ $child ]; $children[ $child ] = array( 'status' => isset( $rec['status'] ) ? (string) $rec['status'] : '', 'meta' => self::meta_index( isset( $rec['meta'] ) ? (array) $rec['meta'] : array(), $child ), ); // Whatever the role, no markup a write couldn't add comes back on a child either (#14). $now = self::current_meta( $child ); foreach ( $children[ $child ]['meta'] as $key => $values ) { if ( ! Adapters\WooCommerce::restorable_child( (string) $key, ! empty( $ctx['stock'] ), ! empty( $ctx['child_prices'] ) ) ) { continue; } Html::refuse_unsafe_additions( array_map( 'maybe_unserialize', $values ), array_map( 'maybe_unserialize', isset( $now[ $key ] ) ? $now[ $key ] : array() ), "Restoring variation #$child's field $key", self::$exact ); } } /** * Other rules can refuse a restore before anything changes (the SEO rule, #11; a SKU another * product took since, Adapters\WooCommerce) by throwing a Tool_Error. $meta: key => recorded values. */ do_action( 'adibridge_check_restore', $post, $row, self::meta_index( $meta, $post->ID ), $children ); $status = $row['post_status']; if ( $status !== $post->post_status && in_array( $status, array( 'publish', 'future', 'private' ), true ) ) { $type = get_post_type_object( $post->post_type ); if ( ! $type || ! current_user_can( $type->cap->publish_posts ) ) { throw new Tool_Error( esc_html( "That restore point has #{$post->ID} as \"$status\", and the connected WordPress user may not publish. Ask an editor to restore it. Nothing was changed." ) ); } } if ( $status !== $post->post_status && 'trash' === $status && ! current_user_can( 'delete_post', $post->ID ) ) { throw new Tool_Error( esc_html( "That restore point has #{$post->ID} in the trash, and the connected WordPress user may not trash it. Ask an editor to restore it. Nothing was changed." ) ); } if ( 'future' === $status && strtotime( $row['post_date_gmt'] . ' UTC' ) <= time() ) { throw new Tool_Error( esc_html( "That restore point has #{$post->ID} scheduled for a time that has passed; restoring it would publish it now. Restore a different point, or reschedule it in wp-admin. Nothing was changed." ) ); } if ( ! current_user_can( 'unfiltered_html' ) ) { // Markup the user couldn't save by hand (scripts, iframes, embeds) doesn't come back through a restore either. foreach ( array( 'post_title', 'post_content', 'post_excerpt' ) as $col ) { if ( $row[ $col ] !== $post->$col && ! Html::equivalent( wp_kses_post( $row[ $col ] ), $row[ $col ] ) ) { throw new Tool_Error( esc_html( "That restore point has markup in #{$post->ID}'s " . str_replace( 'post_', '', $col ) . ' that the connected WordPress user may not save (embeds, iframes, scripts or forms). Ask an editor or administrator to restore it. Nothing was changed.' ) ); } } // Meta a restore writes back (ACF fields, _elementor_data), where it differs from what's there now. $now = self::current_meta( $post->ID ); $recorded = self::wanted_meta( self::meta_index( $meta, $post->ID ), $now, $post->ID, $ctx ); foreach ( $recorded as $key => $values ) { $key = (string) $key; if ( ! self::restorable( $key, $recorded, $now, $ctx ) ) { continue; } $current = isset( $now[ $key ] ) ? $now[ $key ] : array(); foreach ( $values as $value ) { if ( ! is_string( $value ) || in_array( $value, $current, true ) ) { continue; } if ( Adapters\Elementor::META === $key ) { // Elementor stores JSON (HTML escaped inside): check the decoded tree, as the adapter's writes do. if ( ! Adapters\Elementor::markup_survives_kses( $value ) ) { throw new Tool_Error( esc_html( "That restore point has markup in #{$post->ID}'s Elementor content that the connected WordPress user may not save (embeds, iframes, scripts or forms). Ask an editor or administrator to restore it. Nothing was changed." ) ); } } elseif ( '_' !== substr( $key, 0, 1 ) && false !== strpos( $value, '<' ) && ! Html::equivalent( wp_kses_post( $value ), $value ) ) { throw new Tool_Error( esc_html( "That restore point has markup in #{$post->ID}'s field $key that the connected WordPress user may not save (embeds, iframes, scripts or forms). Ask an editor or administrator to restore it. Nothing was changed." ) ); } } } } // Whatever the role, a restore can't bring back scripts, embeds or forms that aren't there now // (a token thief restoring a point from before an admin removed one). Only what a restore // writes is checked: the row and the bridge-written meta (#15). foreach ( array( 'post_title' => 'title', 'post_content' => 'body', 'post_excerpt' => 'excerpt' ) as $col => $what ) { Html::refuse_unsafe_additions( $row[ $col ], $post->$col, "Restoring #{$post->ID}'s $what", self::$exact ); } $current_meta = self::current_meta( $post->ID ); $recorded_meta = self::wanted_meta( self::meta_index( $meta, $post->ID ), $current_meta, $post->ID, $ctx ); foreach ( $recorded_meta as $key => $values ) { $key = (string) $key; if ( ! self::restorable( $key, $recorded_meta, $current_meta, $ctx ) ) { continue; } $now = isset( $current_meta[ $key ] ) ? $current_meta[ $key ] : array(); foreach ( $values as $value ) { // Compare decoded: JSON spells as <\/script> and serialized arrays hide their strings. if ( Adapters\Elementor::META === $key ) { $new = json_decode( (string) $value, true ); $old = json_decode( (string) ( $now ? reset( $now ) : '' ), true ); } else { $new = maybe_unserialize( $value ); $old = array_map( 'maybe_unserialize', $now ); } Html::refuse_unsafe_additions( $new, $old, "Restoring #{$post->ID}'s field $key", self::$exact ); } } // Elementor's Role Manager may deny a role the HTML widget (even with unfiltered_html): a // restore can't change one for that user either. $recorded_data = null; foreach ( $meta as $m ) { if ( Adapters\Elementor::META === $m['meta_key'] ) { $recorded_data = self::dec( $m['meta_value'] ); } } $current_data = get_post_meta( $post->ID, Adapters\Elementor::META, true ); // A point from before the page used Elementor counts as an empty tree (the restore would remove its widgets). if ( '' !== (string) $current_data && null === $recorded_data ) { $recorded_data = '[]'; } if ( null !== $recorded_data && $recorded_data !== $current_data && ! Adapters\Elementor::html_widgets_may_change( $recorded_data, $current_data ) ) { throw new Tool_Error( esc_html( "That restore point changes an HTML widget on #{$post->ID}, and Elementor's Role Manager doesn't let this WordPress user edit HTML widgets. Ask an administrator to restore it. Nothing was changed." ) ); } if ( '' !== $row['post_name'] && $row['post_name'] !== $post->post_name ) { $unique = wp_unique_post_slug( $row['post_name'], $post->ID, $status, $post->post_type, $post->post_parent ); if ( $unique !== $row['post_name'] ) { throw new Tool_Error( esc_html( "That restore point gives #{$post->ID} the address \"{$row['post_name']}\", which another page uses now. Nothing was changed." ) ); } } } /** * @return array { failed: how many database writes failed, skipped: meta keys left as they are * although the restore point recorded other values } */ private static function restore_post( $id, array $data, $as_edit, array $ctx ) { global $wpdb; $failed = 0; $was = get_post( $id ); $row = array_map( array( self::class, 'dec' ), $data['row'] ); // Trashing also parks the post's comments (and records their statuses in meta, restored // below): bring them back with it, or send them along when restoring into the trash. if ( 'trash' === $was->post_status && 'trash' !== $row['post_status'] ) { wp_untrash_post_comments( $id ); } elseif ( 'trash' !== $was->post_status && 'trash' === $row['post_status'] ) { wp_trash_post_comments( $id ); } if ( $as_edit ) { // The content goes back; the modified date moves forward (sitemaps and caches key off it). // A roll-back of a refused change ($as_edit false) restores it exactly: nothing happened. $row['post_modified'] = current_time( 'mysql' ); $row['post_modified_gmt'] = current_time( 'mysql', 1 ); } $failed += false === self::write_row( 'update', $wpdb->posts, $row, array( 'ID' => $id ) ) ? 1 : 0; if ( 'publish' === $was->post_status && $row['post_name'] !== $was->post_name ) { add_post_meta( $id, '_wp_old_slug', $was->post_name ); // the old address keeps redirecting, as after an edit } wp_clear_scheduled_hook( 'publish_future_post', array( $id ) ); if ( 'future' === $row['post_status'] ) { wp_schedule_single_event( strtotime( $row['post_date_gmt'] . ' UTC' ), 'publish_future_post', array( $id ) ); } // Meta: put back every restorable key (see restorable()) with exactly its recorded values (and // order), and remove restorable keys added since. Every other key stays exactly as it is now. $now = self::current_meta( $id ); $want = self::wanted_meta( self::meta_index( $data['meta'], $id ), $now, $id, $ctx ); $skipped = array(); foreach ( array_unique( array_merge( array_keys( $want ), array_keys( $now ) ) ) as $key ) { $key = (string) $key; $old = isset( $want[ $key ] ) ? $want[ $key ] : array(); $cur = isset( $now[ $key ] ) ? $now[ $key ] : array(); if ( $old === $cur ) { continue; } if ( ! self::restorable( $key, $want, $now, $ctx ) ) { // A product's _price is derived (synced from its prices or its variations), not left behind. // …and a variable product's stock status, synced from its variations. $derived = is_int( $id ) && 'product' === get_post_type( $id ) && ( '_price' === $key || ( '_stock_status' === $key && Adapters\WooCommerce::synced_product( $id ) ) ); if ( ! $derived ) { $skipped[] = $key; } continue; } $failed += false === $wpdb->delete( $wpdb->postmeta, array( 'post_id' => $id, 'meta_key' => $key ) ) ? 1 : 0; foreach ( $old as $value ) { $failed += false === self::write_row( 'insert', $wpdb->postmeta, array( 'post_id' => $id, 'meta_key' => $key, 'meta_value' => $value ) ) ? 1 : 0; } } // Term relationships the point records (a product's categories and tags): put back with WordPress's own term // API (counts, caches, WooCommerce's default-category rule), for taxonomies the user may assign; terms deleted // since can't come back and are reported. $gone = array(); $no_assign = array(); $then = self::terms_of( $data ); if ( null !== $then ) { $current = self::object_terms( $id, array_keys( $then ) ); foreach ( $then as $taxonomy => $ids ) { $ids = array_map( 'intval', (array) $ids ); $keep = array(); if ( ! in_array( $taxonomy, isset( $ctx['taxonomies'] ) ? $ctx['taxonomies'] : array(), true ) ) { if ( taxonomy_exists( $taxonomy ) && isset( $current[ $taxonomy ] ) && $ids !== $current[ $taxonomy ] ) { $no_assign[] = $taxonomy; // the user may not assign these terms: left as they are } continue; } foreach ( $ids as $term_id ) { if ( get_term( $term_id, $taxonomy ) instanceof \WP_Term ) { $keep[] = $term_id; } elseif ( ! in_array( $term_id, isset( $current[ $taxonomy ] ) ? $current[ $taxonomy ] : array(), true ) ) { $gone[] = "$taxonomy #$term_id"; } } if ( ! taxonomy_exists( $taxonomy ) || ( isset( $current[ $taxonomy ] ) && $keep === $current[ $taxonomy ] ) ) { continue; } $failed += is_wp_error( wp_set_object_terms( $id, $keep, $taxonomy, false ) ) ? 1 : 0; } } sort( $skipped ); // Elementor renders from its element cache: a restored _elementor_data must not keep showing // the newer render (the adapter clears these on every write too). if ( isset( $want['_elementor_data'] ) || isset( $now['_elementor_data'] ) ) { $wpdb->delete( $wpdb->postmeta, array( 'post_id' => $id, 'meta_key' => '_elementor_element_cache' ) ); $wpdb->delete( $wpdb->postmeta, array( 'post_id' => $id, 'meta_key' => '_elementor_css' ) ); } clean_post_cache( $id ); wp_cache_delete( $id, 'post_meta' ); if ( function_exists( 'acf_get_store' ) ) { acf_get_store( 'values' )->reset(); } return array( 'failed' => $failed, 'skipped' => $skipped, 'gone' => $gone, 'no_assign' => $no_assign ); } /** * Put back the children (variations) a point records (#22): their status (publish/private only — enabled or * not) and the meta the adapter writes on them (Adapters\WooCommerce::restorable_child()). A child deleted or * moved to another parent since is skipped and reported; every other key stays as it is now; `_price` is * recomputed afterwards (adibridge_after_restore), never written back. * * @return array { failed, skipped, gone } */ private static function restore_children( $id, array $data, array $ctx ) { $out = array( 'failed' => 0, 'skipped' => array(), 'gone' => array(), 'images' => array() ); global $wpdb; foreach ( self::child_ids( $data ) as $child ) { $rec = $data['children'][ $child ]; // Deleted, moved, or no longer enabled/disabled (drafted, trashed): not a variation ADI edits now. if ( ! Adapters\WooCommerce::is_child( $child, $id ) || ! is_array( $rec ) || ! in_array( get_post_status( $child ), array( 'publish', 'private' ), true ) ) { $out['gone'][] = "variation #$child"; continue; } $status = isset( $rec['status'] ) ? (string) $rec['status'] : ''; $current = (string) get_post_field( 'post_status', $child, 'raw' ); if ( $status !== $current && in_array( $status, array( 'publish', 'private' ), true ) && in_array( $current, array( 'publish', 'private' ), true ) ) { $out['failed'] += false === self::write_row( 'update', $wpdb->posts, array( 'post_status' => $status ), array( 'ID' => $child ) ) ? 1 : 0; } $want = self::meta_index( isset( $rec['meta'] ) ? (array) $rec['meta'] : array(), $child ); $now = self::current_meta( $child ); // An image that is gone (deleted, trashed, no longer an image) isn't put back: the current one stays. if ( isset( $want['_thumbnail_id'] ) && 1 === count( $want['_thumbnail_id'] ) ) { $image = (int) $want['_thumbnail_id'][0]; $cur = isset( $now['_thumbnail_id'] ) ? array_map( 'intval', $now['_thumbnail_id'] ) : array(); if ( $image && ! in_array( $image, $cur, true ) && ! Adapters\WooCommerce::usable_image( $image ) ) { $out['images'][] = "image #$image"; if ( isset( $now['_thumbnail_id'] ) ) { $want['_thumbnail_id'] = $now['_thumbnail_id']; } else { unset( $want['_thumbnail_id'] ); } } } foreach ( array_unique( array_merge( array_keys( $want ), array_keys( $now ) ) ) as $key ) { $key = (string) $key; $old = isset( $want[ $key ] ) ? $want[ $key ] : array(); $cur = isset( $now[ $key ] ) ? $now[ $key ] : array(); if ( $old === $cur ) { continue; } if ( ! Adapters\WooCommerce::restorable_child( $key, ! empty( $ctx['stock'] ), ! empty( $ctx['child_prices'] ) ) ) { if ( '_price' !== $key ) { $out['skipped'][] = "variation #$child $key"; } continue; } $out['failed'] += false === $wpdb->delete( $wpdb->postmeta, array( 'post_id' => $child, 'meta_key' => $key ) ) ? 1 : 0; foreach ( $old as $value ) { $out['failed'] += false === self::write_row( 'insert', $wpdb->postmeta, array( 'post_id' => $child, 'meta_key' => $key, 'meta_value' => $value ) ) ? 1 : 0; } } clean_post_cache( $child ); wp_cache_delete( $child, 'post_meta' ); } return $out; } /** Put back an options-type point: an ACF options page ("options:"), or what else the edition records as option rows. */ private static function restore_option_target( $target, array $data, array $units = array() ) { return self::restore_options( substr( $target, 8 ), $data ); } /** The units a point's change touched: recorded for a restore's own point, else its path. */ private static function units( $snapshot_id ) { $units = json_decode( (string) get_post_meta( $snapshot_id, '_adibridge_units', true ), true ); return is_array( $units ) ? $units : array( (string) get_post_meta( $snapshot_id, '_adibridge_path', true ) ); } /** What the option hooks name: the options page slug, or the whole target when it is not an options page. */ private static function option_key( $target ) { return self::is_site_area( $target ) ? (string) $target : substr( $target, 8 ); } /** Whether $target is a site-wide area ("site:"). The WordPress.org edition has none (scripts/flavour.sh). */ private static function is_site_area( $target ) { $is = false; return $is; } /** @return int How many database writes failed. */ private static function restore_options( $slug, array $data ) { global $wpdb; // Ownership is decided now, not when the point was taken: a field since moved to a stricter // page on the same store is that page's, and is neither written nor removed here. $scope = self::option_scope( $slug ); $failed = 0; $want = array(); foreach ( $data['options'] as $o ) { if ( self::owns( $scope, $o['option_name'] ) ) { $o['option_value'] = self::dec( $o['option_value'] ); $want[ $o['option_name'] ] = $o; } } foreach ( self::option_rows( $scope ) as $o ) { if ( ! isset( $want[ $o['option_name'] ] ) ) { $failed += false === $wpdb->delete( $wpdb->options, array( 'option_name' => $o['option_name'] ) ) ? 1 : 0; wp_cache_delete( $o['option_name'], 'options' ); } } foreach ( $want as $name => $o ) { $failed += false === self::write_row( 'replace', $wpdb->options, $o ) ? 1 : 0; wp_cache_delete( $name, 'options' ); } wp_cache_delete( 'alloptions', 'options' ); wp_cache_delete( 'notoptions', 'options' ); if ( function_exists( 'acf_get_store' ) ) { acf_get_store( 'values' )->reset(); } return $failed; } }