options`. The object cache can bring back an old value after a raw write, so it * never decides what a page applies, and it never decides whether the migration has run. * 2. Every write is fenced. The same SQL statement that changes a record also requires the * writer's exact lock value and a lease that has not run out by the database's own clock, * so a holder that lost the lock can write nothing at all, not even a record its successor * has not touched yet. * 3. A page reads one snapshot in one query, and applies the delivery record (rules and * statement) only when its generation equals the connection record's. * 4. Each change of several records is ordered so that stopping after any single write leaves * a state a page may serve: the old connection's own fixes, the new one's, or nothing. * * The atomic primitive is one SQL statement against the options table, whose `option_name` * column is unique: an `INSERT IGNORE` creates a row or changes nothing, and a conditional * `UPDATE` or `DELETE` applies or changes nothing, and the affected-row count says which. * `add_option()` is not that (it checks, then upserts) and neither is a transient, so neither * is used. Core's own `WP_Upgrader::create_lock()` is built the same way. * * Every `$wpdb` call is in this file and goes through `db()`, `read_raw()` and the few * statement builders below, so the tests can run the real class over a double. * * Records are JSON written without JSON_UNESCAPED_UNICODE, which is plain ASCII: the `SHA2()` * comparison of a fenced write is then byte-exact whatever the table's or the connection's * character set, and a query that is all ASCII never goes through core's charset rewriting. */ if ( ! defined( 'ABSPATH' ) ) { exit; } // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared -- the lock and the fenced writes are single SQL statements on the options table by design (an options API call is not atomic), the table name is core's own `$wpdb->options`, and every value goes through `prepare()`. class EqualSites_Connect_Store { const CONNECTION = 'ableguard_connection'; const DELIVERY = 'ableguard_delivery'; const PENDING = 'ableguard_connect_pending'; const LOCK = 'ableguard_connect_lock'; const VERSION = 'ableguard_storage_version'; const UNSUPPORTED = 'ableguard_storage_unsupported'; const PROBE = 'ableguard_store_probe'; /** What `VERSION` holds once the migration has run. */ const CURRENT_VERSION = '2'; /** What `UNSUPPORTED` holds once the store probe has failed on three requests. */ const UNSUPPORTED_MARK = '1'; /** Failed probes, on separate requests, before the site is marked unsupported. */ const PROBE_FAILURES = 3; /** How long a lock lasts without renewal, by the database's clock. */ const LEASE_SECONDS = 30; /** The 0.3.1 options that moved into the records, by the name each had after its prefix. */ const MOVED_BASES = array( 'api_url', 'site_id', 'token', 'rules', 'last_sync', 'statement_html', 'statement_synced_at', 'zero_rules_since' ); /** The 0.3.1 options that stay core-managed options, read with `get_option()`. */ const KEPT_BASES = array( 'enabled', 'alt_written', 'statement_last_attempt' ); /** Of those, the two the owner's settings own: the switch and the alt-text counter. */ const SETTING_BASES = array( 'enabled', 'alt_written' ); /** The reason Start gives on a database that refused the store's statements. */ const UNSUPPORTED_REASON = "this site's database isn't supported"; /** @var array|null One request's snapshot of the four names a page needs. */ private static $snapshot = null; /** @var array|null What this request's pages apply, built from that snapshot. */ private static $page = null; /** @var bool Whether this request has already counted a failed probe. */ private static $probe_counted = false; /** @var string|null Which request the two memos above belong to. */ private static $request_key = null; /** * What a request has read and counted is kept in statics, which a PHP process that serves * several requests (a worker-mode server, a long WP-CLI run) would carry from one to the * next. A request is told apart by its start time, so a memo is never older than its request. */ private static function this_request() { $key = isset( $_SERVER['REQUEST_TIME_FLOAT'] ) ? sanitize_text_field( wp_unslash( (string) $_SERVER['REQUEST_TIME_FLOAT'] ) ) : ''; if ( $key !== self::$request_key ) { self::$request_key = $key; self::$snapshot = null; self::$page = null; self::$probe_counted = false; } } /** * Forgets what this request has read, so it reads again. Called after a write, so the same * request sees what it just wrote. */ public static function forget() { self::$snapshot = null; self::$page = null; } /** * Starts a request over: forgets what was read and what was counted. Production never * needs it, since a request ends; the tests call it between two simulated requests. */ public static function new_request() { self::forget(); self::$probe_counted = false; } private static function db() { return isset( $GLOBALS['wpdb'] ) && is_object( $GLOBALS['wpdb'] ) ? $GLOBALS['wpdb'] : null; } private static function random_hex( $bytes = 16 ) { try { return bin2hex( random_bytes( $bytes ) ); } catch ( Exception $e ) { return substr( hash( 'sha256', uniqid( (string) wp_rand(), true ) . microtime() ), 0, $bytes * 2 ); } } /** A fresh generation: 32 random hex characters, never reused. */ public static function new_generation() { return self::random_hex( 16 ); } // Records as text /** @return string|false */ public static function encode( array $data ) { return json_encode( $data, JSON_INVALID_UTF8_SUBSTITUTE ); } /** @return array|null A record, or null for an absent, empty or unreadable one. */ public static function decode( $raw ) { if ( ! is_string( $raw ) || '' === $raw ) { return null; } $data = json_decode( $raw, true ); return is_array( $data ) ? $data : null; } // Direct reads /** * One option's stored text, straight from the options table. * * @return string|null|false The text, null when there is no row, false on an SQL error. * A caller that reads false as "absent" would treat a failed * read of a record it means to delete as already deleted. */ public static function read_raw( $name ) { $db = self::db(); if ( ! $db ) { return false; } $value = $db->get_var( $db->prepare( "SELECT option_value FROM {$db->options} WHERE option_name = %s LIMIT 1", $name ) ); if ( '' !== (string) $db->last_error ) { return false; } return null === $value ? null : (string) $value; } /** A record, read directly. */ public static function read_record( $name ) { return self::decode( self::read_raw( $name ) ); } /** * The storage version and the unsupported marker, read directly. * * @return array|false array( 'version' => ?string, 'unsupported' => ?string ), or false on an SQL error. */ public static function read_flags() { $version = self::read_raw( self::VERSION ); $unsupported = self::read_raw( self::UNSUPPORTED ); if ( false === $version || false === $unsupported ) { return false; } return array( 'version' => $version, 'unsupported' => $unsupported, ); } /** * Which layout a control path (a writer, the settings screen, the sync) is looking at: * 'v2' once the migration has run, 'unsupported' on a database that refused the store's * statements, 'legacy' while the migration is still to come. */ public static function layout() { $flags = self::read_flags(); if ( is_array( $flags ) && self::CURRENT_VERSION === $flags['version'] ) { return 'v2'; } if ( is_array( $flags ) && self::UNSUPPORTED_MARK === $flags['unsupported'] ) { return 'unsupported'; } return 'legacy'; } public static function is_unsupported() { $flags = self::read_flags(); return is_array( $flags ) && self::CURRENT_VERSION !== $flags['version'] && self::UNSUPPORTED_MARK === $flags['unsupported']; } /** Whether a connection record names a site and holds its token. */ public static function connection_active( $connection ) { return is_array( $connection ) && '' !== (string) ( isset( $connection['site_id'] ) ? $connection['site_id'] : '' ) && '' !== (string) ( isset( $connection['token'] ) ? $connection['token'] : '' ); } /** Whether a delivery record belongs to the site a connection record names. */ public static function same_site( $record, $connection ) { return is_array( $record ) && is_array( $connection ) && (string) ( isset( $record['api_url'] ) ? $record['api_url'] : '' ) === (string) ( isset( $connection['api_url'] ) ? $connection['api_url'] : '' ) && (string) ( isset( $record['site_id'] ) ? $record['site_id'] : '' ) === (string) ( isset( $connection['site_id'] ) ? $connection['site_id'] : '' ); } // What a page applies /** * The one query a page makes, and what it found: the storage version, the unsupported * marker, and the two records, as stored text. Memoised for the request, so the buffer, * the shortcode and the baseline check all see the same snapshot. */ public static function snapshot() { self::this_request(); if ( null !== self::$snapshot ) { return self::$snapshot; } $found = array( self::VERSION => null, self::UNSUPPORTED => null, self::CONNECTION => null, self::DELIVERY => null, ); $db = self::db(); if ( $db ) { $rows = $db->get_results( $db->prepare( "SELECT option_name, option_value FROM {$db->options} WHERE option_name IN (%s, %s, %s, %s)", self::VERSION, self::UNSUPPORTED, self::CONNECTION, self::DELIVERY ), ARRAY_A ); if ( is_array( $rows ) ) { foreach ( $rows as $row ) { if ( isset( $row['option_name'], $row['option_value'] ) && array_key_exists( $row['option_name'], $found ) ) { $found[ $row['option_name'] ] = (string) $row['option_value']; } } } } self::$snapshot = array( 'version' => $found[ self::VERSION ], 'unsupported' => self::UNSUPPORTED_MARK === $found[ self::UNSUPPORTED ], 'connection' => self::decode( $found[ self::CONNECTION ] ), 'delivery' => self::decode( $found[ self::DELIVERY ] ), 'layout' => self::CURRENT_VERSION === $found[ self::VERSION ] ? 'v2' : 'legacy', ); return self::$snapshot; } /** * What this request's pages apply, as one array whichever layout the site is in: * * layout, api_url, site_id, token, account, method, generation the connection, as saved * has_connection the connection names a site and holds its token * applies the fixes below may be served: in the new layout the connection is * active and the delivery record carries its generation, in the old one * always, as 0.3.1 did * rules, last_sync, statement_html, statement_synced_at, zero_rules_since * the delivery, or empty when `applies` is false * * With no storage version the page takes its 0.3.1 snapshot, then reads the version again * with a direct query. A migration that committed in between has already written the new * records and is about to delete the old options, so the 0.3.1 snapshot may be half gone: * the page throws it away and reads the new records instead. The migration deletes the old * options only after it writes the version, so a page that still sees no version on its * second read took a complete 0.3.1 snapshot. * * @param bool $fresh Take a new snapshot instead of this request's memoised one. */ public static function page( $fresh = false ) { self::this_request(); if ( $fresh ) { self::forget(); } if ( null !== self::$page ) { return self::$page; } $snapshot = self::snapshot(); if ( 'v2' === $snapshot['layout'] ) { return self::$page = self::compose_v2( $snapshot['connection'], $snapshot['delivery'] ); } $page = self::legacy_view(); if ( ! $snapshot['unsupported'] ) { $again = self::read_flags(); if ( is_array( $again ) && self::CURRENT_VERSION === $again['version'] ) { self::$snapshot = null; $snapshot = self::snapshot(); $page = self::compose_v2( $snapshot['connection'], $snapshot['delivery'] ); } } return self::$page = $page; } /** * The same view, built from direct reads. For the settings screen, which never reuses the * request's snapshot. */ public static function view_direct() { if ( 'v2' === self::layout() ) { return self::compose_v2( self::read_record( self::CONNECTION ), self::read_record( self::DELIVERY ) ); } return self::legacy_view(); } /** * The connection alone, from direct reads: what a control path needs to know whether the * site is connected and where to. The delivery fields of the view are empty. */ public static function connection_direct() { if ( 'v2' === self::layout() ) { return self::compose_v2( self::read_record( self::CONNECTION ), null ); } return self::legacy_view(); } private static function compose_v2( $connection, $delivery ) { $connection = is_array( $connection ) ? $connection : array(); $view = array( 'layout' => 'v2', 'api_url' => (string) ( isset( $connection['api_url'] ) ? $connection['api_url'] : '' ), 'site_id' => (string) ( isset( $connection['site_id'] ) ? $connection['site_id'] : '' ), 'token' => (string) ( isset( $connection['token'] ) ? $connection['token'] : '' ), 'account' => (string) ( isset( $connection['account'] ) ? $connection['account'] : '' ), 'method' => (string) ( isset( $connection['method'] ) ? $connection['method'] : '' ), 'generation' => (string) ( isset( $connection['generation'] ) ? $connection['generation'] : '' ), 'has_connection' => self::connection_active( $connection ), 'applies' => false, 'rules' => array(), 'last_sync' => 0, 'statement_html' => '', 'statement_synced_at' => 0, 'zero_rules_since' => 0, ); if ( ! $view['has_connection'] || '' === $view['generation'] || ! is_array( $delivery ) ) { return $view; } if ( (string) ( isset( $delivery['generation'] ) ? $delivery['generation'] : '' ) !== $view['generation'] ) { return $view; } $view['applies'] = true; $view['rules'] = isset( $delivery['rules'] ) && is_array( $delivery['rules'] ) ? $delivery['rules'] : array(); $view['last_sync'] = (int) ( isset( $delivery['last_sync'] ) ? $delivery['last_sync'] : 0 ); $view['statement_html'] = (string) ( isset( $delivery['statement_html'] ) ? $delivery['statement_html'] : '' ); $view['statement_synced_at'] = (int) ( isset( $delivery['statement_synced_at'] ) ? $delivery['statement_synced_at'] : 0 ); $view['zero_rules_since'] = (int) ( isset( $delivery['zero_rules_since'] ) ? $delivery['zero_rules_since'] : 0 ); return $view; } /** * The 0.3.1 page reader: the individual options, exactly as 0.3.1 read them, through * `get_option()`. What a page reads before the migration has run, and for good on a * database that refused the store's statements. */ public static function legacy_view() { $api_url = ableguard_option( 'ableguard_api_url', 'equalsites_api_url', '' ); if ( '' === $api_url ) { $api_url = get_option( 'equalsites_api_url', '' ); } $site_id = (string) ableguard_option( 'ableguard_site_id', 'equalsites_site_id', '' ); $token = (string) ableguard_option( 'ableguard_token', 'equalsites_token', '' ); $rules = ableguard_option( 'ableguard_rules', 'equalsites_rules', array() ); return array( 'layout' => 'legacy', 'api_url' => (string) $api_url, 'site_id' => $site_id, 'token' => $token, 'account' => '', 'method' => '', 'generation' => '', 'has_connection' => '' !== $site_id && '' !== $token, 'applies' => true, 'rules' => is_array( $rules ) ? $rules : array(), 'last_sync' => (int) ableguard_option( 'ableguard_last_sync', 'equalsites_last_sync', 0 ), 'statement_html' => (string) ableguard_option( 'ableguard_statement_html', 'equalsites_statement_html', '' ), 'statement_synced_at' => (int) ableguard_option( 'ableguard_statement_synced_at', 'equalsites_statement_synced_at', 0 ), 'zero_rules_since' => (int) ableguard_option( 'ableguard_zero_rules_since', 'equalsites_zero_rules_since', 0 ), ); } /** * When the rate-limit clock for the statement was last started, as a direct query. Falls * back to the 0.3.1 read while the site is not on the new layout. */ public static function statement_last_attempt() { if ( 'v2' === self::layout() ) { $raw = self::read_raw( 'ableguard_statement_last_attempt' ); return is_string( $raw ) ? (int) $raw : 0; } return (int) ableguard_option( 'ableguard_statement_last_attempt', 'equalsites_statement_last_attempt', 0 ); } // The lock /** * Takes the site-wide lock, once. * * The value is `||`: a 128-bit hex token, a counter, * and the lease end in Unix seconds by the database's clock. PHP's clock is never used for * a lease. A lock whose lease has run out may be taken over by anyone, but only from the * exact value read, so two takeovers cannot both win. * * @return string|null|false The exact value now held, null when someone else holds it, or * false when the database refused the statement. */ public static function acquire() { $db = self::db(); if ( ! $db ) { return false; } $token = self::random_hex( 16 ); for ( $round = 0; $round < 2; $round++ ) { $inserted = $db->query( $db->prepare( "INSERT IGNORE INTO {$db->options} (option_name, option_value, autoload) VALUES ('" . self::LOCK . "', CONCAT(%s, '|0|', UNIX_TIMESTAMP() + " . self::LEASE_SECONDS . "), 'no')", $token ) ); if ( false === $inserted ) { return false; } if ( 1 === (int) $inserted ) { return self::confirm_lock( $token . '|' ); } $current = self::read_raw( self::LOCK ); if ( false === $current ) { return false; } if ( null === $current ) { continue; } $taken = $db->query( $db->prepare( "UPDATE {$db->options} SET option_value = CONCAT(%s, '|0|', UNIX_TIMESTAMP() + " . self::LEASE_SECONDS . "), autoload = 'no' WHERE option_name = '" . self::LOCK . "' AND option_value = %s AND CAST(SUBSTRING_INDEX(option_value, '|', -1) AS UNSIGNED) <= UNIX_TIMESTAMP()", $token, $current ) ); if ( false === $taken ) { return false; } return 1 === (int) $taken ? self::confirm_lock( $token . '|' ) : null; } return null; } /** The holder reads its value back: that exact string is what every later statement names. */ private static function confirm_lock( $prefix ) { $value = self::read_raw( self::LOCK ); return is_string( $value ) && 0 === strpos( $value, $prefix ) ? $value : null; } /** * Keeps trying for the lock for up to `$seconds`. The return handler uses this after * `/token` has answered: the server has already acted, so it cannot just give up. * * An SQL error is retried like a busy lock, because a deadlock or a dropped connection is * gone a moment later and the exchange cannot be made again. It is reported only if the * last attempt, at the deadline, still met one. * * @return string|null|false As `acquire()`, of the last attempt. */ public static function acquire_waiting( $seconds ) { $deadline = microtime( true ) + $seconds; do { $held = self::acquire(); if ( is_string( $held ) ) { return $held; } usleep( 100000 ); } while ( microtime( true ) < $deadline ); return $held; } /** * Extends a lease. Refused once the holder's own lease has run out, even when nobody took * over, and the counter makes every renewal change the value, so one affected row always * means it worked. * * @return string|null The new exact value, or null when the lock is no longer the holder's. */ public static function renew( $held ) { $db = self::db(); $parts = explode( '|', (string) $held ); if ( ! $db || 3 !== count( $parts ) ) { return null; } $next = (int) $parts[1] + 1; $done = $db->query( $db->prepare( "UPDATE {$db->options} SET option_value = CONCAT(%s, '|', %d, '|', UNIX_TIMESTAMP() + " . self::LEASE_SECONDS . ") WHERE option_name = '" . self::LOCK . "' AND option_value = %s AND CAST(SUBSTRING_INDEX(option_value, '|', -1) AS UNSIGNED) > UNIX_TIMESTAMP()", $parts[0], $next, $held ) ); if ( 1 !== (int) $done ) { return null; } $value = self::read_raw( self::LOCK ); return is_string( $value ) && 0 === strpos( $value, $parts[0] . '|' . $next . '|' ) ? $value : null; } /** Releases the lock, but only if the row still holds exactly the holder's value. */ public static function release( $held ) { $db = self::db(); if ( ! $db || ! is_string( $held ) || '' === $held ) { return false; } $done = $db->query( $db->prepare( "DELETE FROM {$db->options} WHERE option_name = '" . self::LOCK . "' AND option_value = %s", $held ) ); return 1 === (int) $done; } // Fenced writes /** * Creates a record, only while `$held` is still the lock row and its lease has not run * out. The lock check is in the same statement as the write, so there is no gap between * checking and writing for a stalled holder to fall into. */ public static function fenced_create( $held, $name, $value ) { return 1 === self::run_fenced_create( $held, $name, $value ); } /** Replaces a record, only if it still holds the text whose SHA-256 is `$old_hash`. */ public static function fenced_replace( $held, $name, $old_raw, $value ) { return 1 === self::run_fenced_replace( $held, $name, $old_raw, $value ); } /** Deletes a record, only if it still holds the text whose SHA-256 is `$old_hash`. */ public static function fenced_delete( $held, $name, $old_raw ) { return 1 === self::run_fenced_delete( $held, $name, $old_raw ); } /** @return int|false Affected rows, or false on an SQL error. */ private static function run_fenced_create( $held, $name, $value ) { $db = self::db(); if ( ! $db ) { return false; } $done = $db->query( $db->prepare( "INSERT IGNORE INTO {$db->options} (option_name, option_value, autoload) SELECT %s, %s, 'no' FROM {$db->options} AS l WHERE l.option_name = '" . self::LOCK . "' AND l.option_value = %s AND CAST(SUBSTRING_INDEX(l.option_value, '|', -1) AS UNSIGNED) > UNIX_TIMESTAMP()", $name, $value, $held ) ); return self::after_write( $done, $name ); } /** @return int|false */ private static function run_fenced_replace( $held, $name, $old_raw, $value ) { $db = self::db(); if ( ! $db ) { return false; } $done = $db->query( $db->prepare( "UPDATE {$db->options} AS r JOIN {$db->options} AS l ON l.option_name = '" . self::LOCK . "' SET r.option_value = %s, r.autoload = 'no' WHERE r.option_name = %s AND SHA2(r.option_value, 256) = %s AND l.option_value = %s AND CAST(SUBSTRING_INDEX(l.option_value, '|', -1) AS UNSIGNED) > UNIX_TIMESTAMP()", $value, $name, hash( 'sha256', (string) $old_raw ), $held ) ); return self::after_write( $done, $name ); } /** @return int|false */ private static function run_fenced_delete( $held, $name, $old_raw ) { $db = self::db(); if ( ! $db ) { return false; } $done = $db->query( $db->prepare( "DELETE r FROM {$db->options} AS r JOIN {$db->options} AS l ON l.option_name = '" . self::LOCK . "' WHERE r.option_name = %s AND SHA2(r.option_value, 256) = %s AND l.option_value = %s AND CAST(SUBSTRING_INDEX(l.option_value, '|', -1) AS UNSIGNED) > UNIX_TIMESTAMP()", $name, hash( 'sha256', (string) $old_raw ), $held ) ); return self::after_write( $done, $name ); } private static function after_write( $done, $name ) { self::forget(); if ( false === $done ) { return false; } if ( (int) $done > 0 ) { self::touch_cache( $name ); } return (int) $done; } /** * Cache upkeep after a raw write, for any other code that calls `get_option()` on these * names: drop the name's cache entry, take it out of the cached `notoptions` array (one * `notoptions` key in the `options` group), and drop `alloptions` if the row had been * autoloaded. Best effort, and nothing here depends on it: every read above is a query. */ private static function touch_cache( $name ) { if ( ! function_exists( 'wp_cache_delete' ) ) { return; } $alloptions = wp_cache_get( 'alloptions', 'options' ); wp_cache_delete( $name, 'options' ); $notoptions = wp_cache_get( 'notoptions', 'options' ); if ( is_array( $notoptions ) && isset( $notoptions[ $name ] ) ) { unset( $notoptions[ $name ] ); wp_cache_set( 'notoptions', $notoptions, 'options' ); } if ( is_array( $alloptions ) && isset( $alloptions[ $name ] ) ) { wp_cache_delete( 'alloptions', 'options' ); } } // Sections that hold the lock /** * Runs `$fn( $tx )` while holding the lock, after finishing the migration if it has not * run: every writer migrates first, so nothing 0.3.1 wrote can overwrite what 0.4.0 does * next, and 0.4.0 never writes through 0.3.1's storage. * * Start, Disconnect and the manual save try the lock once and answer busy. The return * handler, whose exchange has already happened on the server, waits up to five seconds. * The sync and the migration try once and skip; the next sync or request retries. * * An SQL error from the lock's own statements is a 'retry' and nothing more: only the probe's * three statements count towards marking a site unsupported (spec 4.10), because the marker is * never lifted and a deadlock or a dropped connection says nothing about the shapes. * * @param callable $fn Receives an EqualSites_Connect_Tx. * @param int|float $wait Seconds to keep trying for the lock; 0 tries once. * @return array array( 'status' => 'ok'|'busy'|'unsupported'|'retry', 'value' => what `$fn` returned ). * 'unsupported': the database refused the store's statements, so there is no * lock and the caller keeps 0.3.1's storage. 'retry': the migration could not * finish on this request. */ public static function locked( $fn, $wait = 0 ) { $flags = self::read_flags(); if ( is_array( $flags ) && self::CURRENT_VERSION !== $flags['version'] && self::UNSUPPORTED_MARK === $flags['unsupported'] ) { return array( 'status' => 'unsupported', 'value' => null, ); } $held = $wait > 0 ? self::acquire_waiting( $wait ) : self::acquire(); if ( false === $held ) { return array( 'status' => 'retry', 'value' => null, ); } if ( null === $held ) { return array( 'status' => 'busy', 'value' => null, ); } $tx = new EqualSites_Connect_Tx( $held ); try { $migrated = self::migrate_under_lock( $tx ); if ( 'done' !== $migrated ) { return array( 'status' => $migrated, 'value' => null, ); } return array( 'status' => 'ok', 'value' => call_user_func( $fn, $tx ), ); } finally { self::release( $tx->held() ); self::forget(); } } // The migration (spec 4.10) /** * The `init` hook: finish the migration if the storage version, read from the database, * says it has not run. Reads the request's snapshot, so a migrated site pays nothing it * was not already going to pay. Skipped quietly when the lock is busy. */ public static function maybe_migrate() { $snapshot = self::snapshot(); if ( 'v2' === $snapshot['layout'] || $snapshot['unsupported'] ) { return; } self::locked( function () { return true; } ); } /** * Under the lock: runs the migration unless it has already run. * * @return string 'done' (the new layout is in place), 'unsupported' (this database refused * the store's statements and 0.3.1's storage stays), or 'retry' (not on this * request: the probe or a write failed, and the next locked request tries * the whole migration again). */ private static function migrate_under_lock( $tx ) { $flags = self::read_flags(); if ( ! is_array( $flags ) ) { return 'retry'; } if ( self::CURRENT_VERSION === $flags['version'] ) { return 'done'; } if ( self::UNSUPPORTED_MARK === $flags['unsupported'] ) { return 'unsupported'; } $probe = self::probe( $tx->held() ); if ( 'error' === $probe ) { return self::record_probe_failure() ? 'unsupported' : 'retry'; } if ( 'ok' !== $probe ) { return 'retry'; } if ( null !== $flags['unsupported'] ) { delete_option( self::UNSUPPORTED ); } return self::migrate( $tx ) ? 'done' : 'retry'; } /** * Before the first migration, the three statement shapes the store relies on (a fenced * insert from the options table, a joined update and a joined delete) run once against a * scratch row, under the lock the migration holds. WordPress needs MySQL or MariaDB, but * the SQLite layer WordPress Playground uses may refuse them. * * @return string 'ok', 'error' (the database answered an SQL error rather than a row * count), or 'mismatch' (it answered, but not as the shapes require). */ private static function probe( $held ) { $db = self::db(); if ( ! $db ) { return 'error'; } $quiet = method_exists( $db, 'suppress_errors' ) ? $db->suppress_errors( true ) : null; try { $name = self::PROBE; $result = 'ok'; $left = self::read_raw( $name ); if ( false === $left ) { return 'error'; } if ( is_string( $left ) ) { $gone = self::run_fenced_delete( $held, $name, $left ); if ( false === $gone ) { return 'error'; } if ( 1 !== $gone ) { return 'mismatch'; } } $made = self::run_fenced_create( $held, $name, 'a' ); if ( false === $made ) { return 'error'; } if ( 1 !== $made ) { return 'mismatch'; } $swapped = self::run_fenced_replace( $held, $name, 'a', 'b' ); if ( 1 === $swapped ) { $removed = self::run_fenced_delete( $held, $name, 'b' ); if ( 1 !== $removed ) { $result = false === $removed ? 'error' : 'mismatch'; } } else { $result = false === $swapped ? 'error' : 'mismatch'; $stuck = self::read_raw( $name ); if ( is_string( $stuck ) ) { self::run_fenced_delete( $held, $name, $stuck ); } } return $result; } finally { if ( null !== $quiet ) { $db->suppress_errors( $quiet ); } } } /** * Counts a failed probe, once per request. The third, on separate requests, records the * marker: from then on the site keeps 0.3.1's storage, readers and sync exactly as they * were, and never migrates. A single transient failure does not mark the site, and a * probe that succeeds clears the count. * * @return bool Whether the site is now marked unsupported. */ private static function record_probe_failure() { self::this_request(); if ( self::$probe_counted ) { return false; } self::$probe_counted = true; $raw = self::read_raw( self::UNSUPPORTED ); if ( false === $raw ) { return false; } if ( self::UNSUPPORTED_MARK === $raw ) { return true; } $failures = preg_match( '/^probe:([0-9]+)$/', (string) $raw, $found ) ? (int) $found[1] : 0; ++$failures; $value = $failures >= self::PROBE_FAILURES ? self::UNSUPPORTED_MARK : 'probe:' . $failures; update_option( self::UNSUPPORTED, $value, false ); return self::UNSUPPORTED_MARK === $value; } /** * The migration proper, under the lock and after a successful probe. Every step reads * what it needs directly, and every write to a record is fenced. A crash before the * version is written re-runs the whole thing on the next locked request, and a re-run * writes both records again under one new generation, never only one of them. A crash * after it leaves 0.3.1 options that nothing reads, which Disconnect and uninstall remove. * * @return bool */ private static function migrate( $tx ) { $found = array(); foreach ( self::MOVED_BASES as $base ) { $found[ $base ] = null; foreach ( array( 'ableguard_', 'equalsites_' ) as $prefix ) { $raw = self::read_raw( $prefix . $base ); if ( false === $raw ) { return false; } if ( is_string( $raw ) && '' !== $raw ) { $found[ $base ] = $raw; break; } } } $api_url = (string) $found['api_url']; $site_id = (string) $found['site_id']; $token = (string) $found['token']; $now = time(); $generation = self::new_generation(); if ( '' !== $site_id && '' !== $token ) { $rules = null === $found['rules'] ? array() : maybe_unserialize( $found['rules'] ); $rules = is_array( $rules ) ? $rules : array(); $zero = (int) $found['zero_rules_since']; $delivery = array( 'generation' => $generation, 'api_url' => $api_url, 'site_id' => $site_id, 'rules' => $rules, 'last_sync' => (int) $found['last_sync'], 'statement_html' => (string) $found['statement_html'], 'statement_synced_at' => (int) $found['statement_synced_at'], 'zero_rules_since' => EqualSites_Api_Client::zero_rules_since_for( $rules, $zero, $now ), ); $connection = array( 'generation' => $generation, 'api_url' => $api_url, 'site_id' => $site_id, 'token' => $token, 'account' => '', 'method' => 'manual', 'saved_at' => $now, ); if ( ! $tx->write( self::DELIVERY, $delivery ) || ! $tx->write( self::CONNECTION, $connection ) ) { return false; } } elseif ( '' !== $api_url ) { $address_only = array( 'generation' => $generation, 'api_url' => $api_url, ); if ( ! $tx->write( self::CONNECTION, $address_only ) || ! $tx->delete( self::DELIVERY ) ) { return false; } } foreach ( array( 'enabled', 'alt_written' ) as $base ) { $new = self::read_raw( 'ableguard_' . $base ); $old = self::read_raw( 'equalsites_' . $base ); if ( false === $new || false === $old ) { return false; } if ( null === $new && is_string( $old ) ) { update_option( 'ableguard_' . $base, maybe_unserialize( $old ), false ); } } if ( ! $tx->write_raw( self::VERSION, self::CURRENT_VERSION ) ) { return false; } self::delete_legacy_options( false ); return true; } /** * Deletes the 0.3.1 options with `delete_option()`, legacy names first. The two options * the owner's settings still own (`enabled` and `alt_written`) and, unless asked, * `statement_last_attempt` keep their `ableguard_` names. * * `$keep_settings` keeps the legacy names of those two as well. On a database that refused * the store's statements nothing was ever migrated, so a paused site's switch and its * alt-text counter may still live under `equalsites_`, and deleting them would turn the * site's fixes back on. */ public static function delete_legacy_options( $drop_attempt_clock, $keep_settings = false ) { foreach ( array_merge( self::MOVED_BASES, self::KEPT_BASES ) as $base ) { if ( $keep_settings && in_array( $base, self::SETTING_BASES, true ) ) { continue; } delete_option( 'equalsites_' . $base ); } foreach ( self::MOVED_BASES as $base ) { delete_option( 'ableguard_' . $base ); } if ( $drop_attempt_clock ) { delete_option( 'ableguard_statement_last_attempt' ); } } // Multi-record changes (spec 4.10, "The order of writes") /** * A connection swap: a committed exchange, or a manual save. Every write is fenced and the * next step runs only if the previous one succeeded, so stopping after any of them leaves * pages applying the old connection's fixes, the new one's, or nothing. * * 1. Read the connection, the delivery and the pending entry directly. * 2. For an exchange, the pending entry must still be this flow's exact entry. * 3. A delivery for another site is deleted first. Nothing is served from here on. * 4. The connection is written with a new generation. * 5. A delivery for the same site is rewritten under the new generation, so the site's * own fixes come back, however that delivery came by its old generation. * 6. If the site changed, or there was no connection, the statement's rate-limit clock * is deleted under both names. * 7. The pending entry is deleted. * * @param EqualSites_Connect_Tx $tx * @param array $connection The new connection; its generation is replaced. * @param array|null $require_pending For an exchange, the entry it must find. * @return array array( 'status' => 'ok'|'superseded'|'failed', 'generation' => the new one ). */ public static function swap_connection( $tx, array $connection, $require_pending = null ) { $old_connection = $tx->read( self::CONNECTION ); $delivery_raw = $tx->read_raw( self::DELIVERY ); $delivery = self::decode( $delivery_raw ); $pending_raw = $tx->read_raw( self::PENDING ); if ( $tx->broken() ) { return array( 'status' => 'failed', 'generation' => '', ); } if ( null !== $require_pending && self::encode( $require_pending ) !== $pending_raw ) { return array( 'status' => 'superseded', 'generation' => '', ); } $generation = self::new_generation(); $connection['generation'] = $generation; $same_site = self::same_site( $delivery, $connection ); $failed = array( 'status' => 'failed', 'generation' => $generation, ); if ( null !== $delivery_raw && ! $same_site && ! $tx->delete( self::DELIVERY ) ) { return $failed; } if ( ! $tx->write( self::CONNECTION, $connection ) ) { return $failed; } if ( $same_site ) { $delivery['generation'] = $generation; if ( ! $tx->write( self::DELIVERY, $delivery ) ) { return $failed; } } if ( ! is_array( $old_connection ) || ! self::same_site( $old_connection, $connection ) ) { delete_option( 'equalsites_statement_last_attempt' ); delete_option( 'ableguard_statement_last_attempt' ); } if ( ! $tx->delete( self::PENDING ) ) { return $failed; } return array( 'status' => 'ok', 'generation' => $generation, ); } /** * Disconnect, in order: the connection (nothing is served from that moment), the delivery, * the pending entry, then the bookkeeping option and any leftover 0.3.1 options. It keeps * `enabled` and `alt_written`, and makes no network call. * * @param EqualSites_Connect_Tx $tx * @return bool */ public static function disconnect( $tx ) { foreach ( array( self::CONNECTION, self::DELIVERY, self::PENDING ) as $name ) { if ( ! $tx->delete( $name ) ) { return false; } } self::delete_legacy_options( true ); return true; } // What the sync needs (spec 4.10, `sync_rules()`) /** * Step 1 of a sync: take the lock, finish the migration if it has not run, read the * connection directly and release. * * @return array 'status' is 'ok', 'busy' (the lock is held: skip this sync) or 'retry' * (the migration could not finish on this request). On 'ok' the array also * holds `layout` ('v2', or 'legacy' on a database that refused the store's * statements), `api_url`, `site_id`, `token` and `generation` as saved, and * `active`, whether the connection names a site and holds its token. */ public static function begin_sync() { $read = self::locked( function ( $tx ) { return $tx->read( EqualSites_Connect_Store::CONNECTION ); } ); if ( 'unsupported' === $read['status'] ) { $view = self::legacy_view(); return array( 'status' => 'ok', 'layout' => 'legacy', 'api_url' => $view['api_url'], 'site_id' => $view['site_id'], 'token' => $view['token'], 'generation' => '', 'active' => $view['has_connection'], ); } if ( 'ok' !== $read['status'] ) { return array( 'status' => $read['status'] ); } $view = self::compose_v2( $read['value'], null ); return array( 'status' => 'ok', 'layout' => 'v2', 'api_url' => $view['api_url'], 'site_id' => $view['site_id'], 'token' => $view['token'], 'generation' => $view['generation'], 'active' => $view['has_connection'], ); } /** * Steps 3 to 5 of a sync: take the lock, and unless the connection has changed since step * 1, write the delivery for the connection's generation. * * The statement is the new one if it was fetched, otherwise the previous statement when * the delivery is for the same site, otherwise empty. `zero_rules_since` keeps today's * meaning: kept while rules stay at zero for the same site, set to now when they first * read zero, cleared when they are not. * * @param array $ctx What `begin_sync()` returned. * @param array $rules * @param string|null $statement The fetched statement, or null when there was none. * @param int $now * @return string 'ok', 'busy', 'retry', 'superseded' (the connection changed: nothing * written) or 'failed' (a fenced write was refused). */ public static function commit_sync( $ctx, $rules, $statement, $now ) { if ( 'legacy' === $ctx['layout'] ) { return self::legacy_commit_sync( $rules, $statement, $now ); } $result = self::locked( function ( $tx ) use ( $ctx, $rules, $statement, $now ) { $connection = $tx->read( EqualSites_Connect_Store::CONNECTION ); if ( ! EqualSites_Connect_Store::connection_active( $connection ) || (string) ( isset( $connection['generation'] ) ? $connection['generation'] : '' ) !== $ctx['generation'] ) { return 'superseded'; } $delivery = $tx->read( EqualSites_Connect_Store::DELIVERY ); $same_site = EqualSites_Connect_Store::same_site( $delivery, $connection ); $record = array( 'generation' => $ctx['generation'], 'api_url' => (string) ( isset( $connection['api_url'] ) ? $connection['api_url'] : '' ), 'site_id' => (string) $connection['site_id'], 'rules' => $rules, 'last_sync' => (int) $now, 'statement_html' => null !== $statement ? $statement : ( $same_site ? (string) ( isset( $delivery['statement_html'] ) ? $delivery['statement_html'] : '' ) : '' ), 'statement_synced_at' => null !== $statement ? (int) $now : ( $same_site ? (int) ( isset( $delivery['statement_synced_at'] ) ? $delivery['statement_synced_at'] : 0 ) : 0 ), 'zero_rules_since' => EqualSites_Api_Client::zero_rules_since_for( $rules, $same_site ? (int) ( isset( $delivery['zero_rules_since'] ) ? $delivery['zero_rules_since'] : 0 ) : 0, $now ), ); return $tx->write( EqualSites_Connect_Store::DELIVERY, $record ) ? 'ok' : 'failed'; } ); return 'ok' === $result['status'] ? $result['value'] : ( 'busy' === $result['status'] ? 'busy' : 'retry' ); } /** * The statement-only refresh the shortcode triggers: commit the statement fields into the * delivery under the lock, and only while both the connection and the delivery are still * at the generation the fetch started under. * * @return string As `commit_sync()`. */ public static function commit_statement( $ctx, $html, $now ) { if ( 'legacy' === $ctx['layout'] ) { update_option( 'ableguard_statement_html', $html, false ); update_option( 'ableguard_statement_synced_at', $now, false ); return 'ok'; } $result = self::locked( function ( $tx ) use ( $ctx, $html, $now ) { $connection = $tx->read( EqualSites_Connect_Store::CONNECTION ); $delivery = $tx->read( EqualSites_Connect_Store::DELIVERY ); if ( ! EqualSites_Connect_Store::connection_active( $connection ) || ! is_array( $delivery ) || (string) ( isset( $connection['generation'] ) ? $connection['generation'] : '' ) !== $ctx['generation'] || (string) ( isset( $delivery['generation'] ) ? $delivery['generation'] : '' ) !== $ctx['generation'] ) { return 'superseded'; } $delivery['statement_html'] = $html; $delivery['statement_synced_at'] = (int) $now; return $tx->write( EqualSites_Connect_Store::DELIVERY, $delivery ) ? 'ok' : 'failed'; } ); return 'ok' === $result['status'] ? $result['value'] : ( 'busy' === $result['status'] ? 'busy' : 'retry' ); } /** * Whether the connection a sync started under is still the connection. Read directly, * without the lock: it is a question, not a write. The alt-text write-back asks it before * each attachment. */ public static function connection_still( $ctx ) { if ( 'legacy' === $ctx['layout'] ) { return true; } $connection = self::read_record( self::CONNECTION ); return self::connection_active( $connection ) && (string) ( isset( $connection['generation'] ) ? $connection['generation'] : '' ) === $ctx['generation']; } /** * What a sync commits on a database that refused the store's statements: the options 0.3.1 * wrote, in the order it wrote them, with no lock because there is none to take there. * * @return string */ private static function legacy_commit_sync( $rules, $statement, $now ) { update_option( 'ableguard_rules', $rules, false ); update_option( 'ableguard_last_sync', $now, false ); if ( empty( $rules ) ) { if ( ! ableguard_option( 'ableguard_zero_rules_since', 'equalsites_zero_rules_since', 0 ) ) { update_option( 'ableguard_zero_rules_since', $now, false ); } } else { delete_option( 'ableguard_zero_rules_since' ); delete_option( 'equalsites_zero_rules_since' ); } if ( null !== $statement ) { update_option( 'ableguard_statement_html', $statement, false ); update_option( 'ableguard_statement_synced_at', $now, false ); } return 'ok'; } } /** * One section that holds the lock. It remembers the text it last read or wrote of each record, * because a fenced replace or delete has to name the exact text it is replacing, and it stops * writing at the first failure: the next step of a multi-record change runs only if the * previous one succeeded. */ class EqualSites_Connect_Tx { /** @var string The exact lock value this section holds. */ private $held; /** @var array Record name => the text last read or written under this lock, or null. */ private $raw = array(); /** @var bool Set by the first failed read or write; every later write then fails at once. */ private $broken = false; public function __construct( $held ) { $this->held = $held; } public function held() { return $this->held; } public function broken() { return $this->broken; } /** Extends the lease. A holder that cannot renew has lost the lock and writes no more. */ public function renew() { $next = EqualSites_Connect_Store::renew( $this->held ); if ( null === $next ) { $this->broken = true; return false; } $this->held = $next; return true; } /** A direct read, remembered as the text a later write replaces. */ public function read_raw( $name ) { $raw = EqualSites_Connect_Store::read_raw( $name ); if ( false === $raw ) { $this->broken = true; return null; } $this->raw[ $name ] = $raw; return $raw; } public function read( $name ) { return EqualSites_Connect_Store::decode( $this->read_raw( $name ) ); } /** * Writes text to a record: a fenced create when the read found no row, a fenced replace * otherwise. Writing the text a record already holds changes nothing and counts as done. */ public function write_raw( $name, $value ) { if ( $this->broken || ! is_string( $value ) ) { return false; } if ( ! array_key_exists( $name, $this->raw ) ) { $this->read_raw( $name ); if ( $this->broken ) { return false; } } $old = $this->raw[ $name ]; if ( $old === $value ) { return true; } $done = null === $old ? EqualSites_Connect_Store::fenced_create( $this->held, $name, $value ) : EqualSites_Connect_Store::fenced_replace( $this->held, $name, $old, $value ); if ( ! $done ) { $this->broken = true; return false; } $this->raw[ $name ] = $value; return true; } public function write( $name, array $data ) { return $this->write_raw( $name, EqualSites_Connect_Store::encode( $data ) ); } /** * Deletes a record with a fenced delete. A record the direct read found absent is already * deleted and counts as done; the next fenced step is what notices a lapsed lease. */ public function delete( $name ) { if ( $this->broken ) { return false; } if ( ! array_key_exists( $name, $this->raw ) ) { $this->read_raw( $name ); if ( $this->broken ) { return false; } } $old = $this->raw[ $name ]; if ( null === $old ) { return true; } if ( ! EqualSites_Connect_Store::fenced_delete( $this->held, $name, $old ) ) { $this->broken = true; return false; } $this->raw[ $name ] = null; return true; } } // phpcs:enable