From 8e49bf0a2c9e74958f80de13a52b5fa720e87949 Mon Sep 17 00:00:00 2001 From: Adam Cassis Date: Thu, 21 Nov 2024 09:57:02 +0100 Subject: [PATCH] feat(reader-data): add a CLI command to align reader membership data (#3548) --- .../reader-activation/class-reader-data.php | 4 +- .../cli/class-sync-reader-data-cli.php | 109 ++++++++++++++++++ 2 files changed, 112 insertions(+), 1 deletion(-) create mode 100644 includes/reader-activation/cli/class-sync-reader-data-cli.php diff --git a/includes/reader-activation/class-reader-data.php b/includes/reader-activation/class-reader-data.php index 40cfb10b8c..a9d651f30e 100644 --- a/includes/reader-activation/class-reader-data.php +++ b/includes/reader-activation/class-reader-data.php @@ -9,6 +9,8 @@ use Newspack\Memberships; +require_once NEWSPACK_ABSPATH . 'includes/reader-activation/cli/class-sync-reader-data-cli.php'; + defined( 'ABSPATH' ) || exit; /** @@ -131,7 +133,7 @@ public static function permission_callback() { * * @param string $key Key. */ - private static function get_meta_key_name( $key ) { + public static function get_meta_key_name( $key ) { return 'newspack_reader_data_item_' . $key; } diff --git a/includes/reader-activation/cli/class-sync-reader-data-cli.php b/includes/reader-activation/cli/class-sync-reader-data-cli.php new file mode 100644 index 0000000000..689cd2abf2 --- /dev/null +++ b/includes/reader-activation/cli/class-sync-reader-data-cli.php @@ -0,0 +1,109 @@ +posts} p + LEFT JOIN {$wpdb->users} u + ON p.post_author = u.ID + LEFT JOIN {$wpdb->prefix}usermeta um + ON u.ID = um.user_id + AND um.meta_key = %s + WHERE p.post_type = 'wc_user_membership' + AND p.post_status = 'wcm-active' + GROUP BY u.ID + HAVING actual_membership_plan_ids != stored_membership_plan_ids + OR stored_membership_plan_ids IS NULL + "; + + $reader_data_user_meta_key = Reader_Data::get_meta_key_name( 'active_memberships' ); + $potentially_misaliged_members = $wpdb->get_results( $wpdb->prepare( $sql, $reader_data_user_meta_key ) ); // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared + foreach ( $potentially_misaliged_members as $reader_data ) { + // Rule out false-positives. + $actual_membership_plan_ids = explode( ',', $reader_data->actual_membership_plan_ids ?? '' ); + $stored_membership_plan_ids = explode( ',', $reader_data->stored_membership_plan_ids ?? '' ); + sort( $actual_membership_plan_ids ); + sort( $stored_membership_plan_ids ); + + if ( $actual_membership_plan_ids === $stored_membership_plan_ids ) { + // False positive. + continue; + } + + if ( $live ) { + $update_result = update_user_meta( $reader_data->user_id, $reader_data_user_meta_key, implode( ',', $actual_membership_plan_ids ) ); + if ( $update_result !== false ) { + \WP_CLI::success( sprintf( 'Updated user #%d reader data.', $reader_data->user_id ) ); + } + } else { + \WP_CLI::log( sprintf( 'Would update user #%d reader data.', $reader_data->user_id ) ); + } + } + + \WP_CLI::line( '' ); + } +} +Sync_Reader_Data_CLI::init();