*/ final class CustomVariablesSync { /** * The five mapping slots, which are also the option names the plugin has * always stored the selected keys under. * * @since 4.4.0 * @var array */ const SLOTS = array( 'custom1', 'custom2', 'custom3', 'custom4', 'custom5' ); /** * The default key of each slot, the one `Migrations` seeds and every read * of an unset slot falls back to. * * @since 4.4.0 * @var array */ const SLOT_DEFAULTS = array( 'custom1' => 'author_display_name', 'custom2' => 'category_0_slug', 'custom3' => 'post_ID', 'custom4' => '', 'custom5' => '', ); /** * Seconds granted to the re-read GET when it runs inside a push request. * * The sender caps the whole push exchange at 15 seconds and the verify * callback has already spent part of it (SPA-25968 precedent), so the GET * cannot afford the client's 30-second default: a slow API would make the * sender time out and redeliver an event the plugin was still processing. * * @since 4.4.0 * @var int */ const PUSH_REREAD_TIMEOUT = 5; /** * Seconds granted to a GET that runs inside the admin save request. * * The publisher is waiting on the save bar and the PATCH may already have * spent the client's full 30-second default, so the arming read and the * conflict fallback get a small budget instead of stacking a second full * timeout on the same flow (the SPA-25974 precedent: bound the flow, not * only each step). * * @since 4.4.0 * @var int */ const SAVE_REREAD_TIMEOUT = 5; /** * Whether the API has confirmed this website is in the rollout * (`release/wordpress-custom-variables-sync`). * * @since 4.4.0 * @var string */ const OPTION_ENABLED = 'customvars-sync-enabled'; /** * The mapping version the plugin currently holds. `0` means the Platform * has nothing stored for this website. * * @since 4.4.0 * @var string */ const OPTION_VERSION = 'customvars-sync-version'; /** * Fingerprint of the last mapping the API handed over or confirmed. * * @since 4.4.0 * @var string */ const OPTION_DIGEST = 'customvars-sync-digest'; /** * The slot names, one per slot, as the Platform holds them. A name is a * string on a Custom value (`customFields_*`, `custom_value`) and `null` * on every other key (contract § 4). * * @since 4.4.0 * @var string */ const OPTION_NAMES = 'customvars-names'; /** * Option holding the identifier the API resolves this website by: the * Actirise website uuid, as `ConfigSync` and the capability report use it. * * @since 4.4.0 * @var string */ const OPTION_IDENTIFIER = 'website-uuid'; /** * Logger context shared by every diagnostic this sync emits. * * @since 4.4.0 * @var string */ const LOG_CONTEXT = 'include/customvars'; /** * Outbound client. * * @since 4.4.0 * @var Api */ private $api; /** * @since 4.4.0 * @param Api|null $api Client to use; a new one by default. */ public function __construct( $api = null ) { $this->api = ( null === $api ) ? new Api() : $api; } /** * Whether this install is an Actirise client the API can resolve. * * Pure option reads and no HTTP, exactly as * {@see \Actirise\Includes\FastCmp\ConfigSync::is_syncable()}: a site that * is not a client behaves as it does today. The "credentials but no uuid" * anomaly is the same stored fact for both syncs and ConfigSync already * logs it once a day, so this one stays silent rather than doubling the * line. * * @since 4.4.0 * @return bool */ public static function is_syncable() { return Helpers::is_user_authenticated() && '' !== self::identifier(); } /** * The identifier the resource is addressed by, or `''` when the site has none. * * @since 4.4.0 * @return string */ private static function identifier() { $identifier = Options::get( self::OPTION_IDENTIFIER, '' ); return is_scalar( $identifier ) ? trim( (string) $identifier ) : ''; } /** * Whether the hourly reconciliation read should run. * * On an armed site it is a *fallback*, as * {@see \Actirise\Includes\FastCmp\ConfigSync::should_poll()}: while the * push channel is live the site already receives every change, and polling * on top of it would spend an hourly request per install for nothing. * {@see \Actirise\Includes\Cron::is_push_active()} is the plugin's single * definition of "push works here". * * An unarmed site runs the read even while push is live: the GET is the * only thing that can arm the sync (a push is refused with a `400` until * then, {@see \Actirise\Includes\Push\Handler\CustomVariablesPushHandler::apply()}), * so gating it on the push would leave a push-active install out of the * rollout forever. This is the counterpart of the FastCMP seed * ({@see \Actirise\Includes\FastCmp\ConfigSync::run_seed()}), which * ignores the push state for the same reason. * * @since 4.4.0 * @return bool */ public static function should_poll() { if ( ! self::is_syncable() ) { return false; } return ! self::armed() || ! Cron::is_push_active(); } /** * Whether the exchange is live for this website. * * `release/wordpress-custom-variables-sync` is a per-website decision * taken in the API, so the plugin can only observe it: a GET the API * answered is the proof (see {@see self::pull()}), and a `404` takes it * away again. Until then the site behaves exactly as the current release. * * @since 4.4.0 * @return bool */ public static function armed() { return self::is_syncable() && true === Options::get( self::OPTION_ENABLED, false ); } /** * The mapping version the plugin currently believes the Platform holds. * * Public because the admin state hands it to the Settings tab alongside * the selected keys. * * @since 4.4.0 * @return int */ public static function version() { return self::int_option( self::OPTION_VERSION ); } /** * The stored slot names, every slot present, `null` when the Platform * never handed one over. * * @since 4.4.0 * @return array */ public static function names() { $stored = Options::get( self::OPTION_NAMES, array() ); $stored = is_array( $stored ) ? $stored : array(); $names = array(); foreach ( self::SLOTS as $slot ) { $names[ $slot ] = isset( $stored[ $slot ] ) && is_string( $stored[ $slot ] ) ? $stored[ $slot ] : null; } return $names; } /** * The stored slot keys, every slot present, the plugin defaults where a * slot was never written. * * @since 4.4.0 * @return array */ public static function selected() { $selected = array(); foreach ( self::SLOT_DEFAULTS as $slot => $default ) { $key = Options::get( $slot, $default ); $selected[ $slot ] = is_scalar( $key ) ? (string) $key : ''; } return $selected; } /** * Read the Platform's mapping and adopt it. * * Also arms the sync, as does the first send's own read ({@see * self::run_seed()}): a GET the API answers proves this website carries * the release flag. The GET is always authoritative (contract § 5.4), * which is why every doubt elsewhere resolves into a call here. The * callers: the hourly cron and the Settings save of an unarmed website, * and, on a website already armed, the push's re-read and the save's * conflict fallback. * * @since 4.4.0 * @param int|null $timeout Seconds granted to the GET; the client default when null. * @return bool Whether the Platform's mapping was read and adopted. */ public function pull( $timeout = null ) { if ( ! self::is_syncable() ) { return false; } $response = $this->read( $timeout ); if ( is_wp_error( $response ) ) { self::disarm_if_refused( $response ); return false; } if ( ! is_array( $response ) ) { return false; } Options::update( self::OPTION_ENABLED, true ); return $this->adopt( $response ); } /** * Read the Platform's mapping, without interpreting the answer. * * The `api` base already carries `/api/wordpress/`, so the resource is the * gateway path of contract § 2 relative to it. * * @since 4.4.0 * @param int|null $timeout Seconds granted to the request; the client default when null. * @return mixed */ private function read( $timeout = null ) { /** @var string $token */ $token = Options::get( 'settings-analytics-token', '' ); $options = ( null === $timeout ) ? array() : array( 'timeout' => $timeout ); return $this->api->get( 'api', 'websites/' . self::identifier() . '/custom_variables', array(), $token, false, $options ); } /** * Disarm the sync when the API refused the exchange for a reason that will * not change on its own: a `404` (unknown website, another organization's, * not a WordPress Plugin website, or the rollout flag off — one body for * all four, contract § 7) or a `401`, after which * {@see \Actirise\Includes\Api::request()} has already deleted the * credentials. Anything else is transient and leaves the state untouched. * * @since 4.4.0 * @param \WP_Error $error The error Api::request() produced. * @return void */ private static function disarm_if_refused( $error ) { $code = (int) $error->get_error_code(); if ( 404 !== $code && 401 !== $code ) { return; } Options::update( self::OPTION_ENABLED, false ); } /** * Whether the one-off first send (contract § 8.3) is still owed. * * @since 4.4.0 * @var string */ const OPTION_SEED_PENDING = 'customvars-initial-sync-pending'; /** * How many times that first send has been attempted. * * @since 4.4.0 * @var string */ const OPTION_SEED_ATTEMPTS = 'customvars-initial-sync-attempts'; /** * Earliest time, as a Unix timestamp, the next attempt may run once the * hourly budget is spent. * * @since 4.4.0 * @var string */ const OPTION_SEED_RETRY_AT = 'customvars-initial-sync-retry-at'; /** * Whether this arming's 422 refusal was already logged. * * The seed retries hourly and `logs` keeps only the last 100 lines, so a * line per attempt would flush the errors support relies on within days: * each arming logs its first refusal and nothing after. * * @since 4.4.0 * @var string */ const OPTION_SEED_REFUSAL_LOGGED = 'customvars-initial-sync-refusal-logged'; /** * Hourly attempts before the seed slows to {@see self::SEED_RETRY_INTERVAL} * (one week of hourly runs, the * {@see \Actirise\Includes\FastCmp\ConfigSync::MAX_SEED_ATTEMPTS} precedent). * * @since 4.4.0 * @var int */ const MAX_SEED_ATTEMPTS = 168; /** * Delay between two attempts once the hourly budget is spent, in seconds. * * @since 4.4.0 * @var int */ const SEED_RETRY_INTERVAL = 86400; /** * Arm the one-off first send. * * Armed for **every** install, including sites that will turn out to have * no Actirise account: at the moment the plugin updates, a free publisher * and a client halfway through onboarding are indistinguishable, and * refusing to arm there would permanently skip anyone who finishes * onboarding afterwards ({@see \Actirise\Includes\FastCmp\ConfigSync::arm_seed()} * precedent). Also lifts a pending daily retry, so a re-arm starts again * from hourly attempts. * * @since 4.4.0 * @return void */ public static function arm_seed() { Options::update( self::OPTION_SEED_PENDING, true ); Options::update( self::OPTION_SEED_ATTEMPTS, 0 ); Options::update( self::OPTION_SEED_RETRY_AT, 0 ); Options::update( self::OPTION_SEED_REFUSAL_LOGGED, false ); } /** * Arm the first send again, if the Platform was never seen to hold a * mapping here. * * The held version tells the two populations apart: `0` means every * exchange so far found the Platform empty, so re-arming cannot overwrite * a curated mapping — and the seed reads before it writes in any case. A * version of 1 or more proves the migration already happened, through the * seed or any other exchange. * * @since 4.4.0 * @return bool Whether the seed was armed. */ public static function rearm_seed() { if ( self::version() > 0 ) { return false; } self::arm_seed(); return true; } /** * Forget the sync state when the install starts pointing at another * website. * * The version, the fingerprint, the names and the armed flag all describe * the website the previous uuid named — the version counter is monotonic * *per website* (contract § 5.4). Carried over, they would block the * re-arm ({@see self::rearm_seed()}), answer `unchanged` for a mapping * the new website never confirmed, and measure pushed versions against * another website's counter: the new website would never receive the * mapping. The local `custom1..custom5` keys stay untouched: they are the * local settings the first send migrates (§ 8.3). * * @since 4.4.0 * @return void */ public static function reset_for_new_website() { Options::update( self::OPTION_ENABLED, false ); Options::update( self::OPTION_VERSION, 0 ); Options::update( self::OPTION_DIGEST, '' ); Options::update( self::OPTION_NAMES, array() ); } /** * Migrate this site's local settings to the Platform once, if it is owed. * * The § 8.3 sequence, after the capability report the update queued: the * GET first, because the first send fills emptiness and nothing else. A * mapping the Platform already holds — saved in the Admin before the * plugin updated — is adopted instead, and the local settings are dropped * (product decision of 2026-10-15). Runs from cron with no save in * flight, so the GET affords the client's default timeout. * * A rejected first send (422) stays the first send: nothing is stored on * either side, no annotation exists anywhere, and the seed retries with * the hourly budget then daily backoff of * {@see \Actirise\Includes\FastCmp\ConfigSync::run_seed()}. The publisher * sees the refusal in the Settings tab when they next save (the rows of * {@see self::publish_save()}), and the site stays in the Krull migration * report until a send lands. * * @since 4.4.0 * @return bool Whether the seed ran to a conclusion and is no longer owed. */ public function run_seed() { if ( true !== Options::get( self::OPTION_SEED_PENDING, false ) ) { return false; } // No credentials or no uuid: nothing is requested, so the hour is not // an attempt. Counting it would retire the budget of a site connected // to Actirise weeks after its update. if ( ! self::is_syncable() ) { return false; } if ( ! self::seed_due() ) { return false; } $read = $this->read(); if ( is_wp_error( $read ) ) { self::disarm_if_refused( $read ); return self::defer_seed(); } if ( ! is_array( $read ) ) { return self::defer_seed(); } Options::update( self::OPTION_ENABLED, true ); // The Platform already holds a mapping: it is the source of truth, so // adopt it and the migration is settled. A version-0 answer leaves // nothing to adopt and falls through to the first send. if ( $this->adopt( $read ) ) { return self::consume_seed(); } if ( null === self::slots_of( $read ) ) { // A malformed body is a schema error: never first-send over a // truth that could not be read. return self::defer_seed(); } $response = $this->send( $this->submitted_slots( array() ) ); if ( ! is_wp_error( $response ) ) { $this->adopt( is_array( $response ) ? $response : array() ); // Only a held version proves the Platform now holds the mapping. if ( self::version() > 0 ) { return self::consume_seed(); } return self::defer_seed(); } if ( 422 === (int) $response->get_error_code() ) { // Nobody reads the rows here — the publisher sees them on their // next save — and the refusal repeats identically until they fix // the settings, so each arming logs its first one and no more // (see {@see self::OPTION_SEED_REFUSAL_LOGGED}). if ( true !== Options::get( self::OPTION_SEED_REFUSAL_LOGGED, false ) ) { self::log_refusal( 'first send', self::violations_of( $response ) ); Options::update( self::OPTION_SEED_REFUSAL_LOGGED, true ); } return self::defer_seed(); } $result = $this->resolve( $response ); // An Admin save raced in between the GET and the PATCH: the Platform // won and concede() adopted its mapping, so the migration is settled. if ( 'conflict' === $result['status'] && self::version() > 0 ) { return self::consume_seed(); } return self::defer_seed(); } /** * Whether the seed may spend a request on this run. * * Always, within the hourly budget. Past it, only once the daily retry * {@see self::defer_seed()} scheduled is due. * * @since 4.4.0 * @return bool */ private static function seed_due() { return self::int_option( self::OPTION_SEED_RETRY_AT ) <= time(); } /** * Leave the seed owed and count the attempt. * * Never retires it: a site the API refuses today (rollout flag off) or * whose settings it rejects (a 422 the publisher has not fixed yet) may * be accepted tomorrow. Once {@see self::MAX_SEED_ATTEMPTS} hourly * attempts are spent, the next ones are spaced by * {@see self::SEED_RETRY_INTERVAL}, which caps a site refused for good at * one request a day. * * @since 4.4.0 * @return bool */ private static function defer_seed() { $attempts = self::int_option( self::OPTION_SEED_ATTEMPTS ) + 1; Options::update( self::OPTION_SEED_ATTEMPTS, $attempts ); if ( $attempts < self::MAX_SEED_ATTEMPTS ) { return false; } if ( self::MAX_SEED_ATTEMPTS === $attempts ) { Logger::add_log( 'Custom variables first send still owed after ' . $attempts . ' attempts; retrying once a day', self::LOG_CONTEXT, 'error' ); } Options::update( self::OPTION_SEED_RETRY_AT, time() + self::SEED_RETRY_INTERVAL ); return false; } /** * Mark the first send as no longer owed. * * @since 4.4.0 * @return bool */ private static function consume_seed() { Options::update( self::OPTION_SEED_PENDING, false ); return true; } /** * Apply a mapping the API pushed (contract § 5.4). * * The version is monotonic per website, which gives three cases: * * - **newer** than the one held: adopt the keys and the names, store the * version, create no annotation (Krull creates every annotation, D50). * - **equal**: compare the content. Identical is a redelivery, ignored. * Different is the pre-commit write race of two Admin saves announcing * the same number — settled by re-reading with the GET, which is always * authoritative, rather than by believing either body. The GET runs * inside the push request, so it is bounded by * {@see self::PUSH_REREAD_TIMEOUT}, and a re-read that fails leaves the * event unmarked: the 400 makes the API redeliver instead of acking a * mapping the plugin could not confirm. * - **older**: ignore. Pushes are retried and can arrive late or twice; a * delayed delivery is never a rollback. * * Unlike the CMP sync there is no echo to recognise here: Krull never * pushes for a write that came from the plugin (contract § 5.2). * * @since 4.4.0 * @param array $data The pushed § 4 projection `{version, custom1..custom5}`. * @return bool Whether the event may be marked processed. */ public function apply_pushed( array $data ) { $version = isset( $data['version'] ) && is_numeric( $data['version'] ) ? (int) $data['version'] : 0; $held = self::version(); if ( $version < $held ) { return true; } $slots = self::slots_of( $data ); if ( null === $slots ) { // A malformed slot is a schema error: the 400 this becomes leaves // the event unmarked, and the signal lands on the sending side. return false; } if ( $version > $held ) { $this->adopt_slots( $slots, $version ); return true; } if ( self::holds_mapping( $slots ) ) { return true; } return $this->pull( self::PUSH_REREAD_TIMEOUT ); } /** * Publish a Settings save and decide what the AJAX handler may do with it. * * Called **before** the options are written: the Platform's answer * arbitrates the save (R18, R19), and a refused one must leave the local * mapping untouched so WordPress and the Platform never describe different * mappings. The one entry point the admin save calls, so the decision of * "does this save reach the Platform, and what happens when it cannot" * lives here rather than spread through the AJAX handler. * * The statuses, and what each lets the caller do: * * - `local`: the exchange is not live here (not armed, even after the * arming GET below, or the PATCH came back 404): save locally only, * exactly as the current release (R20). * - `disconnected`: the API answered 401, after which * {@see \Actirise\Includes\Api::request()} has already deleted the * credentials: refuse the save, so the edit stays on the screen to save * again after reconnecting. A local write instead would report success * for a mapping the pull that follows the reconnection is certain to * overwrite, silently. * - `unchanged`: the submission matches the mapping the Platform already * confirmed: save locally, publish nothing. This is also what keeps a * mapping applied from a push from being sent back: the push stored its * fingerprint, so re-saving it publishes nothing. * - `published`: the Platform stored it, so save locally; a well-formed * answered projection (defaulted names included) was adopted, version * with it. An answer that could not be adopted is replaced by the * bounded GET, so the held version never goes stale on a success. * - `conflict`: the Platform's mapping wins (R19), in two cases: it moved * on first (the 409, adopted from the conflict body or the bounded GET), * or the arming GET below found a mapping it already holds, which the * screen this edit was made on predates (contract § 8.3: only the * version 0 first send may carry the local settings up). The publisher's * change is lost and never replayed * (deliberately unlike {@see \Actirise\Includes\FastCmp\ConfigSync::arbitrate()}, * which replays a field-by-field merge once: here the whole mapping is * one setting, product decision of 2026-10-15). `selected` and `names` * carry what to show instead. * - `invalid`: the Platform refused the choice: `violations` carries the * rows to mark, with the exact messages the Admin shows (R34). * - `failed`: transient (a 5xx, a timeout, a 429, or a 409 whose winning * mapping could not be read — see {@see self::concede()}): the save is * refused so the publisher retries, `retry_after` carrying the rate * limit's delay when it named one. The token and the armed state are * kept. * * @since 4.4.0 * @param array $submitted The posted slot keys, by slot name. * @return array `status`, plus `violations`, `selected`, `names` or `retry_after`. */ public function publish_save( array $submitted ) { $was_armed = self::armed(); if ( ! $was_armed ) { $was_syncable = self::is_syncable(); // The arming GET: an install the hourly run has not armed yet (a // fresh connection, or the plugin just updated) must not keep // saving locally, and nothing else can arm a push-active install // (a push is refused until armed). Bounded, because the publisher // is waiting on the save bar. $this->pull( self::SAVE_REREAD_TIMEOUT ); if ( $was_syncable && ! self::is_syncable() ) { // The GET came back 401 and the client deleted the // credentials: the publisher was just logged out. return array( 'status' => 'disconnected' ); } } if ( ! self::armed() ) { return array( 'status' => 'local' ); } $slots = $this->submitted_slots( $submitted ); if ( self::holds_mapping( $slots ) ) { return array( 'status' => 'unchanged' ); } if ( ! $was_armed && self::version() >= 1 ) { // The arming GET adopted a mapping the Platform already held, and // this edit was made on a screen that predates the adoption. // Publishing it would overwrite slots the publisher never touched, // on the fresh version, with no 409 to stop it: the Platform wins // instead (§ 8.3), exactly as a 409 ends. return array( 'status' => 'conflict', 'selected' => self::selected(), 'names' => self::names(), ); } $response = $this->send( $slots ); if ( ! is_wp_error( $response ) ) { if ( ! $this->adopt( is_array( $response ) ? $response : array() ) ) { // A stale held version would announce an old baseVersion on // the next save and lose that edit to a manufactured 409. $this->pull( self::SAVE_REREAD_TIMEOUT ); } return array( 'status' => 'published' ); } return $this->resolve( $response ); } /** * Build the five slots a save publishes: a full write (§ 8.1), so a slot * the form did not post keeps its stored key. * * The plugin has no name field yet (that screen is US7): a slot whose key * stands keeps the Platform's name, a changed key drops it. A `null` name * on a `customFields_` slot is defaulted to its meta key by the Platform * (R33), which is what names a custom field on its first publication. * * @since 4.4.0 * @param array $submitted The posted slot keys, by slot name. * @return array */ private function submitted_slots( array $submitted ) { $stored = self::selected(); $names = self::names(); $slots = array(); foreach ( self::SLOTS as $slot ) { $key = array_key_exists( $slot, $submitted ) ? $submitted[ $slot ] : $stored[ $slot ]; $slots[ $slot ] = array( 'key' => $key, 'name' => $key === $stored[ $slot ] ? $names[ $slot ] : null, ); } return $slots; } /** * Send one PATCH: `baseVersion` plus the five slots. * * @since 4.4.0 * @param array $slots The slots to publish. * @return mixed */ private function send( array $slots ) { /** @var string $token */ $token = Options::get( 'settings-analytics-token', '' ); $body = array( 'baseVersion' => self::version() ); foreach ( self::SLOTS as $slot ) { $body[ $slot ] = $slots[ $slot ]; } return $this->api->patch( 'api', 'websites/' . self::identifier() . '/custom_variables', $body, $token ); } /** * Decide what a refused PATCH means for the publisher's save. * * A `404` is not a refusal: it means the sync is not live here, so it * steps aside and the save behaves exactly as the current release. A * `401` refuses the save as `disconnected`: the client has already * deleted the credentials, so a local write would report success for an * edit the pull that follows the reconnection is certain to overwrite. * Everything else refuses the save, each code its own way * (see {@see self::publish_save()}). * * @since 4.4.0 * @param \WP_Error $error The error Api::request() produced. * @return array */ private function resolve( $error ) { $code = (int) $error->get_error_code(); if ( 404 === $code ) { self::disarm_if_refused( $error ); return array( 'status' => 'local' ); } if ( 401 === $code ) { self::disarm_if_refused( $error ); return array( 'status' => 'disconnected' ); } if ( 409 === $code ) { return $this->concede( $error ); } if ( 422 === $code ) { $violations = self::violations_of( $error ); self::log_refusal( 'save', $violations ); return array( 'status' => 'invalid', 'violations' => $violations, ); } $result = array( 'status' => 'failed' ); $data = $error->get_error_data(); if ( 429 === $code && is_array( $data ) && isset( $data['retryAfter'] ) && is_numeric( $data['retryAfter'] ) ) { $result['retry_after'] = (int) $data['retryAfter']; } return $result; } /** * Concede a version conflict: the Platform moved on while the publisher * was editing, and the Platform wins (R19). * * The conflict body normally carries the current version and projection, * so adopting costs no extra request. On a genuine write race the broken * transaction cannot report either (§ 8.2), and the GET supplies the same * material, on the save's small budget: the PATCH already spent its own * timeout. The publisher's change is lost and never replayed: replaying * on the refreshed version would push a stale edit over the mapping that * just won. * * `conflict` is only announced once the winning mapping was actually * adopted: when neither the body nor the GET could supply it, the save is * refused as `failed` instead — a `conflict` there would tell the * publisher the Platform's version was kept while showing values that are * not the Platform's, and drop their edit for nothing. `failed` keeps the * edit on screen; the retry lands, or its 409 supplies the projection. * * @since 4.4.0 * @param \WP_Error $error The conflict. * @return array */ private function concede( $error ) { $body = $error->get_error_data(); $body = is_array( $body ) ? $body : array(); $adopted = isset( $body['currentVersion'] ) && is_numeric( $body['currentVersion'] ) && $this->adopt( array_merge( $body, array( 'version' => (int) $body['currentVersion'] ) ) ); if ( ! $adopted ) { $adopted = $this->pull( self::SAVE_REREAD_TIMEOUT ); } if ( ! $adopted ) { return array( 'status' => 'failed' ); } return array( 'status' => 'conflict', 'selected' => self::selected(), 'names' => self::names(), ); } /** * Extract the rows a 422 refused. * * Extraction only, no logging: each caller decides what a refusal is * worth in the 100-line `logs` buffer — a save logs every one, the seed * only its arming's first ({@see self::log_refusal()}). The rows travel * back to the Settings screen with the exact `message` the Admin shows * (R34, US8 scenario 6). * * @since 4.4.0 * @param \WP_Error $error The validation error. * @return array */ private static function violations_of( $error ) { $body = $error->get_error_data(); $raw = ( is_array( $body ) && isset( $body['violations'] ) && is_array( $body['violations'] ) ) ? $body['violations'] : array(); $violations = array(); foreach ( $raw as $violation ) { $violation = (array) $violation; if ( ! isset( $violation['propertyPath'] ) || ! is_string( $violation['propertyPath'] ) ) { continue; } $violations[] = array( 'propertyPath' => $violation['propertyPath'], 'message' => isset( $violation['message'] ) && is_string( $violation['message'] ) ? $violation['message'] : '', 'code' => isset( $violation['code'] ) && is_string( $violation['code'] ) ? $violation['code'] : '', ); } return $violations; } /** * Log a 422 refusal: which exchange, for which website, which fields. * * Property paths and codes only: the messages and the values are the * publisher's settings and have no business in the log. * * @since 4.4.0 * @param string $exchange The refused exchange, for the log line ('save', 'first send'). * @param array $violations The refused rows. * @return void */ private static function log_refusal( $exchange, array $violations ) { $paths = array(); foreach ( $violations as $violation ) { $paths[] = $violation['propertyPath']; } Logger::add_log( 'Custom variables ' . $exchange . ' refused by the API for website ' . self::identifier() . '; fields rejected: ' . ( array() === $paths ? '(none reported)' : implode( ', ', $paths ) ), self::LOG_CONTEXT, 'error' ); } /** * Adopt a `{version, custom1..custom5}` projection: apply the mapping and * record the version it belongs to. * * The push, the GET and the PATCH answer all carry this same shape from * the same projection, so they all land here. * * A version of 0 is never adopted: it means the Platform holds nothing * (contract § 4), and its all-empty slots would erase the local settings * the first send (§ 8.3) exists to migrate. The caller decides what that * emptiness means — the seed fills it, a pull leaves it alone. * * @since 4.4.0 * @param array $envelope The API projection. * @return bool Whether a mapping was applied. */ private function adopt( array $envelope ) { $slots = self::slots_of( $envelope ); if ( null === $slots ) { return false; } $version = isset( $envelope['version'] ) && is_numeric( $envelope['version'] ) ? (int) $envelope['version'] : 0; if ( $version < 1 ) { return false; } $this->adopt_slots( $slots, $version ); return true; } /** * Write an adopted mapping: the keys into the `custom1` to `custom5` * options the website already reads, the names and the fingerprint beside * them, and the version last. * * Every key is stored as the Platform sent it, a key this plugin version * does not know included. The front end computes only the exact fields the * Settings form offers ({@see \Actirise\Includes\Helpers::get_custom_value()} * parses the key against an allow-list and emits `''` for any other one, a * reflected post field like `post_post_password` included), which is more * honest than keeping the previous key: that one would keep labelling the * analytics dimension with values the Platform believes replaced. The * Settings screen shows such a slot as set on the Platform. * * @since 4.4.0 * @param array $slots The normalised slots. * @param int $version The version they belong to. * @return void */ private function adopt_slots( array $slots, $version ) { $names = array(); foreach ( self::SLOTS as $slot ) { Options::update( $slot, $slots[ $slot ]['key'] ); $names[ $slot ] = $slots[ $slot ]['name']; } Options::update( self::OPTION_NAMES, $names ); Options::update( self::OPTION_DIGEST, self::digest( $slots ) ); Options::update( self::OPTION_VERSION, $version ); // A held mapping settles a pending first send: whatever exchange // adopted it (the seed, a save's first send through the Settings tab, // a push, a conceded conflict), the Platform now provably holds a // mapping, and the seed would only re-read what is already known. if ( $version > 0 && true === Options::get( self::OPTION_SEED_PENDING, false ) ) { Options::update( self::OPTION_SEED_PENDING, false ); } } /** * Normalise the five slots of a projection, or refuse the body. * * Strict on the contract's § 4 shape: every slot present, `key` a string, * `name` a string or null (absent reads as null, as the PATCH body rule * § 8.1 words it). Anything else is a schema error, never guessed around: * at adoption, a guessed `""` would erase a real setting. * * @since 4.4.0 * @param array $envelope The projection carrying the slots. * @return array|null Null when malformed. */ private static function slots_of( array $envelope ) { $slots = array(); foreach ( self::SLOTS as $slot ) { if ( ! isset( $envelope[ $slot ] ) || ! is_array( $envelope[ $slot ] ) ) { return null; } $candidate = $envelope[ $slot ]; if ( ! isset( $candidate['key'] ) || ! is_string( $candidate['key'] ) ) { return null; } $name = isset( $candidate['name'] ) ? $candidate['name'] : null; if ( null !== $name && ! is_string( $name ) ) { return null; } $slots[ $slot ] = array( 'key' => $candidate['key'], 'name' => $name, ); } return $slots; } /** * Whether the mapping the plugin last had confirmed is this one. * * Compared on a fingerprint rather than the value, as * {@see \Actirise\Includes\FastCmp\ConfigSync::holds_config()}: key order * is normalised away, so both sides can evolve how they build the slots * without a silent trap. * * @since 4.4.0 * @param array $slots The normalised slots to compare. * @return bool */ public static function holds_mapping( array $slots ) { $held = Options::get( self::OPTION_DIGEST, '' ); return is_string( $held ) && '' !== $held && $held === self::digest( $slots ); } /** * Fingerprint a normalised mapping, independently of key order. * * @since 4.4.0 * @param array $slots The normalised slots. * @return string */ private static function digest( array $slots ) { $encoded = wp_json_encode( self::sort_deep( $slots ) ); return is_string( $encoded ) ? sha1( $encoded ) : ''; } /** * Sort an array's keys recursively, leaving lists in their own order. * * @since 4.4.0 * @param array $value The array to sort. * @return array */ private static function sort_deep( array $value ) { foreach ( $value as $key => $item ) { if ( is_array( $item ) ) { $value[ $key ] = self::sort_deep( $item ); } } ksort( $value ); return $value; } /** * Read an option that holds a counter. * * {@see \Actirise\Includes\Options::get()} maps a stored `'0'` or `'1'` * back to a **boolean**, so a version of 1 arrives as `true`, which no * `is_numeric()` guard would accept. Casting the boolean recovers the * exact value it stood for ({@see \Actirise\Includes\FastCmp\ConfigSync::int_option()} * precedent; getting it wrong would announce `baseVersion: 0` on every * save and conflict every time). * * @since 4.4.0 * @param string $option Full option name. * @return int */ private static function int_option( $option ) { $value = Options::get( $option, 0 ); if ( is_bool( $value ) ) { return (int) $value; } return is_numeric( $value ) ? (int) $value : 0; } }