new name. */ const OPTIONS = array( 'adi_bridge_tokens' => 'adibridge_tokens', 'adi_bridge_last_used' => 'adibridge_last_used', ); /** Meta keys of restore points: old => new. */ const META = array( '_adi_snapshot' => '_adibridge_snapshot', '_adi_target' => '_adibridge_target', '_adi_path' => '_adibridge_path', '_adi_kind' => '_adibridge_kind', '_adi_before' => '_adibridge_before', '_adi_after' => '_adibridge_after', '_adi_token' => '_adibridge_token', '_adi_units' => '_adibridge_units', '_adi_stock' => '_adibridge_stock', '_adi_css' => '_adibridge_css', ); const OLD_POST_TYPE = 'adi_snapshot'; const OLD_LOCKS = '_adi_bridge_lock_'; public static function boot() { if ( (int) get_option( self::OPTION, 0 ) < self::SCHEMA ) { self::run(); } } public static function run() { global $wpdb; foreach ( self::OPTIONS as $old => $new ) { // One statement renames the row, so a request arriving at the same moment cannot write an older // copy over a newer one. It fails when the new name already exists: that row wins, the old one goes. $wpdb->suppress_errors( true ); $renamed = $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->options} SET option_name = %s WHERE option_name = %s", $new, $old ) ); $wpdb->suppress_errors( false ); if ( ! $renamed ) { $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name = %s", $old ) ); } foreach ( array( $old, $new, 'alloptions', 'notoptions' ) as $key ) { wp_cache_delete( $key, 'options' ); } } // Meta keys of restore points only: another plugin's "_adi_path" on some other post is not ours. $moved = 0; foreach ( self::META as $old => $new ) { $moved += (int) $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->postmeta} SET meta_key = %s WHERE meta_key = %s AND post_id IN ( SELECT ID FROM {$wpdb->posts} WHERE post_type IN ( %s, %s ) )", $new, $old, self::OLD_POST_TYPE, Snapshots::POST_TYPE ) ); } $moved += (int) $wpdb->query( $wpdb->prepare( "UPDATE {$wpdb->posts} SET post_type = %s WHERE post_type = %s", Snapshots::POST_TYPE, self::OLD_POST_TYPE ) ); // Locks last minutes at most; one left under the old name would never be read again. $wpdb->query( $wpdb->prepare( "DELETE FROM {$wpdb->options} WHERE option_name LIKE %s", $wpdb->esc_like( self::OLD_LOCKS ) . '%' ) ); delete_site_transient( 'adi_bridge_latest' ); if ( $moved ) { wp_cache_flush(); // posts and meta cached under the old names } update_option( self::OPTION, self::SCHEMA ); } }