diff --git a/.circleci/config.yml b/.circleci/config.yml index 450660de..bccf8561 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -1,6 +1,6 @@ -version: 2 +version: 2.1 workflows: - version: 2 + version: 2.1 main: jobs: - test-behat @@ -16,6 +16,25 @@ workflows: - master jobs: - test-behat +commands: + run_test: + steps: + - run: + name: "Run Tests" + command: | + bash bin/install-wp-tests.sh wordpress_test root '' 127.0.0.1 latest + composer phpunit + WP_MULTISITE=1 composer phpunit + rm -rf $WP_TESTS_DIR $WP_CORE_DIR + bash bin/install-wp-tests.sh wordpress_test root '' 127.0.0.1 nightly true + composer phpunit + bash bin/full-teardown-wp-tests.sh wordpress_test root '' 127.0.0.1 latest + bash bin/install-wp-tests.sh wordpress_test root '' 127.0.0.1 latest + vendor/bin/phpunit --group=cli_command + WP_MULTISITE=1 vendor/bin/phpunit --group=cli_command + rm -rf $WP_TESTS_DIR $WP_CORE_DIR + bash bin/install-wp-tests.sh wordpress_test root '' 127.0.0.1 nightly true + vendor/bin/phpunit --group=cli_command jobs: test-behat: resource_class: small @@ -94,15 +113,8 @@ jobs: sudo docker-php-ext-enable imagick sudo docker-php-ext-install mysqli sudo apt-get install mariadb-client-10.5 - - run: - name: "Run Tests" - command: | - bash bin/install-wp-tests.sh wordpress_test root '' 127.0.0.1 latest - composer phpunit - WP_MULTISITE=1 composer phpunit - rm -rf $WP_TESTS_DIR $WP_CORE_DIR - bash bin/install-wp-tests.sh wordpress_test root '' 127.0.0.1 nightly true - composer phpunit + - run_test + test-phpunit-82: resource_class: small working_directory: ~/pantheon-systems/wp-native-php-sessions @@ -133,12 +145,4 @@ jobs: sudo docker-php-ext-enable imagick sudo docker-php-ext-install mysqli sudo apt-get install mariadb-client-10.6 - - run: - name: "Run Tests" - command: | - bash bin/install-wp-tests.sh wordpress_test root '' 127.0.0.1 latest - composer phpunit - WP_MULTISITE=1 composer phpunit - rm -rf $WP_TESTS_DIR $WP_CORE_DIR - bash bin/install-wp-tests.sh wordpress_test root '' 127.0.0.1 nightly true - composer phpunit + - run_test diff --git a/README.md b/README.md index 915fd35d..cc7cb0e0 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ **Tags:** comments, sessions **Requires at least:** 4.7 **Tested up to:** 6.3 -**Stable tag:** 1.3.7-dev +**Stable tag:** 1.4.0-dev **Requires PHP:** 5.4 **License:** GPLv2 or later **License URI:** http://www.gnu.org/licenses/gpl-2.0.html @@ -42,6 +42,20 @@ To override this use the `pantheon_session_expiration` filter before the WordPre } add_filter( 'pantheon_session_expiration', 'my_session_expiration_override' ); +## CLI Commands ## + +### `wp pantheon session add-index` ### + +Added in 1.4.0-dev. This command should be run if your installation of the plugin occurred before the addition of the primary ID key to the session table in version 1.2.2. You will be automatically notified when you visit any admin page if this is the case. If there's no message, your version is good to go. Note that this command is non-destructive, a new table will be created and the existing one preserved in a backup state until you have verified that the upgrade is functioning as expected. + +### `wp pantheon session primary-key-finalize` ### + +Added in 1.4.0-dev. If you have run the `add-index` command and have verified that the new table is functioning correctly, running the `primary-key-finalize` command will perform a database cleanup and remove the backup table. + +### `wp pantheon session primary-key-revert` ### + +Added in 1.4.0-dev. If you have run the `add-index` command and something unexpected has occurred, just run the `primary-key-revert` command and the backup table will immediately be returned to being the active table. + ## Contributing ## See [CONTRIBUTING.md](https://github.com/pantheon-systems/wp-native-php-sessions/blob/main/CONTRIBUTING.md) for information on contributing. @@ -73,9 +87,16 @@ To fix, create a new file at `wp-content/mu-plugins/000-loader.php` and include This mu-plugin will load WP Native PHP Sessions before all other plugins, while letting you still use the WordPress plugin updater to keep the plugin up-to-date. +## Upgrade Notice ## + +### 1.4.0-dev ### +Adds a WP-CLI command to add an index to the sessions table if one does not exist already. If you installed this plugin before version 1.2.2, you likely need to run this command. However, regardless of version at installation a notice will appear in your admin dashboard if your database table is missing the index. If no notice appears, no action is necessary. + ## Changelog ## -### 1.3.7-dev ### +### 1.4.0-dev ### +* Adds new CLI command to add a Primary Column (id) to the `pantheon_sessions` table for users who do not have one. [[#265](https://github.com/pantheon-systems/wp-native-php-sessions/pull/265)] +* Adds alert to dashboard for users who need to run the new command. * Updates Pantheon WP Coding Standards to 2.0 [[#264](https://github.com/pantheon-systems/wp-native-php-sessions/pull/264)] ### 1.3.6 (June 1, 2023) ### diff --git a/bin/full-teardown-wp-tests.sh b/bin/full-teardown-wp-tests.sh new file mode 100755 index 00000000..2e5db05b --- /dev/null +++ b/bin/full-teardown-wp-tests.sh @@ -0,0 +1,44 @@ +#!/usr/bin/env bash + +if [ $# -lt 3 ]; then + echo "usage: $0 [db-host]" + exit 1 +fi + +DB_NAME=$1 +DB_USER=$2 +DB_PASS=$3 +DB_HOST=${4-localhost} + +TMPDIR=${TMPDIR-/tmp} +WP_TESTS_DIR=${WP_TESTS_DIR-$TMPDIR/wordpress-tests-lib} +WP_CORE_DIR=${WP_CORE_DIR-$TMPDIR/wordpress/} + +file_delete() { + rm -rf $WP_TESTS_DIR $WP_CORE_DIR +} + +drop_db() { + + # parse DB_HOST for port or socket references + local PARTS=(${DB_HOST//\:/ }) + local DB_HOSTNAME=${PARTS[0]}; + local DB_SOCK_OR_PORT=${PARTS[1]}; + local EXTRA="" + + if ! [ -z $DB_HOSTNAME ] ; then + if [ $(echo $DB_SOCK_OR_PORT | grep -e '^[0-9]\{1,\}$') ]; then + EXTRA=" --host=$DB_HOSTNAME --port=$DB_SOCK_OR_PORT --protocol=tcp" + elif ! [ -z $DB_SOCK_OR_PORT ] ; then + EXTRA=" --socket=$DB_SOCK_OR_PORT" + elif ! [ -z $DB_HOSTNAME ] ; then + EXTRA=" --host=$DB_HOSTNAME --protocol=tcp" + fi + fi + + # create database + echo Y | mysqladmin drop $DB_NAME --user="$DB_USER" --password="$DB_PASS"$EXTRA +} + +file_delete +drop_db diff --git a/inc/class-cli-command.php b/inc/class-cli-command.php index 2fd60bac..4b19f512 100644 --- a/inc/class-cli-command.php +++ b/inc/class-cli-command.php @@ -78,6 +78,36 @@ public function delete( $args, $assoc_args ) { } } } + + /** + * Set id as primary key in the Native PHP Sessions plugin table. + * + * @subcommand add-index + */ + public function add_index( $args, $assoc_arc ) { + $pantheon_session = new \Pantheon_Sessions(); + $pantheon_session->add_index(); + } + + /** + * Finalizes the creation of a primary key by deleting the old data. + * + * @subcommand primary-key-finalize + */ + public function primary_key_finalize() { + $pan_session = new \Pantheon_Sessions(); + $pan_session->primary_key_finalize(); + } + + /** + * Reverts addition of primary key. + * + * @subcommand primary-key-revert + */ + public function primary_key_revert() { + $pan_session = new \Pantheon_Sessions(); + $pan_session->primary_key_revert(); + } } \WP_CLI::add_command( 'pantheon session', '\Pantheon_Sessions\CLI_Command' ); diff --git a/pantheon-sessions.php b/pantheon-sessions.php index 9cb5bdcb..929dc705 100644 --- a/pantheon-sessions.php +++ b/pantheon-sessions.php @@ -1,7 +1,7 @@ base_prefix . 'pantheon_sessions'; + $old_table = $wpdb->base_prefix . 'bak_pantheon_sessions'; + $query = "SHOW KEYS FROM {$table_name} WHERE key_name = 'PRIMARY';"; + + $key_existence = $wpdb->get_results( $query ); + + if ( empty( $key_existence ) ) { + // If the key doesn't exist, recommend remediation. + ?> +
+

+ wp pantheon session add-index and verify that the process completes successfully and that this message goes away to resolve this issue on your live environment.', 'wp-native-php-sessions' ) ); + ?> +

+
+ prepare( 'SHOW TABLES LIKE %s', + $wpdb->esc_like( $old_table ) ); + + // Check for table existence and delete if present. + if ( $wpdb->get_var( $query ) == $old_table ) { + // If an old table exists but has not been removed, suggest doing so. + ?> +
+

+ wp pantheon session primary-key-finalize to clean up old data, or run wp pantheon session primary-key-revert if there were issues.', 'wp-native-php-sessions' ) ); + ?> +

+
+ base_prefix . $unprefixed_table; + $temp_clone_table = $wpdb->base_prefix . 'sessions_temp_clone'; + + // If the command has been run multiple times and there is already a + // temp_clone table, drop it. + $query = $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $temp_clone_table ) ); + + if ( $wpdb->get_var( $query ) == $temp_clone_table ) { + $query = "DROP TABLE {$temp_clone_table};"; + $wpdb->query( $query ); + } + + if ( ! PANTHEON_SESSIONS_ENABLED ) { + $this->safe_output( __( 'Pantheon Sessions is currently disabled.', 'wp-native-php-sessions' ), 'error' ); + } + + // Verify that the ID column/primary key does not already exist. + $query = "SHOW KEYS FROM {$table} WHERE key_name = 'PRIMARY';"; + $key_existence = $wpdb->get_results( $query ); + + // Avoid errors by not attempting to add a column that already exists. + if ( ! empty( $key_existence ) ) { + $this->safe_output( __( 'ID column already exists and does not need to be added to the table.', 'wp-native-php-sessions' ), 'error' ); + } + + // Alert the user that the action is going to go through. + $this->safe_output( __( 'Primary Key does not exist, resolution starting.', 'wp-native-php-sessions' ), 'log' ); + + $count_query = "SELECT COUNT(*) FROM {$table};"; + $count_total = $wpdb->get_results( $count_query ); + $count_total = $count_total[0]->{'COUNT(*)'}; + + if ( $count_total >= 20000 ) { + // translators: %s is the total number of rows that exist in the pantheon_sessions table. + $this->safe_output( __( 'A total of %s rows exist. To avoid service interruptions, this operation will be run in batches. Any sessions created between now and when operation completes may need to be recreated.', 'wp-native-php-sessions' ), 'log', [ $count_total ] ); + } + // Create temporary table to copy data into in batches. + $query = "CREATE TABLE {$temp_clone_table} LIKE {$table};"; + $wpdb->query( $query ); + $query = "ALTER TABLE {$temp_clone_table} ADD COLUMN id BIGINT AUTO_INCREMENT PRIMARY KEY FIRST"; + $wpdb->query( $query ); + + $batch_size = 20000; + $loops = ceil( $count_total / $batch_size ); + + for ( $i = 0; $i < $loops; $i++ ) { + $offset = $i * $batch_size; + + $query = sprintf( "INSERT INTO {$temp_clone_table} +(user_id, session_id, secure_session_id, ip_address, datetime, data) +SELECT user_id,session_id,secure_session_id,ip_address,datetime,data +FROM %s ORDER BY user_id LIMIT %d OFFSET %d", $table, $batch_size, $offset ); + $results = $wpdb->query( $query ); + $current_results = $results + ( $batch_size * $i ); + + // translators: %1 and %2 are how many rows have been processed out of how many total. + $this->safe_output( __( 'Updated %1$s / %2$s rows. ', 'wp-native-php-sessions' ), 'log', [ $current_results, $count_total ] ); + } + + // Hot swap the old table and the new table, deleting a previous old + // table if necessary. + $old_table = $wpdb->base_prefix . 'bak_' . $unprefixed_table; + $query = $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $old_table ) ); + + if ( $wpdb->get_var( $query ) == $old_table ) { + $query = "DROP TABLE {$old_table};"; + $wpdb->query( $query ); + } + + $query = "ALTER TABLE {$table} RENAME {$old_table};"; + $wpdb->query( $query ); + $query = "ALTER TABLE {$temp_clone_table} RENAME {$table};"; + $wpdb->query( $query ); + + $this->safe_output( __( 'Operation complete, please verify that your site is working as expected. When ready, run wp pantheon session primary-key-finalize to clean up old data, or run wp pantheon session primary-key-revert if there were issues.', 'wp-native-php-sessions' ), 'log' ); + } + + /** + * Finalizes the creation of a primary key by deleting the old data. + */ + public function primary_key_finalize() { + global $wpdb; + $table = $wpdb->base_prefix . 'bak_pantheon_sessions'; + + $query = $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $table ) ); + + // Check for table existence and delete if present. + if ( ! $wpdb->get_var( $query ) == $table ) { + $this->safe_output( __( 'Old table does not exist to be removed.', 'wp-native-php-sessions' ), 'error' ); + } else { + $query = "DROP TABLE {$table};"; + $wpdb->query( $query ); + + $this->safe_output( __( 'Old table has been successfully removed, process complete.', 'wp-native-php-sessions' ), 'log' ); + + } + } + + /** + * Reverts addition of primary key. + */ + public function primary_key_revert() { + global $wpdb; + $old_clone_table = $wpdb->base_prefix . 'bak_pantheon_sessions'; + $temp_clone_table = $wpdb->base_prefix . 'temp_pantheon_sessions'; + $table = $wpdb->base_prefix . 'pantheon_sessions'; + + // If there is no old table to roll back to, error. + $query = $wpdb->prepare( 'SHOW TABLES LIKE %s', $wpdb->esc_like( $old_clone_table ) ); + + if ( ! $wpdb->get_var( $query ) == $old_clone_table ) { + $this->safe_output( __( 'There is no old table to roll back to.', 'wp-native-php-sessions' ), 'error' ); + } + + // Swap old table and new one. + $query = "ALTER TABLE {$table} RENAME {$temp_clone_table};"; + $wpdb->query( $query ); + $query = "ALTER TABLE {$old_clone_table} RENAME {$table};"; + $wpdb->query( $query ); + $this->safe_output( __( 'Rolled back to previous state successfully, dropping corrupt table.', 'wp-native-php-sessions' ), 'log' ); + + // Remove table which did not function. + $query = "DROP TABLE {$temp_clone_table}"; + $wpdb->query( $query ); + $this->safe_output( __( 'Process complete.', 'wp-native-php-sessions' ), 'log' ); + } + + /** + * Provide output to users, whether it's being run in WP_CLI or not. + * + * @param string $message Message to be printed. + * @param string $type If message is being printed through WP_CLI, what type of message. + * @param array $variables If sprintf is needed, an array of values. + * + * @return void + */ + protected function safe_output( $message, $type, array $variables = [] ) { + if ( defined( 'WP_CLI' ) && WP_CLI ) { + WP_CLI::$type( vsprintf( $message, $variables ) ); + return; + } + + print "\n" . vsprintf( $message, $variables ); + + // Calling WP_CLI::error triggers an exit, but we still need to exist even if we don't have WP_CLI available. + if ( $type === 'error' ) { + exit( 1 ); + } + } } /** @@ -273,5 +471,6 @@ function Pantheon_Sessions() { } add_action( 'activated_plugin', 'Pantheon_Sessions::force_first_load' ); +add_action( 'admin_notices', 'Pantheon_Sessions::check_native_primary_keys' ); Pantheon_Sessions(); diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 4084d58a..e4add2f0 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -11,4 +11,9 @@ ./tests/phpunit/ + + + cli_command + + diff --git a/readme.txt b/readme.txt index 18e59a88..4cf3a4e5 100644 --- a/readme.txt +++ b/readme.txt @@ -3,7 +3,7 @@ Contributors: getpantheon, outlandish josh, mpvanwinkle77, danielbachhuber, andr Tags: comments, sessions Requires at least: 4.7 Tested up to: 6.3 -Stable tag: 1.3.7-dev +Stable tag: 1.4.0-dev Requires PHP: 5.4 License: GPLv2 or later License URI: http://www.gnu.org/licenses/gpl-2.0.html @@ -41,6 +41,20 @@ To override this use the `pantheon_session_expiration` filter before the WordPre } add_filter( 'pantheon_session_expiration', 'my_session_expiration_override' ); +== CLI Commands == + += `wp pantheon session add-index` = + +Added in 1.4.0-dev. This command should be run if your installation of the plugin occurred before the addition of the primary ID key to the session table in version 1.2.2. You will be automatically notified when you visit any admin page if this is the case. If there's no message, your version is good to go. Note that this command is non-destructive, a new table will be created and the existing one preserved in a backup state until you have verified that the upgrade is functioning as expected. + += `wp pantheon session primary-key-finalize` = + +Added in 1.4.0-dev. If you have run the `add-index` command and have verified that the new table is functioning correctly, running the `primary-key-finalize` command will perform a database cleanup and remove the backup table. + += `wp pantheon session primary-key-revert` = + +Added in 1.4.0-dev. If you have run the `add-index` command and something unexpected has occurred, just run the `primary-key-revert` command and the backup table will immediately be returned to being the active table. + == Contributing == See [CONTRIBUTING.md](https://github.com/pantheon-systems/wp-native-php-sessions/blob/main/CONTRIBUTING.md) for information on contributing. @@ -72,8 +86,17 @@ To fix, create a new file at `wp-content/mu-plugins/000-loader.php` and include This mu-plugin will load WP Native PHP Sessions before all other plugins, while letting you still use the WordPress plugin updater to keep the plugin up-to-date. +== Upgrade Notice == + += 1.4.0-dev = +Adds a WP-CLI command to add an index to the sessions table if one does not exist already. If you installed this plugin before version 1.2.2, you likely need to run this command. However, regardless of version at installation a notice will appear in your admin dashboard if your database table is missing the index. If no notice appears, no action is necessary. + == Changelog == += 1.4.0 = +* Adds new CLI command to add a Primary Column (id) to the `pantheon_sessions` table for users who do not have one. [[#265](https://github.com/pantheon-systems/wp-native-php-sessions/pull/265)] +* Adds alert to dashboard for users who need to run the command. + = 1.3.7-dev = * Updates Pantheon WP Coding Standards to 2.0 [[#264](https://github.com/pantheon-systems/wp-native-php-sessions/pull/264)] diff --git a/tests/phpunit/test-sessions.php b/tests/phpunit/test-sessions.php index 4bb41074..354e8336 100644 --- a/tests/phpunit/test-sessions.php +++ b/tests/phpunit/test-sessions.php @@ -172,6 +172,40 @@ public function test_get_client_ip_server() { $this->assertEquals( '192.168.1.4', Session::get_client_ip_server() ); } + /** + * Ensure that the primary key addition command works. + * + * @group cli_command + */ + public function test_primary_key_addition() { + global $wpdb, $table_prefix; + + $table_name = "{$table_prefix}pantheon_sessions"; + + $query = "ALTER TABLE {$table_name} DROP COLUMN id"; + $wpdb->query( $query ); + + $pantheon_session = new Pantheon_Sessions(); + $pantheon_session->add_index(); + $pantheon_session->primary_key_finalize(); + + $column_data = $wpdb->get_results( "SHOW COLUMNS FROM {$table_name}" ); + $columns = wp_list_pluck( $column_data, 'Field' ); + + $this->assertEquals( + [ + 'id', + 'user_id', + 'session_id', + 'secure_session_id', + 'ip_address', + 'datetime', + 'data', + ], + $columns + ); + } + /** * Runs at the end of every test. */