:`. * Every read and write goes through here, so the permission check, the SEO rule, type * coercion and the write verification happen once, for every editor. */ final class Content { /** Post types that hold site plumbing, not content a person edits. */ const EXCLUDED_POST_TYPES = array( 'attachment', 'revision', 'nav_menu_item', 'custom_css', 'customize_changeset', 'oembed_cache', 'user_request', 'wp_block', 'wp_template', 'wp_template_part', 'wp_global_styles', 'wp_navigation', 'wp_font_family', 'wp_font_face', 'adibridge_snapshot', // Commerce records and form plumbing: show_ui, but data rather than content. 'shop_order', 'shop_order_refund', 'shop_order_placehold', 'shop_coupon', 'shop_webhook', 'nf_sub', 'wpcf7_contact_form', 'wpforms', 'wpforms_log', 'flamingo_contact', 'flamingo_inbound', 'elementor_snippet', 'elementor_font', 'elementor_icons', ); /** @var Adapter[]|null */ private static $adapters = null; /** True while putting back a value after a refused write (adapters skip input-only rules). */ private static $restoring = false; public static function is_restoring() { return self::$restoring; } /** @return Adapter[] Available adapters, keyed by id, in display order. */ public static function adapters() { if ( null === self::$adapters ) { $all = apply_filters( 'adibridge_adapters', array( new Adapters\Core(), new Adapters\Classic(), new Adapters\Gutenberg(), new Adapters\Elementor(), new Adapters\Acf(), new Adapters\WooCommerce() ) ); self::$adapters = array(); foreach ( $all as $adapter ) { if ( $adapter instanceof Adapter && $adapter->available() ) { self::$adapters[ $adapter->id() ] = $adapter; } } } return self::$adapters; } /** Test seam: rebuild the adapter list (after activating a plugin mid-request). */ public static function reset() { self::$adapters = null; } /** Post types ADI may work with: everything with an admin UI except plumbing (and ACF's own). */ public static function post_types() { $types = array(); foreach ( get_post_types( array( 'show_ui' => true ), 'objects' ) as $name => $type ) { if ( in_array( $name, self::EXCLUDED_POST_TYPES, true ) || 0 === strpos( $name, 'acf-' ) ) { continue; } $types[ $name ] = $type; } return apply_filters( 'adibridge_post_types', $types ); } /** * The post with this id, if it is content ADI may edit as the current user. * * @param string $cap edit_post (default) — reads require it too, since drafts and private * pages are part of what ADI works on. */ public static function post( $id, $cap = 'edit_post' ) { $post = is_int( $id ) || ( is_string( $id ) && ctype_digit( $id ) ) ? get_post( (int) $id ) : null; if ( ! $post || ! array_key_exists( $post->post_type, self::post_types() ) || 'trash' === $post->post_status || 'auto-draft' === $post->post_status ) { throw new Tool_Error( esc_html( 'There is no editable content with ID ' . self::show( $id ) . '.' ) ); } Auth::require_cap( $cap, $post->ID ); return $post; } /** Adapters holding content for $post, in order. */ public static function editors_for( \WP_Post $post ) { $out = array(); foreach ( self::adapters() as $id => $adapter ) { if ( $adapter->detect( $post ) ) { $out[ $id ] = $adapter; } } return $out; } /** Every field of $post across its editors, with full paths. Re-checks access itself. */ public static function fields( \WP_Post $post ) { $post = self::post( $post->ID ); $fields = array(); $editors = self::editors_for( $post ); foreach ( $editors as $id => $adapter ) { foreach ( $adapter->list_fields( $post ) as $field ) { $fields[] = self::finish( $adapter, $field ); } } // An empty classic body next to another editor (ACF, …) is almost never what the page shows. $others = array_diff( array_keys( $editors ), array( 'core', 'classic' ) ); if ( $others ) { foreach ( $fields as &$field ) { if ( 'classic:html' === $field['path'] && '' === trim( (string) $field['value'] ) ) { $names = array_map( static function ( $id ) use ( $editors ) { return $editors[ $id ]->name(); }, $others ); $field['note'] = 'Empty: this page\'s visible content comes from its ' . implode( ' and ', $names ) . ' fields below.'; } } unset( $field ); } return $fields; } /** One field by path, or a Tool_Error naming what does exist. Re-checks access itself. */ public static function field( \WP_Post $post, $path ) { $post = self::post( $post->ID ); list( $adapter, $locator ) = self::resolve( $post, $path ); $field = $adapter->read( $post, $locator ); if ( null === $field ) { throw new Tool_Error( esc_html( "There is no field $path on #{$post->ID}. Call wp_get_content to see its fields." ) ); } return self::finish( $adapter, $field ); } /** * Every refusal update() can make before it writes (access, lock, read-only, the value's type, * the markup rules, a missed schedule), without writing or recording anything — for callers * that change several fields at once and must know every one will go through first. */ public static function check_update( \WP_Post $post, $path, $value ) { self::prepare_update( $post, $path, $value ); } /** The checks of check_update(); returns what update() needs to write. */ private static function prepare_update( \WP_Post $post, $path, $value ) { $post = self::post( $post->ID ); // re-checks post type, status and edit_post for any caller self::refuse_if_locked( $post ); $field = self::field( $post, $path ); if ( ! $field['writable'] ) { throw new Tool_Error( esc_html( "$path is read-only" . ( ! empty( $field['note'] ) ? ': ' . $field['note'] : '.' ) ) ); } list( $adapter, $locator ) = self::resolve( $post, $path ); $new = Field_Types::coerce( $field, $value ); if ( method_exists( $adapter, 'validate' ) ) { // The adapter's own rules for the value (WooCommerce: prices, unique SKU), before any restore point. $new = $adapter->validate( $post, $locator, $new ); } $column = $adapter->post_column( $locator ); $raw_field = null; if ( null === $column ) { self::guard_meta_kses( $new ); } else { $raw_field = $adapter->read( $post, $locator ); // the adapter's own view, with its internal flags self::guard_post_row_kses( $post, $column, $new, ! empty( $raw_field['whole_column'] ) ); if ( 'future' === $post->post_status && strtotime( $post->post_date_gmt . ' UTC' ) <= time() ) { throw new Tool_Error( esc_html( "#{$post->ID} missed its scheduled publish time; saving any change would publish it now. Publish or reschedule it in wp-admin first. Nothing was changed." ) ); } } // Every role, after the role-based guards (which explain themselves to users without unfiltered_html). Html::refuse_unsafe_additions( $new, $field['value'], $path ); return array( $post, $field, $adapter, $locator, $new, $column, $raw_field ); } /** * Change one field. Checks edit_post, coerces the value to the field's type, refuses writes * WordPress would silently alter, writes, then reads back: if WordPress stored something other * than what was asked (a filter rewrote it), the previous state is put back and the change is * refused — and if even that restore doesn't hold, the error says so. * * @param int|null $shared A restore point the caller already took for several fields at once * (wp_replace_text): used as this write's undo, and the caller keeps or * rolls it back — one point per call, so a long replacement can't prune * its own undo point or older history. * @return array { path, before, after, snapshot_id } */ public static function update( \WP_Post $post, $path, $value, $shared = null ) { list( $post, $field, $adapter, $locator, $new, $column, $raw_field ) = self::prepare_update( $post, $path, $value ); $row_write = null !== $column; $before = $field['value']; $row = self::raw_row( $post->ID ); $snapshot = null !== $shared ? $shared : Snapshots::take( $post->ID, $path, $before ); try { $after = self::write_checked( $post, $adapter, $locator, $new, $path, $before, $row, $row_write, $column, isset( $raw_field ) ? $raw_field : null ); } catch ( \Throwable $e ) { if ( null === $shared ) { try { Snapshots::discard_if_unchanged( $snapshot ); } catch ( \Throwable $ignored ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement -- the write's own error is the one to report } } throw $e; } if ( null === $shared ) { Snapshots::kept( $post->ID ); } do_action( 'adibridge_after_update', $post->ID, $path, $before, $after ); return array( 'path' => $path, 'before' => $before, 'after' => $after, 'snapshot_id' => $snapshot, ); } /** The write and its read-back checks (undoing and refusing on any mismatch). Returns the value read back. */ private static function write_checked( \WP_Post $post, $adapter, $locator, $new, $path, $before, $row, $row_write, $column, $raw_field ) { $adapter->write( $post, $locator, $new ); clean_post_cache( $post->ID ); $fresh = get_post( $post->ID ); try { $after = $adapter->read( $fresh, $locator ); $after = $after ? $after['value'] : null; } catch ( Tool_Error $e ) { $after = null; // the saved content can't even be read back: a mismatch, so the checks below undo it } // A post-row write re-saves every content column: the others must come back unchanged. $collateral = false; if ( $row_write ) { $now = self::raw_row( $post->ID ); foreach ( self::CONTENT_COLUMNS as $col ) { if ( $col !== $column && ! Field_Types::same( $now[ $col ], $row[ $col ] ) ) { $collateral = $col; } } // Status and address must not move as a side effect (publish on save, slug generated). foreach ( array( 'post_status', 'post_name' ) as $col ) { if ( $now[ $col ] !== $row[ $col ] ) { $collateral = $col; } } } // A partial write (one block of the body): the adapter checks the rest of the column it sent. if ( ! $collateral && $row_write && empty( $raw_field['whole_column'] ) && method_exists( $adapter, 'verify_column' ) ) { $problem = $adapter->verify_column( $post->ID, $now[ $column ] ); if ( null !== $problem ) { self::restore( $adapter, $post->ID, $locator, $before, $row ); throw new Tool_Error( esc_html( "$problem So the change was undone. Nothing was saved." ) ); } } if ( $collateral ) { self::restore( $adapter, $post->ID, $locator, $before, $row ); if ( in_array( $collateral, array( 'post_status', 'post_name' ), true ) ) { // WordPress itself does this (publishing a due post, normalising an imported slug). throw new Tool_Error( esc_html( "Saving $path would make WordPress change this page's " . self::COLUMN_NAMES[ $collateral ] . ' (from "' . $row[ $collateral ] . '" to "' . $now[ $collateral ] . '"), so the change was undone. Nothing was saved. Open the page in wp-admin and save it once there, then ADI can edit it.' ) ); } throw new Tool_Error( esc_html( "Saving $path made WordPress change this page's " . self::COLUMN_NAMES[ $collateral ] . ' as well (a filter or plugin rewrote it), so the change was undone. Nothing was saved.' ) ); } if ( ! Field_Types::same( $after, $new ) ) { self::restore( $adapter, $post->ID, $locator, $before, $row_write ? $row : null ); throw new Tool_Error( esc_html( "WordPress changed the value while saving $path (a filter or plugin rewrote it), so the change was undone. Nothing was saved." ) ); } return $after; } /** * Change a post's status (draft, pending, publish, private, trash) with the same protections as * a field write: lock check, capability (publish / delete), the kses guard on the row WordPress * re-saves (trashing re-saves it too) — all before a restore point is recorded — then a * read-back that the content columns didn't move and that the status is the one predicted. * * Publishing a post dated in the future schedules it (status future): that is predicted, so it * is reported as scheduled; a change that would leave the status as it is is refused. */ public static function set_status( \WP_Post $post, $status ) { $post = self::post( $post->ID ); self::refuse_if_locked( $post ); $type = get_post_type_object( $post->post_type ); if ( in_array( $status, array( 'publish', 'private' ), true ) && ! current_user_can( $type->cap->publish_posts ) ) { $user = wp_get_current_user(); throw new Tool_Error( esc_html( "The WordPress user {$user->user_login} is not allowed to publish " . strtolower( $type->labels->name ) . '. Save it as pending review instead, and someone with publishing rights can publish it.' ) ); } if ( 'trash' === $status ) { Auth::require_cap( 'delete_post', $post->ID ); if ( ! self::trash_enabled() ) { throw new Tool_Error( 'This site deletes content instead of moving it to the trash (EMPTY_TRASH_DAYS is 0), so ADI won\'t remove it. Nothing was changed.' ); } } $before = $post->post_status; $expect = 'publish' === $status && self::scheduled_for( $post ) ? 'future' : $status; if ( $before === $expect ) { throw new Tool_Error( esc_html( 'future' === $expect ? "#{$post->ID} is already scheduled for " . get_date_from_gmt( $post->post_date_gmt, 'Y-m-d H:i' ) . '; it goes live then. Nothing was changed. To publish it now, change its date in wp-admin first.' : "#{$post->ID} is already " . self::STATUS_NAMES[ $status ] . '. Nothing was changed.' ) ); } // wp_update_post() — and wp_trash_post(), which calls it — re-saves the whole row through kses. self::guard_post_row_kses( $post, 'post_status', null, true ); $row = self::raw_row( $post->ID ); $snapshot = Snapshots::take( $post->ID, 'status', $before ); if ( 'trash' === $status ) { if ( ! wp_trash_post( $post->ID ) ) { self::roll_back( $snapshot, $post->ID ); throw new Tool_Error( 'WordPress refused to move it to the trash. The content was put back as it was.' ); } } else { $result = wp_update_post( array( 'ID' => $post->ID, 'post_status' => $status ), true ); if ( is_wp_error( $result ) ) { self::roll_back( $snapshot, $post->ID ); throw new Tool_Error( esc_html( 'WordPress refused the change: ' . $result->get_error_message() . ' The content was put back as it was.' ) ); } } clean_post_cache( $post->ID ); $now = self::raw_row( $post->ID ); if ( ! $now ) { // Only a plugin deleting it on the way can get here (the trash setting is checked above); // its restore points went with it, so there is nothing to name as an undo. Log::line( "#{$post->ID} was deleted while changing its status" ); throw new Tool_Error( esc_html( "WordPress deleted #{$post->ID} permanently instead of changing its status (a plugin or the site's trash setting). It can't be brought back from ADI; check the site's backups." ) ); } // "Put back" rather than "nothing changed": WordPress already ran its save hooks (and may have kept a revision). foreach ( self::CONTENT_COLUMNS as $col ) { if ( ! Field_Types::same( $now[ $col ], $row[ $col ] ) ) { self::roll_back( $snapshot, $post->ID ); throw new Tool_Error( esc_html( 'Changing the status made WordPress rewrite the ' . self::COLUMN_NAMES[ $col ] . ' too (a filter or plugin), so the status change was refused. The content was put back as it was.' ) ); } } $after = $now['post_status']; if ( $after !== $expect ) { self::roll_back( $snapshot, $post->ID ); throw new Tool_Error( esc_html( "WordPress set the status to \"$after\" instead of \"$expect\" (a filter or plugin), so the change was refused. The content was put back as it was." ) ); } Snapshots::kept( $post->ID ); do_action( 'adibridge_after_status', $post->ID, $before, $after ); return array( 'id' => $post->ID, 'before' => $before, 'after' => $after, 'snapshot_id' => $snapshot ); } /** A status as a person says it, after "is already". */ const STATUS_NAMES = array( 'publish' => 'published', 'private' => 'private', 'draft' => 'a draft', 'pending' => 'pending review', 'future' => 'scheduled', 'trash' => 'in the trash', ); /** * Does this site keep trashed content? With EMPTY_TRASH_DAYS 0, wp_trash_post() deletes for good * (and the restore points go with it), which ADI never does. */ public static function trash_enabled() { return defined( 'EMPTY_TRASH_DAYS' ) && (bool) EMPTY_TRASH_DAYS; } /** The publish time of a post dated in the future (a timestamp), or null. Undated drafts publish now. */ private static function scheduled_for( \WP_Post $post ) { if ( '0000-00-00 00:00:00' === $post->post_date_gmt ) { return null; } $time = strtotime( $post->post_date_gmt . ' UTC' ); return $time > time() ? $time : null; } /** Undo a refused status change from its own restore point (row, meta, trashed comments). */ private static function roll_back( $snapshot, $id ) { if ( ! Snapshots::roll_back( $snapshot ) ) { Log::line( "could not put back #$id after a refused status change" ); throw new Tool_Error( esc_html( "WordPress didn't make the status change as asked, and putting the page back didn't fully work either. Check #$id in wp-admin (and the trash) before making more changes; wp_restore_snapshot with snapshot_id $snapshot puts it back as it was." ) ); } } /** * Someone has this page open in wp-admin (block editor, classic editor, Elementor): their next * save or autosave would silently overwrite ADI's change. Refuse, naming them. */ public static function refuse_if_locked( \WP_Post $post ) { // Any recent lock counts — including the connected user's own: the person chatting with ADI // may have the page open in the editor too, and their next save would undo ADI's change. $lock = explode( ':', (string) get_post_meta( $post->ID, '_edit_lock', true ) ); $time = isset( $lock[0] ) ? (int) $lock[0] : 0; $who = isset( $lock[1] ) ? (int) $lock[1] : 0; if ( $time && $time > time() - (int) apply_filters( 'wp_check_post_lock_window', 150 ) ) { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- WordPress core's own filter (wp_check_post_lock()), read so the lock window matches the editor's $user = $who ? get_userdata( $who ) : null; $name = $user ? $user->display_name : 'Someone'; $self = $who && get_current_user_id() === $who ? ' (signed in as the same WordPress user ADI uses)' : ''; throw new Tool_Error( esc_html( "$name has #{$post->ID} open in the WordPress editor right now$self; their next save would overwrite ADI's change. Close the editor (or wait two minutes) and try again. Nothing was changed." ) ); } } /** Columns wp_update_post re-saves through the content filters (kses for some users). */ const CONTENT_COLUMNS = array( 'post_title', 'post_content', 'post_excerpt', 'post_content_filtered' ); const COLUMN_NAMES = array( 'post_status' => 'status', 'post_name' => 'address (slug)', 'post_title' => 'title', 'post_content' => 'body', 'post_excerpt' => 'excerpt', 'post_content_filtered' => 'body source (Markdown)', ); /** The save filter and the kses function WordPress applies to each content column. */ const COLUMN_FILTERS = array( 'post_title' => array( 'title_save_pre', 'wp_filter_kses' ), 'post_content' => array( 'content_save_pre', 'wp_filter_post_kses' ), 'post_excerpt' => array( 'excerpt_save_pre', 'wp_filter_post_kses' ), 'post_content_filtered' => array( 'content_filtered_save_pre', 'wp_filter_post_kses' ), ); /** * The stored row, exactly as in the database (no filters): content columns plus the status and * dates a re-save can also move (a past-dated scheduled post gets published, modified dates change). */ private static function raw_row( $id ) { global $wpdb; // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- the post row exactly as stored (no filters), to put it back after a refused write return $wpdb->get_row( $wpdb->prepare( "SELECT post_title, post_content, post_excerpt, post_content_filtered, post_status, post_name, post_date, post_date_gmt, post_modified, post_modified_gmt FROM {$wpdb->posts} WHERE ID = %d", $id ), ARRAY_A ); } /** * Put back the state before a refused write. A post-row write is restored by writing the stored * columns straight back (going through wp_update_post again would re-run the very filters that * caused the refusal); other adapters restore through their own write. Either way, read back. */ private static function restore( Adapters\Adapter $adapter, $id, $locator, $before, $row ) { global $wpdb; if ( null !== $row ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- putting the stored row back exactly after a refused write; clean_post_cache() follows $wpdb->update( $wpdb->posts, $row, array( 'ID' => $id ) ); clean_post_cache( $id ); $ok = self::raw_row( $id ) === $row; } else { self::$restoring = true; try { $adapter->write( get_post( $id ), $locator, $before ); clean_post_cache( $id ); $now = $adapter->read( get_post( $id ), $locator ); $ok = $now && Field_Types::same( $now['value'], $before ); } catch ( Tool_Error $e ) { $ok = false; } finally { self::$restoring = false; } } /** * After a refused write was undone. The refused write already ran save_post (caches, search * indexes, a revision of the refused value); the raw restore ran no hooks — listeners * (cache purge, #10) re-sync here. */ do_action( 'adibridge_after_restore', $id, $adapter->id() . ':' . $locator ); if ( ! $ok ) { Log::line( "could not restore #$id $locator after a refused write" ); throw new Tool_Error( esc_html( "WordPress changed the value while saving {$adapter->id()}:$locator, and putting the old value back didn't fully work either. Check #$id in wp-admin (Revisions) before making more changes." ) ); } } /** * wp_update_post() re-saves the whole row, and for a user without unfiltered_html WordPress * runs kses over the title, body and excerpt — silently dropping embeds, iframes, scripts and * forms that are already there. Simulate exactly those filters on the row as it would be saved * and refuse up front if anything would be lost, rather than strip a page's video because * someone asked to fix a typo in its title. */ private static function guard_post_row_kses( \WP_Post $post, $column, $new, $whole ) { $values = array(); foreach ( self::CONTENT_COLUMNS as $col ) { $values[ $col ] = (string) $post->$col; } if ( isset( $values[ $column ] ) && is_string( $new ) ) { // A part of a column (one block's text) is checked on its own, alongside the stored column. if ( $whole ) { $values[ $column ] = $new; } else { $values['__part'] = $new; } } $lost = array(); $filters = self::COLUMN_FILTERS; if ( isset( $values['__part'] ) ) { $filters['__part'] = self::COLUMN_FILTERS[ $column ]; } foreach ( $filters as $col => $pair ) { list( $hook, $default ) = $pair; $value = $values[ $col ]; if ( '' === $value ) { continue; } // Use whichever kses function WordPress actually attached to this column's save filter. $kses = has_filter( $hook, 'wp_filter_post_kses' ) ? 'wp_filter_post_kses' : ( has_filter( $hook, 'wp_filter_kses' ) ? 'wp_filter_kses' : null ); if ( null === $kses ) { continue; } // Lost = a tag, attribute, visible text or comment differs. kses also re-spells entities, // re-quotes attributes, writes
as
and tidies inline CSS — none of which // loses anything, and Html::equivalent() doesn't count it. $filtered = wp_unslash( call_user_func( $kses, wp_slash( $value ) ) ); if ( ! Html::equivalent( $filtered, $value ) ) { if ( Html::equivalent( self::without_block_delimiters( $filtered ), self::without_block_delimiters( $value ) ) ) { $settings = true; // only block settings re-encoded, no markup lost continue; } $lost[] = '__part' === $col ? 'new text' : self::COLUMN_NAMES[ $col ]; } } if ( ! $lost && ! empty( $settings ) ) { $user = wp_get_current_user(); throw new Tool_Error( esc_html( "For the WordPress user {$user->user_login}, WordPress would re-save this page's block settings in a different form (it filters every block's settings for users without full HTML rights), which can change how blocks look. Nothing was changed. Connect ADI as an Editor or Administrator to edit this page." ) ); } if ( $lost ) { $user = wp_get_current_user(); throw new Tool_Error( esc_html( "Saving would make WordPress strip markup from this page's " . implode( ' and ', $lost ) . " (embeds, iframes, scripts or forms the WordPress user {$user->user_login} isn't allowed to save). Nothing was changed. Connect ADI as an Editor or Administrator to edit this page." ) ); } } /** * Meta and options writes (ACF, Elementor) skip WordPress's kses, so apply its rule here: a * user without unfiltered_html may not store markup WordPress would strip from them (themes * often echo custom fields unescaped). */ private static function guard_meta_kses( $value ) { if ( current_user_can( 'unfiltered_html' ) ) { return; } $strings = array(); if ( is_array( $value ) ) { array_walk_recursive( $value, static function ( $v ) use ( &$strings ) { if ( is_string( $v ) ) { $strings[] = $v; } } ); } elseif ( is_string( $value ) ) { $strings[] = $value; } foreach ( $strings as $string ) { if ( ! Html::equivalent( wp_kses_post( $string ), $string ) ) { $user = wp_get_current_user(); throw new Tool_Error( esc_html( "This text has markup (scripts, iframes, forms) the WordPress user {$user->user_login} isn't allowed to save. Nothing was changed. Connect ADI as an Editor or Administrator to save it." ) ); } } } // ── ACF options pages (Site Settings, …): content that belongs to no post ───────────── /** Options pages with fields, as targets: slug => { slug, title }. Only those the user may edit. */ public static function options_pages() { $acf = self::adapters()['acf'] ?? null; if ( ! $acf ) { return array(); } $out = array(); foreach ( Adapters\Acf::option_pages() as $slug => $page ) { if ( current_user_can( $page['capability'] ) ) { $out[ $slug ] = array( 'slug' => $slug, 'title' => $page['title'] ); } } return $out; } /** The ACF adapter, after checking the user may edit options page $slug (its own capability). */ private static function options_acf( $slug ) { $acf = self::adapters()['acf'] ?? null; if ( ! $acf ) { throw new Tool_Error( 'Advanced Custom Fields is not active on this site, so there are no options pages.' ); } $page = Adapters\Acf::option_page( is_string( $slug ) ? $slug : '' ); Auth::require_cap( $page['capability'] ); return $acf; } public static function option_fields( $slug ) { $acf = self::options_acf( $slug ); return array_map( static function ( $f ) use ( $acf ) { return self::finish( $acf, $f ); }, $acf->option_fields( $slug ) ); } public static function option_field( $slug, $path ) { $acf = self::options_acf( $slug ); if ( ! is_string( $path ) || 0 !== strpos( $path, 'acf:' ) ) { throw new Tool_Error( esc_html( self::show( $path ) . ' is not an options-page field. Options fields look like acf:popup_delay; take them from wp_get_content.' ) ); } $field = $acf->option_read( $slug, substr( $path, 4 ) ); if ( null === $field ) { throw new Tool_Error( esc_html( "There is no field $path on the \"$slug\" options page. Call wp_get_content to see its fields." ) ); } return self::finish( $acf, $field ); } /** Every refusal option_update() can make before it writes; see check_update(). */ public static function check_option_update( $slug, $path, $value ) { self::prepare_option_update( $slug, $path, $value ); } private static function prepare_option_update( $slug, $path, $value ) { $field = self::option_field( $slug, $path ); $acf = self::options_acf( $slug ); if ( ! $field['writable'] ) { throw new Tool_Error( esc_html( "$path is read-only" . ( ! empty( $field['note'] ) ? ': ' . $field['note'] : '.' ) ) ); } $new = Field_Types::coerce( $field, $value ); self::guard_meta_kses( $new ); Html::refuse_unsafe_additions( $new, $field['value'], $path ); return array( $field, $acf, $new ); } /** * Change one options-page field: the same rules as a post field (type coercion, the markup * rule, read back, put back and refuse if WordPress stored something else). $shared: see update(). */ public static function option_update( $slug, $path, $value, $shared = null ) { list( $field, $acf, $new ) = self::prepare_option_update( $slug, $path, $value ); $locator = substr( $path, 4 ); $before = $field['value']; $snapshot = null !== $shared ? $shared : Snapshots::take( "options:$slug", $path, $before ); try { $after = self::option_write_checked( $acf, $slug, $locator, $new, $path, $before ); } catch ( \Throwable $e ) { if ( null === $shared ) { try { Snapshots::discard_if_unchanged( $snapshot ); } catch ( \Throwable $ignored ) { // phpcs:ignore Generic.CodeAnalysis.EmptyStatement -- the write's own error is the one to report } } throw $e; } if ( null === $shared ) { Snapshots::kept( "options:$slug" ); } do_action( 'adibridge_after_option_update', $slug, $path, $before, $after ); return array( 'path' => $path, 'before' => $before, 'after' => $after, 'snapshot_id' => $snapshot, ); } /** The options write and its read-back (put back and refuse on mismatch). Returns the value read back. */ private static function option_write_checked( $acf, $slug, $locator, $new, $path, $before ) { $acf->option_write( $slug, $locator, $new ); $after = $acf->option_read( $slug, $locator ); $after = $after ? $after['value'] : null; if ( ! Field_Types::same( $after, $new ) ) { self::$restoring = true; try { $acf->option_write( $slug, $locator, $before ); } catch ( Tool_Error $e ) { Log::line( "options put-back of $slug $path failed: " . Tool_Error::text( $e ) ); } finally { self::$restoring = false; } $back = $acf->option_read( $slug, $locator ); do_action( 'adibridge_after_option_restore', $slug, $path ); if ( ! $back || ! Field_Types::same( $back['value'], $before ) ) { Log::line( "could not restore options:$slug $path after a refused write" ); throw new Tool_Error( esc_html( "WordPress changed the value while saving $path, and putting the old value back didn't fully work either. Check the \"$slug\" options page in wp-admin before making more changes." ) ); } throw new Tool_Error( esc_html( "WordPress changed the value while saving $path (a filter or plugin rewrote it), so the change was undone. Nothing was saved." ) ); } return $after; } /** Block delimiter comments () removed: what's left is the page's markup and text. */ private static function without_block_delimiters( $html ) { return preg_replace( Block_Map::DELIMITER, '', (string) $html ); } /** A value for an error message, whatever the caller sent. */ private static function show( $value ) { if ( is_int( $value ) || ( is_string( $value ) && ctype_digit( $value ) ) ) { return (string) $value; } return is_scalar( $value ) ? '"' . $value . '"' : wp_json_encode( $value ); } /** @return array{0: Adapter, 1: string} */ private static function resolve( \WP_Post $post, $path ) { if ( ! is_string( $path ) || ! preg_match( '/^([a-z][a-z0-9_]*):(.+)\z/s', $path, $m ) ) { throw new Tool_Error( esc_html( self::show( $path ) . ' is not a field path. Paths look like core:post_title or acf:hero/0/heading; take them from wp_get_content.' ) ); } $editors = self::editors_for( $post ); if ( ! isset( $editors[ $m[1] ] ) ) { $known = implode( ', ', array_keys( $editors ) ); throw new Tool_Error( esc_html( "#{$post->ID} has no {$m[1]} content (it has: $known). Call wp_get_content to see its fields." ) ); } return array( $editors[ $m[1] ], $m[2] ); } private static function finish( Adapter $adapter, array $field ) { $path = $adapter->id() . ':' . $field['locator']; $field = array_merge( array( 'path' => $path, 'editor' => $adapter->id(), 'label' => $field['locator'], 'type' => 'readonly', 'value' => null, 'writable' => false, ), $field ); unset( $field['locator'], $field['kind'], $field['whole_column'] ); // adapter-internal flags $field['path'] = $path; /** Central veto over writability. */ $field['writable'] = (bool) apply_filters( 'adibridge_field_writable', $field['writable'] && 'readonly' !== $field['type'], $field ); // SEO data is never writable here, whatever an adapter or filter says. $field = Seo::apply( $field ); unset( $field['within'], $field['acf_key'] ); // only the SEO rule needs them return $field; } }