diff --git a/includes/class-activity-dispatcher.php b/includes/class-activity-dispatcher.php index f37e709..462a75a 100644 --- a/includes/class-activity-dispatcher.php +++ b/includes/class-activity-dispatcher.php @@ -23,9 +23,6 @@ class Activity_Dispatcher { * Initialize the class, registering WordPress hooks. */ public static function init() { - // check if a migration is needed before sending new posts - Migration::maybe_migrate(); - \add_action( 'activitypub_send_activity', array( self::class, 'send_activity' ), 10, 2 ); \add_action( 'activitypub_send_activity', array( self::class, 'send_activity_or_announce' ), 10, 2 ); } @@ -39,6 +36,9 @@ class Activity_Dispatcher { * @return void */ public static function send_activity_or_announce( WP_Post $wp_post, $type ) { + // check if a migration is needed before sending new posts + Migration::maybe_migrate(); + if ( is_user_type_disabled( 'blog' ) ) { return; } @@ -93,9 +93,6 @@ class Activity_Dispatcher { * @return void */ public static function send_announce( WP_Post $wp_post, $type ) { - // check if a migration is needed before sending new posts - Migration::maybe_migrate(); - if ( ! in_array( $type, array( 'Create', 'Update' ), true ) ) { return; } diff --git a/includes/class-migration.php b/includes/class-migration.php index c03476a..e81f5dc 100644 --- a/includes/class-migration.php +++ b/includes/class-migration.php @@ -38,6 +38,46 @@ class Migration { return get_option( 'activitypub_db_version', 0 ); } + /** + * Locks the database migration process to prevent simultaneous migrations. + * + * @return void + */ + public static function lock() { + \update_option( 'activitypub_migration_lock', \time() ); + } + + /** + * Unlocks the database migration process. + * + * @return void + */ + public static function unlock() { + \delete_option( 'activitypub_migration_lock' ); + } + + /** + * Whether the database migration process is locked. + * + * @return boolean + */ + public static function is_locked() { + $lock = \get_option( 'activitypub_migration_lock' ); + + if ( ! $lock ) { + return false; + } + + $lock = (int) $lock; + + if ( $lock < \time() - 1800 ) { + self::unlock(); + return false; + } + + return true; + } + /** * Whether the database structure is up to date. * @@ -59,16 +99,24 @@ class Migration { return; } + if ( self::is_locked() ) { + return; + } + + self::lock(); + $version_from_db = self::get_version(); - if ( version_compare( $version_from_db, '0.16.0', '<' ) ) { + if ( version_compare( $version_from_db, '0.17.0', '<' ) ) { self::migrate_from_0_16(); } - if ( version_compare( $version_from_db, '0.17.0', '<' ) ) { + if ( version_compare( $version_from_db, '1.0.0', '<' ) ) { self::migrate_from_0_17(); } update_option( 'activitypub_db_version', self::get_target_version() ); + + self::unlock(); } /**